Line data Source code
1 : interface HighlightQueryPart {
2 : text: string
3 : highlighted: boolean
4 : }
5 :
6 2355 : const MAX_QUERY_LENGTH = 1024
7 :
8 17647 : export function highlightQuery(
9 : text: string,
10 : query: string
11 : ): HighlightQueryPart[] {
12 17647 : if (!query || query.length > text.length || query.length > MAX_QUERY_LENGTH) {
13 13377 : return [{ text, highlighted: false }]
14 : }
15 :
16 4270 : const pattern = Array.from(query)
17 : .map((ch) => ch.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
18 : .join('[ ]?')
19 :
20 4270 : const regex = new RegExp(pattern, 'gi')
21 4270 : const parts: HighlightQueryPart[] = []
22 4270 : let lastIndex = 0
23 :
24 11458 : for (const match of text.matchAll(regex)) {
25 718 : if (match.index > lastIndex) {
26 203 : parts.push({
27 : text: text.slice(lastIndex, match.index),
28 : highlighted: false
29 : })
30 : }
31 718 : parts.push({ text: match[0], highlighted: true })
32 718 : lastIndex = match.index + match[0].length
33 : }
34 :
35 17647 : if (lastIndex < text.length || parts.length === 0) {
36 4143 : parts.push({ text: text.slice(lastIndex), highlighted: false })
37 : }
38 :
39 4270 : return parts
40 : }
|