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