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