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 commentInputRef.current?.focus({ preventScroll: true });
197 return false;
198 }}
199 finalFocus={
200 commentEditor.onRestoreFocus
201 ? () => {
202 const activeElement = document.activeElement;
203 if (
204 activeElement === document.body ||
205 (activeElement !== null && commentPopupRef.current?.contains(activeElement))
206 ) {
207 commentEditor.onRestoreFocus?.();
208 }
209 return false;
210 }
211 : undefined
212 }
213 ref={commentPopupRef}
214 aria-label="Edit citation comment"
215 width="md"
216 padding="compact"
217 onPointerDown={(event) => event.stopPropagation()}
218 >
219 <AssistantCitationCommentEditor
220 key={serializeAssistantCitation(citation)}
221 citation={citation}
222 inputRef={commentInputRef}
223 onVoiceSetupOpenChange={setVoiceSetupOpen}
224 onDraftChange={(comment) => {
225 draftCommentRef.current = comment;
226 commentEditor.onDraftChange?.(comment);
227 }}
228 onSubmit={(comment) => {
229 if (!commentEditor.onSave(comment)) return false;
230 commentEditor.onOpenChange(false);
231 return true;
232 }}
233 {...(commentEditor.onSaveAndSend
234 ? {
235 onSubmitAndSend: (comment: string) => {
236 if (!commentEditor.onSaveAndSend?.(comment)) return false;
237 commentEditor.onOpenChange(false);
238 return true;
239 },
240 }
241 : {})}
242 onCancel={() => {
243 if (commentEditor.onCancel) {
244 commentEditor.onCancel();
245 } else {
246 commentEditor.onOpenChange(false);
247 }
248 }}
249 />
250 </PopoverPopup>
251 ) : null}
252 </Popover>
253 ) : null}
254 </ContextChip>
255 );
256}
257
258function AssistantCitationQuote({ citation }: { citation: AssistantCitation }) {
259 const [fade, setFade] = useState({ top: false, bottom: false });
260 const updateFade = (element: HTMLElement) => {
261 const top = element.scrollTop > 1;
262 const bottom = element.scrollHeight - element.clientHeight - element.scrollTop > 1;
263 setFade((current) =>
264 current.top === top && current.bottom === bottom ? current : { top, bottom },
265 );
266 };
267 const observeFade = (element: HTMLDivElement | null) =>
268 element ? observeResize(element, () => updateFade(element)) : undefined;
269 return (
270 <div
271 ref={observeFade}
272 onScroll={(event) => updateFade(event.currentTarget)}
273 className={cn(
274 "max-h-64 min-h-0 space-y-3 self-stretch overflow-y-auto whitespace-pre-wrap wrap-break-word",
275 getVirtualizedScrollFadeClassName(fade),
276 )}
277 >
278 <blockquote
279 className="border-l-2 border-border pl-3 text-muted-foreground"
280 dir={textDirection(citation.text)}
281 >
282 {citation.text}
283 </blockquote>
284 {citation.comment ? <p dir={textDirection(citation.comment)}>{citation.comment}</p> : null}
285 </div>
286 );
287}