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