Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

htmlRenderSelectionScript.ts

350 lines12.9 KB

1// Served in the HTML response so document URLs and CSP remain independent of the client.
2export const HTML_RENDER_SELECTION_SCRIPT = String.raw`// Loaded as raw source into sandboxed HTML documents, including older saved renders.
3(() => {
4 const method = "t3/selection";
5 const excluded =
6 "button,input,textarea,select,[role=button],[contenteditable],[hidden],[aria-hidden=true],script,style,template,noscript,svg";
7 const normalize = (text) => text.replace(/\s+/g, " ");
8 let down = false;
9 let active = false;
10 let timer;
11 let pending = false;
12 let pointer = null;
13 let marked = null;
14 let commentQuote = null;
15 let commentTarget = null;
16 const post = (params) => window.parent.postMessage({ jsonrpc: "2.0", method, params }, "*");
17 const cancel = () => {
18 clearTimeout(timer);
19 pending = false;
20 active = false;
21 pointer = null;
22 post(null);
23 };
24 const stream = () => {
25 let text = "";
26 let separator = false;
27 const chunks = [];
28 const visit = (node) => {
29 if (node.nodeType === 3 && node.length) {
30 if (separator && text.length) text += "\n";
31 separator = false;
32 chunks.push({ node, start: text.length, end: text.length + node.length });
33 text += node.data;
34 } else if (node.nodeType === 1 && !node.matches(excluded)) {
35 const display = getComputedStyle(node).display;
36 if (display === "none") return;
37 const block =
38 (display && display !== "contents" && !display.startsWith("inline")) ||
39 node.tagName === "BR";
40 if (block) separator = true;
41 for (const child of node.childNodes) visit(child);
42 if (block) separator = true;
43 }
44 };
45 if (document.body) visit(document.body);
46 return { text, chunks };
47 };
48 const rect = (range, entire = false) => {
49 // Paragraph selection may include a trailing newline with an empty rect.
50 const rects = Array.from(range.getClientRects());
51 const r =
52 (!entire && rects.findLast((rect) => rect.width > 0 && rect.height > 0)) || range.getBoundingClientRect();
53 return { left: r.left, top: r.top, width: r.width, height: r.height };
54 };
55 const selector = (text, start, end) => {
56 const normalized = normalize(text);
57 let a = normalize(text.slice(0, start)).length;
58 if (start > 0 && /\s/.test(text[start - 1]) && /\s/.test(text[start])) a--;
59 const b = normalize(text.slice(0, end)).length;
60 let before = Math.max(0, a - 32);
61 let after = Math.min(normalized.length, b + 32);
62 const splitsPair = (offset) =>
63 /[\uD800-\uDBFF]/.test(normalized[offset - 1] || "") &&
64 /[\uDC00-\uDFFF]/.test(normalized[offset] || "");
65 if (splitsPair(before)) before++;
66 if (splitsPair(after)) after--;
67 return {
68 text: text.slice(start, end),
69 start: a,
70 end: b,
71 prefix: normalized.slice(before, a),
72 suffix: normalized.slice(b, after),
73 };
74 };
75 const capture = () => {
76 const selection = window.getSelection();
77 if (!selection || selection.isCollapsed || selection.rangeCount !== 1) return null;
78 const range = selection.getRangeAt(0).cloneRange();
79 const boundary = (node, last) => {
80 if (!range.intersectsNode(node)) return null;
81 if (node.nodeType === 3) {
82 const start = node === range.startContainer ? range.startOffset : 0;
83 const end = node === range.endContainer ? range.endOffset : node.length;
84 return start < end ? node : null;
85 }
86 for (
87 let child = last ? node.lastChild : node.firstChild;
88 child;
89 child = last ? child.previousSibling : child.nextSibling
90 ) {
91 const found = boundary(child, last);
92 if (found) return found;
93 }
94 return null;
95 };
96 const first = boundary(range.commonAncestorContainer, false);
97 const last = boundary(range.commonAncestorContainer, true);
98 if (!first || !last) return null;
99 range.setStart(first, first === range.startContainer ? range.startOffset : 0);
100 range.setEnd(last, last === range.endContainer ? range.endOffset : last.length);
101 const ancestor = (node) => (node.nodeType === 1 ? node : node.parentElement)?.closest(excluded);
102 if (ancestor(range.startContainer) || ancestor(range.endContainer)) return null;
103 const { text, chunks } = stream();
104 let start = null;
105 let end = 0;
106 for (const chunk of chunks) {
107 if (!range.intersectsNode(chunk.node)) continue;
108 const a = range.startContainer === chunk.node ? range.startOffset : 0;
109 const b = range.endContainer === chunk.node ? range.endOffset : chunk.node.length;
110 if (a === b) continue;
111 start ??= chunk.start + a;
112 end = chunk.start + b;
113 }
114 if (start === null || !text.slice(start, end).trim()) return null;
115 // Keep oversized quotes local; the parent can display its normal shorten action.
116 if (end - start > 8000) return { tooLong: true, rect: rect(range, true), pointer };
117 return { selector: selector(text, start, end), rect: rect(range, true), pointer };
118 };
119 const schedule = (delay = 0) => {
120 clearTimeout(timer);
121 pending = true;
122 timer = setTimeout(() => {
123 pending = false;
124 if (active && !down) post(capture());
125 }, delay);
126 };
127 document.addEventListener(
128 "pointerdown",
129 (event) => {
130 if (!event.isPrimary) return;
131 cancel();
132 down = event.button === 0;
133 active =
134 down &&
135 !event.target.closest?.("button,[role=button],input,textarea,select,[contenteditable]");
136 },
137 true,
138 );
139 window.addEventListener("pointerup", (event) => {
140 if (event.isPrimary) down = false;
141 });
142 window.addEventListener("pointercancel", () => {
143 down = false;
144 cancel();
145 });
146 window.addEventListener("mouseup", (event) => {
147 down = false;
148 if (!active || event.button !== 0) return;
149 pointer = { x: event.clientX, y: event.clientY };
150 schedule(event.detail >= 2 ? 500 : 0);
151 });
152 document.addEventListener("selectionchange", () => {
153 if (active && !down && !pending) schedule();
154 });
155 document.addEventListener("keydown", (event) => {
156 if (event.key === "Escape") cancel();
157 else if (
158 event.key === "Tab" &&
159 !event.shiftKey &&
160 !event.altKey &&
161 !event.ctrlKey &&
162 !event.metaKey &&
163 active &&
164 capture()?.selector
165 ) {
166 event.preventDefault();
167 post({ focus: true });
168 } else if (
169 (event.shiftKey && event.key.startsWith("Arrow")) ||
170 ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "a")
171 ) {
172 active = true;
173 pointer = null;
174 schedule();
175 }
176 });
177 document.addEventListener("contextmenu", cancel);
178 document.addEventListener(
179 "scroll",
180 () => {
181 if (!down) cancel();
182 },
183 true,
184 );
185 window.addEventListener("resize", cancel);
186 const clearMark = () => {
187 if (window.CSS?.highlights) CSS.highlights.delete("t3-html-citation");
188 marked = null;
189 };
190 const markQuote = (quote, action, changesOnly = false) => {
191 const ownsMark = action === "mark" || !commentQuote;
192 if (ownsMark) clearMark();
193 const reply = (target) => {
194 if (changesOnly && (
195 target === commentTarget ||
196 target && commentTarget && ["left", "top", "width", "height"].every(
197 (key) => target[key] === commentTarget[key],
198 )
199 )) return;
200 if (action === "mark") commentTarget = target;
201 post({ target, selector: quote, action });
202 };
203 if (
204 !quote ||
205 typeof quote.text !== "string" ||
206 !quote.text.trim() ||
207 quote.text.length > 8000 ||
208 typeof quote.prefix !== "string" ||
209 typeof quote.suffix !== "string"
210 ) {
211 reply(null);
212 return;
213 }
214 const { text, chunks } = stream();
215 const normalized = normalize(text);
216 const needle = normalize(quote.text);
217 const matches = [];
218 for (let at = normalized.indexOf(needle); at >= 0; at = normalized.indexOf(needle, at + 1))
219 matches.push(at);
220 const contextual = matches.filter(
221 (at) =>
222 normalized.slice(Math.max(0, at - quote.prefix.length), at) === quote.prefix &&
223 normalized.slice(at + needle.length, at + needle.length + quote.suffix.length) ===
224 quote.suffix,
225 );
226 const at =
227 contextual.length === 1
228 ? contextual[0]
229 : contextual.length === 0 && matches.length === 1
230 ? matches[0]
231 : undefined;
232 if (at === undefined) {
233 reply(null);
234 return;
235 }
236 const rawOffset = (offset) => {
237 let count = 0;
238 for (const match of text.matchAll(/\s+|\S+/g)) {
239 const whitespace = /\s/.test(match[0][0]);
240 const length = whitespace ? 1 : match[0].length;
241 if (offset <= count + length)
242 return match.index + (whitespace && offset > count ? match[0].length : offset - count);
243 count += length;
244 }
245 return text.length;
246 };
247 const start = rawOffset(at);
248 const end = rawOffset(at + needle.length);
249 const first = chunks.find((chunk) => chunk.end > start);
250 const last = chunks.findLast((chunk) => chunk.start < end);
251 if (!first || !last) {
252 reply(null);
253 return;
254 }
255 marked = document.createRange();
256 marked.setStart(first.node, Math.max(0, start - first.start));
257 marked.setEnd(last.node, Math.min(last.node.length, end - last.start));
258 if (action === "target") {
259 // Reveal the quoted range, even when its containing element is much taller.
260 for (let element = last.node.parentElement; element; element = element.parentElement) {
261 if (element === document.scrollingElement) continue;
262 const style = getComputedStyle(element);
263 const box = element.getBoundingClientRect();
264 const bounds = rect(marked);
265 const top = box.top + element.clientTop;
266 const left = box.left + element.clientLeft;
267 let dy = 0;
268 let dx = 0;
269 if (
270 /^(auto|scroll|hidden)$/.test(style.overflowY) &&
271 element.scrollHeight > element.clientHeight
272 )
273 dy =
274 bounds.top < top
275 ? bounds.top - top
276 : Math.max(0, bounds.top + bounds.height - top - element.clientHeight);
277 if (
278 /^(auto|scroll|hidden)$/.test(style.overflowX) &&
279 element.scrollWidth > element.clientWidth
280 )
281 dx =
282 bounds.left < left
283 ? bounds.left - left
284 : Math.max(0, bounds.left + bounds.width - left - element.clientWidth);
285 if (dx || dy) element.scrollBy({ left: dx, top: dy, behavior: "instant" });
286 }
287 const bounds = marked.getBoundingClientRect();
288 const marginX = Math.min(80, window.innerWidth / 3);
289 const dx = bounds.left < 0
290 ? bounds.left - marginX
291 : bounds.right > window.innerWidth
292 ? bounds.right - window.innerWidth + marginX
293 : 0;
294 const dy = bounds.top < 0 || bounds.bottom > window.innerHeight
295 ? bounds.top - Math.min(80, window.innerHeight / 3)
296 : 0;
297 // Page CSS can request smooth scrolling; return geometry only after positioning.
298 if (dx || dy) window.scrollBy({ left: dx, top: dy, behavior: "instant" });
299 }
300 if (ownsMark && window.CSS?.highlights && window.Highlight)
301 CSS.highlights.set("t3-html-citation", new Highlight(marked));
302 reply(rect(marked));
303 };
304 // Only an open comment needs ongoing quote validation; coalesce page changes.
305 let validation;
306 const validateComment = () => {
307 if (!commentQuote || validation) return;
308 validation = requestAnimationFrame(() => {
309 validation = null;
310 if (commentQuote) markQuote(commentQuote, "mark", true);
311 });
312 };
313 const commentObserver = new MutationObserver(validateComment);
314 const commentResize = window.ResizeObserver ? new ResizeObserver(validateComment) : null;
315 window.addEventListener("resize", validateComment);
316 document.addEventListener("scroll", validateComment, true);
317 window.addEventListener("message", (event) => {
318 if (event.source !== window.parent || event.data?.method !== "t3/selection-command") return;
319 const { action, selector: quote } = event.data.params || {};
320 if (action === "clear") {
321 cancel();
322 window.getSelection()?.removeAllRanges();
323 }
324 if (action === "dismiss") cancel();
325 if (action === "untarget" && !commentQuote) clearMark();
326 if (action === "target") {
327 markQuote(quote, action);
328 return;
329 }
330 if (action === "unmark") {
331 commentQuote = null;
332 commentTarget = null;
333 commentObserver.disconnect();
334 commentResize?.disconnect();
335 clearMark();
336 }
337 if (action !== "mark" && action !== "target") return;
338 commentQuote = action === "mark" ? quote : null;
339 if (commentQuote) {
340 // Any attribute can affect page CSS; validation replies only when the target changes.
341 commentObserver.observe(document.documentElement, { subtree: true, childList: true, characterData: true, attributes: true });
342 commentResize?.observe(document.documentElement);
343 } else {
344 commentObserver.disconnect();
345 commentResize?.disconnect();
346 }
347 markQuote(quote, action);
348 });
349})();
350`;