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

AssistantCitationChip.tsx

228 lines8.8 KB

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 { cn } from "~/lib/utils";
17import {
18 assistantCitationHash,
19 assistantCitationNavigation,
20} from "../../lib/assistantCitationNavigation";
21import {
22 CHAT_INLINE_CHIP_CLASS_NAME,
23 COMPOSER_INLINE_CHIP_CLASS_NAME,
24 COMPOSER_INLINE_CHIP_DISMISS_BUTTON_CLASS_NAME,
25 COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
26 COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
27 CONTEXT_INLINE_CHIP_TONE_CLASS_NAMES,
28} from "../composerInlineChip";
29import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
30import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
31import { AssistantCitationCommentEditor } from "./AssistantCitationCommentEditor";
32import { resolveAssistantCitationCommentDismissal } from "./assistantCitationCommentDismissal";
33import { observeAssistantCitationCommentSource } from "./AssistantCitationSource";
34import { composerFloatingLayerProps } from "./composerEventScope";
35​
36const CITATION_ACTION_BUTTON_CLASS_NAME = cn(
37 COMPOSER_INLINE_CHIP_DISMISS_BUTTON_CLASS_NAME,
38 "text-current hover:bg-[color-mix(in_oklab,var(--context-chip-accent)_17%,transparent)] hover:text-current",
39);
40​
41export function AssistantCitationChip({
42 citation,
43 composer = false,
44 commentEditor,
45}: {
46 citation: AssistantCitation;
47 composer?: boolean;
48 commentEditor?: {
49 open: boolean;
50 sourceAnchor?: AssistantCitationSourceAnchor | undefined;
51 onOpenChange: (open: boolean) => void;
52 onCancel?: () => void;
53 onSave: (comment: string) => boolean;
54 onSaveAndSend?: (comment: string) => boolean;
55 };
56}) {
57 const navigate = useNavigate();
58 const commentInputRef = useRef<HTMLTextAreaElement>(null);
59 const draftCommentRef = useRef<string | null>(null);
60 const [unavailableSourceAnchor, setUnavailableSourceAnchor] =
61 useState<AssistantCitationSourceAnchor | null>(null);
62 const commentOpen = commentEditor?.open ?? false;
63 const sourceAnchor = commentEditor?.sourceAnchor;
64 const activeSourceAnchor = sourceAnchor === unavailableSourceAnchor ? undefined : sourceAnchor;
65 useEffect(() => {
66 if (!commentOpen) draftCommentRef.current = null;
67 }, [commentOpen]);
68 const settleDraftOnClose = (reason: string): boolean => {
69 const dismissal = resolveAssistantCitationCommentDismissal({
70 reason,
71 draft: draftCommentRef.current,
72 savedComment: citation.comment,
73 });
74 if (dismissal.kind === "commit") return commentEditor?.onSave(dismissal.comment) ?? true;
75 return dismissal.kind !== "keep-open";
76 };
77 const onSourceUnavailable = useEffectEvent(() => {
78 if (!sourceAnchor) return;
79 if (settleDraftOnClose("none")) {
80 commentEditor?.onOpenChange(false);
81 } else {
82 // Keep the draft mounted, positioned at the composer trigger instead of a detached range.
83 setUnavailableSourceAnchor(sourceAnchor);
84 }
85 });
86 useEffect(() => {
87 if (!commentOpen || sourceAnchor === unavailableSourceAnchor) return;
88 const anchor = sourceAnchor ?? findAssistantCitationSourceAnchor(document, citation);
89 if (!anchor) return;
90 return observeAssistantCitationCommentSource({
91 anchor,
92 citation,
93 onUnavailable: onSourceUnavailable,
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 getBoundingClientRect: () => {
102 const rects = activeSourceAnchor.range.getClientRects();
103 return rects.item(rects.length - 1) ?? activeSourceAnchor.range.getBoundingClientRect();
104 },
105 }
106 : undefined;
107 const preview = (citation.comment?.trim() || citation.text).replace(/\s+/g, " ");
108 const label = preview.length > 64 ? `${preview.slice(0, 64)}…` : preview;
109 const sourceLinkProps = {
110 to: "/$environmentId/$threadId" as const,
111 params: { environmentId: citation.environmentId, threadId: citation.threadId },
112 hash: assistantCitationHash(citation),
113 "data-markdown-copy": serializeAssistantCitation(citation),
114 resetScroll: false,
115 onClick: (event: ReactMouseEvent<HTMLAnchorElement>) => {
116 if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
117 return;
118 }
119 event.preventDefault();
120 void navigate(assistantCitationNavigation(citation));
121 },
122 };
123 const composerSourceLink = (
124 <Link
125 {...sourceLinkProps}
126 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-[var(--contrast-foreground)]"
127 aria-label={`View cited assistant text: ${label}`}
128 >
129 <QuoteIcon aria-hidden="true" className={COMPOSER_INLINE_CHIP_ICON_CLASS_NAME} />
130 <span className={cn(COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME, "max-w-[16em]")}>{label}</span>
131 </Link>
132 );
133 const chatSourceLink = (
134 <Link
135 {...sourceLinkProps}
136 className="inline-flex h-full min-w-0 items-center gap-[0.33em] rounded-sm text-inherit no-underline hover:bg-[color-mix(in_oklab,var(--context-chip-accent)_17%,transparent)] focus-visible:outline-2 focus-visible:outline-[var(--contrast-foreground)]"
137 aria-label={`View cited assistant text: ${label}`}
138 >
139 <QuoteIcon aria-hidden="true" className={COMPOSER_INLINE_CHIP_ICON_CLASS_NAME} />
140 <span className={cn(COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME, "max-w-[16em]")}>{label}</span>
141 </Link>
142 );
143 return (
144 <span
145 className={cn(
146 composer ? COMPOSER_INLINE_CHIP_CLASS_NAME : CHAT_INLINE_CHIP_CLASS_NAME,
147 CONTEXT_INLINE_CHIP_TONE_CLASS_NAMES.citation,
148 )}
149 contentEditable={false}
150 data-assistant-citation-chip="true"
151 data-markdown-copy={serializeAssistantCitation(citation)}
152 >
153 {composer ? (
154 composerSourceLink
155 ) : (
156 <Tooltip>
157 <TooltipTrigger render={chatSourceLink} />
158 <TooltipPopup side="top">View source</TooltipPopup>
159 </Tooltip>
160 )}
161 {commentEditor ? (
162 <Popover
163 open={commentEditor.open}
164 onOpenChange={(open, eventDetails) => {
165 if (!open && !settleDraftOnClose(eventDetails.reason)) {
166 eventDetails.cancel();
167 return;
168 }
169 commentEditor.onOpenChange(open);
170 }}
171 >
172 <PopoverTrigger
173 aria-label={citation.comment ? "Edit citation comment" : "Add comment to citation"}
174 className={CITATION_ACTION_BUTTON_CLASS_NAME}
175 >
176 <PencilIcon aria-hidden="true" className="size-[0.85em]" />
177 </PopoverTrigger>
178 {commentEditor.open ? (
179 <PopoverPopup
180 {...composerFloatingLayerProps}
181 side={activeSourceAnchor ? "bottom" : "top"}
182 align="end"
183 anchor={popupAnchor}
184 initialFocus={() => {
185 commentInputRef.current?.focus({ preventScroll: true });
186 return false;
187 }}
188 aria-label="Edit citation comment"
189 width="md"
190 viewportClassName="p-3"
191 onPointerDown={(event) => event.stopPropagation()}
192 >
193 <AssistantCitationCommentEditor
194 key={serializeAssistantCitation(citation)}
195 citation={citation}
196 inputRef={commentInputRef}
197 onDraftChange={(comment) => {
198 draftCommentRef.current = comment;
199 }}
200 onSubmit={(comment) => {
201 if (!commentEditor.onSave(comment)) return false;
202 commentEditor.onOpenChange(false);
203 return true;
204 }}
205 {...(commentEditor.onSaveAndSend
206 ? {
207 onSubmitAndSend: (comment: string) => {
208 if (!commentEditor.onSaveAndSend?.(comment)) return false;
209 commentEditor.onOpenChange(false);
210 return true;
211 },
212 }
213 : {})}
214 onCancel={() => {
215 if (commentEditor.onCancel) {
216 commentEditor.onCancel();
217 } else {
218 commentEditor.onOpenChange(false);
219 }
220 }}
221 />
222 </PopoverPopup>
223 ) : null}
224 </Popover>
225 ) : null}
226 </span>
227 );