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

AssistantCitationChip.tsx

212 lines8.0 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 {
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 };
43}) {
44 const navigate = useNavigate();
45 const commentInputRef = useRef<HTMLTextAreaElement>(null);
46 const draftCommentRef = useRef<string | null>(null);
47 const [unavailableSourceAnchor, setUnavailableSourceAnchor] =
48 useState<AssistantCitationSourceAnchor | null>(null);
49 const commentOpen = commentEditor?.open ?? false;
50 const sourceAnchor = commentEditor?.sourceAnchor;
51 const activeSourceAnchor = sourceAnchor === unavailableSourceAnchor ? undefined : sourceAnchor;
52 useEffect(() => {
53 if (!commentOpen) draftCommentRef.current = null;
54 }, [commentOpen]);
55 const settleDraftOnClose = (reason: string): boolean => {
56 const dismissal = resolveAssistantCitationCommentDismissal({
57 reason,
58 draft: draftCommentRef.current,
59 savedComment: citation.comment,
60 });
61 if (dismissal.kind === "commit") return commentEditor?.onSave(dismissal.comment) ?? true;
62 return dismissal.kind !== "keep-open";
63 };
64 const onSourceUnavailable = useEffectEvent(() => {
65 if (!sourceAnchor) return;
66 if (settleDraftOnClose("none")) {
67 commentEditor?.onOpenChange(false);
68 } else {
69 // Keep the draft mounted, positioned at the composer trigger instead of a detached range.
70 setUnavailableSourceAnchor(sourceAnchor);
71 }
72 });
73 useEffect(() => {
74 if (!commentOpen || sourceAnchor === unavailableSourceAnchor) return;
75 const anchor = sourceAnchor ?? findAssistantCitationSourceAnchor(document, citation);
76 if (!anchor) return;
77 return observeAssistantCitationCommentSource({
78 anchor,
79 citation,
80 onUnavailable: onSourceUnavailable,
81 });
82 }, [citation, commentOpen, sourceAnchor, unavailableSourceAnchor]);
83 // A multi-line selection's bounding box spans the full message width; anchor
84 // the bubble to the selection's last line, where the pointer released.
85 const popupAnchor = activeSourceAnchor
86 ? {
87 contextElement: activeSourceAnchor.source,
88 getBoundingClientRect: () => {
89 const rects = activeSourceAnchor.range.getClientRects();
90 return rects.item(rects.length - 1) ?? activeSourceAnchor.range.getBoundingClientRect();
91 },
92 }
93 : undefined;
94 const preview = (citation.comment?.trim() || citation.text).replace(/\s+/g, " ");
95 const label = preview.length > 64 ? `${preview.slice(0, 64)}…` : preview;
96 const sourceLinkProps = {
97 to: "/$environmentId/$threadId" as const,
98 params: { environmentId: citation.environmentId, threadId: citation.threadId },
99 hash: assistantCitationHash(citation),
100 "data-markdown-copy": serializeAssistantCitation(citation),
101 resetScroll: false,
102 onClick: (event: ReactMouseEvent<HTMLAnchorElement>) => {
103 if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
104 return;
105 }
106 event.preventDefault();
107 void navigate(assistantCitationNavigation(citation));
108 },
109 };
110 const composerSourceLink = (
111 <Link
112 {...sourceLinkProps}
113 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"
114 aria-label={`View cited assistant text: ${label}`}
115 >
116 <QuoteIcon aria-hidden="true" />
117 <ContextChipLabel className="max-w-[16em]">{label}</ContextChipLabel>
118 </Link>
119 );
120 const chatSourceLink = (
121 <Link
122 {...sourceLinkProps}
123 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"
124 aria-label={`View cited assistant text: ${label}`}
125 >
126 <QuoteIcon aria-hidden="true" />
127 <ContextChipLabel className="max-w-[16em]">{label}</ContextChipLabel>
128 </Link>
129 );
130 return (
131 <ContextChip
132 kind="citation"
133 contentEditable={false}
134 data-assistant-citation-chip="true"
135 data-markdown-copy={serializeAssistantCitation(citation)}
136 >
137 {composer ? (
138 composerSourceLink
139 ) : (
140 <Tooltip>
141 <TooltipTrigger render={chatSourceLink} />
142 <TooltipPopup side="top">View source</TooltipPopup>
143 </Tooltip>
144 )}
145 {commentEditor ? (
146 <Popover
147 open={commentEditor.open}
148 onOpenChange={(open, eventDetails) => {
149 if (!open && !settleDraftOnClose(eventDetails.reason)) {
150 eventDetails.cancel();
151 return;
152 }
153 commentEditor.onOpenChange(open);
154 }}
155 >
156 <PopoverTrigger
157 aria-label={citation.comment ? "Edit citation comment" : "Add comment to citation"}
158 render={<ContextChipAction />}
159 >
160 <PencilIcon aria-hidden="true" />
161 </PopoverTrigger>
162 {commentEditor.open ? (
163 <PopoverPopup
164 {...composerFloatingLayerProps}
165 side={activeSourceAnchor ? "bottom" : "top"}
166 align="end"
167 anchor={popupAnchor}
168 initialFocus={() => {
169 commentInputRef.current?.focus({ preventScroll: true });
170 return false;
171 }}
172 aria-label="Edit citation comment"
173 width="md"
174 padding="compact"
175 onPointerDown={(event) => event.stopPropagation()}
176 >
177 <AssistantCitationCommentEditor
178 key={serializeAssistantCitation(citation)}
179 citation={citation}
180 inputRef={commentInputRef}
181 onDraftChange={(comment) => {
182 draftCommentRef.current = comment;
183 }}
184 onSubmit={(comment) => {
185 if (!commentEditor.onSave(comment)) return false;
186 commentEditor.onOpenChange(false);
187 return true;
188 }}
189 {...(commentEditor.onSaveAndSend
190 ? {
191 onSubmitAndSend: (comment: string) => {
192 if (!commentEditor.onSaveAndSend?.(comment)) return false;
193 commentEditor.onOpenChange(false);
194 return true;
195 },
196 }
197 : {})}
198 onCancel={() => {
199 if (commentEditor.onCancel) {
200 commentEditor.onCancel();
201 } else {
202 commentEditor.onOpenChange(false);
203 }
204 }}
205 />
206 </PopoverPopup>
207 ) : null}
208 </Popover>
209 ) : null}
210 </ContextChip>
211 );