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