Open History to see the last commit
1import type { AssistantCitation } from "@t3tools/contracts";
2import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations";
3import { Link, useNavigate } from "@tanstack/react-router";
4import { PencilIcon, QuoteIcon } from "lucide-react";
5import {
6 useEffect,
7 useEffectEvent,
8 useRef,
9 useState,
10 type MouseEvent as ReactMouseEvent,
11} from "react";
12import {
13 findAssistantCitationSourceAnchor,
14 type AssistantCitationSourceAnchor,
15} from "~/lib/assistantTextSelection";
16import {
17 assistantCitationHash,
18 assistantCitationNavigation,
19} from "../../lib/assistantCitationNavigation";
20import { ContextChip, ContextChipAction, ContextChipLabel } from "../ContextChip";
21import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
22import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
23import { AssistantCitationCommentEditor } from "./AssistantCitationCommentEditor";
24import { resolveAssistantCitationCommentDismissal } from "./assistantCitationCommentDismissal";
25import { observeAssistantCitationCommentSource } from "./AssistantCitationSource";
26import { composerFloatingLayerProps } from "./composerEventScope";
27
28export function AssistantCitationChip({
29 citation,
30 composer = false,
31 commentEditor,
32}: {
33 citation: AssistantCitation;
34 composer?: boolean;
35 commentEditor?: {
36 open: boolean;
37 sourceAnchor?: AssistantCitationSourceAnchor | undefined;
38 onOpenChange: (open: boolean) => void;
39 onCancel?: () => void;
40 onSave: (comment: string) => boolean;
41 onSaveAndSend?: (comment: string) => boolean;
42 /** Returns focus to the host editor when the popover closes instead of to the pencil trigger. */
43 onRestoreFocus?: () => void;
44 };
45}) {
46 const navigate = useNavigate();
47 const commentInputRef = useRef<HTMLTextAreaElement>(null);
48 const commentPopupRef = useRef<HTMLDivElement>(null);
49 const draftCommentRef = useRef<string | null>(null);
50 const [unavailableSourceAnchor, setUnavailableSourceAnchor] =
51 useState<AssistantCitationSourceAnchor | null>(null);
52 const commentOpen = commentEditor?.open ?? false;
53 const sourceAnchor = commentEditor?.sourceAnchor;
54 const activeSourceAnchor = sourceAnchor === unavailableSourceAnchor ? undefined : sourceAnchor;
55 useEffect(() => {
56 if (!commentOpen) draftCommentRef.current = null;
57 }, [commentOpen]);
58 const settleDraftOnClose = (reason: string): boolean => {
59 const dismissal = resolveAssistantCitationCommentDismissal({
60 reason,
61 draft: draftCommentRef.current,
62 savedComment: citation.comment,
63 });
64 if (dismissal.kind === "commit") return commentEditor?.onSave(dismissal.comment) ?? true;
65 return dismissal.kind !== "keep-open";
66 };
67 const onSourceUnavailable = useEffectEvent(() => {
68 if (!sourceAnchor) return;
69 if (settleDraftOnClose("none")) {
70 commentEditor?.onOpenChange(false);
71 } else {
72 // Keep the draft mounted, positioned at the composer trigger instead of a detached range.
73 setUnavailableSourceAnchor(sourceAnchor);
74 }
75 });
76 useEffect(() => {
77 if (!commentOpen || sourceAnchor === unavailableSourceAnchor) return;
78 const anchor = sourceAnchor ?? findAssistantCitationSourceAnchor(document, citation);
79 if (!anchor) return;
80 return observeAssistantCitationCommentSource({
81 anchor,
82 citation,
83 onUnavailable: onSourceUnavailable,
84 });
85 }, [citation, commentOpen, sourceAnchor, unavailableSourceAnchor]);
86 // A multi-line selection's bounding box spans the full message width; anchor
87 // the bubble to the selection's last line, where the pointer released.
88 const popupAnchor = activeSourceAnchor
89 ? {
90 contextElement: activeSourceAnchor.source,
91 getBoundingClientRect: () => {
92 const rects = activeSourceAnchor.range.getClientRects();
93 return rects.item(rects.length - 1) ?? activeSourceAnchor.range.getBoundingClientRect();
94 },
95 }
96 : undefined;
97 const preview = (citation.comment?.trim() || citation.text).replace(/\s+/g, " ");
98 const label = preview.length > 64 ? `${preview.slice(0, 64)}…` : preview;
99 const sourceLinkProps = {
100 to: "/$environmentId/$threadId" as const,
101 params: { environmentId: citation.environmentId, threadId: citation.threadId },
102 hash: assistantCitationHash(citation),
103 "data-markdown-copy": serializeAssistantCitation(citation),
104 resetScroll: false,
105 onClick: (event: ReactMouseEvent<HTMLAnchorElement>) => {
106 if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
107 return;
108 }
109 event.preventDefault();
110 void navigate(assistantCitationNavigation(citation));
111 },
112 };
113 const composerSourceLink = (
114 <Link
115 {...sourceLinkProps}
116 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"
117 aria-label={`View cited assistant text: ${label}`}
118 >
119 <QuoteIcon aria-hidden="true" />
120 <ContextChipLabel className="max-w-[16em]">{label}</ContextChipLabel>
121 </Link>
122 );
123 const chatSourceLink = (
124 <Link
125 {...sourceLinkProps}
126 className="inline-flex h-full min-w-0 items-center gap-[0.33em] rounded-sm text-inherit no-underline hover:bg-(--context-chip-accent)/17 focus-visible:outline-2 focus-visible:outline-foreground"
127 aria-label={`View cited assistant text: ${label}`}
128 >
129 <QuoteIcon aria-hidden="true" />
130 <ContextChipLabel className="max-w-[16em]">{label}</ContextChipLabel>
131 </Link>
132 );
133 return (
134 <ContextChip
135 kind="citation"
136 contentEditable={false}
137 data-assistant-citation-chip="true"
138 data-markdown-copy={serializeAssistantCitation(citation)}
139 >
140 {composer ? (
141 composerSourceLink
142 ) : (
143 <Tooltip>
144 <TooltipTrigger render={chatSourceLink} />
145 <TooltipPopup side="top">View source</TooltipPopup>
146 </Tooltip>
147 )}
148 {commentEditor ? (
149 <Popover
150 open={commentEditor.open}
151 onOpenChange={(open, eventDetails) => {
152 if (!open && !settleDraftOnClose(eventDetails.reason)) {
153 eventDetails.cancel();
154 return;
155 }
156 commentEditor.onOpenChange(open);
157 }}
158 >
159 <PopoverTrigger
160 aria-label={citation.comment ? "Edit citation comment" : "Add comment to citation"}
161 data-citation-comment-trigger="true"
162 render={<ContextChipAction />}
163 >
164 <PencilIcon aria-hidden="true" />
165 </PopoverTrigger>
166 {commentEditor.open ? (
167 <PopoverPopup
168 {...composerFloatingLayerProps}
169 side={activeSourceAnchor ? "bottom" : "top"}
170 align="end"
171 anchor={popupAnchor}
172 initialFocus={() => {
173 commentInputRef.current?.focus({ preventScroll: true });
174 return false;
175 }}
176 finalFocus={
177 commentEditor.onRestoreFocus
178 ? () => {
179 // Leave focus alone when the user closed the popover by moving to another control.
180 const activeElement = document.activeElement;
181 if (
182 activeElement === document.body ||
183 (activeElement !== null && commentPopupRef.current?.contains(activeElement))
184 ) {
185 commentEditor.onRestoreFocus?.();
186 }
187 return false;
188 }
189 : undefined
190 }
191 ref={commentPopupRef}
192 aria-label="Edit citation comment"
193 width="md"
194 padding="compact"
195 onPointerDown={(event) => event.stopPropagation()}
196 >
197 <AssistantCitationCommentEditor
198 key={serializeAssistantCitation(citation)}
199 citation={citation}
200 inputRef={commentInputRef}
201 onDraftChange={(comment) => {
202 draftCommentRef.current = comment;
203 }}
204 onSubmit={(comment) => {
205 if (!commentEditor.onSave(comment)) return false;
206 commentEditor.onOpenChange(false);
207 return true;
208 }}
209 {...(commentEditor.onSaveAndSend
210 ? {
211 onSubmitAndSend: (comment: string) => {
212 if (!commentEditor.onSaveAndSend?.(comment)) return false;
213 commentEditor.onOpenChange(false);
214 return true;
215 },
216 }
217 : {})}
218 onCancel={() => {
219 if (commentEditor.onCancel) {
220 commentEditor.onCancel();
221 } else {
222 commentEditor.onOpenChange(false);
223 }
224 }}
225 />
226 </PopoverPopup>
227 ) : null}
228 </Popover>
229 ) : null}
230 </ContextChip>
231 );
232}