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

AssistantCitationSource.tsx

378 lines13.0 KB

1import type { LegendListRef } from "@legendapp/list/react";
2import type { AssistantCitation, MessageId, ScopedThreadRef } from "@t3tools/contracts";
3import { useEffect, useRef, type ReactNode, type RefObject } from "react";
4import {
5 resolveAssistantCitationRange,
6 type AssistantCitationSourceAnchor,
7} from "~/lib/assistantTextSelection";
8import { toastManager } from "../ui/toast";
9​
10const CITATION_PULSE_DURATION_MS = 650;
11// The second pulse settles into a held highlight so late glances still find the quote.
12const CITATION_HIGHLIGHT_HOLD_MS = 1575;
13const CITATION_HIGHLIGHT_FADE_MS = 450;
14const CITATION_HIGHLIGHT_TOTAL_MS =
15 1.5 * CITATION_PULSE_DURATION_MS + CITATION_HIGHLIGHT_HOLD_MS + CITATION_HIGHLIGHT_FADE_MS;
16const CITATION_HIGHLIGHT_OPACITY = "--assistant-citation-highlight-opacity";
17// Matches the comment-editing highlight strength in index.css.
18const CITATION_HIGHLIGHT_PEAK = 0.45;
19const COMMENT_HIGHLIGHT_NAME = "t3-assistant-citation-comment";
20​
21/** Keep source text marked while its comment editor is open, without changing native selection. */
22export function observeAssistantCitationCommentSource({
23 anchor,
24 citation,
25 onUnavailable,
26}: {
27 anchor: AssistantCitationSourceAnchor;
28 citation: AssistantCitation;
29 onUnavailable: () => void;
30}): () => void {
31 const { source, range, viewport } = anchor;
32 const registry = typeof CSS !== "undefined" ? CSS.highlights : undefined;
33 let highlight: Highlight | null = null;
34 let stopped = false;
35 const observer = new MutationObserver((records) => {
36 if (stopped) return;
37 const sourceChanged = records.some((record) => source.contains(record.target));
38 validate(sourceChanged);
39 });
40 const dispose = () => {
41 if (stopped) return;
42 stopped = true;
43 observer.disconnect();
44 if (!highlight) return;
45 highlight.delete(range);
46 if (highlight.size === 0 && registry?.get(COMMENT_HIGHLIGHT_NAME) === highlight) {
47 registry.delete(COMMENT_HIGHLIGHT_NAME);
48 }
49 };
50 const unavailable = () => {
51 if (stopped) return;
52 dispose();
53 onUnavailable();
54 };
55 const validate = (sourceChanged: boolean): boolean => {
56 if (!source.isConnected || !viewport.contains(source)) {
57 unavailable();
58 return false;
59 }
60 if (
61 sourceChanged ||
62 range.collapsed ||
63 !source.contains(range.startContainer) ||
64 !source.contains(range.endContainer)
65 ) {
66 const repaired = resolveAssistantCitationRange(source, citation);
67 if (!repaired) {
68 unavailable();
69 return false;
70 }
71 range.setStart(repaired.startContainer, repaired.startOffset);
72 range.setEnd(repaired.endContainer, repaired.endOffset);
73 }
74 return true;
75 };
76​
77 if (!validate(false)) return dispose;
78 if (typeof Highlight !== "undefined" && registry) {
79 const existing = registry.get(COMMENT_HIGHLIGHT_NAME);
80 highlight = existing ?? new Highlight();
81 highlight.add(range);
82 if (!existing) registry.set(COMMENT_HIGHLIGHT_NAME, highlight);
83 }
84 observer.observe(viewport, { childList: true, subtree: true, characterData: true });
85 return dispose;
87​
88export interface AssistantCitationRequest {
89 citation: AssistantCitation;
90 key: string;
92​
93/** Navigation owns the ref so virtual row remounts cannot replay an activation. */
94export interface AssistantCitationTarget extends AssistantCitationRequest {
95 activationRef: RefObject<{
96 scrolled: boolean;
97 dismissed: boolean;
98 cancelScroll?: () => void;
99 pulse?: { startedAt: number; reducedMotion: boolean };
100 }>;
101 onComplete: () => void;
103​
104/** Observe only the active source, including virtual containers moved above its root. */
105export function observeAssistantCitationSource({
106 root,
107 itemKey,
108 request,
109 list,
110}: {
111 root: HTMLElement;
112 itemKey: string;
113 request: AssistantCitationTarget;
114 list: LegendListRef;
115}) {
116 const activation = request.activationRef.current;
117 if (activation.dismissed) return;
118 const scrollNode = list.getScrollableNode();
119 if (!(scrollNode instanceof HTMLElement)) return;
120 const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
121 let highlighted: Highlight | null = null;
122 let ownedRange: Range | null = null;
123 let selected: { range: Range; snapshot: Range } | null = null;
124 let frame: number | null = null;
125 let scrolling = false;
126 let stopped = false;
127 let pulseAnimation: Animation | null = null;
128 let canReplaceSelection = !activation.scrolled;
129 const ownsSelection = (selection: Selection | null) =>
130 selected !== null &&
131 selection?.rangeCount === 1 &&
132 selection.getRangeAt(0) === selected.range &&
133 selected.range.startContainer === selected.snapshot.startContainer &&
134 selected.range.startOffset === selected.snapshot.startOffset &&
135 selected.range.endContainer === selected.snapshot.endContainer &&
136 selected.range.endOffset === selected.snapshot.endOffset;
137 const clear = () => {
138 if (highlighted && CSS.highlights.get("t3-assistant-citation") === highlighted) {
139 CSS.highlights.delete("t3-assistant-citation");
140 }
141 highlighted = null;
142 ownedRange = null;
143 const selection = selected ? root.ownerDocument.getSelection() : null;
144 if (selected && ownsSelection(selection)) selection?.removeRange(selected.range);
145 selected = null;
146 delete root.dataset.citationHighlighted;
147 };
148 const finishHighlight = () => {
149 if (stopped) return;
150 activation.dismissed = true;
151 dispose();
152 };
153 const highlight = () => {
154 frame = null;
155 if (stopped || activation.dismissed || !root.isConnected || !scrollNode.contains(root)) {
156 clear();
157 return;
158 }
159 if (
160 activation.pulse &&
161 performance.now() - activation.pulse.startedAt >= CITATION_HIGHLIGHT_TOTAL_MS
162 ) {
163 finishHighlight();
164 return;
165 }
166 const state = list.getState();
167 const index = state.indexByKey(itemKey);
168 // alwaysRender mounts this row before navigation. Estimates are not measurements.
169 if (index === undefined || !(state.sizeAtIndex(index) > 0)) return;
170 const range = resolveAssistantCitationRange(root, request.citation);
171 const rect = (range ?? root).getBoundingClientRect();
172 if (rect.height <= 0 || scrollNode.clientHeight <= 0) {
173 clear();
174 return;
175 }
176 if (!activation.scrolled) {
177 if (scrolling) return;
178 const scrollRect = scrollNode.getBoundingClientRect();
179 const offset = Math.max(
180 0,
181 Math.min(
182 scrollNode.scrollHeight - scrollNode.clientHeight,
183 state.scroll + rect.top - scrollRect.top - Math.min(120, scrollNode.clientHeight / 3),
184 ),
185 );
186 if (Math.abs(offset - state.scroll) > 1) {
187 scrolling = true;
188 void list.scrollToOffset({ offset, animated: !reducedMotion }).then(
189 () => {
190 scrolling = false;
191 if (!stopped && !activation.dismissed) schedule();
192 },
193 () => {
194 scrolling = false;
195 if (stopped || activation.dismissed) return;
196 activation.dismissed = true;
197 clear();
198 request.onComplete();
199 toastManager.add({
200 type: "warning",
201 title: "Could not open the cited response",
202 description: "Click the citation to try again.",
203 });
204 },
205 );
206 return;
207 }
208 // A prepend or row measurement can still change geometry during the scroll promise.
209 if (rect.bottom <= scrollRect.top || rect.top >= scrollRect.bottom) return;
210 activation.scrolled = true;
211 request.onComplete();
212 if (!range) {
213 toastManager.add({
214 type: "warning",
215 title: "The quoted text has changed",
216 description: "Showing the source response. The saved quote is unchanged.",
217 });
218 }
219 }
220 if (!range) {
221 finishHighlight();
222 return;
223 }
224 if (typeof Highlight !== "undefined" && typeof CSS !== "undefined" && CSS.highlights) {
225 highlighted = new Highlight(range);
226 CSS.highlights.set("t3-assistant-citation", highlighted);
227 ownedRange = range;
228 root.dataset.citationHighlighted = "true";
229 } else {
230 const selection = root.ownerDocument.getSelection();
231 // Only a fresh activation may replace a selection we do not own.
232 if (selection && (canReplaceSelection || ownsSelection(selection))) {
233 selection.removeAllRanges();
234 selection.addRange(range);
235 selected = { range: selection.getRangeAt(0), snapshot: range.cloneRange() };
236 canReplaceSelection = false;
237 ownedRange = range;
238 root.dataset.citationHighlighted = "true";
239 } else {
240 finishHighlight();
241 return;
242 }
243 }
244 if (!pulseAnimation) {
245 // Preserve the original deadline through virtual remounts and range repairs.
246 const pulse = (activation.pulse ??= {
247 startedAt: performance.now(),
248 reducedMotion,
249 });
250 const at = (milliseconds: number) => milliseconds / CITATION_HIGHLIGHT_TOTAL_MS;
251 const holdEnd = at(CITATION_HIGHLIGHT_TOTAL_MS - CITATION_HIGHLIGHT_FADE_MS);
252 pulseAnimation = root.animate(
253 pulse.reducedMotion
254 ? [
255 { offset: 0, [CITATION_HIGHLIGHT_OPACITY]: CITATION_HIGHLIGHT_PEAK },
256 { offset: holdEnd, [CITATION_HIGHLIGHT_OPACITY]: CITATION_HIGHLIGHT_PEAK },
257 { offset: 1, [CITATION_HIGHLIGHT_OPACITY]: 0 },
258 ]
259 : [
260 { offset: 0, [CITATION_HIGHLIGHT_OPACITY]: 0 },
261 {
262 offset: at(CITATION_PULSE_DURATION_MS * 0.5),
263 [CITATION_HIGHLIGHT_OPACITY]: CITATION_HIGHLIGHT_PEAK,
264 },
265 { offset: at(CITATION_PULSE_DURATION_MS), [CITATION_HIGHLIGHT_OPACITY]: 0 },
266 {
267 offset: at(CITATION_PULSE_DURATION_MS * 1.5),
268 [CITATION_HIGHLIGHT_OPACITY]: CITATION_HIGHLIGHT_PEAK,
269 },
270 { offset: holdEnd, [CITATION_HIGHLIGHT_OPACITY]: CITATION_HIGHLIGHT_PEAK },
271 { offset: 1, [CITATION_HIGHLIGHT_OPACITY]: 0 },
272 ],
273 { duration: CITATION_HIGHLIGHT_TOTAL_MS, easing: "ease-in-out" },
274 );
275 pulseAnimation.id = "t3-assistant-citation-pulse";
276 pulseAnimation.currentTime = Math.max(0, performance.now() - pulse.startedAt);
277 void pulseAnimation.finished.then(finishHighlight, () => {});
278 }
279 };
280 const schedule = () => {
281 if (frame !== null) cancelAnimationFrame(frame);
282 frame = requestAnimationFrame(highlight);
283 };
284 const observer = new MutationObserver((records) => {
285 const rangeMoved =
286 ownedRange !== null &&
287 (ownedRange.collapsed ||
288 !root.contains(ownedRange.startContainer) ||
289 !root.contains(ownedRange.endContainer));
290 if (rangeMoved) {
291 canReplaceSelection ||= selected !== null && ownsSelection(root.ownerDocument.getSelection());
292 clear();
293 }
294 if (
295 rangeMoved ||
296 records.some(
297 (record) =>
298 root.contains(record.target) ||
299 [...record.addedNodes, ...record.removedNodes].some((node) => node.contains(root)),
300 )
301 ) {
302 schedule();
303 }
304 });
305 observer.observe(scrollNode, { childList: true, characterData: true, subtree: true });
306 const resizeObserver = new ResizeObserver(schedule);
307 resizeObserver.observe(root);
308 resizeObserver.observe(scrollNode);
309 const state = list.getState();
310 const unsubscribe = [
311 state.listenToPosition(itemKey, schedule),
312 state.listen("totalSize", schedule),
313 state.listen("headerSize", schedule),
314 ];
315 const cancelScroll = () => {
316 if (scrolling) {
317 scrolling = false;
318 // Supersede a queued list scroll before the user's gesture or minimap action runs.
319 void list.scrollToOffset({
320 // Legend may defer this call too. Read the user's position when it executes.
321 get offset() {
322 return scrollNode.scrollTop;
323 },
324 animated: false,
325 });
326 }
327 };
328 activation.cancelScroll = cancelScroll;
329 schedule();
330 const dispose = () => {
331 if (stopped) return;
332 stopped = true;
333 cancelScroll();
334 pulseAnimation?.cancel();
335 if (frame !== null) cancelAnimationFrame(frame);
336 observer.disconnect();
337 resizeObserver.disconnect();
338 for (const stop of unsubscribe) stop();
339 if (activation.cancelScroll === cancelScroll) delete activation.cancelScroll;
340 clear();
341 };
342 return dispose;
344​
345export function AssistantCitationSource({
346 messageId,
347 threadRef,
348 itemKey,
349 request,
350 listRef,
351 children,
352}: {
353 messageId: MessageId;
354 threadRef?: ScopedThreadRef;
355 itemKey: string;
356 request: AssistantCitationTarget | null;
357 listRef: RefObject<LegendListRef | null>;
358 children: ReactNode;
359}) {
360 const rootRef = useRef<HTMLDivElement>(null);
361 useEffect(() => {
362 const root = rootRef.current;
363 const list = listRef.current;
364 if (!root || !list || !request || request.citation.messageId !== messageId) return;
365 return observeAssistantCitationSource({ root, itemKey, request, list });
366 }, [itemKey, listRef, messageId, request]);
367​
368 return (
369 <div
370 ref={rootRef}
371 data-assistant-citation-source={messageId}
372 data-assistant-citation-environment={threadRef?.environmentId}
373 data-assistant-citation-thread={threadRef?.threadId}
374 >
375 {children}
376 </div>
377 );