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

composerContextPresentation.tsx

453 lines15.8 KB

1import ChatMarkdown from "./ChatMarkdown";
2import { ReadOnlySourcePreview } from "./files/AttachmentFilePreview";
3import type { PreviewAnnotationPayload, ThreadContextRecord } 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 { ThreadContextChip } from "./ThreadContextChip";
35import {
36 createContextPresentationRegistry,
37 type ContextPresentationCapability,
38} from "./contextPresentationRegistry";
39import type { ContextChipKind } from "./ContextChip";
40import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
41import {
42 ContextChipPopover,
43 ContextChipShell,
44 FileChip,
45 ImageChipButton,
46 PULL_REQUEST_CHIP_KINDS,
47 PullRequestChip,
48 UnresolvedChip,
49} from "./contextChipParts";
50​
51export type ComposerDraftContextRecord =
52 | { kind: "terminal"; record: TerminalContextDraft }
53 | { kind: "review-comment"; record: ReviewCommentContext }
54 | {
55 kind: "preview-annotation";
56 record: PreviewAnnotationPayload;
57 screenshot?: ComposerImageAttachment | undefined;
58 }
59 | { kind: "image"; record: ComposerImageAttachment; upload?: AttachmentUploadState | undefined }
60 | { kind: "file"; record: ComposerFileAttachment; upload?: AttachmentUploadState | undefined }
61 | { kind: "thread"; record: ThreadContextRecord };
62​
63export interface ComposerContextActions {
64 environmentId: EnvironmentId | null;
65 cwd?: string | undefined;
66 expandImage: (imageId: string) => void;
67 expandVideo: (fileId: string) => void;
68 openFile: (fileId: string) => void;
69 openMention: (path: string) => void;
70 openPullRequest: (event: MouseEvent<HTMLElement>, url: string) => void;
72​
73export const ComposerContextActionsContext = createContext<ComposerContextActions>({
74 environmentId: null,
75 expandImage: () => {},
76 expandVideo: () => {},
77 openFile: () => {},
78 openMention: () => {},
79 openPullRequest: () => {},
80});
81​
82export type ComposerDraftContextRecords = ReadonlyMap<string, ComposerDraftContextRecord>;
83​
84export const EMPTY_COMPOSER_CONTEXT_RECORDS: ComposerDraftContextRecords = new Map();
85​
86export function uploadedContextRecordFromDraft(entry: ComposerDraftContextRecord) {
87 if (entry.kind !== "image" && entry.kind !== "file") return null;
88 return uploadedAttachmentContextRecord(entry.record, entry.upload);
90​
91export const ComposerContextRecordsContext = createContext<ComposerDraftContextRecords>(
92 EMPTY_COMPOSER_CONTEXT_RECORDS,
93);
94​
95export function composerContextRecordsFromDraft(input: {
96 terminalContexts: ReadonlyArray<TerminalContextDraft>;
97 reviewComments?: ReadonlyArray<ReviewCommentContext>;
98 previewAnnotations?: ReadonlyArray<PreviewAnnotationPayload>;
99 threadContexts?: ReadonlyArray<ThreadContextRecord>;
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 const imagesById = new Map((input.images ?? []).map((image) => [image.id, image]));
126 for (const record of input.previewAnnotations ?? []) {
127 records.set(previewAnnotationContextId(record.id), {
128 kind: "preview-annotation",
129 record,
130 screenshot: imagesById.get(record.id),
131 });
132 }
133 for (const record of input.threadContexts ?? []) {
134 records.set(record.contextId, { kind: "thread", record });
135 }
136 return records;
138​
139function ContextChip(props: {
140 icon: ReactElement;
141 label: string;
142 kindLabel: string;
143 details: ReactNode;
144 detailsMode: ContextPresentationCapability["details"];
145 kind: ContextChipKind;
146}) {
147 if (props.detailsMode === "popover") {
148 return (
149 <ContextChipPopover
150 kind={props.kind}
151 icon={props.icon}
152 label={props.label}
153 accessibleLabel={props.kindLabel + ", " + props.label}
154 >
155 {props.details}
156 </ContextChipPopover>
157 );
158 }
159 return (
160 <ContextChipShell
161 kind={props.kind}
162 icon={props.icon}
163 label={props.label}
164 aria-label={
165 props.detailsMode === "tooltip" ? `${props.kindLabel}, ${props.label}` : undefined
166 }
167 tooltip={props.detailsMode === "tooltip" ? props.details : undefined}
168 />
169 );
171​
172function uploadStatusSuffix(upload: AttachmentUploadState | undefined): string | null {
173 if (upload?.status === "uploading") return formatAttachmentUploadProgress(upload.progress);
174 if (upload?.status === "failed") return "upload failed";
175 return null;
177​
178function attachmentTooltip(
179 attachment: ComposerImageAttachment | ComposerFileAttachment,
180 upload: AttachmentUploadState | undefined,
181): string {
182 const lines = [attachment.name, formatAttachmentSize(attachment.sizeBytes)];
183 if (upload?.status === "failed") lines.push("", upload.reason);
184 return lines.join("\n");
186​
187function ImageContextChip(props: {
188 record: ComposerImageAttachment;
189 upload: AttachmentUploadState | undefined;
190}) {
191 const actions = use(ComposerContextActionsContext);
192 return (
193 <Tooltip>
194 <TooltipTrigger
195 render={
196 <ImageChipButton
197 name={props.record.name}
198 previewUrl={props.record.previewUrl}
199 size={formatAttachmentSize(props.record.sizeBytes)}
200 suffix={uploadStatusSuffix(props.upload)}
201 onClick={() => actions.expandImage(props.record.id)}
202 />
203 }
204 />
205 <TooltipPopup side="top" className="whitespace-pre-wrap">
206 {attachmentTooltip(props.record, props.upload)}
207 </TooltipPopup>
208 </Tooltip>
209 );
211​
212function FileContextChip(props: {
213 record: ComposerFileAttachment;
214 upload: AttachmentUploadState | undefined;
215}) {
216 const actions = use(ComposerContextActionsContext);
217 const { resolvedTheme } = useTheme();
218 const needsReattach = composerFileNeedsReattach(props.record);
219 const suffix = needsReattach ? "attach again" : uploadStatusSuffix(props.upload);
220 const size = formatAttachmentSize(props.record.sizeBytes);
221 const isVideo = videoMimeType(props.record) !== null;
222 return (
223 <FileChip
224 name={props.record.name}
225 size={size}
226 isVideo={isVideo}
227 theme={resolvedTheme}
228 error={props.upload?.status === "failed"}
229 unresolved={needsReattach}
230 suffix={suffix}
231 accessibleLabel={`${isVideo && !needsReattach ? "Preview video" : "File"} attachment, ${props.record.name}, ${size}`}
232 onOpen={
233 !needsReattach
234 ? () =>
235 isVideo ? actions.expandVideo(props.record.id) : actions.openFile(props.record.id)
236 : undefined
237 }
238 tooltip={
239 needsReattach
240 ? `${props.record.name} was not saved with this draft. Attach it again to send it.`
241 : attachmentTooltip(props.record, props.upload)
242 }
243 />
244 );
246​
247function PullRequestContextChip(props: { record: ReviewCommentContext; kind: ContextChipKind }) {
248 const actions = use(ComposerContextActionsContext);
249 const metadata = props.record.pullRequest;
250 if (metadata === undefined) return null;
251 return (
252 <PullRequestChip
253 metadata={metadata}
254 environmentId={actions.environmentId}
255 label={reviewCommentContextLabel(props.record)}
256 kindLabel={pullRequestContextKindLabel(props.record)}
257 kind={props.kind}
258 onOpen={actions.openPullRequest}
259 />
260 );
262​
263function previewAnnotationTooltip(annotation: PreviewAnnotationPayload): string {
264 const lines = [annotation.pageTitle?.trim() || annotation.pageUrl];
265 if (annotation.comment.trim()) lines.push("", annotation.comment.trim());
266 const targets: string[] = [];
267 const plural = (count: number, noun: string) => `${count} ${noun}${count === 1 ? "" : "s"}`;
268 if (annotation.elements.length > 0) targets.push(plural(annotation.elements.length, "element"));
269 if (annotation.regions.length > 0) targets.push(plural(annotation.regions.length, "region"));
270 if (annotation.strokes.length > 0) targets.push(plural(annotation.strokes.length, "drawing"));
271 if (annotation.styleChanges.length > 0) {
272 targets.push(plural(annotation.styleChanges.length, "style change"));
273 }
274 if (targets.length > 0) lines.push("", targets.join(", "));
275 return lines.join("\n");
277​
278function ComposerReviewCommentDetails({ comment }: { comment: ReviewCommentContext }) {
279 return (
280 <div className="space-y-2 overflow-hidden rounded-lg border border-border/70 bg-background/70 p-3">
281 <div className="space-y-1">
282 <div className="truncate text-xs font-medium text-foreground">{comment.filePath}</div>
283 <div className="text-secondary-label text-2xs">
284 {comment.sectionTitle} · {comment.rangeLabel}
285 </div>
286 </div>
287 {comment.text.trim() ? <ChatMarkdown text={comment.text.trim()} cwd={undefined} /> : null}
288 {comment.diff.trim() ? (
289 <div className="flex h-64 min-h-0 flex-col overflow-hidden rounded-md border border-border">
290 <ReadOnlySourcePreview name="review.diff" text={comment.diff} />
291 </div>
292 ) : null}
293 </div>
294 );
296​
297function ComposerPreviewAnnotationDetails({
298 annotation,
299 screenshot,
300}: {
301 annotation: PreviewAnnotationPayload;
302 screenshot: ComposerImageAttachment | undefined;
303}) {
304 const summary = previewAnnotationTooltip(annotation);
305 const screenshotUrl = annotation.screenshot?.dataUrl || screenshot?.previewUrl;
306 return (
307 <div className="overflow-hidden rounded-lg border border-border/70 bg-background/70">
308 {screenshotUrl ? (
309 <img
310 src={screenshotUrl}
311 alt="Annotated preview crop"
312 className="max-h-64 w-full border-border/70 border-b bg-muted object-contain"
313 />
314 ) : (
315 <div className="border-border/70 border-b bg-muted/40 px-3 py-2 text-secondary-label text-xs">
316 Screenshot unavailable
317 </div>
318 )}
319 <div className="whitespace-pre-wrap wrap-break-word px-3 py-2.5 text-sm text-foreground">
320 {summary}
321 </div>
322 </div>
323 );
325​
326function UnresolvedContextChip(props: { label: string }) {
327 return (
328 <UnresolvedChip
329 label={props.label}
330 tooltip="This context is no longer available. Remove it or attach it again."
331 />
332 );
334​
335interface ComposerContextRenderContext {
336 label: string;
338​
339const composerContextPresentationRegistry = createContextPresentationRegistry<
340 ComposerDraftContextRecord,
341 ComposerContextRenderContext,
342 ReactElement
343>({
344 requiredKinds: ["image", "file", "terminal", "review-comment", "preview-annotation", "thread"],
345 handlers: [
346 {
347 kind: "terminal",
348 canRender: (entry) => entry.kind === "terminal",
349 render: (entry, context, definition) =>
350 entry.kind === "terminal" ? (
351 <ComposerPendingTerminalContextChip
352 context={entry.record}
353 detailsMode={definition.capabilities.details}
354 />
355 ) : (
356 <UnresolvedContextChip label={context.label} />
357 ),
358 },
359 {
360 kind: "image",
361 canRender: (entry) => entry.kind === "image",
362 render: (entry, context) =>
363 entry.kind === "image" ? (
364 <ImageContextChip record={entry.record} upload={entry.upload} />
365 ) : (
366 <UnresolvedContextChip label={context.label} />
367 ),
368 },
369 {
370 kind: "file",
371 canRender: (entry) => entry.kind === "file",
372 render: (entry, context) =>
373 entry.kind === "file" ? (
374 <FileContextChip record={entry.record} upload={entry.upload} />
375 ) : (
376 <UnresolvedContextChip label={context.label} />
377 ),
378 },
379 {
380 kind: "review-comment",
381 canRender: (entry) => entry.kind === "review-comment",
382 render: (entry, context, definition) => {
383 if (entry.kind !== "review-comment") {
384 return <UnresolvedContextChip label={context.label} />;
385 }
386 const isPullRequest = isPullRequestSummaryContext(entry.record);
387 const pullRequestState = pullRequestContextDisplayState(entry.record) ?? "unknown";
388 if (isPullRequest && entry.record.pullRequest !== undefined) {
389 return (
390 <PullRequestContextChip
391 record={entry.record}
392 kind={PULL_REQUEST_CHIP_KINDS[pullRequestState]}
393 />
394 );
395 }
396 return (
397 <ContextChip
398 icon={isPullRequest ? <PullRequestGlyph.pullRequest /> : <MessageCircleIcon />}
399 label={reviewCommentContextLabel(entry.record)}
400 kindLabel={isPullRequest ? pullRequestContextKindLabel(entry.record) : "Review comment"}
401 details={<ComposerReviewCommentDetails comment={entry.record} />}
402 detailsMode={definition.capabilities.details}
403 kind={isPullRequest ? PULL_REQUEST_CHIP_KINDS[pullRequestState] : "review-comment"}
404 />
405 );
406 },
407 },
408 {
409 kind: "preview-annotation",
410 canRender: (entry) => entry.kind === "preview-annotation",
411 render: (entry, context, definition) =>
412 entry.kind === "preview-annotation" ? (
413 <ContextChip
414 icon={<MousePointerClickIcon />}
415 label={previewAnnotationContextLabel(entry.record)}
416 kindLabel="Preview annotation"
417 details={
418 <ComposerPreviewAnnotationDetails
419 annotation={entry.record}
420 screenshot={entry.screenshot}
421 />
422 }
423 detailsMode={definition.capabilities.details}
424 kind="preview-annotation"
425 />
426 ) : (
427 <UnresolvedContextChip label={context.label} />
428 ),
429 },
430 {
431 kind: "thread",
432 canRender: (entry) => entry.kind === "thread",
433 render: (entry, context) =>
434 entry.kind === "thread" ? (
435 <ThreadContextChip record={entry.record} />
436 ) : (
437 <UnresolvedContextChip label={context.label} />
438 ),
439 },
440 ],
441 fallback: (_kind, _entry, context) => <UnresolvedContextChip label={context.label} />,
442});
443​
444export function ComposerContextReferenceChip(props: {
445 kind: string;
446 contextId: string;
447 label: string;
448}): ReactElement {
449 const records = use(ComposerContextRecordsContext);
450 return composerContextPresentationRegistry.render(props.kind, records.get(props.contextId), {
451 label: props.label,
452 });