Open History to see the last commit
1import {
2 ASSISTANT_CITATION_MAX_TEXT_LENGTH,
3 MessageId,
4 type AssistantCitation,
5 type ScopedThreadRef,
6} from "@t3tools/contracts";
7import { QuoteIcon } from "lucide-react";
8import { use, useEffect, useLayoutEffect, useRef, useState } from "react";
9import { createPortal } from "react-dom";
10import {
11 captureAssistantTextSelection,
12 type AssistantCitationSourceAnchor,
13} from "~/lib/assistantTextSelection";
14import {
15 isSelectionRectVisible,
16 observeSelectionActions,
17 resolveSelectionActionPosition,
18 type SelectionActionPoint,
19} from "~/lib/selectionActions";
20import { Button } from "../ui/button";
21import {
22 htmlSelectionClientRect,
23 htmlSelectionCommand,
24 htmlSelectionParams,
25 readHtmlSelection,
26 readHtmlSelectionRect,
27} from "~/lib/htmlRenderSelection";
28import { BackgroundThreadContext } from "./backgroundThread";
29
30export function AssistantSelectionToolbar({
31 viewport,
32 threadRef,
33 onCite,
34}: {
35 viewport: HTMLElement | null;
36 threadRef: ScopedThreadRef;
37 onCite: (citation: AssistantCitation, sourceAnchor: AssistantCitationSourceAnchor) => boolean;
38}) {
39 const [selection, setSelection] = useState<{
40 citation: AssistantCitation;
41 position: SelectionActionPoint;
42 sourceAnchor: AssistantCitationSourceAnchor;
43 tooLong?: boolean;
44 } | null>(null);
45 const toolbarRef = useRef<HTMLButtonElement>(null);
46 const actionsRef = useRef<ReturnType<typeof observeSelectionActions> | null>(null);
47 const backgroundThread = use(BackgroundThreadContext);
48
49 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the toolbar DOM node and clamps its position inside the window before paint
50 useLayoutEffect(() => {
51 const toolbar = toolbarRef.current;
52 if (!toolbar || !selection) return;
53 const rect = toolbar.getBoundingClientRect();
54 toolbar.style.left = `${Math.max(8, Math.min(selection.position.x, window.innerWidth - rect.width - 8))}px`;
55 toolbar.style.top = `${Math.max(8, Math.min(selection.position.y, window.innerHeight - rect.height - 8))}px`;
56 }, [selection]);
57
58 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to document selectionchange and keydown to track text selections in the viewport
59 useEffect(() => {
60 if (!viewport) return;
61 const clear = () => setSelection(null);
62 const update = (pointer: SelectionActionPoint | null) => {
63 const nativeSelection = window.getSelection();
64 const captured = captureAssistantTextSelection(viewport, nativeSelection);
65 const messageId = captured?.source.dataset.assistantCitationSource;
66 if (!captured || !messageId) {
67 clear();
68 return;
69 }
70 const rect = captured.range.getBoundingClientRect();
71 const viewportRect = viewport.getBoundingClientRect();
72 if (!isSelectionRectVisible(rect, [viewportRect])) {
73 clear();
74 return;
75 }
76 // A selection can cross blocks with different clipping ancestors.
77 const common = captured.range.commonAncestorContainer;
78 const walker = document.createTreeWalker(common, NodeFilter.SHOW_TEXT);
79 let node = common.nodeType === Node.TEXT_NODE ? common : walker.nextNode();
80 let visible = false;
81 for (; node && !visible; node = walker.nextNode()) {
82 if (!captured.range.intersectsNode(node)) continue;
83 if (node.parentElement && getComputedStyle(node.parentElement).userSelect === "none")
84 continue;
85 const fragment = document.createRange();
86 fragment.selectNodeContents(node);
87 if (node === captured.range.startContainer) {
88 fragment.setStart(node, captured.range.startOffset);
89 }
90 if (node === captured.range.endContainer) {
91 fragment.setEnd(node, captured.range.endOffset);
92 }
93 if (!fragment.toString().trim()) continue;
94 const lines = Array.from(fragment.getClientRects());
95 if (!lines.some((line) => isSelectionRectVisible(line, [viewportRect]))) continue;
96 const clips: Pick<DOMRect, "left" | "right" | "top" | "bottom">[] = [viewportRect];
97 for (
98 let element = node.parentElement;
99 element && element !== viewport;
100 element = element.parentElement
101 ) {
102 const style = getComputedStyle(element);
103 const clipX = style.overflowX !== "visible";
104 const clipY = style.overflowY !== "visible";
105 if (!clipX && !clipY) continue;
106 const bounds = element.getBoundingClientRect();
107 const left = bounds.left + element.clientLeft;
108 const top = bounds.top + element.clientTop;
109 clips.push({
110 left: clipX ? left : -Infinity,
111 right: clipX ? left + element.clientWidth : Infinity,
112 top: clipY ? top : -Infinity,
113 bottom: clipY ? top + element.clientHeight : Infinity,
114 });
115 }
116 visible = lines.some((line) => isSelectionRectVisible(line, clips));
117 }
118 if (!visible) {
119 clear();
120 return;
121 }
122 const rects = captured.range.getClientRects();
123 const pointerOnText =
124 pointer !== null &&
125 Array.from(rects).some(
126 (line) =>
127 pointer.x >= line.left - 8 &&
128 pointer.x <= line.right + 8 &&
129 pointer.y >= line.top - 8 &&
130 pointer.y <= line.bottom + 8,
131 );
132 setSelection({
133 sourceAnchor: { source: captured.source, range: captured.range, viewport },
134 citation: {
135 version: 1,
136 ...threadRef,
137 messageId: MessageId.make(messageId),
138 ...captured.selector,
139 },
140 position: resolveSelectionActionPosition({
141 bounds: viewportRect,
142 selectionRect: rects.item(rects.length - 1) ?? rect,
143 pointer: pointerOnText ? pointer : null,
144 viewport: { width: window.innerWidth, height: window.innerHeight },
145 }),
146 });
147 };
148 const actions = observeSelectionActions({
149 element: viewport,
150 getActionElement: () => toolbarRef.current,
151 restoreAfterScroll: true,
152 onSelection: update,
153 onDismiss: clear,
154 });
155 actionsRef.current = actions;
156 const focusActions = (event: KeyboardEvent) => {
157 const toolbar = toolbarRef.current;
158 if (
159 event.key !== "Tab" ||
160 event.shiftKey ||
161 event.altKey ||
162 event.ctrlKey ||
163 event.metaKey ||
164 event.isComposing ||
165 event.defaultPrevented ||
166 !toolbar ||
167 toolbar.contains(event.target as Node)
168 ) {
169 return;
170 }
171 if (toolbar.disabled) return;
172 event.preventDefault();
173 event.stopPropagation();
174 toolbar.focus({ preventScroll: true });
175 };
176 // Tab belongs to the foreground chat; a background timeline only follows its selection.
177 if (!backgroundThread) document.addEventListener("keydown", focusActions, true);
178 document.addEventListener("selectionchange", actions.selectionChanged);
179 const htmlSelection = (event: MessageEvent) => {
180 const params = htmlSelectionParams(event.data);
181 if (params === undefined) return;
182 const frame = [
183 ...viewport.querySelectorAll<HTMLIFrameElement>("iframe[data-html-selection-bridge]"),
184 ].find((frame) => frame.contentWindow === event.source);
185 const source = frame?.closest<HTMLElement>("[data-assistant-citation-source]");
186 const messageId = source?.dataset.assistantCitationSource;
187 if (!frame || !source || !messageId) return;
188 if (params === null) {
189 setSelection((previous) =>
190 document.activeElement === frame || previous?.sourceAnchor.htmlRender === frame
191 ? null
192 : previous,
193 );
194 return;
195 }
196 if (params.focus === true) {
197 if (document.activeElement === frame) toolbarRef.current?.focus({ preventScroll: true });
198 return;
199 }
200 if ("target" in params) return;
201 if (document.activeElement !== frame) return;
202 const captured = readHtmlSelection(event.data);
203 const localRect =
204 captured?.rect ?? (params.tooLong === true ? readHtmlSelectionRect(params.rect) : null);
205 if (!localRect) {
206 clear();
207 return;
208 }
209 const rect = htmlSelectionClientRect(frame, localRect);
210 const bounds = viewport.getBoundingClientRect();
211 const frameBounds = frame.getBoundingClientRect();
212 if (
213 rect.bottom < bounds.top ||
214 rect.top > bounds.bottom ||
215 rect.bottom < frameBounds.top ||
216 rect.top > frameBounds.bottom
217 ) {
218 clear();
219 return;
220 }
221 const selector = captured?.selector ?? { text: "", start: 0, end: 1, prefix: "", suffix: "" };
222 let currentRect = localRect;
223 const sourceRect = () => htmlSelectionClientRect(frame, currentRect);
224 setSelection({
225 tooLong: params.tooLong === true,
226 citation: { version: 1, ...threadRef, messageId: MessageId.make(messageId), ...selector },
227 sourceAnchor: {
228 source,
229 viewport,
230 htmlRender: frame,
231 updateRange: (next) => {
232 const changed = (["left", "top", "width", "height"] as const).some(
233 (key) => next[key] !== currentRect[key],
234 );
235 currentRect = next;
236 return changed;
237 },
238 range: {
239 getBoundingClientRect: sourceRect,
240 getClientRects: () =>
241 Object.assign([sourceRect()], {
242 item: (index: number) => (index === 0 ? sourceRect() : null),
243 }),
244 },
245 },
246 position: resolveSelectionActionPosition({
247 bounds,
248 selectionRect: rect,
249 pointer: captured?.pointer
250 ? { x: frameBounds.left + captured.pointer.x, y: frameBounds.top + captured.pointer.y }
251 : null,
252 viewport: { width: window.innerWidth, height: window.innerHeight },
253 }),
254 });
255 };
256 window.addEventListener("message", htmlSelection);
257 return () => {
258 window.removeEventListener("message", htmlSelection);
259 document.removeEventListener("keydown", focusActions, true);
260 document.removeEventListener("selectionchange", actions.selectionChanged);
261 actions.dispose();
262 actionsRef.current = null;
263 };
264 }, [backgroundThread, threadRef, viewport]);
265
266 if (!selection) return null;
267 const tooLong =
268 selection.tooLong || selection.citation.text.length > ASSISTANT_CITATION_MAX_TEXT_LENGTH;
269 const dismiss = () => {
270 actionsRef.current?.cancel();
271 setSelection(null);
272 };
273 const cite = () => {
274 if (tooLong || !onCite(selection.citation, selection.sourceAnchor)) return false;
275 if (selection.sourceAnchor.htmlRender) {
276 htmlSelectionCommand(selection.sourceAnchor.htmlRender, "clear");
277 } else window.getSelection()?.removeAllRanges();
278 dismiss();
279 return true;
280 };
281 return createPortal(
282 <Button
283 ref={toolbarRef}
284 type="button"
285 size="xs"
286 variant="glass"
287 disabled={tooLong}
288 aria-label={tooLong ? "Selection is too long to cite" : "Cite selection in composer"}
289 className="fixed z-50 max-w-[calc(100vw-1rem)]"
290 style={{ left: selection.position.x, top: selection.position.y }}
291 onPointerDown={(event) => event.preventDefault()}
292 onClick={cite}
293 onKeyDown={(event) => {
294 event.stopPropagation();
295 if (event.key === "Escape" && !event.nativeEvent.isComposing) {
296 event.preventDefault();
297 if (selection.sourceAnchor.htmlRender)
298 htmlSelectionCommand(selection.sourceAnchor.htmlRender, "dismiss");
299 dismiss();
300 }
301 }}
302 >
303 <QuoteIcon aria-hidden="true" className="size-3.5" />
304 {tooLong ? "Shorten selection" : "Cite"}
305 </Button>,
306 document.body,
307 );
308}