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

composerContextPresentation.tsx

473 lines16.5 KB

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