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