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

AssistantCitationChip.tsx

385 lines14.2 KB

1import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2import type { AssistantCitation, ResponseContextRecord } from "@t3tools/contracts";
3import {
4 assistantCitationLabel,
5 serializeAssistantCitation,
6} from "@t3tools/shared/assistantCitations";
7import { Link, useNavigate } from "@tanstack/react-router";
8import { useGT } from "gt-react";
9import { PencilIcon, QuoteIcon } from "lucide-react";
10import {
11 useEffect,
12 useEffectEvent,
13 useRef,
14 useState,
15 type MouseEvent as ReactMouseEvent,
16 type ReactNode,
17} from "react";
18import {
19 findAssistantCitationSourceAnchor,
20 type AssistantCitationSourceAnchor,
21} from "~/lib/assistantTextSelection";
22import {
23 assistantCitationNavigation,
24 assistantCitationRoute,
25} from "../../lib/assistantCitationNavigation";
26import { cn } from "~/lib/utils";
27import { useQuietThreadShell } from "~/state/entities";
28import { ContextChip, ContextChipAction, ContextChipLabel } from "../ContextChip";
29import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
30import {
31 AssistantCitationCommentEditor,
32 type AssistantCitationCommentDictation,
33} from "./AssistantCitationCommentEditor";
34import { resolveAssistantCitationCommentDismissal } from "./assistantCitationCommentDismissal";
35import { observeAssistantCitationCommentSource } from "./AssistantCitationSource";
36import { composerFloatingLayerProps } from "./composerEventScope";
37import { textDirection } from "~/textDirection";
38​
39function useCitationSourceLinkProps(citation: AssistantCitation) {
40 const navigate = useNavigate();
41 const sourceThread = useQuietThreadShell(
42 scopeThreadRef(citation.environmentId, citation.threadId),
43 );
44 return {
45 ...assistantCitationRoute(citation, sourceThread),
46 "data-markdown-copy": serializeAssistantCitation(citation),
47 onClick: (event: ReactMouseEvent<HTMLAnchorElement>) => {
48 if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
49 return;
50 }
51 event.preventDefault();
52 void navigate(assistantCitationNavigation(citation, sourceThread));
53 },
54 };
56​
57const flat = (text: string) => text.replace(/\s+/g, " ");
58​
59/**
60 * The card a response shows as inside a message. Clicking it goes to the source; a comment follows
61 * as text. `leading` and `trailing` say it starts or ends its block, which already has spacing.
62 */
63function ResponseCard({
64 citation,
65 copyMarkdown,
66 cardCopyMarkdown = copyMarkdown,
67 label,
68 title,
69 preview,
70 comment,
71 leading,
72 trailing,
73}: {
74 citation: AssistantCitation;
75 copyMarkdown: string;
76 cardCopyMarkdown?: string;
77 label: string;
78 title?: string | undefined;
79 preview: ReactNode;
80 comment?: string | undefined;
81 leading: boolean;
82 trailing: boolean;
83}) {
84 const linkProps = useCitationSourceLinkProps(citation);
85 return (
86 // One copy boundary for the card and its comment, so a copied card carries the comment once.
87 <span
88 data-markdown-copy={copyMarkdown}
89 className={cn("block", !leading && "mt-[0.65rem]", !trailing && "mb-[0.65rem]")}
90 >
91 <Link
92 {...linkProps}
93 // A selection inside the card's boundary copies the card here and the comment as text.
94 data-markdown-copy={cardCopyMarkdown}
95 // The response is findable in its own message; here it is clamped and mostly hidden.
96 data-thread-find-ignore
97 aria-label={label}
98 // The message's markdown styles colour and underline links; a card is neither.
99 className="block min-w-0 rounded-lg bg-black/10 px-2.5 py-1.5 text-start text-sm text-muted-foreground! no-underline! wrap-break-word hover:bg-black/14 focus-visible:outline-2 focus-visible:outline-ring dark:bg-black/35 dark:hover:bg-black/50"
100 >
101 {title ? (
102 <span className="block truncate text-xs font-medium text-foreground/80" dir="auto">
103 {title}
104 </span>
105 ) : null}
106 <span className="line-clamp-2" dir={textDirection(citation.text)}>
107 {preview}
108 </span>
109 </Link>
110 {comment ? (
111 <span className="mt-1.5 block whitespace-pre-wrap" dir={textDirection(comment)}>
112 {comment}
113 </span>
114 ) : null}
115 </span>
116 );
118​
119/** A passage quoted from a response, with its surrounding context and the user's comment. */
120export function AssistantCitationEmbed({
121 citation,
122 leading,
123 trailing,
124}: {
125 citation: AssistantCitation;
126 leading: boolean;
127 trailing: boolean;
128}) {
129 const gt = useGT();
130 const wholeResponse = citation.prefix === "" && citation.suffix === "";
131 const { comment, ...quoted } = citation;
132 return (
133 <ResponseCard
134 citation={citation}
135 copyMarkdown={serializeAssistantCitation(citation)}
136 cardCopyMarkdown={serializeAssistantCitation(quoted)}
137 label={gt("Go to quoted response: {label}", { label: assistantCitationLabel(quoted) })}
138 comment={comment}
139 leading={leading}
140 trailing={trailing}
141 preview={
142 wholeResponse ? (
143 flat(citation.text)
144 ) : (
145 <>
146 {citation.prefix ? `…${flat(citation.prefix)}` : null}
147 <mark className="rounded-sm bg-foreground/12 px-0.5 text-foreground">
148 {flat(citation.text)}
149 </mark>
150 {citation.suffix ? `${flat(citation.suffix)}…` : null}
151 </>
152 )
153 }
154 />
155 );
157​
158/** The response a message replies to: its subagents, when it had any, and how it starts. */
159export function ResponseReplyCard({
160 record,
161 copyMarkdown,
162 leading,
163 trailing,
164}: {
165 record: ResponseContextRecord;
166 copyMarkdown: string;
167 leading: boolean;
168 trailing: boolean;
169}) {
170 const gt = useGT();
171 return (
172 <ResponseCard
173 citation={record.citation}
174 copyMarkdown={copyMarkdown}
175 label={gt("Go to the response this replies to: {label}", { label: record.label })}
176 title={record.subagents?.map((subagent) => subagent.title).join(", ")}
177 preview={flat(record.citation.text)}
178 leading={leading}
179 trailing={trailing}
180 />
181 );
183​
184/** The citation chip in the composer, with its comment editor. */
185export function AssistantCitationChip({
186 citation,
187 commentEditor,
188}: {
189 citation: AssistantCitation;
190 commentEditor?: {
191 open: boolean;
192 sourceAnchor?: AssistantCitationSourceAnchor | undefined;
193 onOpenChange: (open: boolean) => void;
194 onCancel?: () => void;
195 onSave: (comment: string) => boolean;
196 onSaveAndSend?: (comment: string) => boolean;
197 onDraftChange?: (comment: string) => void;
198 onRestoreFocus?: () => void;
199 };
200}) {
201 const gt = useGT();
202 const sourceLinkProps = useCitationSourceLinkProps(citation);
203 const commentInputRef = useRef<HTMLTextAreaElement>(null);
204 const commentPopupRef = useRef<HTMLDivElement>(null);
205 const draftCommentRef = useRef<string | null>(null);
206 const dictationRef = useRef<AssistantCitationCommentDictation>(null);
207 const [voiceSetupOpen, setVoiceSetupOpen] = useState(false);
208 const [unavailableSourceAnchor, setUnavailableSourceAnchor] =
209 useState<AssistantCitationSourceAnchor | null>(null);
210 const commentOpen = commentEditor?.open ?? false;
211 const sourceAnchor = commentEditor?.sourceAnchor;
212 const activeSourceAnchor = sourceAnchor === unavailableSourceAnchor ? undefined : sourceAnchor;
213 // 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
214 useEffect(() => {
215 if (!commentOpen) draftCommentRef.current = null;
216 }, [commentOpen]);
217 const settleDraft = (reason: string): boolean => {
218 const dismissal = resolveAssistantCitationCommentDismissal({
219 reason,
220 draft: draftCommentRef.current,
221 savedComment: citation.comment,
222 });
223 if (dismissal.kind === "commit") return commentEditor?.onSave(dismissal.comment) ?? true;
224 return dismissal.kind !== "keep-open";
225 };
226 // Closing unmounts the editor, which would discard its dictation, so it stays open until that lands.
227 const settleDraftOnClose = (reason: string): boolean => {
228 const finishing =
229 reason !== "escape-key" &&
230 dictationRef.current?.finish((comment) => {
231 draftCommentRef.current = comment;
232 if (settleDraft(reason)) commentEditor?.onOpenChange(false);
233 });
234 return !finishing && settleDraft(reason);
235 };
236 // The timeline virtualizes rows, so a vanished source is routine; the user may still be typing.
237 const onSourceUnavailable = useEffectEvent(() => {
238 if (sourceAnchor) setUnavailableSourceAnchor(sourceAnchor);
239 });
240 // 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
241 useEffect(() => {
242 if (!commentOpen || sourceAnchor === unavailableSourceAnchor) return;
243 const anchor = sourceAnchor ?? findAssistantCitationSourceAnchor(document, citation);
244 if (!anchor) return;
245 return observeAssistantCitationCommentSource({
246 anchor,
247 citation,
248 onUnavailable: onSourceUnavailable,
249 });
250 }, [citation, commentOpen, sourceAnchor, unavailableSourceAnchor]);
251 const popupAnchor = activeSourceAnchor
252 ? {
253 contextElement: activeSourceAnchor.source,
254 getBoundingClientRect: () => {
255 const rects = activeSourceAnchor.range.getClientRects();
256 const rect =
257 rects.item(rects.length - 1) ?? activeSourceAnchor.range.getBoundingClientRect();
258 // Code blocks and tables scroll sideways inside the message, so the cited
259 // text can end in their hidden overflow. Base UI only shifts the popup while
260 // it still touches the anchor, so clamp the anchor to the message's width.
261 const bounds = activeSourceAnchor.source.getBoundingClientRect();
262 const left = Math.min(Math.max(rect.left, bounds.left), bounds.right);
263 const right = Math.max(Math.min(rect.right, bounds.right), left);
264 return new DOMRect(left, rect.top, right - left, rect.height);
265 },
266 }
267 : undefined;
268 const label = assistantCitationLabel(citation);
269 const composerSourceLink = (
270 <Link
271 {...sourceLinkProps}
272 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"
273 aria-label={gt("View cited assistant text: {label}", { label })}
274 >
275 <QuoteIcon aria-hidden="true" />
276 <ContextChipLabel className="max-w-[16em]" dir={textDirection(label)}>
277 {label}
278 </ContextChipLabel>
279 </Link>
280 );
281 return (
282 <ContextChip
283 kind="citation"
284 contentEditable={false}
285 data-assistant-citation-chip="true"
286 data-markdown-copy={serializeAssistantCitation(citation)}
287 >
288 {composerSourceLink}
289 {commentEditor ? (
290 <Popover
291 open={commentEditor.open && !voiceSetupOpen}
292 onOpenChange={(open, eventDetails) => {
293 if (!open && !settleDraftOnClose(eventDetails.reason)) {
294 eventDetails.cancel();
295 return;
296 }
297 commentEditor.onOpenChange(open);
298 }}
299 >
300 <PopoverTrigger
301 aria-label={
302 citation.comment ? gt("Edit citation comment") : gt("Add comment to citation")
303 }
304 data-citation-comment-trigger="true"
305 render={<ContextChipAction />}
306 >
307 <PencilIcon aria-hidden="true" />
308 </PopoverTrigger>
309 {commentEditor.open ? (
310 <PopoverPopup
311 // The editor stays mounted while its voice setup dialog replaces the popover.
312 keepMounted
313 {...composerFloatingLayerProps}
314 side={activeSourceAnchor ? "bottom" : "top"}
315 align="end"
316 anchor={popupAnchor}
317 initialFocus={() => {
318 const input = commentInputRef.current;
319 if (input) {
320 input.focus({ preventScroll: true });
321 input.setSelectionRange(input.value.length, input.value.length);
322 // Moving the caret doesn't scroll a long comment to it.
323 input.scrollTop = input.scrollHeight;
324 }
325 return false;
326 }}
327 finalFocus={
328 commentEditor.onRestoreFocus
329 ? () => {
330 const activeElement = document.activeElement;
331 if (
332 activeElement === document.body ||
333 (activeElement !== null && commentPopupRef.current?.contains(activeElement))
334 ) {
335 commentEditor.onRestoreFocus?.();
336 }
337 return false;
338 }
339 : undefined
340 }
341 ref={commentPopupRef}
342 aria-label={gt("Edit citation comment")}
343 width="md"
344 padding="compact"
345 onPointerDown={(event) => event.stopPropagation()}
346 >
347 <AssistantCitationCommentEditor
348 key={serializeAssistantCitation(citation)}
349 citation={citation}
350 inputRef={commentInputRef}
351 dictationRef={dictationRef}
352 onVoiceSetupOpenChange={setVoiceSetupOpen}
353 onDraftChange={(comment) => {
354 draftCommentRef.current = comment;
355 commentEditor.onDraftChange?.(comment);
356 }}
357 onSubmit={(comment) => {
358 if (!commentEditor.onSave(comment)) return false;
359 commentEditor.onOpenChange(false);
360 return true;
361 }}
362 {...(commentEditor.onSaveAndSend
363 ? {
364 onSubmitAndSend: (comment: string) => {
365 if (!commentEditor.onSaveAndSend?.(comment)) return false;
366 commentEditor.onOpenChange(false);
367 return true;
368 },
369 }
370 : {})}
371 onCancel={() => {
372 if (commentEditor.onCancel) {
373 commentEditor.onCancel();
374 } else {
375 commentEditor.onOpenChange(false);
376 }
377 }}
378 />
379 </PopoverPopup>
380 ) : null}
381 </Popover>
382 ) : null}
383 </ContextChip>
384 );