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 { usePortalContainer } from "~/lib/portalContainer";
15import {
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 portalContainer = usePortalContainer();
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
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 useEffect(() => {
49 if (!viewport) return;
50 const clear = () => setSelection(null);
51 const update = (pointer: SelectionActionPoint | null) => {
52 const nativeSelection = window.getSelection();
53 const captured = captureAssistantTextSelection(viewport, nativeSelection);
54 const messageId = captured?.source.dataset.assistantCitationSource;
55 if (!captured || !messageId) {
56 clear();
57 return;
58 }
59 const rect = captured.range.getBoundingClientRect();
60 const viewportRect = viewport.getBoundingClientRect();
61 if (rect.bottom < viewportRect.top || rect.top > viewportRect.bottom || rect.width === 0) {
62 clear();
63 return;
64 }
65 const rects = captured.range.getClientRects();
66 const pointerOnText =
67 pointer !== null &&
68 Array.from(rects).some(
69 (line) =>
70 pointer.x >= line.left - 8 &&
71 pointer.x <= line.right + 8 &&
72 pointer.y >= line.top - 8 &&
73 pointer.y <= line.bottom + 8,
74 );
75 setSelection({
76 sourceAnchor: { source: captured.source, range: captured.range, viewport },
77 citation: {
78 version: 1,
79 ...threadRef,
80 messageId: MessageId.make(messageId),
81 ...captured.selector,
82 },
83 position: resolveSelectionActionPosition({
84 bounds: viewportRect,
85 selectionRect: rects.item(rects.length - 1) ?? rect,
86 pointer: pointerOnText ? pointer : null,
87 viewport: { width: window.innerWidth, height: window.innerHeight },
88 }),
89 });
90 };
91 const actions = observeSelectionActions({
92 element: viewport,
93 getActionElement: () => toolbarRef.current,
94 onSelection: update,
95 onDismiss: clear,
96 });
97 actionsRef.current = actions;
98 const focusActions = (event: KeyboardEvent) => {
99 const toolbar = toolbarRef.current;
100 if (
101 event.key !== "Tab" ||
102 event.shiftKey ||
103 event.altKey ||
104 event.ctrlKey ||
105 event.metaKey ||
106 event.isComposing ||
107 event.defaultPrevented ||
108 !toolbar ||
109 toolbar.contains(event.target as Node)
110 ) {
111 return;
112 }
113 if (toolbar.disabled) return;
114 event.preventDefault();
115 event.stopPropagation();
116 toolbar.focus({ preventScroll: true });
117 };
118 document.addEventListener("keydown", focusActions, true);
119 document.addEventListener("selectionchange", actions.selectionChanged);
120 return () => {
121 document.removeEventListener("keydown", focusActions, true);
122 document.removeEventListener("selectionchange", actions.selectionChanged);
123 actions.dispose();
124 actionsRef.current = null;
125 };
126 }, [threadRef, viewport]);
127
128 if (!selection) return null;
129 const tooLong = selection.citation.text.length > ASSISTANT_CITATION_MAX_TEXT_LENGTH;
130 const dismiss = () => {
131 actionsRef.current?.cancel();
132 setSelection(null);
133 };
134 const cite = () => {
135 if (tooLong || !onCite(selection.citation, selection.sourceAnchor)) return false;
136 window.getSelection()?.removeAllRanges();
137 dismiss();
138 return true;
139 };
140 return createPortal(
141 <Button
142 ref={toolbarRef}
143 type="button"
144 size="xs"
145 variant="glass"
146 disabled={tooLong}
147 aria-label={tooLong ? "Selection is too long to cite" : "Cite selection in composer"}
148 className="fixed z-50 max-w-[calc(100vw-1rem)]"
149 style={{ left: selection.position.x, top: selection.position.y }}
150 onPointerDown={(event) => event.preventDefault()}
151 onClick={cite}
152 onKeyDown={(event) => {
153 event.stopPropagation();
154 if (event.key === "Escape" && !event.nativeEvent.isComposing) {
155 event.preventDefault();
156 dismiss();
157 }
158 }}
159 >
160 <QuoteIcon aria-hidden="true" className="size-3.5" />
161 {tooLong ? "Shorten selection" : "Cite"}
162 </Button>,
163 portalContainer ?? document.body,
164 );
165}