Skip to content

Commit 66e1df9

Browse files
committed
Fix highlight on non-strings
1 parent 89ca6aa commit 66e1df9

File tree

1 file changed

+12
-13
lines changed

1 file changed

+12
-13
lines changed

src/adapter/highlight-adapter.ts

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,22 +11,21 @@ import { InstantSearchParams } from '../types'
1111
* @returns string
1212
*/
1313
function replaceHighlightTags(
14-
value: string,
14+
value: any,
1515
highlightPreTag?: string,
1616
highlightPostTag?: string
1717
): string {
18-
// Value has to be a string to have highlight.
19-
// Highlight is applied by MeiliSearch (<em> tags)
20-
// We replace the <em> by the expected tag for InstantSearch
2118
highlightPreTag = highlightPreTag || '__ais-highlight__'
2219
highlightPostTag = highlightPostTag || '__/ais-highlight__'
23-
if (isString(value)) {
24-
return value
25-
.replace(/<em>/g, highlightPreTag)
26-
.replace(/<\/em>/g, highlightPostTag)
27-
}
28-
// We JSON stringify to avoid loss of nested information
29-
return JSON.stringify(value)
20+
// Highlight is applied by MeiliSearch (<em> tags)
21+
// We replace the <em> by the expected tag for InstantSearch
22+
const stringifiedValue = isString(value)
23+
? value
24+
: JSON.stringify(value, null, 2)
25+
26+
return stringifiedValue
27+
.replace(/<em>/g, highlightPreTag)
28+
.replace(/<\/em>/g, highlightPostTag)
3029
}
3130

3231
/**
@@ -43,7 +42,7 @@ function adaptHighlight(
4342
// formattedHit is the `_formatted` object returned by MeiliSearch.
4443
// It contains all the highlighted and croped attributes
4544
return Object.keys(formattedHit).reduce((result, key) => {
46-
;(result[key] as any) = {
45+
; (result[key] as any) = {
4746
value: replaceHighlightTags(
4847
formattedHit[key],
4948
highlightPreTag,
@@ -109,7 +108,7 @@ function adaptSnippet(
109108
// It contains all the highlighted and croped attributes
110109
return (Object.keys(formattedHit) as any[]).reduce((result, key) => {
111110
if (attributesToSnippet?.includes(key)) {
112-
;(result[key] as any) = {
111+
; (result[key] as any) = {
113112
value: snippetValue(
114113
formattedHit[key],
115114
snippetEllipsisText,

0 commit comments

Comments
 (0)