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

AssistantCitationChip.tsx

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