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 { useEffect, useLayoutEffect, useRef, useState } from "react";
9import { createPortal } from "react-dom";
10import {
11 captureAssistantTextSelection,
12 type AssistantCitationSourceAnchor,
13} from "~/lib/assistantTextSelection";
14import {
15 observeSelectionActions,
16 resolveSelectionActionPosition,
17 type SelectionActionPoint,
18} from "~/lib/selectionActions";
19import { Button } from "../ui/button";
20
21export function AssistantSelectionToolbar({
22 viewport,
23 threadRef,
24 onCite,
25}: {
26 viewport: HTMLElement | null;
27 threadRef: ScopedThreadRef;
28 onCite: (citation: AssistantCitation, sourceAnchor: AssistantCitationSourceAnchor) => boolean;
29}) {
30 const [selection, setSelection] = useState<{
31 citation: AssistantCitation;
32 position: SelectionActionPoint;
33 sourceAnchor: AssistantCitationSourceAnchor;
34 } | null>(null);
35 const toolbarRef = useRef<HTMLButtonElement>(null);
36 const actionsRef = useRef<ReturnType<typeof observeSelectionActions> | null>(null);
37
38 useLayoutEffect(() => {
39 const toolbar = toolbarRef.current;
40 if (!toolbar || !selection) return;
41 const rect = toolbar.getBoundingClientRect();
42 toolbar.style.left = `${Math.max(8, Math.min(selection.position.x, window.innerWidth - rect.width - 8))}px`;
43 toolbar.style.top = `${Math.max(8, Math.min(selection.position.y, window.innerHeight - rect.height - 8))}px`;
44 }, [selection]);
45
46 useEffect(() => {
47 if (!viewport) return;
48 const clear = () => setSelection(null);
49 const update = (pointer: SelectionActionPoint | null) => {
50 const nativeSelection = window.getSelection();
51 const captured = captureAssistantTextSelection(viewport, nativeSelection);
52 const messageId = captured?.source.dataset.assistantCitationSource;
53 if (!captured || !messageId) {
54 clear();
55 return;
56 }
57 const rect = captured.range.getBoundingClientRect();
58 const viewportRect = viewport.getBoundingClientRect();
59 if (rect.bottom < viewportRect.top || rect.top > viewportRect.bottom || rect.width === 0) {
60 clear();
61 return;
62 }
63 const rects = captured.range.getClientRects();
64 setSelection({
65 sourceAnchor: { source: captured.source, range: captured.range, viewport },
66 citation: {
67 version: 1,
68 ...threadRef,
69 messageId: MessageId.make(messageId),
70 ...captured.selector,
71 },
72 position: resolveSelectionActionPosition({
73 bounds: viewportRect,
74 selectionRect: rects.item(rects.length - 1) ?? rect,
75 pointer,
76 viewport: { width: window.innerWidth, height: window.innerHeight },
77 }),
78 });
79 };
80 const actions = observeSelectionActions({
81 element: viewport,
82 getActionElement: () => toolbarRef.current,
83 onSelection: update,
84 onDismiss: clear,
85 });
86 actionsRef.current = actions;
87 const focusActions = (event: KeyboardEvent) => {
88 const toolbar = toolbarRef.current;
89 if (
90 event.key !== "Tab" ||
91 event.shiftKey ||
92 event.altKey ||
93 event.ctrlKey ||
94 event.metaKey ||
95 event.isComposing ||
96 event.defaultPrevented ||
97 !toolbar ||
98 toolbar.contains(event.target as Node)
99 ) {
100 return;
101 }
102 if (toolbar.disabled) return;
103 event.preventDefault();
104 event.stopPropagation();
105 toolbar.focus({ preventScroll: true });
106 };
107 document.addEventListener("keydown", focusActions, true);
108 document.addEventListener("selectionchange", actions.selectionChanged);
109 return () => {
110 document.removeEventListener("keydown", focusActions, true);
111 document.removeEventListener("selectionchange", actions.selectionChanged);
112 actions.dispose();
113 actionsRef.current = null;
114 };
115 }, [threadRef, viewport]);
116
117 if (!selection) return null;
118 const tooLong = selection.citation.text.length > ASSISTANT_CITATION_MAX_TEXT_LENGTH;
119 const dismiss = () => {
120 actionsRef.current?.cancel();
121 setSelection(null);
122 };
123 const cite = () => {
124 if (tooLong || !onCite(selection.citation, selection.sourceAnchor)) return false;
125 window.getSelection()?.removeAllRanges();
126 dismiss();
127 return true;
128 };
129 return createPortal(
130 <Button
131 ref={toolbarRef}
132 type="button"
133 size="xs"
134 variant="glass"
135 disabled={tooLong}
136 aria-label={tooLong ? "Selection is too long to cite" : "Cite selection in composer"}
137 className="fixed z-50 max-w-[calc(100vw-1rem)]"
138 style={{ left: selection.position.x, top: selection.position.y }}
139 onPointerDown={(event) => event.preventDefault()}
140 onClick={cite}
141 onKeyDown={(event) => {
142 event.stopPropagation();
143 if (event.key === "Escape" && !event.nativeEvent.isComposing) {
144 event.preventDefault();
145 dismiss();
146 }
147 }}
148 >
149 <QuoteIcon aria-hidden="true" className="size-3.5" />
150 {tooLong ? "Shorten selection" : "Cite"}
151 </Button>,
152 document.body,
153 );
154}