Open History to see the last commit
1import type { LegendListRef } from "@legendapp/list/react";
2import {
3 htmlSelectionClientRect,
4 htmlSelectionCommand,
5 htmlSelectionParams,
6 readHtmlSelectionRect,
7} from "~/lib/htmlRenderSelection";
8import { observeResize } from "~/lib/observeResize";
9import type { AssistantCitationTarget } from "./AssistantCitationSource";
10import { toastManager } from "../ui/toast";
11
12/** Resolves and marks the quote inside its opaque frame before scrolling the timeline. */
13export function observeHtmlRenderCitationSource({
14 root,
15 itemKey,
16 request,
17 list,
18}: {
19 root: HTMLElement;
20 itemKey: string;
21 request: AssistantCitationTarget;
22 list: LegendListRef;
23}) {
24 const activation = request.activationRef.current;
25 if (activation.dismissed) return;
26 const scrollNode = list.getScrollableNode();
27 if (!(scrollNode instanceof HTMLElement)) return;
28 let stopped = false;
29 let frame: HTMLIFrameElement | null = null;
30 let scrolling = false;
31 let expiry: ReturnType<typeof setTimeout> | undefined;
32 let responseTimeout: ReturnType<typeof setTimeout> | undefined;
33 const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
34 const resolve = () => {
35 if (stopped || activation.dismissed || !root.isConnected || scrolling) return;
36 if (root.querySelector("[data-html-render-error]")) {
37 activation.dismissed = true;
38 request.onComplete();
39 toastManager.add({
40 type: "warning",
41 title: "Could not load the cited HTML",
42 description: "Reconnect to the environment and try again. The saved quote is unchanged.",
43 });
44 return;
45 }
46 responseTimeout ??= setTimeout(() => {
47 if (stopped || activation.dismissed) return;
48 activation.dismissed = true;
49 if (frame) htmlSelectionCommand(frame, "untarget");
50 request.onComplete();
51 toastManager.add({
52 type: "warning",
53 title: "Could not open the cited HTML",
54 description:
55 "Update or reconnect to the environment and try again. The saved quote is unchanged.",
56 });
57 }, 5000);
58 frame = root.querySelector<HTMLIFrameElement>("iframe[data-html-selection-ready]");
59 if (frame) {
60 htmlSelectionCommand(frame, "target", request.citation);
61 }
62 };
63 const receive = (event: MessageEvent) => {
64 if (stopped || activation.dismissed || !frame || event.source !== frame.contentWindow) return;
65 const params = htmlSelectionParams(event.data);
66 if (!params || !("target" in params)) return;
67 const selector = params.selector as Partial<typeof request.citation> | undefined;
68 if (
69 !selector ||
70 selector.text !== request.citation.text ||
71 selector.start !== request.citation.start ||
72 selector.end !== request.citation.end ||
73 selector.prefix !== request.citation.prefix ||
74 selector.suffix !== request.citation.suffix
75 )
76 return;
77 const local = readHtmlSelectionRect(params.target);
78 clearTimeout(responseTimeout);
79 responseTimeout = undefined;
80 const rect = local ? htmlSelectionClientRect(frame, local) : root.getBoundingClientRect();
81 const state = list.getState();
82 const index = state.indexByKey(itemKey);
83 if (index === undefined || !(state.sizeAtIndex(index) > 0) || scrollNode.clientHeight <= 0)
84 return;
85 if (!activation.scrolled) {
86 if (scrolling) return;
87 const offset = Math.max(
88 0,
89 Math.min(
90 scrollNode.scrollHeight - scrollNode.clientHeight,
91 state.scroll +
92 rect.top -
93 scrollNode.getBoundingClientRect().top -
94 Math.min(120, scrollNode.clientHeight / 3),
95 ),
96 );
97 if (Math.abs(offset - state.scroll) > 1) {
98 scrolling = true;
99 void list.scrollToOffset({ offset, animated: !reducedMotion }).then(
100 () => {
101 scrolling = false;
102 resolve();
103 },
104 () => {
105 scrolling = false;
106 if (stopped || activation.dismissed) return;
107 activation.dismissed = true;
108 request.onComplete();
109 toastManager.add({
110 type: "warning",
111 title: "Could not open the cited response",
112 description: "Click the citation to try again.",
113 });
114 },
115 );
116 return;
117 }
118 activation.scrolled = true;
119 request.onComplete();
120 if (!local)
121 toastManager.add({
122 type: "warning",
123 title: "The quoted text has changed",
124 description: "Showing the source response. The saved quote is unchanged.",
125 });
126 }
127 if (expiry === undefined) {
128 const pulse = (activation.pulse ??= { startedAt: performance.now(), reducedMotion });
129 expiry = setTimeout(
130 () => {
131 activation.dismissed = true;
132 if (frame) htmlSelectionCommand(frame, "untarget");
133 },
134 Math.max(0, 3000 - (performance.now() - pulse.startedAt)),
135 );
136 }
137 };
138 const observer = new MutationObserver(resolve);
139 observer.observe(root, { childList: true, subtree: true });
140 const stopResize = observeResize(root, resolve);
141 const stopPosition = list.getState().listenToPosition(itemKey, resolve);
142 const cancelScroll = () => {
143 if (scrolling) {
144 scrolling = false;
145 void list.scrollToOffset({
146 get offset() {
147 return scrollNode.scrollTop;
148 },
149 animated: false,
150 });
151 }
152 };
153 activation.cancelScroll = cancelScroll;
154 root.addEventListener("t3-html-selection-ready", resolve);
155 window.addEventListener("message", receive);
156 resolve();
157 return () => {
158 stopped = true;
159 cancelScroll();
160 clearTimeout(expiry);
161 clearTimeout(responseTimeout);
162 observer.disconnect();
163 stopResize();
164 stopPosition();
165 root.removeEventListener("t3-html-selection-ready", resolve);
166 window.removeEventListener("message", receive);
167 if (activation.cancelScroll === cancelScroll) delete activation.cancelScroll;
168 if (frame) htmlSelectionCommand(frame, "untarget");
169 };
170}