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

AssistantCitationChip.tsx

192 lines7.4 KB

1import type { AssistantCitation } from "@t3tools/contracts";
2import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations";
3import { Link, useNavigate } from "@tanstack/react-router";
4import { PencilIcon, QuoteIcon, XIcon } from "lucide-react";
5import { useEffect, useEffectEvent, useRef, type MouseEvent as ReactMouseEvent } from "react";
6import {
7 findAssistantCitationSourceAnchor,
8 type AssistantCitationSourceAnchor,
9} from "~/lib/assistantTextSelection";
10import { cn } from "~/lib/utils";
11import {
12 assistantCitationHash,
13 assistantCitationNavigation,
14} from "../../lib/assistantCitationNavigation";
15import {
16 CHAT_INLINE_CHIP_CLASS_NAME,
17 COMPOSER_INLINE_CHIP_CLASS_NAME,
18 COMPOSER_INLINE_CHIP_DISMISS_BUTTON_CLASS_NAME,
19 COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
20 COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
21} from "../composerInlineChip";
22import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
23import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
24import { AssistantCitationCommentEditor } from "./AssistantCitationCommentEditor";
25import { observeAssistantCitationCommentSource } from "./AssistantCitationSource";
26import { composerFloatingLayerProps } from "./composerEventScope";
27​
28const CITATION_ACTION_BUTTON_CLASS_NAME = cn(
29 COMPOSER_INLINE_CHIP_DISMISS_BUTTON_CLASS_NAME,
30 "text-primary/80 hover:bg-primary/10 hover:text-primary",
31);
32​
33export function AssistantCitationChip({
34 citation,
35 onRemove,
36 commentEditor,
37}: {
38 citation: AssistantCitation;
39 onRemove?: () => void;
40 commentEditor?: {
41 open: boolean;
42 sourceAnchor?: AssistantCitationSourceAnchor | undefined;
43 onOpenChange: (open: boolean) => void;
44 onSave: (comment: string) => boolean;
45 onSaveAndSend?: (comment: string) => boolean;
46 };
47}) {
48 const navigate = useNavigate();
49 const commentInputRef = useRef<HTMLTextAreaElement>(null);
50 const commentOpen = commentEditor?.open ?? false;
51 const sourceAnchor = commentEditor?.sourceAnchor;
52 const onSourceUnavailable = useEffectEvent(() => {
53 if (sourceAnchor) commentEditor?.onOpenChange(false);
54 });
55 useEffect(() => {
56 if (!commentOpen) return;
57 const anchor = sourceAnchor ?? findAssistantCitationSourceAnchor(document, citation);
58 if (!anchor) return;
59 return observeAssistantCitationCommentSource({
60 anchor,
61 citation,
62 onUnavailable: onSourceUnavailable,
63 });
64 }, [citation, commentOpen, sourceAnchor]);
65 // A multi-line selection's bounding box spans the full message width; anchor
66 // the bubble to the selection's last line, where the pointer released.
67 const popupAnchor = sourceAnchor
68 ? {
69 contextElement: sourceAnchor.source,
70 getBoundingClientRect: () => {
71 const rects = sourceAnchor.range.getClientRects();
72 return rects.item(rects.length - 1) ?? sourceAnchor.range.getBoundingClientRect();
73 },
74 }
75 : undefined;
76 const preview = (citation.comment?.trim() || citation.text).replace(/\s+/g, " ");
77 const label = preview.length > 64 ? `${preview.slice(0, 64)}…` : preview;
78 const sourceLinkProps = {
79 to: "/$environmentId/$threadId" as const,
80 params: { environmentId: citation.environmentId, threadId: citation.threadId },
81 hash: assistantCitationHash(citation),
82 "data-markdown-copy": serializeAssistantCitation(citation),
83 resetScroll: false,
84 onClick: (event: ReactMouseEvent<HTMLAnchorElement>) => {
85 if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
86 return;
87 }
88 event.preventDefault();
89 void navigate(assistantCitationNavigation(citation));
90 },
91 };
92 const composerSourceLink = (
93 <Link
94 {...sourceLinkProps}
95 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-primary"
96 aria-label={`View cited assistant text: ${label}`}
97 >
98 <QuoteIcon aria-hidden="true" className={COMPOSER_INLINE_CHIP_ICON_CLASS_NAME} />
99 <span className={cn(COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME, "max-w-[16em]")}>{label}</span>
100 </Link>
101 );
102 const chatSourceLink = (
103 <Link
104 {...sourceLinkProps}
105 className="inline-flex h-full min-w-0 items-center gap-[0.33em] rounded-sm text-inherit no-underline hover:bg-primary/10 focus-visible:outline-2 focus-visible:outline-primary"
106 aria-label={`View cited assistant text: ${label}`}
107 >
108 <QuoteIcon aria-hidden="true" className={COMPOSER_INLINE_CHIP_ICON_CLASS_NAME} />
109 <span className={cn(COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME, "max-w-[16em]")}>{label}</span>
110 </Link>
111 );
112 return (
113 <span
114 className={cn(
115 onRemove ? COMPOSER_INLINE_CHIP_CLASS_NAME : CHAT_INLINE_CHIP_CLASS_NAME,
116 "border-primary/20 bg-primary/8 text-primary",
117 )}
118 contentEditable={false}
119 data-assistant-citation-chip="true"
120 data-markdown-copy={serializeAssistantCitation(citation)}
121 >
122 {onRemove ? (
123 composerSourceLink
124 ) : (
125 <Tooltip>
126 <TooltipTrigger render={chatSourceLink} />
127 <TooltipPopup side="top">View source</TooltipPopup>
128 </Tooltip>
129 )}
130 {commentEditor ? (
131 <Popover open={commentEditor.open} onOpenChange={commentEditor.onOpenChange}>
132 <PopoverTrigger
133 aria-label={citation.comment ? "Edit citation comment" : "Add comment to citation"}
134 className={CITATION_ACTION_BUTTON_CLASS_NAME}
135 >
136 <PencilIcon aria-hidden="true" className="size-[0.85em]" />
137 </PopoverTrigger>
138 {commentEditor.open ? (
139 <PopoverPopup
140 {...composerFloatingLayerProps}
141 side={sourceAnchor ? "bottom" : "top"}
142 align="end"
143 anchor={popupAnchor}
144 initialFocus={() => {
145 commentInputRef.current?.focus({ preventScroll: true });
146 return false;
147 }}
148 aria-label="Edit citation comment"
149 className="w-72 max-w-[calc(100vw-1rem)]"
150 viewportClassName="p-3"
151 onPointerDown={(event) => event.stopPropagation()}
152 >
153 <AssistantCitationCommentEditor
154 key={serializeAssistantCitation(citation)}
155 citation={citation}
156 inputRef={commentInputRef}
157 onSubmit={(comment) => {
158 if (!commentEditor.onSave(comment)) return false;
159 commentEditor.onOpenChange(false);
160 return true;
161 }}
162 {...(commentEditor.onSaveAndSend
163 ? {
164 onSubmitAndSend: (comment: string) => {
165 if (!commentEditor.onSaveAndSend?.(comment)) return false;
166 commentEditor.onOpenChange(false);
167 return true;
168 },
169 }
170 : {})}
171 onCancel={() => commentEditor.onOpenChange(false)}
172 />
173 </PopoverPopup>
174 ) : null}
175 </Popover>
176 ) : null}
177 {onRemove ? (
178 <button
179 type="button"
180 onClick={onRemove}
181 aria-label="Remove assistant citation"
182 className={cn(
183 COMPOSER_INLINE_CHIP_DISMISS_BUTTON_CLASS_NAME,
184 "text-primary/85 hover:bg-primary/10 hover:text-primary",
185 )}
186 >
187 <XIcon aria-hidden="true" className="size-[0.85em]" />
188 </button>
189 ) : null}
190 </span>
191 );