-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata-highlight.js
More file actions
191 lines (155 loc) · 4.94 KB
/
data-highlight.js
File metadata and controls
191 lines (155 loc) · 4.94 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import { attribute, effect } from "datastar";
const registry = CSS.highlights;
const findMatchingRange = (highlight, range) =>
Array.from(highlight?.values() || []).find(
(r) =>
r.startContainer === range.startContainer &&
r.endContainer === range.endContainer &&
r.compareBoundaryPoints(Range.START_TO_START, range) === 0 &&
r.compareBoundaryPoints(Range.END_TO_END, range) === 0,
);
const getRange = (el, start, end) => {
let range = new Range();
let i = 0;
for (const node of el.childNodes) {
if (start >= i && start <= i + node.length) {
range.setStart(node, start - i);
}
if (end <= i + node.length) {
range.setEnd(node, end - i);
return range;
}
i += node.length;
}
return undefined;
};
attribute({
name: "highlight",
requirement: "exclusive",
apply: ({ el, key, error, value, mods }) => {
let cachedHighlights = new Map();
const language = key ?? value;
if (!language) {
throw error("MissingLanguageKey");
}
const applyHighlights = (mutationRecords) => {
if (!mutationRecords && cachedHighlights.size > 0) {
// No mutations, no need to re-apply highlights
return;
}
if (
!el.childNodes.length ||
!Array.from(el.childNodes).every((n) => n.nodeType === Node.TEXT_NODE)
) {
error("ExpectedTextNodesOnly");
return;
}
import(`data-highlight:${language}`)
.then(({ default: getTokens }) => {
const highlights = new Map();
const tokens = getTokens(el.textContent, language);
if (mods.has("debug")) {
console.log({ input: el.textContent, language, tokens });
}
tokens.forEach(({ type, start, end }) => {
const range = getRange(el, start, end);
if (!range) return;
// Add to existing highlight, or create new highlight
highlights.get(type)?.add(range) ??
highlights.set(type, new Highlight(range));
// Remove range from cache (if it exists), so we know not to delete it later
const r = findMatchingRange(cachedHighlights.get(type), range);
r && cachedHighlights.get(type)?.delete(r);
// Paint by adding range to the global registry
const global = registry.get(type);
if (global) {
!findMatchingRange(global, range) && global.add(range);
} else {
registry.set(type, new Highlight(range));
}
});
cachedHighlights.entries().forEach(([type, highlight]) => {
// Any remaining cached highlights are no longer relevant
// for the current text node, so we delete them.
highlight.forEach((range) => registry.get(type)?.delete(range));
// Ranges become orphaned when textNodes are replaced, and are
// assigned to their parent node. We should also delete these.
registry
.get(type)
?.forEach(
(range) =>
(range.collapsed || range.startContainer === el) &&
registry.get(type).delete(range),
);
});
cachedHighlights = highlights;
})
.catch(console.error);
};
applyHighlights();
const observer = new MutationObserver(applyHighlights);
observer.observe(el, {
childList: true,
subtree: true,
characterData: true,
});
return () => {
observer.disconnect();
// Tidy up global CSS.highlights; remove this element's types/ranges
for (const [type, cache] of cachedHighlights) {
if (registry.has(type)) {
cache.forEach((range) => registry.get(type)?.delete(range));
registry.get(type)?.size === 0 && registry.delete(type);
}
}
};
},
});
attribute({
name: "highlight-text",
requirement: {
key: "denied",
value: "must",
},
returnsValue: true,
apply({ el, rx }) {
const update = () => {
observer.disconnect();
const nodes = el.childNodes;
const lines = `${rx()}`.split("\n").map((line) => line + "\n");
let i = 0;
while (i < nodes.length) {
const node = nodes[i];
const line = lines[i];
if (node.data === line) {
i++;
continue;
}
if (!line) {
node.remove();
continue;
}
let index = 0;
while (node.data[index] === line[index]) {
index++;
}
node.replaceData(
index,
node.length,
index > 0 ? line.slice(index) : line,
);
i++;
}
el.append(...lines.slice(nodes.length));
observer.observe(el, {
attributeFilter: ["data-highlight-text"],
});
};
const observer = new MutationObserver(update);
const cleanup = effect(update);
return () => {
observer.disconnect();
cleanup();
};
},
});