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

ComposerAttachmentStrip.tsx

777 lines28.1 KB

1import type {
2 ChatAttachment,
3 ChatFileAttachment,
4 EnvironmentId,
5 ScopedThreadRef,
6 SnapShotSource,
7} from "@t3tools/contracts";
8import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
9import { T, useGT, useMessages } from "gt-react";
10import { CircleAlertIcon, ImageIcon, PaperclipIcon, PlayIcon, XIcon } from "lucide-react";
11import { type ComponentProps, type Ref, useLayoutEffect, useRef } from "react";
12​
13import {
14 type ComposerFileAttachment,
15 type ComposerImageAttachment,
16 type DraftId,
17 composerFileNeedsReattach,
18} from "../../composerDraftStore";
19import { retryAttachmentUpload, useAttachmentUploadStore } from "../../lib/attachmentUploadQueue";
20import {
21 attachmentUploadFailureText,
22 type AttachmentUploadState,
23} from "../../lib/attachmentUploadState";
24import { useAttachmentUploadProgress } from "../../hooks/useAttachmentUploadProgress";
25import { isHeicImageFile } from "../../lib/imageCompression";
26import {
27 type PendingSnapShotAnimation,
28 scheduleSnapShotAnimationDestination,
29 setSnapShotAnimationDestination,
30 shouldAnimateSnapShotArrival,
31} from "../../lib/snapShotAnimation";
32import { cn } from "~/lib/utils";
33import { getRestingComposerImagePreviewCounts } from "../composerFooterLayout";
34import { RefreshIcon } from "~/components/ui/refresh-icon";
35import { AttachmentFilePreview } from "../files/AttachmentFilePreview";
36import { AttachmentImage } from "../media/AttachmentImage";
37import { Button } from "../ui/button";
38import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog";
39import { ComposerImageThumbnail } from "./ComposerImageThumbnail";
40import { composerFloatingLayerProps } from "./composerEventScope";
41import type { PreparingComposerImage } from "./preparingComposerImages";
42import {
43 attachVideoThumbnail,
44 buildExpandedImagePreview,
45 type ExpandedImagePreview,
46} from "./ExpandedImagePreview";
47import { PierreEntryIcon } from "./PierreEntryIcon";
48import {
49 SNAP_SHOT_ATTACHMENT_FRAME_CLASS,
50 SnapShotAttachmentDetails,
51} from "./SnapShotAttachmentDetails";
52import { prepareVideoFirstFrame } from "../../lib/videoFirstFrame";
53import { SharedTooltipTrigger } from "../ui/shared-tooltip";
54​
55function ComposerAttachmentUploadProgress({
56 id,
57 upload,
58 fallback,
59}: {
60 id: string;
61 upload: AttachmentUploadState | undefined;
62 fallback?: string;
63}) {
64 return useAttachmentUploadProgress(id, upload) ?? fallback ?? null;
66​
67function ComposerImageFallback() {
68 const gt = useGT();
69 return (
70 <span
71 role="img"
72 aria-label={gt("Image attachment")}
73 className="flex size-full items-center justify-center p-3 text-secondary-label"
74 >
75 <ImageIcon aria-hidden="true" className="size-4" />
76 </span>
77 );
79​
80function ComposerVideoThumbnail({ file }: { file: File }) {
81 const setVideo = (video: HTMLVideoElement | null) => {
82 if (!video) return;
83 return attachVideoThumbnail(video, file);
84 };
85​
86 return (
87 <video
88 ref={setVideo}
89 muted
90 playsInline
91 preload="metadata"
92 aria-hidden="true"
93 onLoadedMetadata={(event) => prepareVideoFirstFrame(event.currentTarget)}
94 className="pointer-events-none absolute inset-0 size-full object-cover"
95 />
96 );
98​
99function SnapShotAttachmentFrame({
100 animationId,
101 animationSource,
102 arrival,
103 animateArrival,
104 className,
105 ...props
106}: ComponentProps<"div"> & {
107 readonly animationId?: string | undefined;
108 readonly animationSource?: SnapShotSource | undefined;
109 readonly arrival?: boolean | undefined;
110 readonly animateArrival?: boolean | undefined;
111}) {
112 const frameRef = useRef<HTMLDivElement>(null);
113​
114 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls the mounted tile into view and registers it as the SnapShot animation destination
115 useLayoutEffect(() => {
116 const frame = frameRef.current;
117 if (!frame || (!animationId && !arrival)) return;
118 frame.scrollIntoView({ block: "nearest", inline: "nearest" });
119 if (!animationId) return;
120​
121 return scheduleSnapShotAnimationDestination(animationId, () =>
122 setSnapShotAnimationDestination(animationId, frame, animationSource),
123 );
124 }, [animationId, animationSource, arrival]);
125​
126 return (
127 <div
128 ref={frameRef}
129 className={cn(
130 animateArrival &&
131 !animationId &&
132 "origin-center transition-[opacity,scale] duration-300 ease-drawer starting:scale-95 starting:opacity-0 motion-reduce:transition-none motion-reduce:starting:scale-100 motion-reduce:starting:opacity-100",
133 className,
134 )}
135 {...props}
136 />
137 );
139​
140/** Image, SnapShot and video tiles above the composer editor. */
141export function ComposerAttachmentMediaRow({
142 images,
143 expandedImages,
144 preparingImages,
145 videos,
146 pendingSnapShotAnimations,
147 pendingSnapShotIds,
148 uncommittedSnapShotIds,
149 nonPersistedImageIds,
150 snapShotAnimations,
151 supportsAttachmentUploads,
152 maxFileAttachmentBytes,
153 environmentId,
154 attachmentDraftTarget,
155 canOperateThread,
156 onExpandImage,
157 onCopySnapshot,
158 onFileOpen,
159 onRemoveImage,
160 onRemoveFile,
161}: {
162 readonly images: ReadonlyArray<ComposerImageAttachment>;
163 readonly expandedImages: ReadonlyArray<ComposerImageAttachment>;
164 readonly preparingImages: ReadonlyArray<PreparingComposerImage>;
165 readonly videos: ReadonlyArray<ComposerFileAttachment>;
166 readonly pendingSnapShotAnimations: ReadonlyArray<PendingSnapShotAnimation>;
167 readonly pendingSnapShotIds: ReadonlyArray<string>;
168 readonly uncommittedSnapShotIds: ReadonlyArray<string>;
169 readonly nonPersistedImageIds: ReadonlyArray<string>;
170 readonly snapShotAnimations: boolean;
171 readonly supportsAttachmentUploads: boolean;
172 readonly maxFileAttachmentBytes: number | null;
173 readonly environmentId: EnvironmentId;
174 readonly attachmentDraftTarget: ScopedThreadRef | DraftId;
175 readonly canOperateThread: boolean;
176 readonly onCopySnapshot: (imageId: string) => Promise<void>;
177 readonly onExpandImage: (preview: ExpandedImagePreview) => void;
178 readonly onFileOpen: (attachment: ChatFileAttachment) => void;
179 readonly onRemoveImage: (imageId: string) => void;
180 readonly onRemoveFile: (fileId: string) => void;
181}) {
182 const gt = useGT();
183 const messages = useMessages();
184 const uploadsByImageId = useAttachmentUploadStore((state) => state.uploadsByImageId);
185 const pendingSnapShotIdSet = new Set(pendingSnapShotIds);
186 const nonPersistedImageIdSet = new Set(nonPersistedImageIds);
187 return (
188 <div
189 className={cn(
190 "mb-3 flex max-w-full gap-2",
191 pendingSnapShotIds.length > 0 ||
192 expandedImages.some((image) => image.source?.kind === "snap-shot")
193 ? "snap-x snap-proximity overflow-x-auto overscroll-x-contain pb-1 scrollbar-thumb-foreground/18 scrollbar-track-transparent [scrollbar-width:thin] [&::-webkit-scrollbar]:h-2.5 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:border-3 [&::-webkit-scrollbar-thumb]:border-transparent [&::-webkit-scrollbar-thumb]:bg-foreground/18 [&::-webkit-scrollbar-thumb]:bg-clip-content [&::-webkit-scrollbar-thumb:hover]:bg-foreground/28 [&::-webkit-scrollbar-track]:mx-1 [&::-webkit-scrollbar-track]:bg-transparent"
194 : "flex-wrap",
195 )}
196 >
197 {/* A preparing image renders through the same tile, keyed by the id its compressed image
198 takes, so the thumbnail element survives the swap. */}
199 {[
200 ...expandedImages.map((image) => ({ image, ready: image })),
201 ...preparingImages.map((image) => ({ image, ready: null })),
202 ]
203 .map(({ image, ready }) => {
204 const upload =
205 ready && supportsAttachmentUploads ? uploadsByImageId[image.id] : undefined;
206 const source = ready?.source;
207 const snapShotAnimationPending =
208 source?.kind === "snap-shot" && pendingSnapShotIdSet.has(image.id);
209 const snapShotArrival =
210 source?.kind === "snap-shot" && shouldAnimateSnapShotArrival(source.capturedAt);
211 return (
212 <SnapShotAttachmentFrame
213 key={image.id}
214 data-chat-composer-expanded-image="true"
215 aria-hidden={snapShotAnimationPending || undefined}
216 inert={snapShotAnimationPending || undefined}
217 arrival={snapShotArrival}
218 animateArrival={snapShotAnimations && !snapShotAnimationPending && snapShotArrival}
219 animationId={snapShotAnimationPending ? image.id : undefined}
220 animationSource={snapShotAnimationPending ? source : undefined}
221 className={cn(
222 "group/attachment shrink-0 snap-start bg-background",
223 source?.kind === "snap-shot"
224 ? SNAP_SHOT_ATTACHMENT_FRAME_CLASS
225 : "relative h-16 w-16 overflow-hidden rounded-lg border border-border/80",
226 snapShotAnimationPending && "invisible",
227 )}
228 >
229 {!ready || ready.previewUrl ? (
230 <button
231 type="button"
232 className={cn("h-full w-full", ready && "cursor-zoom-in")}
233 aria-label={gt("Preview {name}", { name: image.name })}
234 disabled={!ready}
235 onClick={() => {
236 const preview = buildExpandedImagePreview(images, image.id, onCopySnapshot);
237 if (!preview) return;
238 onExpandImage(preview);
239 }}
240 >
241 <ComposerImageThumbnail
242 file={image.file}
243 alt={image.name}
244 className="h-full w-full object-cover"
245 fallback={
246 ready && isHeicImageFile({ name: ready.name, type: ready.mimeType }) ? (
247 <AttachmentImage
248 name={ready.name}
249 mimeType={ready.mimeType}
250 src={ready.previewUrl}
251 alt=""
252 className="h-full w-full object-cover"
253 />
254 ) : (
255 <ComposerImageFallback />
256 )
257 }
258 />
259 </button>
260 ) : (
261 <ComposerImageFallback />
262 )}
263 {source?.kind === "snap-shot" ? (
264 <SnapShotAttachmentDetails
265 source={source}
266 onCopySnapshot={ready ? () => onCopySnapshot(ready.id) : undefined}
267 className={cn(
268 upload?.status === "uploading" && "bottom-4",
269 upload?.status === "failed" && "bottom-8",
270 )}
271 />
272 ) : null}
273 {nonPersistedImageIdSet.has(image.id) && (
274 <SharedTooltipTrigger
275 render={
276 <span
277 role="img"
278 aria-label={gt("Draft attachment may not persist")}
279 className="absolute left-1 top-1 inline-flex items-center justify-center rounded bg-background/85 p-0.5 text-warning-foreground"
280 >
281 <CircleAlertIcon className="size-3" />
282 </span>
283 }
284 label={
285 <>
286 <T>
287 Draft attachment could not be saved locally and may be lost on navigation.
288 </T>
289 </>
290 }
291 />
292 )}
293 {(!ready || upload?.status === "uploading") && (
294 <span className="pointer-events-none absolute inset-x-0 bottom-0 bg-background/85 px-1 text-center text-3xs text-foreground">
295 {upload?.status === "uploading" ? (
296 <ComposerAttachmentUploadProgress id={image.id} upload={upload} />
297 ) : (
298 gt("Preparing", {
299 $context: "attachment status while an image is being processed",
300 })
301 )}
302 </span>
303 )}
304 {ready && upload?.status === "failed" && (
305 <SharedTooltipTrigger
306 render={
307 <Button
308 variant="overlay"
309 size="icon-xs"
310 className="absolute bottom-1 left-1"
311 onClick={() =>
312 retryAttachmentUpload({
313 environmentId,
314 image: ready,
315 draftTarget: attachmentDraftTarget,
316 })
317 }
318 disabled={!canOperateThread}
319 aria-label={gt("Retry upload for {name}", { name: image.name })}
320 />
321 }
322 label={attachmentUploadFailureText(upload, messages)}
323 >
324 <RefreshIcon />
325 </SharedTooltipTrigger>
326 )}
327 <span
328 className={cn(
329 "absolute right-1 top-1 flex",
330 source?.kind === "snap-shot" &&
331 "opacity-0 transition-opacity pointer-coarse:opacity-100 group-hover/attachment:opacity-100 group-focus-within/attachment:opacity-100",
332 )}
333 >
334 <Button
335 variant="media-close"
336 size="icon-xs"
337 onClick={() => onRemoveImage(image.id)}
338 aria-label={gt("Remove {name}", { name: image.name })}
339 >
340 <XIcon />
341 </Button>
342 </span>
343 </SnapShotAttachmentFrame>
344 );
345 })
346 .concat(
347 uncommittedSnapShotIds.map((captureId) => (
348 <SnapShotAttachmentFrame
349 key={captureId}
350 aria-hidden="true"
351 animationId={captureId}
352 animationSource={
353 pendingSnapShotAnimations.find((capture) => capture.id === captureId)?.source
354 }
355 className={cn(
356 SNAP_SHOT_ATTACHMENT_FRAME_CLASS,
357 "invisible shrink-0 snap-start bg-background",
358 )}
359 />
360 )),
361 )}
362 {videos.map((file) => {
363 const fileCanUpload =
364 supportsAttachmentUploads &&
365 maxFileAttachmentBytes !== null &&
366 file.sizeBytes <= maxFileAttachmentBytes;
367 const upload = fileCanUpload ? uploadsByImageId[file.id] : undefined;
368 return (
369 <div
370 key={file.id}
371 className="relative h-16 w-16 shrink-0 snap-start overflow-hidden rounded-lg border border-border/80 bg-black"
372 >
373 <button
374 type="button"
375 className="flex h-full w-full cursor-zoom-in flex-col items-center justify-center gap-1 px-1 text-white"
376 aria-label={gt("Play {name}", { name: file.name })}
377 onClick={() => {
378 if (file.file !== null) {
379 const preview = buildExpandedImagePreview([file], file.id);
380 if (preview) onExpandImage(preview);
381 return;
382 }
383 if (!file.uploadedAttachmentId) return;
384 onFileOpen({ ...file, id: file.uploadedAttachmentId });
385 }}
386 >
387 {file.file && (
388 <>
389 <ComposerVideoThumbnail file={file.file} />
390 <span className="pointer-events-none absolute inset-0 bg-gradient-to-t from-black/70 via-black/10 to-black/10" />
391 </>
392 )}
393 <PlayIcon className="relative z-10 size-4 fill-current drop-shadow-md" />
394 </button>
395 {upload?.status === "uploading" && (
396 <span className="pointer-events-none absolute inset-x-0 bottom-0 bg-background/85 px-1 text-center text-3xs text-foreground">
397 <ComposerAttachmentUploadProgress id={file.id} upload={upload} />
398 </span>
399 )}
400 {upload?.status === "failed" && (
401 <SharedTooltipTrigger
402 render={
403 <Button
404 variant="overlay"
405 size="icon-xs"
406 className="absolute bottom-1 left-1"
407 onClick={() =>
408 retryAttachmentUpload({
409 environmentId,
410 image: file,
411 draftTarget: attachmentDraftTarget,
412 })
413 }
414 disabled={!canOperateThread}
415 aria-label={gt("Retry upload for {name}", { name: file.name })}
416 />
417 }
418 label={attachmentUploadFailureText(upload, messages)}
419 >
420 <RefreshIcon />
421 </SharedTooltipTrigger>
422 )}
423 <Button
424 variant="media-close"
425 size="icon-xs"
426 className="absolute right-1 top-1"
427 onClick={() => onRemoveFile(file.id)}
428 aria-label={gt("Remove {name}", { name: file.name })}
429 >
430 <XIcon />
431 </Button>
432 </div>
433 );
434 })}
435 </div>
436 );
438​
439/** Non-media file attachments, listed under the media row. */
440export function ComposerAttachmentFileList({
441 files,
442 resolvedTheme,
443 supportsAttachmentUploads,
444 maxFileAttachmentBytes,
445 fileStagingLimit,
446 environmentId,
447 attachmentDraftTarget,
448 canOperateThread,
449 onPreviewFile,
450 onRemoveFile,
451}: {
452 readonly files: ReadonlyArray<ComposerFileAttachment>;
453 readonly resolvedTheme: "light" | "dark";
454 readonly supportsAttachmentUploads: boolean;
455 readonly maxFileAttachmentBytes: number | null;
456 readonly fileStagingLimit: number | null;
457 readonly environmentId: EnvironmentId;
458 readonly attachmentDraftTarget: ScopedThreadRef | DraftId;
459 readonly canOperateThread: boolean;
460 readonly onPreviewFile: (fileId: string) => void;
461 readonly onRemoveFile: (fileId: string) => void;
462}) {
463 const gt = useGT();
464 const messages = useMessages();
465 const uploadsByImageId = useAttachmentUploadStore((state) => state.uploadsByImageId);
466 return (
467 <div className="mb-3 flex flex-col gap-1">
468 {files.map((file) => {
469 const fileCanUpload =
470 supportsAttachmentUploads &&
471 maxFileAttachmentBytes !== null &&
472 file.sizeBytes <= maxFileAttachmentBytes;
473 const upload = fileCanUpload ? uploadsByImageId[file.id] : undefined;
474 const needsReattach = composerFileNeedsReattach(file);
475 const canReattachFile = fileStagingLimit !== null && file.sizeBytes <= fileStagingLimit;
476 return (
477 <div
478 key={file.id}
479 className="flex min-w-0 items-center gap-2 py-1 text-sm text-foreground"
480 >
481 <PierreEntryIcon pathValue={file.name} kind="file" theme={resolvedTheme} />
482 <button
483 type="button"
484 disabled={needsReattach}
485 className="min-w-0 flex-1 truncate text-left hover:underline focus-visible:outline-2"
486 onClick={() => onPreviewFile(file.id)}
487 >
488 {file.name}
489 </button>
490 <span className="shrink-0 text-xs text-secondary-label">
491 {needsReattach ? (
492 canReattachFile ? (
493 gt("Attach again")
494 ) : (
495 gt("Remove to send")
496 )
497 ) : upload?.status === "uploading" ? (
498 <ComposerAttachmentUploadProgress
499 id={file.id}
500 upload={upload}
501 fallback={formatAttachmentSize(file.sizeBytes, messages)}
502 />
503 ) : (
504 formatAttachmentSize(file.sizeBytes, messages)
505 )}
506 </span>
507 {!needsReattach && upload?.status === "failed" ? (
508 <SharedTooltipTrigger
509 render={
510 <Button
511 variant="ghost"
512 size="icon-xs"
513 onClick={() =>
514 retryAttachmentUpload({
515 environmentId,
516 image: file,
517 draftTarget: attachmentDraftTarget,
518 })
519 }
520 disabled={!canOperateThread}
521 aria-label={gt("Retry upload for {name}", { name: file.name })}
522 />
523 }
524 label={attachmentUploadFailureText(upload, messages)}
525 >
526 <RefreshIcon />
527 </SharedTooltipTrigger>
528 ) : null}
529 <Button
530 variant="ghost"
531 size="icon-xs"
532 onClick={() => onRemoveFile(file.id)}
533 aria-label={gt("Remove {name}", { name: file.name })}
534 >
535 <XIcon />
536 </Button>
537 </div>
538 );
539 })}
540 </div>
541 );
543​
544export function ComposerFilePreviewDialog({
545 file,
546 onRemove,
547 onPreviewFileIdChange,
548}: {
549 readonly file: ComposerFileAttachment;
550 readonly onRemove: (fileId: string) => void;
551 readonly onPreviewFileIdChange: (fileId: string | null) => void;
552}) {
553 const gt = useGT();
554 const onClose = () => onPreviewFileIdChange(null);
555 return (
556 <Dialog
557 open
558 onOpenChange={(open) => {
559 if (!open) onClose();
560 }}
561 >
562 <DialogPopup
563 {...composerFloatingLayerProps}
564 className="h-[min(85vh,52rem)] max-w-4xl overflow-hidden"
565 showCloseButton={false}
566 >
567 <DialogTitle className="sr-only">{file.name}</DialogTitle>
568 <AttachmentFilePreview
569 key={file.id}
570 name={file.name}
571 mimeType={file.mimeType}
572 sizeBytes={file.sizeBytes}
573 file={file.file}
574 origin={gt("Draft", { $context: "where an attachment comes from: the unsent message" })}
575 {...(file.uploadedAttachmentId && file.uploadEnvironmentId
576 ? {
577 asset: {
578 environmentId: file.uploadEnvironmentId,
579 attachmentId: file.uploadedAttachmentId,
580 },
581 }
582 : {})}
583 onRemove={() => {
584 onRemove(file.id);
585 onClose();
586 }}
587 onClose={onClose}
588 />
589 </DialogPopup>
590 </Dialog>
591 );
593​
594/** Thumbnails beside the single-line prompt while the composer rests. */
595export function ComposerRestingImagePreviews({
596 images,
597 allImages,
598 resolvedTheme,
599 onExpandImage,
600 onCopySnapshot,
601 onShowMore,
602}: {
603 readonly images: ReadonlyArray<ComposerImageAttachment>;
604 readonly allImages: ReadonlyArray<ComposerImageAttachment>;
605 readonly resolvedTheme: "light" | "dark";
606 readonly onCopySnapshot: (imageId: string) => Promise<void>;
607 readonly onExpandImage: (preview: ExpandedImagePreview) => void;
608 readonly onShowMore: () => void;
609}) {
610 const gt = useGT();
611 const counts = getRestingComposerImagePreviewCounts(images.length);
612 const visibleImages = images.slice(0, counts.visibleCount);
613 return (
614 <div data-chat-composer-resting-images="true" className="flex shrink-0 items-center gap-1 ps-1">
615 {visibleImages.map((image) => (
616 <button
617 key={image.id}
618 type="button"
619 className="relative size-7 shrink-0 cursor-zoom-in overflow-hidden rounded-md border border-border/70 bg-muted/60"
620 aria-label={gt("Preview {name}", { name: image.name })}
621 onPointerDown={(event) => event.preventDefault()}
622 onClick={() => {
623 const preview = buildExpandedImagePreview(allImages, image.id, onCopySnapshot);
624 if (preview) onExpandImage(preview);
625 }}
626 >
627 {image.previewUrl ? (
628 <ComposerImageThumbnail
629 file={image.file}
630 alt=""
631 className="size-full object-cover"
632 fallback={
633 isHeicImageFile({ name: image.name, type: image.mimeType }) ? (
634 <AttachmentImage
635 name={image.name}
636 mimeType={image.mimeType}
637 src={image.previewUrl}
638 alt=""
639 className="size-full object-cover"
640 />
641 ) : (
642 <PierreEntryIcon
643 pathValue={image.name}
644 kind="file"
645 theme={resolvedTheme}
646 className="m-auto size-3.5"
647 />
648 )
649 }
650 />
651 ) : (
652 <PierreEntryIcon
653 pathValue={image.name}
654 kind="file"
655 theme={resolvedTheme}
656 className="m-auto size-3.5"
657 />
658 )}
659 </button>
660 ))}
661 {counts.overflowCount > 0 ? (
662 <button
663 type="button"
664 className="flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-md border border-border/70 bg-muted/60 font-medium text-secondary-label text-xs tabular-nums outline-none hover:bg-muted focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background"
665 aria-label={gt(
666 "{count, plural, one {Show {count} more image attachment} other {Show {count} more image attachments}}",
667 {
668 count: counts.overflowCount,
669 },
670 )}
671 onPointerDown={(event) => event.preventDefault()}
672 onClick={onShowMore}
673 >
674 +{counts.overflowCount}
675 </button>
676 ) : null}
677 </div>
678 );
680​
681/** Attachments of the queued message being edited; they are already uploaded. */
682export function ComposerQueuedAttachmentRow({
683 attachments,
684 onRemove,
685}: {
686 readonly attachments: ReadonlyArray<{
687 readonly attachment: ChatAttachment;
688 readonly url: string | null;
689 }>;
690 readonly onRemove: (attachmentId: string) => void;
691}) {
692 const gt = useGT();
693 return (
694 <div className="mb-3 flex flex-wrap gap-2">
695 {attachments.map(({ attachment, url }) => (
696 <div
697 key={attachment.id}
698 className="relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
699 >
700 {attachment.type === "image" && url ? (
701 <img src={url} alt={attachment.name} className="h-full w-full object-cover" />
702 ) : (
703 <div className="flex h-full w-full items-center justify-center px-1 text-center text-3xs text-secondary-label">
704 {attachment.name}
705 </div>
706 )}
707 <Button
708 variant="media-close"
709 size="icon-xs"
710 className="absolute right-1 top-1"
711 onClick={() => onRemove(attachment.id)}
712 aria-label={gt("Remove {name}", { name: attachment.name })}
713 >
714 <XIcon />
715 </Button>
716 </div>
717 ))}
718 </div>
719 );
721​
722// Kept outside the composer footer: on mobile the picker blurs the editor and the
723// footer unmounts, and a detached input never delivers its change event.
724export function ComposerAttachInput({
725 ref,
726 addComposerAttachments,
727 focusComposer,
728}: {
729 readonly ref: Ref<HTMLInputElement>;
730 readonly addComposerAttachments: (files: File[]) => Promise<boolean>;
731 readonly focusComposer: () => void;
732}) {
733 return (
734 <input
735 ref={ref}
736 type="file"
737 multiple
738 className="hidden"
739 onChange={(event) => {
740 const files = Array.from(event.currentTarget.files ?? []);
741 event.currentTarget.value = "";
742 // Inserting a chip refocuses the editor after the draft renders;
743 // focusing synchronously here would report the editor's stale text
744 // over the prompt that was just written.
745 void addComposerAttachments(files).then((inserted) => {
746 if (!inserted) focusComposer();
747 });
748 }}
749 />
750 );
752​
753export function ComposerAttachButton({ onOpenPicker }: { readonly onOpenPicker: () => void }) {
754 const gt = useGT();
755 return (
756 <SharedTooltipTrigger
757 render={
758 <Button
759 type="button"
760 variant="ghost"
761 size="icon-sm"
762 onPointerDown={(event) => event.preventDefault()}
763 onClick={onOpenPicker}
764 aria-label={gt("Attach files")}
765 />
766 }
767 label={
768 <>
769 <T>Attach files</T>
770 </>
771 }
772 >
773 {/* The clip's weight sits in its upper loop; 1px down reads as centered on the row. */}
774 <PaperclipIcon className="translate-y-px" />
775 </SharedTooltipTrigger>
776 );