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

composerContextPresentation.tsx

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