Open History to see the last commit
1import ChatMarkdown from "./ChatMarkdown";
2import { ReadOnlySourcePreview } from "./files/AttachmentFilePreview";
3import type { PreviewAnnotationPayload } from "@t3tools/contracts";
4import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
5import { videoMimeType } from "@t3tools/shared/video";
6import { MessageCircleIcon, MousePointerClickIcon } from "lucide-react";
7import { createContext, type MouseEvent, type ReactElement, type ReactNode, use } from "react";
8import type { EnvironmentId } from "@t3tools/contracts";
9
10import type { ComposerFileAttachment, ComposerImageAttachment } from "~/composerDraftStore";
11import { composerFileNeedsReattach } from "~/composerDraftStore";
12import { useTheme } from "~/hooks/useTheme";
13import {
14 formatAttachmentUploadProgress,
15 type AttachmentUploadState,
16} from "~/lib/attachmentUploadState";
17import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons";
18import {
19 fileContextReference,
20 imageContextReference,
21 isPullRequestSummaryContext,
22 pullRequestContextDisplayState,
23 pullRequestContextKindLabel,
24 previewAnnotationContextId,
25 previewAnnotationContextLabel,
26 reviewCommentContextId,
27 reviewCommentContextLabel,
28 terminalContextReference,
29 uploadedAttachmentContextRecord,
30} from "~/lib/composerContextRecords";
31import type { TerminalContextDraft } from "~/lib/terminalContext";
32import type { ReviewCommentContext } from "~/reviewCommentContext";
33import { ComposerPendingTerminalContextChip } from "./chat/ComposerPendingTerminalContexts";
34import {
35 createContextPresentationRegistry,
36 type ContextPresentationCapability,
37} from "./contextPresentationRegistry";
38import type { ContextChipKind } from "./ContextChip";
39import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
40import {
41 ContextChipPopover,
42 ContextChipShell,
43 FileChip,
44 ImageChipButton,
45 PULL_REQUEST_CHIP_KINDS,
46 PullRequestChip,
47 UnresolvedChip,
48} from "./contextChipParts";
49
50/**
51 * Draft-side payload behind a context reference chip. Each kind keeps its existing draft
52 * shape; the editor only needs a way to look one up by id.
53 */
54export type ComposerDraftContextRecord =
55 | { kind: "terminal"; record: TerminalContextDraft }
56 | { kind: "review-comment"; record: ReviewCommentContext }
57 | { kind: "preview-annotation"; record: PreviewAnnotationPayload }
58 | { kind: "image"; record: ComposerImageAttachment; upload?: AttachmentUploadState | undefined }
59 | { kind: "file"; record: ComposerFileAttachment; upload?: AttachmentUploadState | undefined };
60
61/** What a chip can do beyond showing itself; the composer supplies the handlers. */
62export interface ComposerContextActions {
63 environmentId: EnvironmentId | null;
64 expandImage: (imageId: string) => void;
65 expandVideo: (fileId: string) => void;
66 openFile: (fileId: string) => void;
67 openMention: (path: string) => void;
68 openPullRequest: (event: MouseEvent<HTMLElement>, url: string) => void;
69}
70
71export const ComposerContextActionsContext = createContext<ComposerContextActions>({
72 environmentId: null,
73 expandImage: () => {},
74 expandVideo: () => {},
75 openFile: () => {},
76 openMention: () => {},
77 openPullRequest: () => {},
78});
79
80export type ComposerDraftContextRecords = ReadonlyMap<string, ComposerDraftContextRecord>;
81
82export const EMPTY_COMPOSER_CONTEXT_RECORDS: ComposerDraftContextRecords = new Map();
83
84export function uploadedContextRecordFromDraft(entry: ComposerDraftContextRecord) {
85 if (entry.kind !== "image" && entry.kind !== "file") return null;
86 return uploadedAttachmentContextRecord(entry.record, entry.upload);
87}
88
89export const ComposerContextRecordsContext = createContext<ComposerDraftContextRecords>(
90 EMPTY_COMPOSER_CONTEXT_RECORDS,
91);
92
93export function composerContextRecordsFromDraft(input: {
94 terminalContexts: ReadonlyArray<TerminalContextDraft>;
95 reviewComments?: ReadonlyArray<ReviewCommentContext>;
96 previewAnnotations?: ReadonlyArray<PreviewAnnotationPayload>;
97 images?: ReadonlyArray<ComposerImageAttachment>;
98 files?: ReadonlyArray<ComposerFileAttachment>;
99 uploadsByImageId?: Readonly<Record<string, AttachmentUploadState>>;
100}): ComposerDraftContextRecords {
101 const records = new Map<string, ComposerDraftContextRecord>();
102 for (const record of input.images ?? []) {
103 records.set(imageContextReference(record).contextId, {
104 kind: "image",
105 record,
106 upload: input.uploadsByImageId?.[record.id],
107 });
108 }
109 for (const record of input.files ?? []) {
110 records.set(fileContextReference(record).contextId, {
111 kind: "file",
112 record,
113 upload: input.uploadsByImageId?.[record.id],
114 });
115 }
116 for (const record of input.terminalContexts) {
117 records.set(terminalContextReference(record).contextId, { kind: "terminal", record });
118 }
119 for (const record of input.reviewComments ?? []) {
120 records.set(reviewCommentContextId(record.id), { kind: "review-comment", record });
121 }
122 for (const record of input.previewAnnotations ?? []) {
123 records.set(previewAnnotationContextId(record.id), { kind: "preview-annotation", record });
124 }
125 return records;
126}
127
128function ContextChip(props: {
129 icon: ReactElement;
130 label: string;
131 kindLabel: string;
132 details: ReactNode;
133 detailsMode: ContextPresentationCapability["details"];
134 kind: ContextChipKind;
135}) {
136 if (props.detailsMode === "popover") {
137 return (
138 <ContextChipPopover
139 kind={props.kind}
140 icon={props.icon}
141 label={props.label}
142 accessibleLabel={props.kindLabel + ", " + props.label}
143 >
144 {props.details}
145 </ContextChipPopover>
146 );
147 }
148 return (
149 <ContextChipShell
150 kind={props.kind}
151 icon={props.icon}
152 label={props.label}
153 aria-label={
154 props.detailsMode === "tooltip" ? `${props.kindLabel}, ${props.label}` : undefined
155 }
156 tooltip={props.detailsMode === "tooltip" ? props.details : undefined}
157 />
158 );
159}
160
161function uploadStatusSuffix(upload: AttachmentUploadState | undefined): string | null {
162 if (upload?.status === "uploading") return formatAttachmentUploadProgress(upload.progress);
163 if (upload?.status === "failed") return "upload failed";
164 return null;
165}
166
167function attachmentTooltip(
168 attachment: ComposerImageAttachment | ComposerFileAttachment,
169 upload: AttachmentUploadState | undefined,
170): string {
171 const lines = [attachment.name, formatAttachmentSize(attachment.sizeBytes)];
172 if (upload?.status === "failed") lines.push("", upload.reason);
173 return lines.join("\n");
174}
175
176function ImageContextChip(props: {
177 record: ComposerImageAttachment;
178 upload: AttachmentUploadState | undefined;
179}) {
180 const actions = use(ComposerContextActionsContext);
181 return (
182 <Tooltip>
183 <TooltipTrigger
184 render={
185 <ImageChipButton
186 name={props.record.name}
187 previewUrl={props.record.previewUrl}
188 size={formatAttachmentSize(props.record.sizeBytes)}
189 suffix={uploadStatusSuffix(props.upload)}
190 onClick={() => actions.expandImage(props.record.id)}
191 />
192 }
193 />
194 <TooltipPopup side="top" className="whitespace-pre-wrap">
195 {attachmentTooltip(props.record, props.upload)}
196 </TooltipPopup>
197 </Tooltip>
198 );
199}
200
201function FileContextChip(props: {
202 record: ComposerFileAttachment;
203 upload: AttachmentUploadState | undefined;
204}) {
205 const actions = use(ComposerContextActionsContext);
206 const { resolvedTheme } = useTheme();
207 const needsReattach = composerFileNeedsReattach(props.record);
208 const suffix = needsReattach ? "attach again" : uploadStatusSuffix(props.upload);
209 const size = formatAttachmentSize(props.record.sizeBytes);
210 const isVideo = videoMimeType(props.record) !== null;
211 return (
212 <FileChip
213 name={props.record.name}
214 size={size}
215 isVideo={isVideo}
216 theme={resolvedTheme}
217 error={props.upload?.status === "failed"}
218 unresolved={needsReattach}
219 suffix={suffix}
220 accessibleLabel={`${isVideo && !needsReattach ? "Preview video" : "File"} attachment, ${props.record.name}, ${size}`}
221 onOpen={
222 !needsReattach
223 ? () =>
224 isVideo ? actions.expandVideo(props.record.id) : actions.openFile(props.record.id)
225 : undefined
226 }
227 tooltip={
228 needsReattach
229 ? `${props.record.name} was not saved with this draft. Attach it again to send it.`
230 : attachmentTooltip(props.record, props.upload)
231 }
232 />
233 );
234}
235
236function PullRequestContextChip(props: { record: ReviewCommentContext; kind: ContextChipKind }) {
237 const actions = use(ComposerContextActionsContext);
238 const metadata = props.record.pullRequest;
239 if (metadata === undefined) return null;
240 return (
241 <PullRequestChip
242 metadata={metadata}
243 environmentId={actions.environmentId}
244 label={reviewCommentContextLabel(props.record)}
245 kindLabel={pullRequestContextKindLabel(props.record)}
246 kind={props.kind}
247 onOpen={actions.openPullRequest}
248 />
249 );
250}
251
252function previewAnnotationTooltip(annotation: PreviewAnnotationPayload): string {
253 const lines = [annotation.pageTitle?.trim() || annotation.pageUrl];
254 if (annotation.comment.trim()) lines.push("", annotation.comment.trim());
255 const targets: string[] = [];
256 const plural = (count: number, noun: string) => `${count} ${noun}${count === 1 ? "" : "s"}`;
257 if (annotation.elements.length > 0) targets.push(plural(annotation.elements.length, "element"));
258 if (annotation.regions.length > 0) targets.push(plural(annotation.regions.length, "region"));
259 if (annotation.strokes.length > 0) targets.push(plural(annotation.strokes.length, "drawing"));
260 if (annotation.styleChanges.length > 0) {
261 targets.push(plural(annotation.styleChanges.length, "style change"));
262 }
263 if (targets.length > 0) lines.push("", targets.join(", "));
264 return lines.join("\n");
265}
266
267function ComposerReviewCommentDetails({ comment }: { comment: ReviewCommentContext }) {
268 return (
269 <div className="space-y-2 overflow-hidden rounded-lg border border-border/70 bg-background/70 p-3">
270 <div className="space-y-1">
271 <div className="truncate text-xs font-medium text-foreground">{comment.filePath}</div>
272 <div className="text-secondary-label text-2xs">
273 {comment.sectionTitle} · {comment.rangeLabel}
274 </div>
275 </div>
276 {comment.text.trim() ? <ChatMarkdown text={comment.text.trim()} cwd={undefined} /> : null}
277 {comment.diff.trim() ? (
278 <div className="flex h-64 min-h-0 flex-col overflow-hidden rounded-md border border-border">
279 <ReadOnlySourcePreview name="review.diff" text={comment.diff} />
280 </div>
281 ) : null}
282 </div>
283 );
284}
285
286function ComposerPreviewAnnotationDetails({
287 annotation,
288}: {
289 annotation: PreviewAnnotationPayload;
290}) {
291 const summary = previewAnnotationTooltip(annotation);
292 return (
293 <div className="overflow-hidden rounded-lg border border-border/70 bg-background/70">
294 {annotation.screenshot?.dataUrl ? (
295 <img
296 src={annotation.screenshot.dataUrl}
297 alt="Annotated preview crop"
298 className="max-h-64 w-full border-border/70 border-b bg-muted object-contain"
299 />
300 ) : (
301 <div className="border-border/70 border-b bg-muted/40 px-3 py-2 text-secondary-label text-xs">
302 Screenshot unavailable
303 </div>
304 )}
305 <div className="whitespace-pre-wrap wrap-break-word px-3 py-2.5 text-sm text-foreground">
306 {summary}
307 </div>
308 </div>
309 );
310}
311
312function UnresolvedContextChip(props: { label: string }) {
313 return (
314 <UnresolvedChip
315 label={props.label}
316 tooltip="This context is no longer available. Remove it or attach it again."
317 />
318 );
319}
320
321interface ComposerContextRenderContext {
322 label: string;
323}
324
325const composerContextPresentationRegistry = createContextPresentationRegistry<
326 ComposerDraftContextRecord,
327 ComposerContextRenderContext,
328 ReactElement
329>({
330 requiredKinds: ["image", "file", "terminal", "review-comment", "preview-annotation"],
331 handlers: [
332 {
333 kind: "terminal",
334 canRender: (entry) => entry.kind === "terminal",
335 render: (entry, context, definition) =>
336 entry.kind === "terminal" ? (
337 <ComposerPendingTerminalContextChip
338 context={entry.record}
339 detailsMode={definition.capabilities.details}
340 />
341 ) : (
342 <UnresolvedContextChip label={context.label} />
343 ),
344 },
345 {
346 kind: "image",
347 canRender: (entry) => entry.kind === "image",
348 render: (entry, context) =>
349 entry.kind === "image" ? (
350 <ImageContextChip record={entry.record} upload={entry.upload} />
351 ) : (
352 <UnresolvedContextChip label={context.label} />
353 ),
354 },
355 {
356 kind: "file",
357 canRender: (entry) => entry.kind === "file",
358 render: (entry, context) =>
359 entry.kind === "file" ? (
360 <FileContextChip record={entry.record} upload={entry.upload} />
361 ) : (
362 <UnresolvedContextChip label={context.label} />
363 ),
364 },
365 {
366 kind: "review-comment",
367 canRender: (entry) => entry.kind === "review-comment",
368 render: (entry, context, definition) => {
369 if (entry.kind !== "review-comment") {
370 return <UnresolvedContextChip label={context.label} />;
371 }
372 const isPullRequest = isPullRequestSummaryContext(entry.record);
373 const pullRequestState = pullRequestContextDisplayState(entry.record) ?? "unknown";
374 if (isPullRequest && entry.record.pullRequest !== undefined) {
375 return (
376 <PullRequestContextChip
377 record={entry.record}
378 kind={PULL_REQUEST_CHIP_KINDS[pullRequestState]}
379 />
380 );
381 }
382 return (
383 <ContextChip
384 icon={isPullRequest ? <PullRequestGlyph.pullRequest /> : <MessageCircleIcon />}
385 label={reviewCommentContextLabel(entry.record)}
386 kindLabel={isPullRequest ? pullRequestContextKindLabel(entry.record) : "Review comment"}
387 details={<ComposerReviewCommentDetails comment={entry.record} />}
388 detailsMode={definition.capabilities.details}
389 kind={isPullRequest ? PULL_REQUEST_CHIP_KINDS[pullRequestState] : "review-comment"}
390 />
391 );
392 },
393 },
394 {
395 kind: "preview-annotation",
396 canRender: (entry) => entry.kind === "preview-annotation",
397 render: (entry, context, definition) =>
398 entry.kind === "preview-annotation" ? (
399 <ContextChip
400 icon={<MousePointerClickIcon />}
401 label={previewAnnotationContextLabel(entry.record)}
402 kindLabel="Preview annotation"
403 details={<ComposerPreviewAnnotationDetails annotation={entry.record} />}
404 detailsMode={definition.capabilities.details}
405 kind="preview-annotation"
406 />
407 ) : (
408 <UnresolvedContextChip label={context.label} />
409 ),
410 },
411 ],
412 fallback: (_kind, _entry, context) => <UnresolvedContextChip label={context.label} />,
413});
414
415/** Compact chip for one reference. Unknown kinds and missing records use the registry fallback. */
416export function ComposerContextReferenceChip(props: {
417 kind: string;
418 contextId: string;
419 label: string;
420}): ReactElement {
421 const records = use(ComposerContextRecordsContext);
422 return composerContextPresentationRegistry.render(props.kind, records.get(props.contextId), {
423 label: props.label,
424 });
425}