Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AssistantSelectionToolbar.tsx

211 lines7.5 KB

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