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 useLayoutEffect,
12 useRef,
13 useState,
14 type MouseEvent as ReactMouseEvent,
15} from "react";
16import {
17 findAssistantCitationSourceAnchor,
18 type AssistantCitationSourceAnchor,
19} from "~/lib/assistantTextSelection";
20import {
21 assistantCitationHash,
22 assistantCitationNavigation,
23} from "../../lib/assistantCitationNavigation";
24import { cn } from "~/lib/utils";
25import { ContextChip, ContextChipAction, ContextChipLabel } from "../ContextChip";
26import { ContextChipPopover } from "../contextChipParts";
27import { Button } from "../ui/button";
28import { Popover, PopoverClose, PopoverPopup, PopoverTrigger } from "../ui/popover";
29import { getVirtualizedScrollFadeClassName } from "../ui/scroll-area";
30import { AssistantCitationCommentEditor } from "./AssistantCitationCommentEditor";
31import { resolveAssistantCitationCommentDismissal } from "./assistantCitationCommentDismissal";
32import { observeAssistantCitationCommentSource } from "./AssistantCitationSource";
33import { composerFloatingLayerProps } from "./composerEventScope";
34import { observeResize } from "~/lib/observeResize";
35import { assistantCitationAnchorRect } from "~/lib/assistantCitationPosition";
36
37export function AssistantCitationChip({
38 citation,
39 composer = false,
40 commentEditor,
41}: {
42 citation: AssistantCitation;
43 composer?: boolean;
44 commentEditor?: {
45 open: boolean;
46 sourceAnchor?: AssistantCitationSourceAnchor | undefined;
47 onOpenChange: (open: boolean) => void;
48 onCancel?: () => void;
49 onSave: (comment: string) => boolean;
50 onSaveAndSend?: (comment: string) => boolean;
51 onDraftChange?: (comment: string) => void;
52 onRestoreFocus?: () => void;
53 };
54}) {
55 const navigate = useNavigate();
56 const commentInputRef = useRef<HTMLTextAreaElement>(null);
57 const commentPopupRef = useRef<HTMLDivElement>(null);
58 const draftCommentRef = useRef<string | null>(null);
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 const boundary = activeSourceAnchor?.boundary;
65 const [boundaryRect, setBoundaryRect] = useState<
66 { element: HTMLElement; rect: Pick<DOMRect, "x" | "y" | "width" | "height"> } | undefined
67 >();
68 useLayoutEffect(() => {
69 if (!commentOpen || !boundary) return;
70 return observeResize(boundary, () => {
71 // Base UI compares rect values; resizing the same boundary element does not reposition it.
72 const { x, y, width, height } = boundary.getBoundingClientRect();
73 setBoundaryRect({ element: boundary, rect: { x, y, width, height } });
74 });
75 }, [commentOpen, boundary]);
76 useEffect(() => {
77 if (!commentOpen) draftCommentRef.current = null;
78 }, [commentOpen]);
79 const settleDraftOnClose = (reason: string): boolean => {
80 const dismissal = resolveAssistantCitationCommentDismissal({
81 reason,
82 draft: draftCommentRef.current,
83 savedComment: citation.comment,
84 });
85 if (dismissal.kind === "commit") return commentEditor?.onSave(dismissal.comment) ?? true;
86 return dismissal.kind !== "keep-open";
87 };
88 const onSourceUnavailable = useEffectEvent(() => {
89 if (!sourceAnchor) return;
90 if (settleDraftOnClose("none")) {
91 commentEditor?.onOpenChange(false);
92 } else {
93 setUnavailableSourceAnchor(sourceAnchor);
94 }
95 });
96 useEffect(() => {
97 if (!commentOpen || sourceAnchor === unavailableSourceAnchor) return;
98 const anchor = sourceAnchor ?? findAssistantCitationSourceAnchor(document, citation);
99 if (!anchor) return;
100 return observeAssistantCitationCommentSource({
101 anchor,
102 citation,
103 onUnavailable: onSourceUnavailable,
104 });
105 }, [citation, commentOpen, sourceAnchor, unavailableSourceAnchor]);
106 const popupAnchor = activeSourceAnchor
107 ? {
108 contextElement: activeSourceAnchor.source,
109 getBoundingClientRect: () => assistantCitationAnchorRect(activeSourceAnchor),
110 }
111 : undefined;
112 const label = assistantCitationLabel(citation);
113 const sourceLinkProps = {
114 to: "/$environmentId/$threadId" as const,
115 params: { environmentId: citation.environmentId, threadId: citation.threadId },
116 hash: assistantCitationHash(citation),
117 "data-markdown-copy": serializeAssistantCitation(citation),
118 resetScroll: false,
119 onClick: (event: ReactMouseEvent<HTMLAnchorElement>) => {
120 if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
121 return;
122 }
123 event.preventDefault();
124 void navigate(assistantCitationNavigation(citation));
125 },
126 };
127 const composerSourceLink = (
128 <Link
129 {...sourceLinkProps}
130 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"
131 aria-label={`View cited assistant text: ${label}`}
132 >
133 <QuoteIcon aria-hidden="true" />
134 <ContextChipLabel className="max-w-[16em]">{label}</ContextChipLabel>
135 </Link>
136 );
137 if (!composer) {
138 return (
139 <ContextChipPopover
140 kind="citation"
141 icon={<QuoteIcon />}
142 label={label}
143 accessibleLabel={`Quoted assistant text: ${label}`}
144 copyMarkdown={serializeAssistantCitation(citation)}
145 >
146 <div className="flex max-h-[calc(var(--available-height)_-_1rem_-_2px)] flex-col items-start gap-3 p-1 text-sm">
147 <AssistantCitationQuote citation={citation} />
148 <PopoverClose
149 render={<Button variant="outline" size="sm" render={<Link {...sourceLinkProps} />} />}
150 >
151 <ArrowUpRightIcon aria-hidden="true" />
152 Go to source
153 </PopoverClose>
154 </div>
155 </ContextChipPopover>
156 );
157 }
158 return (
159 <ContextChip
160 kind="citation"
161 contentEditable={false}
162 data-assistant-citation-chip="true"
163 data-markdown-copy={serializeAssistantCitation(citation)}
164 >
165 {composerSourceLink}
166 {commentEditor ? (
167 <Popover
168 open={commentEditor.open}
169 onOpenChange={(open, eventDetails) => {
170 if (!open && !settleDraftOnClose(eventDetails.reason)) {
171 eventDetails.cancel();
172 return;
173 }
174 commentEditor.onOpenChange(open);
175 }}
176 >
177 <PopoverTrigger
178 aria-label={citation.comment ? "Edit citation comment" : "Add comment to citation"}
179 data-citation-comment-trigger="true"
180 render={<ContextChipAction />}
181 >
182 <PencilIcon aria-hidden="true" />
183 </PopoverTrigger>
184 {commentEditor.open ? (
185 <PopoverPopup
186 {...composerFloatingLayerProps}
187 side={activeSourceAnchor ? "bottom" : "top"}
188 align="end"
189 anchor={popupAnchor}
190 sticky={Boolean(popupAnchor)}
191 collisionBoundary={
192 popupAnchor
193 ? boundaryRect?.element === boundary
194 ? boundaryRect?.rect
195 : boundary
196 : undefined
197 }
198 initialFocus={() => {
199 commentInputRef.current?.focus({ preventScroll: true });
200 return false;
201 }}
202 finalFocus={
203 commentEditor.onRestoreFocus
204 ? () => {
205 const activeElement = document.activeElement;
206 if (
207 activeElement === document.body ||
208 (activeElement !== null && commentPopupRef.current?.contains(activeElement))
209 ) {
210 commentEditor.onRestoreFocus?.();
211 }
212 return false;
213 }
214 : undefined
215 }
216 ref={commentPopupRef}
217 aria-label="Edit citation comment"
218 width="md"
219 padding="compact"
220 onPointerDown={(event) => event.stopPropagation()}
221 >
222 <AssistantCitationCommentEditor
223 key={serializeAssistantCitation(citation)}
224 citation={citation}
225 inputRef={commentInputRef}
226 onDraftChange={(comment) => {
227 draftCommentRef.current = comment;
228 commentEditor.onDraftChange?.(comment);
229 }}
230 onSubmit={(comment) => {
231 if (!commentEditor.onSave(comment)) return false;
232 commentEditor.onOpenChange(false);
233 return true;
234 }}
235 {...(commentEditor.onSaveAndSend
236 ? {
237 onSubmitAndSend: (comment: string) => {
238 if (!commentEditor.onSaveAndSend?.(comment)) return false;
239 commentEditor.onOpenChange(false);
240 return true;
241 },
242 }
243 : {})}
244 onCancel={() => {
245 if (commentEditor.onCancel) {
246 commentEditor.onCancel();
247 } else {
248 commentEditor.onOpenChange(false);
249 }
250 }}
251 />
252 </PopoverPopup>
253 ) : null}
254 </Popover>
255 ) : null}
256 </ContextChip>
257 );
258}
259
260function AssistantCitationQuote({ citation }: { citation: AssistantCitation }) {
261 const [fade, setFade] = useState({ top: false, bottom: false });
262 const updateFade = (element: HTMLElement) => {
263 const top = element.scrollTop > 1;
264 const bottom = element.scrollHeight - element.clientHeight - element.scrollTop > 1;
265 setFade((current) =>
266 current.top === top && current.bottom === bottom ? current : { top, bottom },
267 );
268 };
269 const observeFade = (element: HTMLDivElement | null) =>
270 element ? observeResize(element, () => updateFade(element)) : undefined;
271 return (
272 <div
273 ref={observeFade}
274 onScroll={(event) => updateFade(event.currentTarget)}
275 className={cn(
276 "max-h-64 min-h-0 space-y-3 self-stretch overflow-y-auto whitespace-pre-wrap wrap-break-word",
277 getVirtualizedScrollFadeClassName(fade),
278 )}
279 >
280 <blockquote className="border-l-2 border-border pl-3 text-muted-foreground">
281 {citation.text}
282 </blockquote>
283 {citation.comment ? <p>{citation.comment}</p> : null}
284 </div>
285 );
286}