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

composerContextPresentation.tsx

464 lines16.8 KB

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