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 useCallback,
10 useEffect,
11 useEffectEvent,
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";
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 useEffect(() => {
64 if (!commentOpen) draftCommentRef.current = null;
65 }, [commentOpen]);
66 const settleDraftOnClose = (reason: string): boolean => {
67 const dismissal = resolveAssistantCitationCommentDismissal({
68 reason,
69 draft: draftCommentRef.current,
70 savedComment: citation.comment,
71 });
72 if (dismissal.kind === "commit") return commentEditor?.onSave(dismissal.comment) ?? true;
73 return dismissal.kind !== "keep-open";
74 };
75 const onSourceUnavailable = useEffectEvent(() => {
76 if (!sourceAnchor) return;
77 if (settleDraftOnClose("none")) {
78 commentEditor?.onOpenChange(false);
79 } else {
80 setUnavailableSourceAnchor(sourceAnchor);
81 }
82 });
83 useEffect(() => {
84 if (!commentOpen || sourceAnchor === unavailableSourceAnchor) return;
85 const anchor = sourceAnchor ?? findAssistantCitationSourceAnchor(document, citation);
86 if (!anchor) return;
87 return observeAssistantCitationCommentSource({
88 anchor,
89 citation,
90 onUnavailable: onSourceUnavailable,
91 });
92 }, [citation, commentOpen, sourceAnchor, unavailableSourceAnchor]);
93 const popupAnchor = activeSourceAnchor
94 ? {
95 contextElement: activeSourceAnchor.source,
96 getBoundingClientRect: () => {
97 const rects = activeSourceAnchor.range.getClientRects();
98 return rects.item(rects.length - 1) ?? activeSourceAnchor.range.getBoundingClientRect();
99 },
100 }
101 : undefined;
102 const label = assistantCitationLabel(citation);
103 const sourceLinkProps = {
104 to: "/$environmentId/$threadId" as const,
105 params: { environmentId: citation.environmentId, threadId: citation.threadId },
106 hash: assistantCitationHash(citation),
107 "data-markdown-copy": serializeAssistantCitation(citation),
108 resetScroll: false,
109 onClick: (event: ReactMouseEvent<HTMLAnchorElement>) => {
110 if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
111 return;
112 }
113 event.preventDefault();
114 void navigate(assistantCitationNavigation(citation));
115 },
116 };
117 const composerSourceLink = (
118 <Link
119 {...sourceLinkProps}
120 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"
121 aria-label={`View cited assistant text: ${label}`}
122 >
123 <QuoteIcon aria-hidden="true" />
124 <ContextChipLabel className="max-w-[16em]">{label}</ContextChipLabel>
125 </Link>
126 );
127 if (!composer) {
128 return (
129 <ContextChipPopover
130 kind="citation"
131 icon={<QuoteIcon />}
132 label={label}
133 accessibleLabel={`Quoted assistant text: ${label}`}
134 copyMarkdown={serializeAssistantCitation(citation)}
135 >
136 <div className="flex max-h-[calc(var(--available-height)_-_1rem_-_2px)] flex-col items-start gap-3 p-1 text-sm">
137 <AssistantCitationQuote citation={citation} />
138 <PopoverClose
139 render={<Button variant="outline" size="sm" render={<Link {...sourceLinkProps} />} />}
140 >
141 <ArrowUpRightIcon aria-hidden="true" />
142 Go to source
143 </PopoverClose>
144 </div>
145 </ContextChipPopover>
146 );
147 }
148 return (
149 <ContextChip
150 kind="citation"
151 contentEditable={false}
152 data-assistant-citation-chip="true"
153 data-markdown-copy={serializeAssistantCitation(citation)}
154 >
155 {composerSourceLink}
156 {commentEditor ? (
157 <Popover
158 open={commentEditor.open}
159 onOpenChange={(open, eventDetails) => {
160 if (!open && !settleDraftOnClose(eventDetails.reason)) {
161 eventDetails.cancel();
162 return;
163 }
164 commentEditor.onOpenChange(open);
165 }}
166 >
167 <PopoverTrigger
168 aria-label={citation.comment ? "Edit citation comment" : "Add comment to citation"}
169 data-citation-comment-trigger="true"
170 render={<ContextChipAction />}
171 >
172 <PencilIcon aria-hidden="true" />
173 </PopoverTrigger>
174 {commentEditor.open ? (
175 <PopoverPopup
176 {...composerFloatingLayerProps}
177 side={activeSourceAnchor ? "bottom" : "top"}
178 align="end"
179 anchor={popupAnchor}
180 initialFocus={() => {
181 commentInputRef.current?.focus({ preventScroll: true });
182 return false;
183 }}
184 finalFocus={
185 commentEditor.onRestoreFocus
186 ? () => {
187 const activeElement = document.activeElement;
188 if (
189 activeElement === document.body ||
190 (activeElement !== null && commentPopupRef.current?.contains(activeElement))
191 ) {
192 commentEditor.onRestoreFocus?.();
193 }
194 return false;
195 }
196 : undefined
197 }
198 ref={commentPopupRef}
199 aria-label="Edit citation comment"
200 width="md"
201 padding="compact"
202 onPointerDown={(event) => event.stopPropagation()}
203 >
204 <AssistantCitationCommentEditor
205 key={serializeAssistantCitation(citation)}
206 citation={citation}
207 inputRef={commentInputRef}
208 onDraftChange={(comment) => {
209 draftCommentRef.current = comment;
210 commentEditor.onDraftChange?.(comment);
211 }}
212 onSubmit={(comment) => {
213 if (!commentEditor.onSave(comment)) return false;
214 commentEditor.onOpenChange(false);
215 return true;
216 }}
217 {...(commentEditor.onSaveAndSend
218 ? {
219 onSubmitAndSend: (comment: string) => {
220 if (!commentEditor.onSaveAndSend?.(comment)) return false;
221 commentEditor.onOpenChange(false);
222 return true;
223 },
224 }
225 : {})}
226 onCancel={() => {
227 if (commentEditor.onCancel) {
228 commentEditor.onCancel();
229 } else {
230 commentEditor.onOpenChange(false);
231 }
232 }}
233 />
234 </PopoverPopup>
235 ) : null}
236 </Popover>
237 ) : null}
238 </ContextChip>
239 );
240}
241
242function AssistantCitationQuote({ citation }: { citation: AssistantCitation }) {
243 const [fade, setFade] = useState({ top: false, bottom: false });
244 const updateFade = useCallback((element: HTMLElement) => {
245 const top = element.scrollTop > 1;
246 const bottom = element.scrollHeight - element.clientHeight - element.scrollTop > 1;
247 setFade((current) =>
248 current.top === top && current.bottom === bottom ? current : { top, bottom },
249 );
250 }, []);
251 const observeFade = useCallback(
252 (element: HTMLDivElement | null) =>
253 element ? observeResize(element, () => updateFade(element)) : undefined,
254 [updateFade],
255 );
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}