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";
33
34export function AssistantCitationChip({
35 citation,
36 composer = false,
37 commentEditor,
38}: {
39 citation: AssistantCitation;
40 composer?: boolean;
41 commentEditor?: {
42 open: boolean;
43 sourceAnchor?: AssistantCitationSourceAnchor | undefined;
44 onOpenChange: (open: boolean) => void;
45 onCancel?: () => void;
46 onSave: (comment: string) => boolean;
47 onSaveAndSend?: (comment: string) => boolean;
48 /** Returns focus to the host editor when the popover closes instead of to the pencil trigger. */
49 onRestoreFocus?: () => void;
50 };
51}) {
52 const navigate = useNavigate();
53 const commentInputRef = useRef<HTMLTextAreaElement>(null);
54 const commentPopupRef = useRef<HTMLDivElement>(null);
55 const draftCommentRef = useRef<string | null>(null);
56 const [unavailableSourceAnchor, setUnavailableSourceAnchor] =
57 useState<AssistantCitationSourceAnchor | null>(null);
58 const commentOpen = commentEditor?.open ?? false;
59 const sourceAnchor = commentEditor?.sourceAnchor;
60 const activeSourceAnchor = sourceAnchor === unavailableSourceAnchor ? undefined : sourceAnchor;
61 useEffect(() => {
62 if (!commentOpen) draftCommentRef.current = null;
63 }, [commentOpen]);
64 const settleDraftOnClose = (reason: string): boolean => {
65 const dismissal = resolveAssistantCitationCommentDismissal({
66 reason,
67 draft: draftCommentRef.current,
68 savedComment: citation.comment,
69 });
70 if (dismissal.kind === "commit") return commentEditor?.onSave(dismissal.comment) ?? true;
71 return dismissal.kind !== "keep-open";
72 };
73 const onSourceUnavailable = useEffectEvent(() => {
74 if (!sourceAnchor) return;
75 if (settleDraftOnClose("none")) {
76 commentEditor?.onOpenChange(false);
77 } else {
78 // Keep the draft mounted, positioned at the composer trigger instead of a detached range.
79 setUnavailableSourceAnchor(sourceAnchor);
80 }
81 });
82 useEffect(() => {
83 if (!commentOpen || sourceAnchor === unavailableSourceAnchor) return;
84 const anchor = sourceAnchor ?? findAssistantCitationSourceAnchor(document, citation);
85 if (!anchor) return;
86 return observeAssistantCitationCommentSource({
87 anchor,
88 citation,
89 onUnavailable: onSourceUnavailable,
90 });
91 }, [citation, commentOpen, sourceAnchor, unavailableSourceAnchor]);
92 // A multi-line selection's bounding box spans the full message width; anchor
93 // the bubble to the selection's last line, where the pointer released.
94 const popupAnchor = activeSourceAnchor
95 ? {
96 contextElement: activeSourceAnchor.source,
97 getBoundingClientRect: () => {
98 const rects = activeSourceAnchor.range.getClientRects();
99 return rects.item(rects.length - 1) ?? activeSourceAnchor.range.getBoundingClientRect();
100 },
101 }
102 : undefined;
103 const label = assistantCitationLabel(citation);
104 const sourceLinkProps = {
105 to: "/$environmentId/$threadId" as const,
106 params: { environmentId: citation.environmentId, threadId: citation.threadId },
107 hash: assistantCitationHash(citation),
108 "data-markdown-copy": serializeAssistantCitation(citation),
109 resetScroll: false,
110 onClick: (event: ReactMouseEvent<HTMLAnchorElement>) => {
111 if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
112 return;
113 }
114 event.preventDefault();
115 void navigate(assistantCitationNavigation(citation));
116 },
117 };
118 const composerSourceLink = (
119 <Link
120 {...sourceLinkProps}
121 className="inline-flex h-full min-w-0 items-center gap-[0.33em] rounded-sm text-inherit no-underline focus-visible:outline-2 focus-visible:outline-foreground"
122 aria-label={`View cited assistant text: ${label}`}
123 >
124 <QuoteIcon aria-hidden="true" />
125 <ContextChipLabel className="max-w-[16em]">{label}</ContextChipLabel>
126 </Link>
127 );
128 if (!composer) {
129 return (
130 <ContextChipPopover
131 kind="citation"
132 icon={<QuoteIcon />}
133 label={label}
134 accessibleLabel={`Quoted assistant text: ${label}`}
135 copyMarkdown={serializeAssistantCitation(citation)}
136 >
137 <div className="flex max-h-[calc(var(--available-height)_-_1rem_-_2px)] flex-col items-start gap-3 p-1 text-sm">
138 <AssistantCitationQuote citation={citation} />
139 <PopoverClose
140 render={<Button variant="outline" size="sm" render={<Link {...sourceLinkProps} />} />}
141 >
142 <ArrowUpRightIcon aria-hidden="true" />
143 Go to source
144 </PopoverClose>
145 </div>
146 </ContextChipPopover>
147 );
148 }
149 return (
150 <ContextChip
151 kind="citation"
152 contentEditable={false}
153 data-assistant-citation-chip="true"
154 data-markdown-copy={serializeAssistantCitation(citation)}
155 >
156 {composerSourceLink}
157 {commentEditor ? (
158 <Popover
159 open={commentEditor.open}
160 onOpenChange={(open, eventDetails) => {
161 if (!open && !settleDraftOnClose(eventDetails.reason)) {
162 eventDetails.cancel();
163 return;
164 }
165 commentEditor.onOpenChange(open);
166 }}
167 >
168 <PopoverTrigger
169 aria-label={citation.comment ? "Edit citation comment" : "Add comment to citation"}
170 data-citation-comment-trigger="true"
171 render={<ContextChipAction />}
172 >
173 <PencilIcon aria-hidden="true" />
174 </PopoverTrigger>
175 {commentEditor.open ? (
176 <PopoverPopup
177 {...composerFloatingLayerProps}
178 side={activeSourceAnchor ? "bottom" : "top"}
179 align="end"
180 anchor={popupAnchor}
181 initialFocus={() => {
182 commentInputRef.current?.focus({ preventScroll: true });
183 return false;
184 }}
185 finalFocus={
186 commentEditor.onRestoreFocus
187 ? () => {
188 // Leave focus alone when the user closed the popover by moving to another control.
189 const activeElement = document.activeElement;
190 if (
191 activeElement === document.body ||
192 (activeElement !== null && commentPopupRef.current?.contains(activeElement))
193 ) {
194 commentEditor.onRestoreFocus?.();
195 }
196 return false;
197 }
198 : undefined
199 }
200 ref={commentPopupRef}
201 aria-label="Edit citation comment"
202 width="md"
203 padding="compact"
204 onPointerDown={(event) => event.stopPropagation()}
205 >
206 <AssistantCitationCommentEditor
207 key={serializeAssistantCitation(citation)}
208 citation={citation}
209 inputRef={commentInputRef}
210 onDraftChange={(comment) => {
211 draftCommentRef.current = comment;
212 }}
213 onSubmit={(comment) => {
214 if (!commentEditor.onSave(comment)) return false;
215 commentEditor.onOpenChange(false);
216 return true;
217 }}
218 {...(commentEditor.onSaveAndSend
219 ? {
220 onSubmitAndSend: (comment: string) => {
221 if (!commentEditor.onSaveAndSend?.(comment)) return false;
222 commentEditor.onOpenChange(false);
223 return true;
224 },
225 }
226 : {})}
227 onCancel={() => {
228 if (commentEditor.onCancel) {
229 commentEditor.onCancel();
230 } else {
231 commentEditor.onOpenChange(false);
232 }
233 }}
234 />
235 </PopoverPopup>
236 ) : null}
237 </Popover>
238 ) : null}
239 </ContextChip>
240 );
241}
242
243function AssistantCitationQuote({ citation }: { citation: AssistantCitation }) {
244 const [fade, setFade] = useState({ top: false, bottom: false });
245 const updateFade = (element: HTMLElement) => {
246 const top = element.scrollTop > 1;
247 const bottom = element.scrollHeight - element.clientHeight - element.scrollTop > 1;
248 setFade((current) =>
249 current.top === top && current.bottom === bottom ? current : { top, bottom },
250 );
251 };
252 return (
253 <div
254 ref={(element) => {
255 if (!element) return;
256 const observer = new ResizeObserver(() => updateFade(element));
257 observer.observe(element);
258 return () => observer.disconnect();
259 }}
260 onScroll={(event) => updateFade(event.currentTarget)}
261 className={cn(
262 "max-h-64 min-h-0 space-y-3 self-stretch overflow-y-auto whitespace-pre-wrap wrap-break-word",
263 getVirtualizedScrollFadeClassName(fade),
264 )}
265 >
266 <blockquote className="border-l-2 border-border pl-3 text-muted-foreground">
267 {citation.text}
268 </blockquote>
269 {citation.comment ? <p>{citation.comment}</p> : null}
270 </div>
271 );
272}