|
| 1 | +import { |
| 2 | + parseAlgoliaHitHighlight, |
| 3 | + parseAlgoliaHitReverseHighlight, |
| 4 | + parseAlgoliaHitSnippet, |
| 5 | + parseAlgoliaHitReverseSnippet, |
| 6 | +} from '@algolia/autocomplete-preset-algolia'; |
| 7 | + |
| 8 | +function concatParts(parts, { |
| 9 | + highlightPreTag, |
| 10 | + highlightPostTag |
| 11 | +}) { |
| 12 | + return parts.reduce((acc, current) => { |
| 13 | + return (acc + |
| 14 | + (current.isHighlighted ? |
| 15 | + `${highlightPreTag}${current.value}${highlightPostTag}` : |
| 16 | + current.value)); |
| 17 | + }, ''); |
| 18 | +} |
| 19 | +/** |
| 20 | + * Highlights and escapes the matching parts of an Algolia hit. |
| 21 | + */ |
| 22 | +export function highlightHit({ |
| 23 | + hit, |
| 24 | + attribute, |
| 25 | + highlightPreTag = '<mark>', |
| 26 | + highlightPostTag = '</mark>', |
| 27 | + ignoreEscape, |
| 28 | +}) { |
| 29 | + return concatParts(parseAlgoliaHitHighlight({ |
| 30 | + hit, |
| 31 | + attribute, |
| 32 | + ignoreEscape, |
| 33 | + }), { |
| 34 | + highlightPreTag, |
| 35 | + highlightPostTag |
| 36 | + }); |
| 37 | +} |
| 38 | +/** |
| 39 | + * Highlights and escapes the non-matching parts of an Algolia hit. |
| 40 | + * |
| 41 | + * This is a common pattern for Query Suggestions. |
| 42 | + */ |
| 43 | +export function reverseHighlightHit({ |
| 44 | + hit, |
| 45 | + attribute, |
| 46 | + highlightPreTag = '<mark>', |
| 47 | + highlightPostTag = '</mark>', |
| 48 | + ignoreEscape, |
| 49 | +}) { |
| 50 | + return concatParts(parseAlgoliaHitReverseHighlight({ |
| 51 | + hit, |
| 52 | + attribute, |
| 53 | + ignoreEscape, |
| 54 | + }), { |
| 55 | + highlightPreTag, |
| 56 | + highlightPostTag |
| 57 | + }); |
| 58 | +} |
| 59 | +/** |
| 60 | + * Highlights and escapes the matching parts of an Algolia hit snippet. |
| 61 | + */ |
| 62 | +export function snippetHit({ |
| 63 | + hit, |
| 64 | + attribute, |
| 65 | + highlightPreTag = '<mark>', |
| 66 | + highlightPostTag = '</mark>', |
| 67 | + ignoreEscape, |
| 68 | +}) { |
| 69 | + return concatParts(parseAlgoliaHitSnippet({ |
| 70 | + hit, |
| 71 | + attribute, |
| 72 | + ignoreEscape, |
| 73 | + }), { |
| 74 | + highlightPreTag, |
| 75 | + highlightPostTag |
| 76 | + }); |
| 77 | +} |
| 78 | +/** |
| 79 | + * Highlights and escapes the non-matching parts of an Algolia hit snippet. |
| 80 | + * |
| 81 | + * This is a common pattern for Query Suggestions. |
| 82 | + */ |
| 83 | +export function reverseSnippetHit({ |
| 84 | + hit, |
| 85 | + attribute, |
| 86 | + highlightPreTag = '<mark>', |
| 87 | + highlightPostTag = '</mark>', |
| 88 | + ignoreEscape, |
| 89 | +}) { |
| 90 | + return concatParts(parseAlgoliaHitReverseSnippet({ |
| 91 | + hit, |
| 92 | + attribute, |
| 93 | + ignoreEscape, |
| 94 | + }), { |
| 95 | + highlightPreTag, |
| 96 | + highlightPostTag |
| 97 | + }); |
| 98 | +} |
0 commit comments