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