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