export const SEARCH_HIGHLIGHT = "line-search"; export const CURRENT_HIGHLIGHT = "line-search-current"; export const textRange = (root: Node, start: number, end: number): Range | null => { const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); const range = document.createRange(); let offset = 0; let started = false; for (let node = walker.nextNode(); node; node = walker.nextNode()) { const length = (node as Text).length; if (!started && start < offset + length) { range.setStart(node, start - offset); started = true; } if (started && end <= offset + length) { range.setEnd(node, end - offset); return range; } offset += length; } return null; }; const supported = (): boolean => typeof CSS !== "undefined" && "highlights" in CSS; export const paintHighlights = (all: Range[], current: Range | null): void => { if (!supported()) return; CSS.highlights.set(SEARCH_HIGHLIGHT, new Highlight(...all)); if (!current) { CSS.highlights.delete(CURRENT_HIGHLIGHT); return; } const highlight = new Highlight(current); highlight.priority = 1; CSS.highlights.set(CURRENT_HIGHLIGHT, highlight); }; export const clearHighlights = (): void => { if (!supported()) return; CSS.highlights.delete(SEARCH_HIGHLIGHT); CSS.highlights.delete(CURRENT_HIGHLIGHT); };