Open History to see the last commit
1import type { AssistantCitation } from "@t3tools/contracts";
2import {
3 assistantCitationLabel,
4 serializeAssistantCitation,
5} from "@t3tools/shared/assistantCitations";
6import { Link, useNavigate } from "@tanstack/react-router";
7import { ArrowUpRightIcon, PencilIcon, QuoteIcon } from "lucide-react";
8import {
9 useEffect,
10 useEffectEvent,
11 useRef,
12 useState,
13 type MouseEvent as ReactMouseEvent,
14} from "react";
15import {
16 findAssistantCitationSourceAnchor,
17 type AssistantCitationSourceAnchor,
18} from "~/lib/assistantTextSelection";
19import {
20 assistantCitationHash,
21 assistantCitationNavigation,
22} from "../../lib/assistantCitationNavigation";
23import { cn } from "~/lib/utils";
24import { ContextChip, ContextChipAction, ContextChipLabel } from "../ContextChip";
25import { ContextChipPopover } from "../contextChipParts";
26import { Button } from "../ui/button";
27import { Popover, PopoverClose, PopoverPopup, PopoverTrigger } from "../ui/popover";
28import { getVirtualizedScrollFadeClassName } from "../ui/scroll-area";
29import { AssistantCitationCommentEditor } from "./AssistantCitationCommentEditor";
30import { resolveAssistantCitationCommentDismissal } from "./assistantCitationCommentDismissal";
31import { observeAssistantCitationCommentSource } from "./AssistantCitationSource";
32import { composerFloatingLayerProps } from "./composerEventScope";
33import { observeResize } from "~/lib/observeResize";
34import { textDirection } from "~/textDirection";
35
36export function AssistantCitationChip({
37 citation,
38 composer = false,
39 commentEditor,
40}: {
41 citation: AssistantCitation;
42 composer?: boolean;
43 commentEditor?: {
44 open: boolean;
45 sourceAnchor?: AssistantCitationSourceAnchor | undefined;
46 onOpenChange: (open: boolean) => void;
47 onCancel?: () => void;
48 onSave: (comment: string) => boolean;
49 onSaveAndSend?: (comment: string) => boolean;
50 onDraftChange?: (comment: string) => void;
51 onRestoreFocus?: () => void;
52 };
53}) {
54 const navigate = useNavigate();
55 const commentInputRef = useRef<HTMLTextAreaElement>(null);
56 const commentPopupRef = useRef<HTMLDivElement>(null);
57 const draftCommentRef = useRef<string | null>(null);
58 const [voiceSetupOpen, setVoiceSetupOpen] = useState(false);
59 const [unavailableSourceAnchor, setUnavailableSourceAnchor] =
60 useState<AssistantCitationSourceAnchor | null>(null);
61 const commentOpen = commentEditor?.open ?? false;
62 const sourceAnchor = commentEditor?.sourceAnchor;
63 const activeSourceAnchor = sourceAnchor === unavailableSourceAnchor ? undefined : sourceAnchor;
64 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- drops the uncommitted comment draft held in a ref once the parent closes the comment editor
65 useEffect(() => {
66 if (!commentOpen) draftCommentRef.current = null;
67 }, [commentOpen]);
68 const settleDraftOnClose = (reason: string): boolean => {
69 const dismissal = resolveAssistantCitationCommentDismissal({
70 reason,
71 draft: draftCommentRef.current,
72 savedComment: citation.comment,
73 });
74 if (dismissal.kind === "commit") return commentEditor?.onSave(dismissal.comment) ?? true;
75 return dismissal.kind !== "keep-open";
76 };
77 const onSourceUnavailable = useEffectEvent(() => {
78 if (!sourceAnchor) return;
79 if (settleDraftOnClose("none")) {
80 commentEditor?.onOpenChange(false);
81 } else {
82 setUnavailableSourceAnchor(sourceAnchor);
83 }
84 });
85 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- observes the cited DOM source while the comment editor is open and reacts when it disappears
86 useEffect(() => {
87 if (!commentOpen || sourceAnchor === unavailableSourceAnchor) return;
88 const anchor = sourceAnchor ?? findAssistantCitationSourceAnchor(document, citation);
89 if (!anchor) return;
90 return observeAssistantCitationCommentSource({
91 anchor,
92 citation,
93 onUnavailable: onSourceUnavailable,
94 });
95 }, [citation, commentOpen, sourceAnchor, unavailableSourceAnchor]);
96 const popupAnchor = activeSourceAnchor
97 ? {
98 contextElement: activeSourceAnchor.source,
99 getBoundingClientRect: () => {
100 const rects = activeSourceAnchor.range.getClientRects();
101 const rect =
102 rects.item(rects.length - 1) ?? activeSourceAnchor.range.getBoundingClientRect();
103 // Code blocks and tables scroll sideways inside the message, so the cited
104 // text can end in their hidden overflow. Base UI only shifts the popup while
105 // it still touches the anchor, so clamp the anchor to the message's width.
106 const bounds = activeSourceAnchor.source.getBoundingClientRect();
107 const left = Math.min(Math.max(rect.left, bounds.left), bounds.right);
108 const right = Math.max(Math.min(rect.right, bounds.right), left);
109 return new DOMRect(left, rect.top, right - left, rect.height);
110 },
111 }
112 : undefined;
113 const label = assistantCitationLabel(citation);
114 const sourceLinkProps = {
115 to: "/$environmentId/$threadId" as const,
116 params: { environmentId: citation.environmentId, threadId: citation.threadId },
117 hash: assistantCitationHash(citation),
118 "data-markdown-copy": serializeAssistantCitation(citation),
119 resetScroll: false,
120 onClick: (event: ReactMouseEvent<HTMLAnchorElement>) => {
121 if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
122 return;
123 }
124 event.preventDefault();
125 void navigate(assistantCitationNavigation(citation));
126 },
127 };
128 const composerSourceLink = (
129 <Link
130 {...sourceLinkProps}
131 className="inline-flex min-w-0 items-center gap-[0.2em] self-baseline text-inherit no-underline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-current rounded-sm"
132 aria-label={`View cited assistant text: ${label}`}
133 >
134 <QuoteIcon aria-hidden="true" />
135 <ContextChipLabel className="max-w-[16em]" dir={textDirection(label)}>
136 {label}
137 </ContextChipLabel>
138 </Link>
139 );
140 if (!composer) {
141 return (
142 <ContextChipPopover
143 kind="citation"
144 icon={<QuoteIcon />}
145 label={label}
146 accessibleLabel={`Quoted assistant text: ${label}`}
147 copyMarkdown={serializeAssistantCitation(citation)}
148 >
149 <div className="flex max-h-[calc(var(--available-height)_-_1rem_-_2px)] flex-col items-start gap-3 p-1 text-sm">
150 <AssistantCitationQuote citation={citation} />
151 <PopoverClose
152 render={<Button variant="outline" size="sm" render={<Link {...sourceLinkProps} />} />}
153 >
154 <ArrowUpRightIcon aria-hidden="true" />
155 Go to source
156 </PopoverClose>
157 </div>
158 </ContextChipPopover>
159 );
160 }
161 return (
162 <ContextChip
163 kind="citation"
164 contentEditable={false}
165 data-assistant-citation-chip="true"
166 data-markdown-copy={serializeAssistantCitation(citation)}
167 >
168 {composerSourceLink}
169 {commentEditor ? (
170 <Popover
171 open={commentEditor.open && !voiceSetupOpen}
172 onOpenChange={(open, eventDetails) => {
173 if (!open && !settleDraftOnClose(eventDetails.reason)) {
174 eventDetails.cancel();
175 return;
176 }
177 commentEditor.onOpenChange(open);
178 }}
179 >
180 <PopoverTrigger
181 aria-label={citation.comment ? "Edit citation comment" : "Add comment to citation"}
182 data-citation-comment-trigger="true"
183 render={<ContextChipAction />}
184 >
185 <PencilIcon aria-hidden="true" />
186 </PopoverTrigger>
187 {commentEditor.open ? (
188 <PopoverPopup
189 // The editor stays mounted while its voice setup dialog replaces the popover.
190 keepMounted
191 {...composerFloatingLayerProps}
192 side={activeSourceAnchor ? "bottom" : "top"}
193 align="end"
194 anchor={popupAnchor}
195 initialFocus={() => {
196 const input = commentInputRef.current;
197 if (input) {
198 input.focus({ preventScroll: true });
199 input.setSelectionRange(input.value.length, input.value.length);
200 // Moving the caret doesn't scroll a long comment to it.
201 input.scrollTop = input.scrollHeight;
202 }
203 return false;
204 }}
205 finalFocus={
206 commentEditor.onRestoreFocus
207 ? () => {
208 const activeElement = document.activeElement;
209 if (
210 activeElement === document.body ||
211 (activeElement !== null && commentPopupRef.current?.contains(activeElement))
212 ) {
213 commentEditor.onRestoreFocus?.();
214 }
215 return false;
216 }
217 : undefined
218 }
219 ref={commentPopupRef}
220 aria-label="Edit citation comment"
221 width="md"
222 padding="compact"
223 onPointerDown={(event) => event.stopPropagation()}
224 >
225 <AssistantCitationCommentEditor
226 key={serializeAssistantCitation(citation)}
227 citation={citation}
228 inputRef={commentInputRef}
229 onVoiceSetupOpenChange={setVoiceSetupOpen}
230 onDraftChange={(comment) => {
231 draftCommentRef.current = comment;
232 commentEditor.onDraftChange?.(comment);
233 }}
234 onSubmit={(comment) => {
235 if (!commentEditor.onSave(comment)) return false;
236 commentEditor.onOpenChange(false);
237 return true;
238 }}
239 {...(commentEditor.onSaveAndSend
240 ? {
241 onSubmitAndSend: (comment: string) => {
242 if (!commentEditor.onSaveAndSend?.(comment)) return false;
243 commentEditor.onOpenChange(false);
244 return true;
245 },
246 }
247 : {})}
248 onCancel={() => {
249 if (commentEditor.onCancel) {
250 commentEditor.onCancel();
251 } else {
252 commentEditor.onOpenChange(false);
253 }
254 }}
255 />
256 </PopoverPopup>
257 ) : null}
258 </Popover>
259 ) : null}
260 </ContextChip>
261 );
262}
263
264function AssistantCitationQuote({ citation }: { citation: AssistantCitation }) {
265 const [fade, setFade] = useState({ top: false, bottom: false });
266 const updateFade = (element: HTMLElement) => {
267 const top = element.scrollTop > 1;
268 const bottom = element.scrollHeight - element.clientHeight - element.scrollTop > 1;
269 setFade((current) =>
270 current.top === top && current.bottom === bottom ? current : { top, bottom },
271 );
272 };
273 const observeFade = (element: HTMLDivElement | null) =>
274 element ? observeResize(element, () => updateFade(element)) : undefined;
275 return (
276 <div
277 ref={observeFade}
278 onScroll={(event) => updateFade(event.currentTarget)}
279 className={cn(
280 "max-h-64 min-h-0 space-y-3 self-stretch overflow-y-auto whitespace-pre-wrap wrap-break-word",
281 getVirtualizedScrollFadeClassName(fade),
282 )}
283 >
284 <blockquote
285 className="border-l-2 border-border pl-3 text-muted-foreground"
286 dir={textDirection(citation.text)}
287 >
288 {citation.text}
289 </blockquote>
290 {citation.comment ? <p dir={textDirection(citation.comment)}>{citation.comment}</p> : null}
291 </div>
292 );
293}