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

assistantTextSelection.ts

274 lines10.1 KB

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