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