* Marks literal, case-insensitive matches in a label or primitive value. * @param props - The text, normalized search term, and shared highlight instance. * @returns Text with matching substrings marked.
(props: {
text: string
term?: string
highlight?: SearchHighlight
})
| 364 | * @returns Text with matching substrings marked. |
| 365 | */ |
| 366 | function HighlightedText(props: { |
| 367 | text: string |
| 368 | term?: string |
| 369 | highlight?: SearchHighlight |
| 370 | }) { |
| 371 | const matches = createMemo(() => { |
| 372 | const term = props.term |
| 373 | if (!term) return [] |
| 374 | const lower = props.text.toLowerCase() |
| 375 | let originalStart = 0 |
| 376 | let originalEnd = 0 |
| 377 | let lowercaseEnd = 0 |
| 378 | const originalPosition = (index: number) => { |
| 379 | while (lowercaseEnd <= index) { |
| 380 | const character = String.fromCodePoint( |
| 381 | props.text.codePointAt(originalEnd)!, |
| 382 | ) |
| 383 | originalStart = originalEnd |
| 384 | originalEnd += character.length |
| 385 | lowercaseEnd += character.toLowerCase().length |
| 386 | } |
| 387 | return { start: originalStart, end: originalEnd } |
| 388 | } |
| 389 | const ranges: Array<{ start: number; end: number }> = [] |
| 390 | let index = lower.indexOf(term) |
| 391 | while (index !== -1 && ranges.length < MAX_HIGHLIGHT_RANGES) { |
| 392 | const from = originalPosition(index).start |
| 393 | const to = originalPosition(index + term.length - 1).end |
| 394 | ranges.push({ start: from, end: to }) |
| 395 | index = lower.indexOf(term, index + term.length) |
| 396 | } |
| 397 | return ranges |
| 398 | }) |
| 399 | const text = document.createTextNode('') |
| 400 | createEffect(() => { |
| 401 | text.data = props.text |
| 402 | const highlight = props.highlight |
| 403 | if (!highlight) return |
| 404 | const ranges: Array<Range> = [] |
| 405 | for (const match of matches()) { |
| 406 | if (highlight.size >= MAX_HIGHLIGHT_RANGES) break |
| 407 | const range = text.ownerDocument.createRange() |
| 408 | range.setStart(text, match.start) |
| 409 | range.setEnd(text, match.end) |
| 410 | highlight.add(range) |
| 411 | ranges.push(range) |
| 412 | } |
| 413 | onCleanup(() => { |
| 414 | for (const range of ranges) highlight.delete(range) |
| 415 | }) |
| 416 | }) |
| 417 | return text |
| 418 | } |
| 419 | |
| 420 | /** |
| 421 | * Checks whether a value is iterable. |
nothing calls this directly
no test coverage detected