Repository navigation
Expand file tree
/
Copy pathassistantTextSelection.ts
More file actions
229 lines (205 loc) · 8.88 KB
/
Copy pathassistantTextSelection.ts
File metadata and controls
229 lines (205 loc) · 8.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import { type AssistantCitation } from "@t3tools/contracts";
import { mathWrapperOf } from "../markdown-clipboard";
export {
createAssistantTextSelector,
findAssistantCitationText,
} from "@t3tools/shared/assistantCitations";
import {
createAssistantTextSelector,
findAssistantCitationText,
splitsSurrogatePair,
type AssistantTextSelector,
} from "@t3tools/shared/assistantCitations";
export type { AssistantTextSelector } from "@t3tools/shared/assistantCitations";
export type AssistantCitationSourceAnchor = {
source: HTMLElement;
range: Range;
viewport: HTMLElement;
};
export function findAssistantCitationSourceAnchor(
document: Document,
citation: AssistantCitation,
): AssistantCitationSourceAnchor | null {
const source = [
...document.querySelectorAll<HTMLElement>("[data-assistant-citation-source]"),
].find(
(element) =>
element.dataset.assistantCitationSource === citation.messageId &&
element.dataset.assistantCitationEnvironment === citation.environmentId &&
element.dataset.assistantCitationThread === citation.threadId,
);
const viewport = source?.closest<HTMLElement>("[data-assistant-citation-viewport]");
if (!source || !viewport) return null;
const range = resolveAssistantCitationRange(source, citation);
return range ? { source, range, viewport } : null;
}
const CONTROL_SELECTOR = "button, input, textarea, select, [role=button], [contenteditable]";
const EXCLUDED_SELECTOR = `${CONTROL_SELECTOR}, [hidden], [aria-hidden=true], script, style, template, noscript, svg`;
const BLOCK_SELECTOR =
"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";
/** A text node, or a whole rendered formula standing for its TeX. */
type TextChunk = { node: Text | Element; start: number; end: number };
const isText = (node: Node): node is Text => node.nodeType === 3;
function readAssistantText(root: HTMLElement) {
const parts: string[] = [];
const chunks: TextChunk[] = [];
let length = 0;
let separator = false;
const append = (node: Text | Element, text: string) => {
if (separator && length > 0) {
parts.push("\n");
length += 1;
}
separator = false;
chunks.push({ node, start: length, end: length + text.length });
parts.push(text);
length += text.length;
};
const visit = (node: Node) => {
if (node.nodeType === 3) {
const text = node as Text;
if (text.length > 0) append(text, text.data);
return;
}
if (node.nodeType !== 1) return;
const element = node as Element;
if (element.matches(EXCLUDED_SELECTOR)) return;
const block = element.matches(BLOCK_SELECTOR);
if (block || element.tagName === "BR") separator = true;
if (element.matches("[data-markdown-math]")) {
append(element, element.getAttribute("data-markdown-copy")?.trim() ?? "");
} else {
for (const child of element.childNodes) visit(child);
}
if (block) separator = true;
};
visit(root);
return { text: parts.join(""), chunks };
}
function excludedAncestor(node: Node): Element | null {
const element = node.nodeType === 1 ? (node as Element) : node.parentElement;
return element?.closest(EXCLUDED_SELECTOR) ?? null;
}
function isUsableRange(root: HTMLElement, range: Range): boolean {
if (
range.collapsed ||
!root.contains(range.startContainer) ||
!root.contains(range.endContainer) ||
excludedAncestor(range.startContainer) !== null ||
excludedAncestor(range.endContainer) !== null
) {
return false;
}
return true;
}
function isUnselectable(text: Text): boolean {
const element = mathWrapperOf(text.parentElement) ?? text.parentElement;
const view = element?.ownerDocument?.defaultView;
return !!element && !!view && view.getComputedStyle(element).userSelect === "none";
}
function selectedTextBoundary(range: Range, node: Node, last: boolean): Text | null {
if (!range.intersectsNode(node)) return null;
if (node.nodeType === 3) {
const text = node as Text;
const start = node === range.startContainer ? range.startOffset : 0;
const end = node === range.endContainer ? range.endOffset : text.length;
// Triple-click ranges include unselected text from unselectable rows and the next response.
return start < end && !isUnselectable(text) ? text : null;
}
for (
let child = last ? node.lastChild : node.firstChild;
child !== null;
child = last ? child.previousSibling : child.nextSibling
) {
const boundary = selectedTextBoundary(range, child, last);
if (boundary !== null) return boundary;
}
return null;
}
export function captureAssistantTextSelection(
viewport: HTMLElement,
selection: Selection | null,
): { source: HTMLElement; selector: AssistantTextSelector; range: Range } | null {
if (selection === null || selection.isCollapsed || selection.rangeCount !== 1) return null;
const range = selection.getRangeAt(0).cloneRange();
const first = selectedTextBoundary(range, range.commonAncestorContainer, false);
const last = selectedTextBoundary(range, range.commonAncestorContainer, true);
if (first === null || last === null) return null;
const source = first.parentElement?.closest<HTMLElement>("[data-assistant-citation-source]");
if (!source || !viewport.contains(source)) return null;
// Paragraph selection can end at the next block's offset 0 or a parent
// boundary. Validate the text actually selected, not that empty endpoint.
// An endpoint inside a formula's glyphs takes in the whole formula.
const startFormula = mathWrapperOf(first.parentElement);
const endFormula = mathWrapperOf(last.parentElement);
if (startFormula) range.setStartBefore(startFormula);
else range.setStart(first, first === range.startContainer ? range.startOffset : 0);
if (endFormula) range.setEndAfter(endFormula);
else range.setEnd(last, last === range.endContainer ? range.endOffset : last.length);
if (!isUsableRange(source, range)) return null;
const stream = readAssistantText(source);
let rawStart: number | null = null;
let rawEnd = 0;
for (const chunk of stream.chunks) {
if (!range.intersectsNode(chunk.node)) continue;
const start = range.startContainer === chunk.node ? range.startOffset : 0;
const end = range.endContainer === chunk.node ? range.endOffset : chunk.end - chunk.start;
if (start === end) continue;
rawStart ??= chunk.start + start;
rawEnd = chunk.start + end;
}
if (rawStart === null) return null;
const selector = createAssistantTextSelector(stream.text, rawStart, rawEnd);
return selector === null ? null : { source, selector, range };
}
/** How much of a response a reply carries: enough to recognise it, not to resend it. */
const RESPONSE_OPENING_LENGTH = 300;
/** The opening of a response. Falls back to the raw text when the source is virtualized away or
* renders no text, as in an image-only response. */
export function captureAssistantMessageOpening(
source: HTMLElement | null,
fallbackText: string,
): AssistantTextSelector | null {
const rendered = source ? readAssistantText(source).text : "";
const text = rendered.trim() ? rendered : fallbackText;
const rawStart = text.length - text.trimStart().length;
let rawEnd = Math.min(text.trimEnd().length, rawStart + RESPONSE_OPENING_LENGTH);
if (splitsSurrogatePair(text, rawEnd)) rawEnd -= 1;
return createAssistantTextSelector(text, rawStart, rawEnd);
}
function rawTextOffset(text: string, normalizedOffset: number): number {
let offset = 0;
for (const match of text.matchAll(/\s+|\S+/g)) {
const whitespace = /\s/.test(match[0][0]!);
const length = whitespace ? 1 : match[0].length;
if (normalizedOffset <= offset + length) {
return (
match.index +
(whitespace && normalizedOffset > offset ? match[0].length : normalizedOffset - offset)
);
}
offset += length;
}
return text.length;
}
export function resolveAssistantCitationRange(
root: HTMLElement,
selector: AssistantTextSelector,
): Range | null {
if (excludedAncestor(root) !== null) return null;
const stream = readAssistantText(root);
const match = findAssistantCitationText(stream.text, selector);
if (match === null) return null;
const start = rawTextOffset(stream.text, match.start);
const end = rawTextOffset(stream.text, match.end);
const first = stream.chunks.find((chunk) => chunk.end > start);
const last = stream.chunks.findLast((chunk) => chunk.start < end);
if (first === undefined || last === undefined) return null;
const range = root.ownerDocument.createRange();
// A match that touches a formula covers the formula as rendered.
if (isText(first.node)) range.setStart(first.node, Math.max(0, start - first.start));
else range.setStartBefore(first.node);
if (isText(last.node)) range.setEnd(last.node, Math.min(last.node.length, end - last.start));
else range.setEndAfter(last.node);
return isUsableRange(root, range) ? range : null;
}