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

AssistantSelectionToolbar.tsx

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