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

AssistantCitationChip.tsx

284 lines11.3 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 const [sourcePositionRevision, setSourcePositionRevision] = useState(0);
63 // 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
64 useEffect(() => {
65 if (!commentOpen) draftCommentRef.current = null;
66 }, [commentOpen]);
67 const settleDraftOnClose = (reason: string): boolean => {
68 const dismissal = resolveAssistantCitationCommentDismissal({
69 reason,
70 draft: draftCommentRef.current,
71 savedComment: citation.comment,
72 });
73 if (dismissal.kind === "commit") return commentEditor?.onSave(dismissal.comment) ?? true;
74 return dismissal.kind !== "keep-open";
75 };
76 const onSourceUnavailable = useEffectEvent(() => {
77 if (!sourceAnchor) return;
78 if (settleDraftOnClose("none")) {
79 commentEditor?.onOpenChange(false);
80 } else {
81 setUnavailableSourceAnchor(sourceAnchor);
82 }
83 });
84 // 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
85 useEffect(() => {
86 if (!commentOpen || sourceAnchor === unavailableSourceAnchor) return;
87 const anchor = sourceAnchor ?? findAssistantCitationSourceAnchor(document, citation);
88 if (!anchor) return;
89 return observeAssistantCitationCommentSource({
90 anchor,
91 citation,
92 onUnavailable: onSourceUnavailable,
93 onPositionChange: () => setSourcePositionRevision((revision) => revision + 1),
94 });
95 }, [citation, commentOpen, sourceAnchor, unavailableSourceAnchor]);
96 // A multi-line selection's bounding box spans the full message width; anchor
97 // the bubble to the selection's last line, where the pointer released.
98 const popupAnchor = activeSourceAnchor
99 ? {
100 contextElement: activeSourceAnchor.source,
101 // Bridge range updates keep the same source anchor; the revision makes the
102 // compiler hand the popup a new virtual anchor so it repositions.
103 positionRevision: sourcePositionRevision,
104 getBoundingClientRect: () => {
105 const rects = activeSourceAnchor.range.getClientRects();
106 const rect =
107 rects.item(rects.length - 1) ?? activeSourceAnchor.range.getBoundingClientRect();
108 // Code blocks and tables scroll sideways inside the message, so the cited
109 // text can end in their hidden overflow. Base UI only shifts the popup while
110 // it still touches the anchor, so clamp the anchor to the message's width.
111 const bounds = activeSourceAnchor.source.getBoundingClientRect();
112 const left = Math.min(Math.max(rect.left, bounds.left), bounds.right);
113 const right = Math.max(Math.min(rect.right, bounds.right), left);
114 return new DOMRect(left, rect.top, right - left, rect.height);
115 },
116 }
117 : undefined;
118 const label = assistantCitationLabel(citation);
119 const sourceLinkProps = {
120 to: "/$environmentId/$threadId" as const,
121 params: { environmentId: citation.environmentId, threadId: citation.threadId },
122 hash: assistantCitationHash(citation),
123 "data-markdown-copy": serializeAssistantCitation(citation),
124 resetScroll: false,
125 onClick: (event: ReactMouseEvent<HTMLAnchorElement>) => {
126 if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
127 return;
128 }
129 event.preventDefault();
130 void navigate(assistantCitationNavigation(citation));
131 },
132 };
133 const composerSourceLink = (
134 <Link
135 {...sourceLinkProps}
136 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"
137 aria-label={`View cited assistant text: ${label}`}
138 >
139 <QuoteIcon aria-hidden="true" />
140 <ContextChipLabel className="max-w-[16em]">{label}</ContextChipLabel>
141 </Link>
142 );
143 if (!composer) {
144 return (
145 <ContextChipPopover
146 kind="citation"
147 icon={<QuoteIcon />}
148 label={label}
149 accessibleLabel={`Quoted assistant text: ${label}`}
150 copyMarkdown={serializeAssistantCitation(citation)}
151 >
152 <div className="flex max-h-[calc(var(--available-height)_-_1rem_-_2px)] flex-col items-start gap-3 p-1 text-sm">
153 <AssistantCitationQuote citation={citation} />
154 <PopoverClose
155 render={<Button variant="outline" size="sm" render={<Link {...sourceLinkProps} />} />}
156 >
157 <ArrowUpRightIcon aria-hidden="true" />
158 Go to source
159 </PopoverClose>
160 </div>
161 </ContextChipPopover>
162 );
163 }
164 return (
165 <ContextChip
166 kind="citation"
167 contentEditable={false}
168 data-assistant-citation-chip="true"
169 data-markdown-copy={serializeAssistantCitation(citation)}
170 >
171 {composerSourceLink}
172 {commentEditor ? (
173 <Popover
174 open={commentEditor.open}
175 onOpenChange={(open, eventDetails) => {
176 if (!open && !settleDraftOnClose(eventDetails.reason)) {
177 eventDetails.cancel();
178 return;
179 }
180 commentEditor.onOpenChange(open);
181 }}
182 >
183 <PopoverTrigger
184 aria-label={citation.comment ? "Edit citation comment" : "Add comment to citation"}
185 data-citation-comment-trigger="true"
186 render={<ContextChipAction />}
187 >
188 <PencilIcon aria-hidden="true" />
189 </PopoverTrigger>
190 {commentEditor.open ? (
191 <PopoverPopup
192 {...composerFloatingLayerProps}
193 side={activeSourceAnchor ? "bottom" : "top"}
194 align="end"
195 anchor={popupAnchor}
196 initialFocus={() => {
197 commentInputRef.current?.focus({ preventScroll: true });
198 return false;
199 }}
200 finalFocus={
201 commentEditor.onRestoreFocus
202 ? () => {
203 const activeElement = document.activeElement;
204 if (
205 activeElement === document.body ||
206 (activeElement !== null && commentPopupRef.current?.contains(activeElement))
207 ) {
208 commentEditor.onRestoreFocus?.();
209 }
210 return false;
211 }
212 : undefined
213 }
214 ref={commentPopupRef}
215 aria-label="Edit citation comment"
216 width="md"
217 padding="compact"
218 onPointerDown={(event) => event.stopPropagation()}
219 >
220 <AssistantCitationCommentEditor
221 key={serializeAssistantCitation(citation)}
222 citation={citation}
223 inputRef={commentInputRef}
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 );
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 className="border-l-2 border-border pl-3 text-muted-foreground">
279 {citation.text}
280 </blockquote>
281 {citation.comment ? <p>{citation.comment}</p> : null}
282 </div>
283 );