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 [unavailableSourceAnchor, setUnavailableSourceAnchor] =
59 useState<AssistantCitationSourceAnchor | null>(null);
60 const commentOpen = commentEditor?.open ?? false;
61 const sourceAnchor = commentEditor?.sourceAnchor;
62 const activeSourceAnchor = sourceAnchor === unavailableSourceAnchor ? undefined : sourceAnchor;
63 // 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
64 useEffect(() => {
65 if (!commentOpen) draftCommentRef.current = null;
66 }, [commentOpen]);
67 const settleDraftOnClose = (reason: string): boolean => {
68 const dismissal = resolveAssistantCitationCommentDismissal({
69 reason,
70 draft: draftCommentRef.current,
71 savedComment: citation.comment,
72 });
73 if (dismissal.kind === "commit") return commentEditor?.onSave(dismissal.comment) ?? true;
74 return dismissal.kind !== "keep-open";
75 };
76 const onSourceUnavailable = useEffectEvent(() => {
77 if (!sourceAnchor) return;
78 if (settleDraftOnClose("none")) {
79 commentEditor?.onOpenChange(false);
80 } else {
81 setUnavailableSourceAnchor(sourceAnchor);
82 }
83 });
84 // 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
85 useEffect(() => {
86 if (!commentOpen || sourceAnchor === unavailableSourceAnchor) return;
87 const anchor = sourceAnchor ?? findAssistantCitationSourceAnchor(document, citation);
88 if (!anchor) return;
89 return observeAssistantCitationCommentSource({
90 anchor,
91 citation,
92 onUnavailable: onSourceUnavailable,
93 });
94 }, [citation, commentOpen, sourceAnchor, unavailableSourceAnchor]);
95 const popupAnchor = activeSourceAnchor
96 ? {
97 contextElement: activeSourceAnchor.source,
98 getBoundingClientRect: () => {
99 const rects = activeSourceAnchor.range.getClientRects();
100 const rect =
101 rects.item(rects.length - 1) ?? activeSourceAnchor.range.getBoundingClientRect();
102 // Code blocks and tables scroll sideways inside the message, so the cited
103 // text can end in their hidden overflow. Base UI only shifts the popup while
104 // it still touches the anchor, so clamp the anchor to the message's width.
105 const bounds = activeSourceAnchor.source.getBoundingClientRect();
106 const left = Math.min(Math.max(rect.left, bounds.left), bounds.right);
107 const right = Math.max(Math.min(rect.right, bounds.right), left);
108 return new DOMRect(left, rect.top, right - left, rect.height);
109 },
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 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"
131 aria-label={`View cited assistant text: ${label}`}
132 >
133 <QuoteIcon aria-hidden="true" />
134 <ContextChipLabel className="max-w-[16em]" dir={textDirection(label)}>
135 {label}
136 </ContextChipLabel>
137 </Link>
138 );
139 if (!composer) {
140 return (
141 <ContextChipPopover
142 kind="citation"
143 icon={<QuoteIcon />}
144 label={label}
145 accessibleLabel={`Quoted assistant text: ${label}`}
146 copyMarkdown={serializeAssistantCitation(citation)}
147 >
148 <div className="flex max-h-[calc(var(--available-height)_-_1rem_-_2px)] flex-col items-start gap-3 p-1 text-sm">
149 <AssistantCitationQuote citation={citation} />
150 <PopoverClose
151 render={<Button variant="outline" size="sm" render={<Link {...sourceLinkProps} />} />}
152 >
153 <ArrowUpRightIcon aria-hidden="true" />
154 Go to source
155 </PopoverClose>
156 </div>
157 </ContextChipPopover>
158 );
159 }
160 return (
161 <ContextChip
162 kind="citation"
163 contentEditable={false}
164 data-assistant-citation-chip="true"
165 data-markdown-copy={serializeAssistantCitation(citation)}
166 >
167 {composerSourceLink}
168 {commentEditor ? (
169 <Popover
170 open={commentEditor.open}
171 onOpenChange={(open, eventDetails) => {
172 if (!open && !settleDraftOnClose(eventDetails.reason)) {
173 eventDetails.cancel();
174 return;
175 }
176 commentEditor.onOpenChange(open);
177 }}
178 >
179 <PopoverTrigger
180 aria-label={citation.comment ? "Edit citation comment" : "Add comment to citation"}
181 data-citation-comment-trigger="true"
182 render={<ContextChipAction />}
183 >
184 <PencilIcon aria-hidden="true" />
185 </PopoverTrigger>
186 {commentEditor.open ? (
187 <PopoverPopup
188 {...composerFloatingLayerProps}
189 side={activeSourceAnchor ? "bottom" : "top"}
190 align="end"
191 anchor={popupAnchor}
192 initialFocus={() => {
193 commentInputRef.current?.focus({ preventScroll: true });
194 return false;
195 }}
196 finalFocus={
197 commentEditor.onRestoreFocus
198 ? () => {
199 const activeElement = document.activeElement;
200 if (
201 activeElement === document.body ||
202 (activeElement !== null && commentPopupRef.current?.contains(activeElement))
203 ) {
204 commentEditor.onRestoreFocus?.();
205 }
206 return false;
207 }
208 : undefined
209 }
210 ref={commentPopupRef}
211 aria-label="Edit citation comment"
212 width="md"
213 padding="compact"
214 onPointerDown={(event) => event.stopPropagation()}
215 >
216 <AssistantCitationCommentEditor
217 key={serializeAssistantCitation(citation)}
218 citation={citation}
219 inputRef={commentInputRef}
220 onDraftChange={(comment) => {
221 draftCommentRef.current = comment;
222 commentEditor.onDraftChange?.(comment);
223 }}
224 onSubmit={(comment) => {
225 if (!commentEditor.onSave(comment)) return false;
226 commentEditor.onOpenChange(false);
227 return true;
228 }}
229 {...(commentEditor.onSaveAndSend
230 ? {
231 onSubmitAndSend: (comment: string) => {
232 if (!commentEditor.onSaveAndSend?.(comment)) return false;
233 commentEditor.onOpenChange(false);
234 return true;
235 },
236 }
237 : {})}
238 onCancel={() => {
239 if (commentEditor.onCancel) {
240 commentEditor.onCancel();
241 } else {
242 commentEditor.onOpenChange(false);
243 }
244 }}
245 />
246 </PopoverPopup>
247 ) : null}
248 </Popover>
249 ) : null}
250 </ContextChip>
251 );
252}
253
254function AssistantCitationQuote({ citation }: { citation: AssistantCitation }) {
255 const [fade, setFade] = useState({ top: false, bottom: false });
256 const updateFade = (element: HTMLElement) => {
257 const top = element.scrollTop > 1;
258 const bottom = element.scrollHeight - element.clientHeight - element.scrollTop > 1;
259 setFade((current) =>
260 current.top === top && current.bottom === bottom ? current : { top, bottom },
261 );
262 };
263 const observeFade = (element: HTMLDivElement | null) =>
264 element ? observeResize(element, () => updateFade(element)) : undefined;
265 return (
266 <div
267 ref={observeFade}
268 onScroll={(event) => updateFade(event.currentTarget)}
269 className={cn(
270 "max-h-64 min-h-0 space-y-3 self-stretch overflow-y-auto whitespace-pre-wrap wrap-break-word",
271 getVirtualizedScrollFadeClassName(fade),
272 )}
273 >
274 <blockquote
275 className="border-l-2 border-border pl-3 text-muted-foreground"
276 dir={textDirection(citation.text)}
277 >
278 {citation.text}
279 </blockquote>
280 {citation.comment ? <p dir={textDirection(citation.comment)}>{citation.comment}</p> : null}
281 </div>
282 );
283}