@@ -78,19 +78,21 @@ export function fetchMeilisearchResults<TRecord = Record<string, any>>({
7878 ...acc ,
7979 [ field ] : highlightResult . map ( ( highlight ) =>
8080 calculateHighlightMetadata (
81- highlight . value ,
81+ query . query || '' ,
8282 query . params ?. highlightPreTag || HIGHLIGHT_PRE_TAG ,
83- query . params ?. highlightPostTag || HIGHLIGHT_POST_TAG
83+ query . params ?. highlightPostTag || HIGHLIGHT_POST_TAG ,
84+ highlight . value
8485 )
8586 ) ,
8687 }
8788 }
8889 return {
8990 ...acc ,
9091 [ field ] : calculateHighlightMetadata (
91- highlightResult . value ,
92+ query . query || '' ,
9293 query . params ?. highlightPreTag || HIGHLIGHT_PRE_TAG ,
93- query . params ?. highlightPostTag || HIGHLIGHT_POST_TAG
94+ query . params ?. highlightPostTag || HIGHLIGHT_POST_TAG ,
95+ highlightResult . value
9496 ) ,
9597 }
9698 } , { } as HighlightResult < TRecord > ) ,
@@ -102,21 +104,33 @@ export function fetchMeilisearchResults<TRecord = Record<string, any>>({
102104 )
103105}
104106
107+ /**
108+ * Calculate the highlight metadata for a given highlight value.
109+ * @param query - The query string.
110+ * @param preTag - The pre tag.
111+ * @param postTag - The post tag.
112+ * @param highlightValue - The highlight value response from Meilisearch.
113+ * @returns The highlight metadata.
114+ */
105115function calculateHighlightMetadata (
106- value : string ,
116+ query : string ,
107117 preTag : string ,
108- postTag : string
118+ postTag : string ,
119+ highlightValue : string
109120) : HighlightMetadata {
110121 // Extract all highlighted segments
111122 const highlightRegex = new RegExp ( `${ preTag } (.*?)${ postTag } ` , 'g' )
112123 const matches : string [ ] = [ ]
113124 let match
114- while ( ( match = highlightRegex . exec ( value ) ) !== null ) {
125+ while ( ( match = highlightRegex . exec ( highlightValue ) ) !== null ) {
115126 matches . push ( match [ 1 ] )
116127 }
117128
118- // Remove highlight tags to get the original, unhighlighted text
119- const cleanValue = value . replace ( new RegExp ( `${ preTag } |${ postTag } ` , 'g' ) , '' )
129+ // Remove highlight tags to get the highlighted text without the tags
130+ const cleanValue = highlightValue . replace (
131+ new RegExp ( `${ preTag } |${ postTag } ` , 'g' ) ,
132+ ''
133+ )
120134
121135 // Determine if the entire attribute is highlighted
122136 // fullyHighlighted = true if cleanValue and the concatenation of all matched segments are identical
@@ -129,11 +143,11 @@ function calculateHighlightMetadata(
129143 // - 'full' if all text is fully highlighted
130144 let matchLevel : 'none' | 'partial' | 'full' = 'none'
131145 if ( matches . length > 0 ) {
132- matchLevel = fullyHighlighted ? 'full' : 'partial'
146+ matchLevel = cleanValue . includes ( query ) ? 'full' : 'partial'
133147 }
134148
135149 return {
136- value,
150+ value : highlightValue ,
137151 fullyHighlighted,
138152 matchLevel,
139153 matchedWords : matches ,
0 commit comments