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

composerContextPresentation.tsx

469 lines17.0 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";
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 { cn } from "~/lib/utils";
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 {
36 createContextPresentationRegistry,
37 type ContextPresentationCapability,
38} from "./contextPresentationRegistry";
39import {
40 COMPOSER_INLINE_CHIP_CLASS_NAME,
41 COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
42 COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
43 CONTEXT_INLINE_CHIP_ICON_TONE_CLASS_NAMES,
44 CONTEXT_INLINE_CHIP_TONE_CLASS_NAMES,
45 PULL_REQUEST_INLINE_CHIP_TONE_CLASS_NAMES,
46} from "./composerInlineChip";
47import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
48import {
49 ContextChipPopover,
50 ContextChipShell,
51 FileChip,
52 ImageChipButton,
53 PullRequestChip,
54 UnresolvedChip,
55} from "./contextChipParts";
56​
57/**
58 * Draft-side payload behind a context reference chip. Each kind keeps its existing draft
59 * shape; the editor only needs a way to look one up by id.
60 */
61export type ComposerDraftContextRecord =
62 | { kind: "terminal"; record: TerminalContextDraft }
63 | { kind: "review-comment"; record: ReviewCommentContext }
64 | { kind: "preview-annotation"; record: PreviewAnnotationPayload }
65 | { kind: "image"; record: ComposerImageAttachment; upload?: AttachmentUploadState | undefined }
66 | { kind: "file"; record: ComposerFileAttachment; upload?: AttachmentUploadState | undefined };
67​
68/** What a chip can do beyond showing itself; the composer supplies the handlers. */
69export interface ComposerContextActions {
70 environmentId: EnvironmentId | null;
71 expandImage: (imageId: string) => void;
72 expandVideo: (fileId: string) => void;
73 openFile: (fileId: string) => void;
74 openMention: (path: string) => void;
75 openPullRequest: (event: MouseEvent<HTMLElement>, url: string) => void;
77​
78export const ComposerContextActionsContext = createContext<ComposerContextActions>({
79 environmentId: null,
80 expandImage: () => {},
81 expandVideo: () => {},
82 openFile: () => {},
83 openMention: () => {},
84 openPullRequest: () => {},
85});
86​
87export type ComposerDraftContextRecords = ReadonlyMap<string, ComposerDraftContextRecord>;
88​
89export const EMPTY_COMPOSER_CONTEXT_RECORDS: ComposerDraftContextRecords = new Map();
90​
91export function uploadedContextRecordFromDraft(entry: ComposerDraftContextRecord) {
92 if (entry.kind !== "image" && entry.kind !== "file") return null;
93 return uploadedAttachmentContextRecord(entry.record, entry.upload);
95​
96export const ComposerContextRecordsContext = createContext<ComposerDraftContextRecords>(
97 EMPTY_COMPOSER_CONTEXT_RECORDS,
98);
99​
100export function composerContextRecordsFromDraft(input: {
101 terminalContexts: ReadonlyArray<TerminalContextDraft>;
102 reviewComments?: ReadonlyArray<ReviewCommentContext>;
103 previewAnnotations?: ReadonlyArray<PreviewAnnotationPayload>;
104 images?: ReadonlyArray<ComposerImageAttachment>;
105 files?: ReadonlyArray<ComposerFileAttachment>;
106 uploadsByImageId?: Readonly<Record<string, AttachmentUploadState>>;
107}): ComposerDraftContextRecords {
108 const records = new Map<string, ComposerDraftContextRecord>();
109 for (const record of input.images ?? []) {
110 records.set(imageContextReference(record).contextId, {
111 kind: "image",
112 record,
113 upload: input.uploadsByImageId?.[record.id],
114 });
115 }
116 for (const record of input.files ?? []) {
117 records.set(fileContextReference(record).contextId, {
118 kind: "file",
119 record,
120 upload: input.uploadsByImageId?.[record.id],
121 });
122 }
123 for (const record of input.terminalContexts) {
124 records.set(terminalContextReference(record).contextId, { kind: "terminal", record });
125 }
126 for (const record of input.reviewComments ?? []) {
127 records.set(reviewCommentContextId(record.id), { kind: "review-comment", record });
128 }
129 for (const record of input.previewAnnotations ?? []) {
130 records.set(previewAnnotationContextId(record.id), { kind: "preview-annotation", record });
131 }
132 return records;
134​
135function ContextChip(props: {
136 icon: ReactElement;
137 label: string;
138 kindLabel: string;
139 details: ReactNode;
140 detailsMode: ContextPresentationCapability["details"];
141 toneClassName: string;
142}) {
143 const content = (
144 <ContextChipShell
145 icon={props.icon}
146 label={props.label}
147 className={cn(COMPOSER_INLINE_CHIP_CLASS_NAME, props.toneClassName)}
148 labelClassName={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}
149 interactive={props.detailsMode === "popover"}
150 aria-hidden={props.detailsMode === "popover" ? true : undefined}
151 aria-label={
152 props.detailsMode === "tooltip" ? `${props.kindLabel}, ${props.label}` : undefined
153 }
154 tooltip={props.detailsMode === "tooltip" ? props.details : undefined}
155 />
156 );
157 if (props.detailsMode === "popover") {
158 return (
159 <ContextChipPopover accessibleLabel={props.kindLabel + ", " + props.label} chip={content}>
160 {props.details}
161 </ContextChipPopover>
162 );
163 }
164 return content;
166​
167function uploadStatusSuffix(upload: AttachmentUploadState | undefined): string | null {
168 if (upload?.status === "uploading") return formatAttachmentUploadProgress(upload.progress);
169 if (upload?.status === "failed") return "upload failed";
170 return null;
172​
173function attachmentTooltip(
174 attachment: ComposerImageAttachment | ComposerFileAttachment,
175 upload: AttachmentUploadState | undefined,
176): string {
177 const lines = [attachment.name, formatAttachmentSize(attachment.sizeBytes)];
178 if (upload?.status === "failed") lines.push("", upload.reason);
179 return lines.join("\n");
181​
182function ImageContextChip(props: {
183 record: ComposerImageAttachment;
184 upload: AttachmentUploadState | undefined;
185}) {
186 const actions = use(ComposerContextActionsContext);
187 return (
188 <Tooltip>
189 <TooltipTrigger
190 render={
191 <ImageChipButton
192 name={props.record.name}
193 previewUrl={props.record.previewUrl}
194 className={COMPOSER_INLINE_CHIP_CLASS_NAME}
195 labelClassName={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}
196 size={formatAttachmentSize(props.record.sizeBytes)}
197 suffix={uploadStatusSuffix(props.upload)}
198 onClick={() => actions.expandImage(props.record.id)}
199 />
200 }
201 />
202 <TooltipPopup side="top" className="whitespace-pre-wrap">
203 {attachmentTooltip(props.record, props.upload)}
204 </TooltipPopup>
205 </Tooltip>
206 );
208​
209function FileContextChip(props: {
210 record: ComposerFileAttachment;
211 upload: AttachmentUploadState | undefined;
212}) {
213 const actions = use(ComposerContextActionsContext);
214 const { resolvedTheme } = useTheme();
215 const needsReattach = composerFileNeedsReattach(props.record);
216 const suffix = needsReattach ? "attach again" : uploadStatusSuffix(props.upload);
217 const size = formatAttachmentSize(props.record.sizeBytes);
218 const isVideo = videoMimeType(props.record) !== null;
219 return (
220 <FileChip
221 name={props.record.name}
222 size={size}
223 isVideo={isVideo}
224 theme={resolvedTheme}
225 className={COMPOSER_INLINE_CHIP_CLASS_NAME}
226 labelClassName={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}
227 error={props.upload?.status === "failed"}
228 unresolved={needsReattach}
229 suffix={suffix}
230 accessibleLabel={`${isVideo && !needsReattach ? "Preview video" : "File"} attachment, ${props.record.name}, ${size}`}
231 onOpen={
232 !needsReattach
233 ? () =>
234 isVideo ? actions.expandVideo(props.record.id) : actions.openFile(props.record.id)
235 : undefined
236 }
237 tooltip={
238 needsReattach
239 ? `${props.record.name} was not saved with this draft. Attach it again to send it.`
240 : attachmentTooltip(props.record, props.upload)
241 }
242 />
243 );
245​
246function PullRequestContextChip(props: { record: ReviewCommentContext; toneClassName: string }) {
247 const actions = use(ComposerContextActionsContext);
248 const metadata = props.record.pullRequest;
249 if (metadata === undefined) return null;
250 return (
251 <PullRequestChip
252 metadata={metadata}
253 environmentId={actions.environmentId}
254 label={reviewCommentContextLabel(props.record)}
255 kindLabel={pullRequestContextKindLabel(props.record)}
256 className={cn(COMPOSER_INLINE_CHIP_CLASS_NAME, props.toneClassName)}
257 labelClassName={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}
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-[11px]">
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}: {
300 annotation: PreviewAnnotationPayload;
301}) {
302 const summary = previewAnnotationTooltip(annotation);
303 return (
304 <div className="overflow-hidden rounded-lg border border-border/70 bg-background/70">
305 {annotation.screenshot?.dataUrl ? (
306 <img
307 src={annotation.screenshot.dataUrl}
308 alt="Annotated preview crop"
309 className="max-h-64 w-full border-border/70 border-b bg-muted object-contain"
310 />
311 ) : (
312 <div className="border-border/70 border-b bg-muted/40 px-3 py-2 text-secondary-label text-xs">
313 Screenshot unavailable
314 </div>
315 )}
316 <div className="whitespace-pre-wrap wrap-break-word px-3 py-2.5 text-sm text-foreground">
317 {summary}
318 </div>
319 </div>
320 );
322​
323function UnresolvedContextChip(props: { label: string }) {
324 return (
325 <UnresolvedChip
326 label={props.label}
327 className={COMPOSER_INLINE_CHIP_CLASS_NAME}
328 labelClassName={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}
329 tooltip="This context is no longer available. Remove it or attach it again."
330 tooltipClassName="max-w-80 leading-tight"
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"],
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 toneClassName={PULL_REQUEST_INLINE_CHIP_TONE_CLASS_NAMES[pullRequestState]}
393 />
394 );
395 }
396 return (
397 <ContextChip
398 icon={
399 isPullRequest ? (
400 <PullRequestGlyph.pullRequest
401 className={cn(
402 COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
403 CONTEXT_INLINE_CHIP_ICON_TONE_CLASS_NAMES["pull-request"],
404 "size-3.5",
405 )}
406 />
407 ) : (
408 <MessageCircleIcon
409 className={cn(
410 COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
411 CONTEXT_INLINE_CHIP_ICON_TONE_CLASS_NAMES["review-comment"],
412 "size-3.5",
413 )}
414 />
415 )
416 }
417 label={reviewCommentContextLabel(entry.record)}
418 kindLabel={isPullRequest ? pullRequestContextKindLabel(entry.record) : "Review comment"}
419 details={<ComposerReviewCommentDetails comment={entry.record} />}
420 detailsMode={definition.capabilities.details}
421 toneClassName={
422 isPullRequest
423 ? PULL_REQUEST_INLINE_CHIP_TONE_CLASS_NAMES[pullRequestState]
424 : CONTEXT_INLINE_CHIP_TONE_CLASS_NAMES["review-comment"]
425 }
426 />
427 );
428 },
429 },
430 {
431 kind: "preview-annotation",
432 canRender: (entry) => entry.kind === "preview-annotation",
433 render: (entry, context, definition) =>
434 entry.kind === "preview-annotation" ? (
435 <ContextChip
436 icon={
437 <MousePointerClickIcon
438 className={cn(
439 COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
440 CONTEXT_INLINE_CHIP_ICON_TONE_CLASS_NAMES["preview-annotation"],
441 "size-3.5",
442 )}
443 />
444 }
445 label={previewAnnotationContextLabel(entry.record)}
446 kindLabel="Preview annotation"
447 details={<ComposerPreviewAnnotationDetails annotation={entry.record} />}
448 detailsMode={definition.capabilities.details}
449 toneClassName={CONTEXT_INLINE_CHIP_TONE_CLASS_NAMES["preview-annotation"]}
450 />
451 ) : (
452 <UnresolvedContextChip label={context.label} />
453 ),
454 },
455 ],
456 fallback: (_kind, _entry, context) => <UnresolvedContextChip label={context.label} />,
457});
458​
459/** Compact chip for one reference. Unknown kinds and missing records use the registry fallback. */
460export function ComposerContextReferenceChip(props: {
461 kind: string;
462 contextId: string;
463 label: string;
464}): ReactElement {
465 const records = use(ComposerContextRecordsContext);
466 return composerContextPresentationRegistry.render(props.kind, records.get(props.contextId), {
467 label: props.label,
468 });