* 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?: Highlight
})
| 396 | * @returns Text with matching substrings marked. |
| 397 | */ |
| 398 | function HighlightedText(props: { |
| 399 | text: string |
| 400 | term?: string |
| 401 | highlight?: Highlight |
| 402 | }) { |
| 403 | const matches = createMemo(() => { |
| 404 | const term = props.term |
| 405 | if (!term) return [] |
| 406 | const lower = props.text.toLowerCase() |
| 407 | let originalStart = 0 |
| 408 | let originalEnd = 0 |
| 409 | let lowercaseEnd = 0 |
| 410 | const originalPosition = (index: number) => { |
| 411 | while (lowercaseEnd <= index) { |
| 412 | const character = String.fromCodePoint( |
| 413 | props.text.codePointAt(originalEnd)!, |
| 414 | ) |
| 415 | originalStart = originalEnd |
| 416 | originalEnd += character.length |
| 417 | lowercaseEnd += character.toLowerCase().length |
| 418 | } |
| 419 | return { start: originalStart, end: originalEnd } |
| 420 | } |
| 421 | const ranges: Array<{ start: number; end: number }> = [] |
| 422 | let index = lower.indexOf(term) |
| 423 | while (index !== -1 && ranges.length < MAX_HIGHLIGHT_RANGES) { |
| 424 | const from = originalPosition(index).start |
| 425 | const to = originalPosition(index + term.length - 1).end |
| 426 | ranges.push({ start: from, end: to }) |
| 427 | index = lower.indexOf(term, index + term.length) |
| 428 | } |
| 429 | return ranges |
| 430 | }) |
| 431 | const text = document.createTextNode('') |
| 432 | createEffect(() => { |
| 433 | text.data = props.text |
| 434 | const highlight = props.highlight |
| 435 | if (!highlight) return |
| 436 | const ranges: Array<Range> = [] |
| 437 | for (const match of matches()) { |
| 438 | if (highlight.size >= MAX_HIGHLIGHT_RANGES) break |
| 439 | const range = text.ownerDocument.createRange() |
| 440 | range.setStart(text, match.start) |
| 441 | range.setEnd(text, match.end) |
| 442 | highlight.add(range) |
| 443 | ranges.push(range) |
| 444 | } |
| 445 | onCleanup(() => { |
| 446 | for (const range of ranges) highlight.delete(range) |
| 447 | }) |
| 448 | }) |
| 449 | return text |
| 450 | } |
| 451 | |
| 452 | /** |
| 453 | * Checks whether a value is iterable. |
nothing calls this directly
no test coverage detected