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

AssistantCitationChip.tsx

295 lines11.6 KB

1import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2import type { AssistantCitation } from "@t3tools/contracts";
3import {
4 assistantCitationLabel,
5 serializeAssistantCitation,
6} from "@t3tools/shared/assistantCitations";
7import { Link, useNavigate } from "@tanstack/react-router";
8import { ArrowUpRightIcon, PencilIcon, QuoteIcon } from "lucide-react";
9import {
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 assistantCitationNavigation,
22 assistantCitationRoute,
23} from "../../lib/assistantCitationNavigation";
24import { cn } from "~/lib/utils";
25import { useQuietThreadShell } from "~/state/entities";
26import { ContextChip, ContextChipAction, ContextChipLabel } from "../ContextChip";
27import { ContextChipPopover } from "../contextChipParts";
28import { Button } from "../ui/button";
29import { Popover, PopoverClose, PopoverPopup, PopoverTrigger } from "../ui/popover";
30import { getVirtualizedScrollFadeClassName } from "../ui/scroll-area";
31import { AssistantCitationCommentEditor } from "./AssistantCitationCommentEditor";
32import { resolveAssistantCitationCommentDismissal } from "./assistantCitationCommentDismissal";
33import { observeAssistantCitationCommentSource } from "./AssistantCitationSource";
34import { composerFloatingLayerProps } from "./composerEventScope";
35import { observeResize } from "~/lib/observeResize";
36import { textDirection } from "~/textDirection";
37​
38export function AssistantCitationChip({
39 citation,
40 composer = false,
41 commentEditor,
42}: {
43 citation: AssistantCitation;
44 composer?: boolean;
45 commentEditor?: {
46 open: boolean;
47 sourceAnchor?: AssistantCitationSourceAnchor | undefined;
48 onOpenChange: (open: boolean) => void;
49 onCancel?: () => void;
50 onSave: (comment: string) => boolean;
51 onSaveAndSend?: (comment: string) => boolean;
52 onDraftChange?: (comment: string) => void;
53 onRestoreFocus?: () => void;
54 };
55}) {
56 const navigate = useNavigate();
57 const sourceThread = useQuietThreadShell(
58 scopeThreadRef(citation.environmentId, citation.threadId),
59 );
60 const commentInputRef = useRef<HTMLTextAreaElement>(null);
61 const commentPopupRef = useRef<HTMLDivElement>(null);
62 const draftCommentRef = useRef<string | null>(null);
63 const [voiceSetupOpen, setVoiceSetupOpen] = useState(false);
64 const [unavailableSourceAnchor, setUnavailableSourceAnchor] =
65 useState<AssistantCitationSourceAnchor | null>(null);
66 const commentOpen = commentEditor?.open ?? false;
67 const sourceAnchor = commentEditor?.sourceAnchor;
68 const activeSourceAnchor = sourceAnchor === unavailableSourceAnchor ? undefined : sourceAnchor;
69 // 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
70 useEffect(() => {
71 if (!commentOpen) draftCommentRef.current = null;
72 }, [commentOpen]);
73 const settleDraftOnClose = (reason: string): boolean => {
74 const dismissal = resolveAssistantCitationCommentDismissal({
75 reason,
76 draft: draftCommentRef.current,
77 savedComment: citation.comment,
78 });
79 if (dismissal.kind === "commit") return commentEditor?.onSave(dismissal.comment) ?? true;
80 return dismissal.kind !== "keep-open";
81 };
82 const onSourceUnavailable = useEffectEvent(() => {
83 if (!sourceAnchor) return;
84 if (settleDraftOnClose("none")) {
85 commentEditor?.onOpenChange(false);
86 } else {
87 setUnavailableSourceAnchor(sourceAnchor);
88 }
89 });
90 // 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
91 useEffect(() => {
92 if (!commentOpen || sourceAnchor === unavailableSourceAnchor) return;
93 const anchor = sourceAnchor ?? findAssistantCitationSourceAnchor(document, citation);
94 if (!anchor) return;
95 return observeAssistantCitationCommentSource({
96 anchor,
97 citation,
98 onUnavailable: onSourceUnavailable,
99 });
100 }, [citation, commentOpen, sourceAnchor, unavailableSourceAnchor]);
101 const popupAnchor = activeSourceAnchor
102 ? {
103 contextElement: activeSourceAnchor.source,
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 ...assistantCitationRoute(citation, sourceThread),
121 "data-markdown-copy": serializeAssistantCitation(citation),
122 onClick: (event: ReactMouseEvent<HTMLAnchorElement>) => {
123 if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
124 return;
125 }
126 event.preventDefault();
127 void navigate(assistantCitationNavigation(citation, sourceThread));
128 },
129 };
130 const composerSourceLink = (
131 <Link
132 {...sourceLinkProps}
133 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"
134 aria-label={`View cited assistant text: ${label}`}
135 >
136 <QuoteIcon aria-hidden="true" />
137 <ContextChipLabel className="max-w-[16em]" dir={textDirection(label)}>
138 {label}
139 </ContextChipLabel>
140 </Link>
141 );
142 if (!composer) {
143 return (
144 <ContextChipPopover
145 kind="citation"
146 icon={<QuoteIcon />}
147 label={label}
148 accessibleLabel={`Quoted assistant text: ${label}`}
149 copyMarkdown={serializeAssistantCitation(citation)}
150 >
151 <div className="flex max-h-[calc(var(--available-height)_-_1rem_-_2px)] flex-col items-start gap-3 p-1 text-sm">
152 <AssistantCitationQuote citation={citation} />
153 <PopoverClose
154 render={<Button variant="outline" size="sm" render={<Link {...sourceLinkProps} />} />}
155 >
156 <ArrowUpRightIcon aria-hidden="true" />
157 Go to source
158 </PopoverClose>
159 </div>
160 </ContextChipPopover>
161 );
162 }
163 return (
164 <ContextChip
165 kind="citation"
166 contentEditable={false}
167 data-assistant-citation-chip="true"
168 data-markdown-copy={serializeAssistantCitation(citation)}
169 >
170 {composerSourceLink}
171 {commentEditor ? (
172 <Popover
173 open={commentEditor.open && !voiceSetupOpen}
174 onOpenChange={(open, eventDetails) => {
175 if (!open && !settleDraftOnClose(eventDetails.reason)) {
176 eventDetails.cancel();
177 return;
178 }
179 commentEditor.onOpenChange(open);
180 }}
181 >
182 <PopoverTrigger
183 aria-label={citation.comment ? "Edit citation comment" : "Add comment to citation"}
184 data-citation-comment-trigger="true"
185 render={<ContextChipAction />}
186 >
187 <PencilIcon aria-hidden="true" />
188 </PopoverTrigger>
189 {commentEditor.open ? (
190 <PopoverPopup
191 // The editor stays mounted while its voice setup dialog replaces the popover.
192 keepMounted
193 {...composerFloatingLayerProps}
194 side={activeSourceAnchor ? "bottom" : "top"}
195 align="end"
196 anchor={popupAnchor}
197 initialFocus={() => {
198 const input = commentInputRef.current;
199 if (input) {
200 input.focus({ preventScroll: true });
201 input.setSelectionRange(input.value.length, input.value.length);
202 // Moving the caret doesn't scroll a long comment to it.
203 input.scrollTop = input.scrollHeight;
204 }
205 return false;
206 }}
207 finalFocus={
208 commentEditor.onRestoreFocus
209 ? () => {
210 const activeElement = document.activeElement;
211 if (
212 activeElement === document.body ||
213 (activeElement !== null && commentPopupRef.current?.contains(activeElement))
214 ) {
215 commentEditor.onRestoreFocus?.();
216 }
217 return false;
218 }
219 : undefined
220 }
221 ref={commentPopupRef}
222 aria-label="Edit citation comment"
223 width="md"
224 padding="compact"
225 onPointerDown={(event) => event.stopPropagation()}
226 >
227 <AssistantCitationCommentEditor
228 key={serializeAssistantCitation(citation)}
229 citation={citation}
230 inputRef={commentInputRef}
231 onVoiceSetupOpenChange={setVoiceSetupOpen}
232 onDraftChange={(comment) => {
233 draftCommentRef.current = comment;
234 commentEditor.onDraftChange?.(comment);
235 }}
236 onSubmit={(comment) => {
237 if (!commentEditor.onSave(comment)) return false;
238 commentEditor.onOpenChange(false);
239 return true;
240 }}
241 {...(commentEditor.onSaveAndSend
242 ? {
243 onSubmitAndSend: (comment: string) => {
244 if (!commentEditor.onSaveAndSend?.(comment)) return false;
245 commentEditor.onOpenChange(false);
246 return true;
247 },
248 }
249 : {})}
250 onCancel={() => {
251 if (commentEditor.onCancel) {
252 commentEditor.onCancel();
253 } else {
254 commentEditor.onOpenChange(false);
255 }
256 }}
257 />
258 </PopoverPopup>
259 ) : null}
260 </Popover>
261 ) : null}
262 </ContextChip>
263 );
265​
266function AssistantCitationQuote({ citation }: { citation: AssistantCitation }) {
267 const [fade, setFade] = useState({ top: false, bottom: false });
268 const updateFade = (element: HTMLElement) => {
269 const top = element.scrollTop > 1;
270 const bottom = element.scrollHeight - element.clientHeight - element.scrollTop > 1;
271 setFade((current) =>
272 current.top === top && current.bottom === bottom ? current : { top, bottom },
273 );
274 };
275 const observeFade = (element: HTMLDivElement | null) =>
276 element ? observeResize(element, () => updateFade(element)) : undefined;
277 return (
278 <div
279 ref={observeFade}
280 onScroll={(event) => updateFade(event.currentTarget)}
281 className={cn(
282 "max-h-64 min-h-0 space-y-3 self-stretch overflow-y-auto whitespace-pre-wrap wrap-break-word",
283 getVirtualizedScrollFadeClassName(fade),
284 )}
285 >
286 <blockquote
287 className="border-l-2 border-border pl-3 text-muted-foreground"
288 dir={textDirection(citation.text)}
289 >
290 {citation.text}
291 </blockquote>
292 {citation.comment ? <p dir={textDirection(citation.comment)}>{citation.comment}</p> : null}
293 </div>
294 );