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

assistantTextSelection.ts

294 lines11.0 KB

1import { ASSISTANT_CITATION_CONTEXT_LENGTH, type AssistantCitation } from "@t3tools/contracts";
2​
3import { mathWrapperOf } from "../markdown-clipboard";
4​
5export type AssistantTextSelector = {
6 readonly text: string;
7 readonly start: number;
8 readonly end: number;
9 readonly prefix: string;
10 readonly suffix: string;
11};
12​
13export type AssistantCitationSourceAnchor = {
14 source: HTMLElement;
15 range: Range;
16 viewport: HTMLElement;
17};
18​
19export function findAssistantCitationSourceAnchor(
20 document: Document,
21 citation: AssistantCitation,
22): AssistantCitationSourceAnchor | null {
23 const source = [
24 ...document.querySelectorAll<HTMLElement>("[data-assistant-citation-source]"),
25 ].find(
26 (element) =>
27 element.dataset.assistantCitationSource === citation.messageId &&
28 element.dataset.assistantCitationEnvironment === citation.environmentId &&
29 element.dataset.assistantCitationThread === citation.threadId,
30 );
31 const viewport = source?.closest<HTMLElement>("[data-assistant-citation-viewport]");
32 if (!source || !viewport) return null;
33 const range = resolveAssistantCitationRange(source, citation);
34 return range ? { source, range, viewport } : null;
36​
37const CONTROL_SELECTOR = "button, input, textarea, select, [role=button], [contenteditable]";
38const EXCLUDED_SELECTOR = `${CONTROL_SELECTOR}, [hidden], [aria-hidden=true], script, style, template, noscript, svg`;
39const BLOCK_SELECTOR =
40 "address, article, aside, blockquote, dd, div, dl, dt, figcaption, figure, footer, h1, h2, h3, h4, h5, h6, header, hr, li, main, nav, ol, p, pre, section, table, td, th, tr, ul";
41​
42function normalizeWhitespace(text: string): string {
43 return text.replace(/\s+/g, " ");
45​
46function splitsSurrogatePair(text: string, offset: number): boolean {
47 const before = text.charCodeAt(offset - 1);
48 const after = text.charCodeAt(offset);
49 return before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff;
51​
52export function createAssistantTextSelector(
53 text: string,
54 rawStart: number,
55 rawEnd: number,
56): AssistantTextSelector | null {
57 const quote = text.slice(rawStart, rawEnd);
58 if (quote.trim().length === 0) return null;
59​
60 const normalized = normalizeWhitespace(text);
61 let start = normalizeWhitespace(text.slice(0, rawStart)).length;
62 if (rawStart > 0 && /\s/.test(text[rawStart - 1]!) && /\s/.test(text[rawStart]!)) {
63 start -= 1;
64 }
65 const end = normalizeWhitespace(text.slice(0, rawEnd)).length;
66 let prefixStart = Math.max(0, start - ASSISTANT_CITATION_CONTEXT_LENGTH);
67 let suffixEnd = Math.min(normalized.length, end + ASSISTANT_CITATION_CONTEXT_LENGTH);
68 // A split pair becomes a replacement character when the context enters a URL.
69 if (splitsSurrogatePair(normalized, prefixStart)) prefixStart += 1;
70 if (splitsSurrogatePair(normalized, suffixEnd)) suffixEnd -= 1;
71 return {
72 text: quote,
73 start,
74 end,
75 prefix: normalized.slice(prefixStart, start),
76 suffix: normalized.slice(end, suffixEnd),
77 };
79​
80/**
81 * All positions and context lengths use UTF-16 units in that normalized stream,
82 * not markdown offsets or Unicode code points. Even matching saved offsets cannot
83 * break a context tie, since those offsets may have drifted.
84 */
85export function findAssistantCitationText(
86 text: string,
87 selector: AssistantTextSelector,
88): { start: number; end: number } | null {
89 const normalized = normalizeWhitespace(text);
90 const quote = normalizeWhitespace(selector.text);
91 if (quote.trim().length === 0) return null;
92​
93 const prefix = normalizeWhitespace(selector.prefix);
94 const suffix = normalizeWhitespace(selector.suffix);
95 const matchesContext = (start: number, end: number) =>
96 normalized.slice(Math.max(0, start - prefix.length), start) === prefix &&
97 normalized.slice(end, end + suffix.length) === suffix;
98​
99 let match =
100 Number.isSafeInteger(selector.start) &&
101 Number.isSafeInteger(selector.end) &&
102 selector.start >= 0 &&
103 selector.end - selector.start === quote.length &&
104 normalized.slice(selector.start, selector.end) === quote &&
105 matchesContext(selector.start, selector.end)
106 ? { start: selector.start, end: selector.end }
107 : null;
108 let onlyQuote: { start: number; end: number } | null = null;
109 let quoteCount = 0;
110​
111 for (
112 let start = normalized.indexOf(quote);
113 start !== -1;
114 start = normalized.indexOf(quote, start + 1)
115 ) {
116 const end = start + quote.length;
117 quoteCount += 1;
118 onlyQuote = { start, end };
119 if (!matchesContext(start, end)) continue;
120 if (match !== null && match.start !== start) return null;
121 match = { start, end };
122 }
123​
124 return match ?? (quoteCount === 1 ? onlyQuote : null);
126​
127/** A text node, or a whole rendered formula standing for its TeX. */
128type TextChunk = { node: Text | Element; start: number; end: number };
129​
130const isText = (node: Node): node is Text => node.nodeType === 3;
131​
132function readAssistantText(root: HTMLElement) {
133 const parts: string[] = [];
134 const chunks: TextChunk[] = [];
135 let length = 0;
136 let separator = false;
137​
138 const append = (node: Text | Element, text: string) => {
139 if (separator && length > 0) {
140 parts.push("\n");
141 length += 1;
142 }
143 separator = false;
144 chunks.push({ node, start: length, end: length + text.length });
145 parts.push(text);
146 length += text.length;
147 };
148​
149 const visit = (node: Node) => {
150 if (node.nodeType === 3) {
151 const text = node as Text;
152 if (text.length > 0) append(text, text.data);
153 return;
154 }
155 if (node.nodeType !== 1) return;
156 const element = node as Element;
157 if (element.matches(EXCLUDED_SELECTOR)) return;
158 const block = element.matches(BLOCK_SELECTOR);
159 if (block || element.tagName === "BR") separator = true;
160 if (element.matches("[data-markdown-math]")) {
161 append(element, element.getAttribute("data-markdown-copy")?.trim() ?? "");
162 } else {
163 for (const child of element.childNodes) visit(child);
164 }
165 if (block) separator = true;
166 };
167​
168 visit(root);
169 return { text: parts.join(""), chunks };
171​
172function excludedAncestor(node: Node): Element | null {
173 const element = node.nodeType === 1 ? (node as Element) : node.parentElement;
174 return element?.closest(EXCLUDED_SELECTOR) ?? null;
176​
177function isUsableRange(root: HTMLElement, range: Range): boolean {
178 if (
179 range.collapsed ||
180 !root.contains(range.startContainer) ||
181 !root.contains(range.endContainer) ||
182 excludedAncestor(range.startContainer) !== null ||
183 excludedAncestor(range.endContainer) !== null
184 ) {
185 return false;
186 }
187 return true;
189​
190function isUnselectable(text: Text): boolean {
191 const element = mathWrapperOf(text.parentElement) ?? text.parentElement;
192 const view = element?.ownerDocument?.defaultView;
193 return !!element && !!view && view.getComputedStyle(element).userSelect === "none";
195​
196function selectedTextBoundary(range: Range, node: Node, last: boolean): Text | null {
197 if (!range.intersectsNode(node)) return null;
198 if (node.nodeType === 3) {
199 const text = node as Text;
200 const start = node === range.startContainer ? range.startOffset : 0;
201 const end = node === range.endContainer ? range.endOffset : text.length;
202 // Triple-click ranges run through unselectable rows (tool calls, timestamps,
203 // author headings) into the next response; that text is not selected.
204 return start < end && !isUnselectable(text) ? text : null;
205 }
206 for (
207 let child = last ? node.lastChild : node.firstChild;
208 child !== null;
209 child = last ? child.previousSibling : child.nextSibling
210 ) {
211 const boundary = selectedTextBoundary(range, child, last);
212 if (boundary !== null) return boundary;
213 }
214 return null;
216​
217export function captureAssistantTextSelection(
218 viewport: HTMLElement,
219 selection: Selection | null,
220): { source: HTMLElement; selector: AssistantTextSelector; range: Range } | null {
221 if (selection === null || selection.isCollapsed || selection.rangeCount !== 1) return null;
222 const range = selection.getRangeAt(0).cloneRange();
223 const first = selectedTextBoundary(range, range.commonAncestorContainer, false);
224 const last = selectedTextBoundary(range, range.commonAncestorContainer, true);
225 if (first === null || last === null) return null;
226 const source = first.parentElement?.closest<HTMLElement>("[data-assistant-citation-source]");
227 if (!source || !viewport.contains(source)) return null;
228​
229 // Paragraph selection can end at the next block's offset 0 or a parent
230 // boundary. Validate the text actually selected, not that empty endpoint.
231 // An endpoint inside a formula's glyphs takes in the whole formula.
232 const startFormula = mathWrapperOf(first.parentElement);
233 const endFormula = mathWrapperOf(last.parentElement);
234 if (startFormula) range.setStartBefore(startFormula);
235 else range.setStart(first, first === range.startContainer ? range.startOffset : 0);
236 if (endFormula) range.setEndAfter(endFormula);
237 else range.setEnd(last, last === range.endContainer ? range.endOffset : last.length);
238 if (!isUsableRange(source, range)) return null;
239​
240 const stream = readAssistantText(source);
241 let rawStart: number | null = null;
242 let rawEnd = 0;
243 for (const chunk of stream.chunks) {
244 if (!range.intersectsNode(chunk.node)) continue;
245 const start = range.startContainer === chunk.node ? range.startOffset : 0;
246 const end = range.endContainer === chunk.node ? range.endOffset : chunk.end - chunk.start;
247 if (start === end) continue;
248 rawStart ??= chunk.start + start;
249 rawEnd = chunk.start + end;
250 }
251 if (rawStart === null) return null;
252 const selector = createAssistantTextSelector(stream.text, rawStart, rawEnd);
253 return selector === null ? null : { source, selector, range };
255​
256function rawTextOffset(text: string, normalizedOffset: number): number {
257 let offset = 0;
258 for (const match of text.matchAll(/\s+|\S+/g)) {
259 const whitespace = /\s/.test(match[0][0]!);
260 const length = whitespace ? 1 : match[0].length;
261 if (normalizedOffset <= offset + length) {
262 return (
263 match.index +
264 (whitespace && normalizedOffset > offset ? match[0].length : normalizedOffset - offset)
265 );
266 }
267 offset += length;
268 }
269 return text.length;
271​
272export function resolveAssistantCitationRange(
273 root: HTMLElement,
274 selector: AssistantTextSelector,
275): Range | null {
276 if (excludedAncestor(root) !== null) return null;
277 const stream = readAssistantText(root);
278 const match = findAssistantCitationText(stream.text, selector);
279 if (match === null) return null;
280​
281 const start = rawTextOffset(stream.text, match.start);
282 const end = rawTextOffset(stream.text, match.end);
283 const first = stream.chunks.find((chunk) => chunk.end > start);
284 const last = stream.chunks.findLast((chunk) => chunk.start < end);
285 if (first === undefined || last === undefined) return null;
286​
287 const range = root.ownerDocument.createRange();
288 // A match that touches a formula covers the formula as rendered.
289 if (isText(first.node)) range.setStart(first.node, Math.max(0, start - first.start));
290 else range.setStartBefore(first.node);
291 if (isText(last.node)) range.setEnd(last.node, Math.min(last.node.length, end - last.start));
292 else range.setEndAfter(last.node);
293 return isUsableRange(root, range) ? range : null;