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