~james/core

core/web/src/lib/components/lines/highlight.ts -rw-r--r-- 1.3 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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);
};