Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AssistantCitationChip.tsx

275 lines10.4 KB

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 const rect =
98 rects.item(rects.length - 1) ?? activeSourceAnchor.range.getBoundingClientRect();
99 // Code blocks and tables scroll sideways inside the message, so the cited
100 // text can end in their hidden overflow. Base UI only shifts the popup while
101 // it still touches the anchor, so clamp the anchor to the message's width.
102 const bounds = activeSourceAnchor.source.getBoundingClientRect();
103 const left = Math.min(Math.max(rect.left, bounds.left), bounds.right);
104 const right = Math.max(Math.min(rect.right, bounds.right), left);
105 return new DOMRect(left, rect.top, right - left, rect.height);
106 },
107 }
108 : undefined;
109 const label = assistantCitationLabel(citation);
110 const sourceLinkProps = {
111 to: "/$environmentId/$threadId" as const,
112 params: { environmentId: citation.environmentId, threadId: citation.threadId },
113 hash: assistantCitationHash(citation),
114 "data-markdown-copy": serializeAssistantCitation(citation),
115 resetScroll: false,
116 onClick: (event: ReactMouseEvent<HTMLAnchorElement>) => {
117 if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
118 return;
119 }
120 event.preventDefault();
121 void navigate(assistantCitationNavigation(citation));
122 },
123 };
124 const composerSourceLink = (
125 <Link
126 {...sourceLinkProps}
127 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"
128 aria-label={`View cited assistant text: ${label}`}
129 >
130 <QuoteIcon aria-hidden="true" />
131 <ContextChipLabel className="max-w-[16em]">{label}</ContextChipLabel>
132 </Link>
133 );
134 if (!composer) {
135 return (
136 <ContextChipPopover
137 kind="citation"
138 icon={<QuoteIcon />}
139 label={label}
140 accessibleLabel={`Quoted assistant text: ${label}`}
141 copyMarkdown={serializeAssistantCitation(citation)}
142 >
143 <div className="flex max-h-[calc(var(--available-height)_-_1rem_-_2px)] flex-col items-start gap-3 p-1 text-sm">
144 <AssistantCitationQuote citation={citation} />
145 <PopoverClose
146 render={<Button variant="outline" size="sm" render={<Link {...sourceLinkProps} />} />}
147 >
148 <ArrowUpRightIcon aria-hidden="true" />
149 Go to source
150 </PopoverClose>
151 </div>
152 </ContextChipPopover>
153 );
154 }
155 return (
156 <ContextChip
157 kind="citation"
158 contentEditable={false}
159 data-assistant-citation-chip="true"
160 data-markdown-copy={serializeAssistantCitation(citation)}
161 >
162 {composerSourceLink}
163 {commentEditor ? (
164 <Popover
165 open={commentEditor.open}
166 onOpenChange={(open, eventDetails) => {
167 if (!open && !settleDraftOnClose(eventDetails.reason)) {
168 eventDetails.cancel();
169 return;
170 }
171 commentEditor.onOpenChange(open);
172 }}
173 >
174 <PopoverTrigger
175 aria-label={citation.comment ? "Edit citation comment" : "Add comment to citation"}
176 data-citation-comment-trigger="true"
177 render={<ContextChipAction />}
178 >
179 <PencilIcon aria-hidden="true" />
180 </PopoverTrigger>
181 {commentEditor.open ? (
182 <PopoverPopup
183 {...composerFloatingLayerProps}
184 side={activeSourceAnchor ? "bottom" : "top"}
185 align="end"
186 anchor={popupAnchor}
187 initialFocus={() => {
188 commentInputRef.current?.focus({ preventScroll: true });
189 return false;
190 }}
191 finalFocus={
192 commentEditor.onRestoreFocus
193 ? () => {
194 const activeElement = document.activeElement;
195 if (
196 activeElement === document.body ||
197 (activeElement !== null && commentPopupRef.current?.contains(activeElement))
198 ) {
199 commentEditor.onRestoreFocus?.();
200 }
201 return false;
202 }
203 : undefined
204 }
205 ref={commentPopupRef}
206 aria-label="Edit citation comment"
207 width="md"
208 padding="compact"
209 onPointerDown={(event) => event.stopPropagation()}
210 >
211 <AssistantCitationCommentEditor
212 key={serializeAssistantCitation(citation)}
213 citation={citation}
214 inputRef={commentInputRef}
215 onDraftChange={(comment) => {
216 draftCommentRef.current = comment;
217 commentEditor.onDraftChange?.(comment);
218 }}
219 onSubmit={(comment) => {
220 if (!commentEditor.onSave(comment)) return false;
221 commentEditor.onOpenChange(false);
222 return true;
223 }}
224 {...(commentEditor.onSaveAndSend
225 ? {
226 onSubmitAndSend: (comment: string) => {
227 if (!commentEditor.onSaveAndSend?.(comment)) return false;
228 commentEditor.onOpenChange(false);
229 return true;
230 },
231 }
232 : {})}
233 onCancel={() => {
234 if (commentEditor.onCancel) {
235 commentEditor.onCancel();
236 } else {
237 commentEditor.onOpenChange(false);
238 }
239 }}
240 />
241 </PopoverPopup>
242 ) : null}
243 </Popover>
244 ) : null}
245 </ContextChip>
246 );
248​
249function AssistantCitationQuote({ citation }: { citation: AssistantCitation }) {
250 const [fade, setFade] = useState({ top: false, bottom: false });
251 const updateFade = (element: HTMLElement) => {
252 const top = element.scrollTop > 1;
253 const bottom = element.scrollHeight - element.clientHeight - element.scrollTop > 1;
254 setFade((current) =>
255 current.top === top && current.bottom === bottom ? current : { top, bottom },
256 );
257 };
258 const observeFade = (element: HTMLDivElement | null) =>
259 element ? observeResize(element, () => updateFade(element)) : undefined;
260 return (
261 <div
262 ref={observeFade}
263 onScroll={(event) => updateFade(event.currentTarget)}
264 className={cn(
265 "max-h-64 min-h-0 space-y-3 self-stretch overflow-y-auto whitespace-pre-wrap wrap-break-word",
266 getVirtualizedScrollFadeClassName(fade),
267 )}
268 >
269 <blockquote className="border-l-2 border-border pl-3 text-muted-foreground">
270 {citation.text}
271 </blockquote>
272 {citation.comment ? <p>{citation.comment}</p> : null}
273 </div>
274 );