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

AssistantCitationChip.tsx

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