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 { BackgroundThreadContext } from "./backgroundThread";
22
23export function AssistantSelectionToolbar({
24 viewport,
25 threadRef,
26 onCite,
27}: {
28 viewport: HTMLElement | null;
29 threadRef: ScopedThreadRef;
30 onCite: (citation: AssistantCitation, sourceAnchor: AssistantCitationSourceAnchor) => boolean;
31}) {
32 const [selection, setSelection] = useState<{
33 citation: AssistantCitation;
34 position: SelectionActionPoint;
35 sourceAnchor: AssistantCitationSourceAnchor;
36 } | null>(null);
37 const toolbarRef = useRef<HTMLButtonElement>(null);
38 const actionsRef = useRef<ReturnType<typeof observeSelectionActions> | null>(null);
39 const backgroundThread = use(BackgroundThreadContext);
40
41 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the toolbar DOM node and clamps its position inside the window before paint
42 useLayoutEffect(() => {
43 const toolbar = toolbarRef.current;
44 if (!toolbar || !selection) return;
45 const rect = toolbar.getBoundingClientRect();
46 toolbar.style.left = `${Math.max(8, Math.min(selection.position.x, window.innerWidth - rect.width - 8))}px`;
47 toolbar.style.top = `${Math.max(8, Math.min(selection.position.y, window.innerHeight - rect.height - 8))}px`;
48 }, [selection]);
49
50 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to document selectionchange and keydown to track text selections in the viewport
51 useEffect(() => {
52 if (!viewport) return;
53 const clear = () => setSelection(null);
54 const update = (pointer: SelectionActionPoint | null) => {
55 const nativeSelection = window.getSelection();
56 const captured = captureAssistantTextSelection(viewport, nativeSelection);
57 const messageId = captured?.source.dataset.assistantCitationSource;
58 if (!captured || !messageId) {
59 clear();
60 return;
61 }
62 const rect = captured.range.getBoundingClientRect();
63 const viewportRect = viewport.getBoundingClientRect();
64 if (!isSelectionRectVisible(rect, [viewportRect])) {
65 clear();
66 return;
67 }
68 // A selection can cross blocks with different clipping ancestors.
69 const common = captured.range.commonAncestorContainer;
70 const walker = document.createTreeWalker(common, NodeFilter.SHOW_TEXT);
71 let node = common.nodeType === Node.TEXT_NODE ? common : walker.nextNode();
72 let visible = false;
73 for (; node && !visible; node = walker.nextNode()) {
74 if (!captured.range.intersectsNode(node)) continue;
75 if (node.parentElement && getComputedStyle(node.parentElement).userSelect === "none")
76 continue;
77 const fragment = document.createRange();
78 fragment.selectNodeContents(node);
79 if (node === captured.range.startContainer) {
80 fragment.setStart(node, captured.range.startOffset);
81 }
82 if (node === captured.range.endContainer) {
83 fragment.setEnd(node, captured.range.endOffset);
84 }
85 if (!fragment.toString().trim()) continue;
86 const lines = Array.from(fragment.getClientRects());
87 if (!lines.some((line) => isSelectionRectVisible(line, [viewportRect]))) continue;
88 const clips: Pick<DOMRect, "left" | "right" | "top" | "bottom">[] = [viewportRect];
89 for (
90 let element = node.parentElement;
91 element && element !== viewport;
92 element = element.parentElement
93 ) {
94 const style = getComputedStyle(element);
95 const clipX = style.overflowX !== "visible";
96 const clipY = style.overflowY !== "visible";
97 if (!clipX && !clipY) continue;
98 const bounds = element.getBoundingClientRect();
99 const left = bounds.left + element.clientLeft;
100 const top = bounds.top + element.clientTop;
101 clips.push({
102 left: clipX ? left : -Infinity,
103 right: clipX ? left + element.clientWidth : Infinity,
104 top: clipY ? top : -Infinity,
105 bottom: clipY ? top + element.clientHeight : Infinity,
106 });
107 }
108 visible = lines.some((line) => isSelectionRectVisible(line, clips));
109 }
110 if (!visible) {
111 clear();
112 return;
113 }
114 const rects = captured.range.getClientRects();
115 const pointerOnText =
116 pointer !== null &&
117 Array.from(rects).some(
118 (line) =>
119 pointer.x >= line.left - 8 &&
120 pointer.x <= line.right + 8 &&
121 pointer.y >= line.top - 8 &&
122 pointer.y <= line.bottom + 8,
123 );
124 setSelection({
125 sourceAnchor: { source: captured.source, range: captured.range, viewport },
126 citation: {
127 version: 1,
128 ...threadRef,
129 messageId: MessageId.make(messageId),
130 ...captured.selector,
131 },
132 position: resolveSelectionActionPosition({
133 bounds: viewportRect,
134 selectionRect: rects.item(rects.length - 1) ?? rect,
135 pointer: pointerOnText ? pointer : null,
136 viewport: { width: window.innerWidth, height: window.innerHeight },
137 }),
138 });
139 };
140 const actions = observeSelectionActions({
141 element: viewport,
142 getActionElement: () => toolbarRef.current,
143 restoreAfterScroll: true,
144 onSelection: update,
145 onDismiss: clear,
146 });
147 actionsRef.current = actions;
148 const focusActions = (event: KeyboardEvent) => {
149 const toolbar = toolbarRef.current;
150 if (
151 event.key !== "Tab" ||
152 event.shiftKey ||
153 event.altKey ||
154 event.ctrlKey ||
155 event.metaKey ||
156 event.isComposing ||
157 event.defaultPrevented ||
158 !toolbar ||
159 toolbar.contains(event.target as Node)
160 ) {
161 return;
162 }
163 if (toolbar.disabled) return;
164 event.preventDefault();
165 event.stopPropagation();
166 toolbar.focus({ preventScroll: true });
167 };
168 // Tab belongs to the foreground chat; a background timeline only follows its selection.
169 if (!backgroundThread) document.addEventListener("keydown", focusActions, true);
170 document.addEventListener("selectionchange", actions.selectionChanged);
171 return () => {
172 document.removeEventListener("keydown", focusActions, true);
173 document.removeEventListener("selectionchange", actions.selectionChanged);
174 actions.dispose();
175 actionsRef.current = null;
176 };
177 }, [backgroundThread, threadRef, viewport]);
178
179 if (!selection) return null;
180 const tooLong = selection.citation.text.length > ASSISTANT_CITATION_MAX_TEXT_LENGTH;
181 const dismiss = () => {
182 actionsRef.current?.cancel();
183 setSelection(null);
184 };
185 const cite = () => {
186 if (tooLong || !onCite(selection.citation, selection.sourceAnchor)) return false;
187 window.getSelection()?.removeAllRanges();
188 dismiss();
189 return true;
190 };
191 return createPortal(
192 <Button
193 ref={toolbarRef}
194 type="button"
195 size="xs"
196 variant="glass"
197 disabled={tooLong}
198 aria-label={tooLong ? "Selection is too long to cite" : "Cite selection in composer"}
199 className="fixed z-50 max-w-[calc(100vw-1rem)]"
200 style={{ left: selection.position.x, top: selection.position.y }}
201 onPointerDown={(event) => event.preventDefault()}
202 onClick={cite}
203 onKeyDown={(event) => {
204 event.stopPropagation();
205 if (event.key === "Escape" && !event.nativeEvent.isComposing) {
206 event.preventDefault();
207 dismiss();
208 }
209 }}
210 >
211 <QuoteIcon aria-hidden="true" className="size-3.5" />
212 {tooLong ? "Shorten selection" : "Cite"}
213 </Button>,
214 document.body,
215 );
216}