Skip to content

Commit aaed09b

Browse files
authored
Fix: remove newline from highlight objects (#576)
* Fix: remove newline from highlight objects * Fix array becomming string in array highlight
1 parent cebcfc0 commit aaed09b

File tree

2 files changed

+27
-6
lines changed

2 files changed

+27
-6
lines changed

src/adapter/search-response-adapter/highlight-adapter.ts

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,7 @@ function replaceHighlightTags(
1919
highlightPostTag = highlightPostTag || '__/ais-highlight__'
2020
// Highlight is applied by MeiliSearch (<em> tags)
2121
// We replace the <em> by the expected tag for InstantSearch
22-
const stringifiedValue = isString(value)
23-
? value
24-
: JSON.stringify(value, null, 2)
22+
const stringifiedValue = isString(value) ? value : JSON.stringify(value)
2523

2624
return stringifiedValue
2725
.replace(/<em>/g, highlightPreTag)
@@ -46,9 +44,15 @@ function adaptHighlight(
4644
})
4745
return Object.keys(formattedHit).reduce((result, key) => {
4846
const value = formattedHit[key]
49-
result[key] = Array.isArray(value)
50-
? value.map(toHighlightMatch)
51-
: toHighlightMatch(value)
47+
if (Array.isArray(value)) {
48+
result[key] = value.map((val) => ({
49+
value: typeof val === 'object' ? JSON.stringify(val) : val,
50+
}))
51+
} else if (typeof value === 'object' && value !== null) {
52+
result[key] = { value: JSON.stringify(value) }
53+
} else {
54+
result[key] = toHighlightMatch(value)
55+
}
5256
return result
5357
}, {} as any)
5458
}

tests/highlight.tests.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,23 @@ describe('Highlight Browser test', () => {
7878
expect(response.results[0]?.hits[0]).not.toHaveProperty('_highlightResult')
7979
})
8080

81+
test('Test no attributesToHighlight on placeholder', async () => {
82+
const response = await searchClient.search<Movies>([
83+
{
84+
indexName: 'movies',
85+
params: {
86+
attributesToHighlight: ['genres'],
87+
},
88+
},
89+
])
90+
91+
const highlightedHit = response.results[0].hits[0]._highlightResult
92+
if (highlightedHit?.genres) {
93+
expect(highlightedHit?.genres[0]?.value).toEqual('Adventure')
94+
expect(highlightedHit?.genres[1]?.value).toEqual('Action')
95+
}
96+
})
97+
8198
test('Test one attributesToHighlight on specific query', async () => {
8299
const response = await searchClient.search<Movies>([
83100
{

0 commit comments

Comments
 (0)