@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 783 lines 28.5 KB
Raw
1 import type {
2 ChatAttachment,
3 ChatFileAttachment,
4 EnvironmentId,
5 ScopedThreadRef,
6 SnapShotSource,
7 } from "@t3tools/contracts";
8 import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
9 import { T, useGT, useMessages } from "gt-react";
10 import { CircleAlertIcon, ImageIcon, PaperclipIcon, PlayIcon, XIcon } from "lucide-react";
11 import { type ComponentProps, useLayoutEffect, useRef } from "react";
12
13 import {
14 type ComposerFileAttachment,
15 type ComposerImageAttachment,
16 type DraftId,
17 composerFileNeedsReattach,
18 } from "../../composerDraftStore";
19 import { retryAttachmentUpload, useAttachmentUploadStore } from "../../lib/attachmentUploadQueue";
20 import {
21 attachmentUploadFailureText,
22 type AttachmentUploadState,
23 } from "../../lib/attachmentUploadState";
24 import { useAttachmentUploadProgress } from "../../hooks/useAttachmentUploadProgress";
25 import { isHeicImageFile } from "../../lib/imageCompression";
26 import {
27 type PendingSnapShotAnimation,
28 scheduleSnapShotAnimationDestination,
29 setSnapShotAnimationDestination,
30 shouldAnimateSnapShotArrival,
31 } from "../../lib/snapShotAnimation";
32 import { cn } from "~/lib/utils";
33 import { getRestingComposerImagePreviewCounts } from "../composerFooterLayout";
34 import { RefreshIcon } from "~/components/ui/refresh-icon";
35 import { AttachmentFilePreview } from "../files/AttachmentFilePreview";
36 import { AttachmentImage } from "../media/AttachmentImage";
37 import { Button } from "../ui/button";
38 import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog";
39 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
40 import { ComposerImageThumbnail } from "./ComposerImageThumbnail";
41 import { composerFloatingLayerProps } from "./composerEventScope";
42 import type { PreparingComposerImage } from "./preparingComposerImages";
43 import {
44 attachVideoThumbnail,
45 buildExpandedImagePreview,
46 type ExpandedImagePreview,
47 } from "./ExpandedImagePreview";
48 import { PierreEntryIcon } from "./PierreEntryIcon";
49 import {
50 SNAP_SHOT_ATTACHMENT_FRAME_CLASS,
51 SnapShotAttachmentDetails,
52 } from "./SnapShotAttachmentDetails";
53 import { prepareVideoFirstFrame } from "../../lib/videoFirstFrame";
54
55 function 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;
65 }
66
67 function 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 );
78 }
79
80 function 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 );
97 }
98
99 function 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 );
138 }
139
140 /** Image, SnapShot and video tiles above the composer editor. */
141 export 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 <Tooltip>
275 <TooltipTrigger
276 render={
277 <span
278 role="img"
279 aria-label={gt("Draft attachment may not persist")}
280 className="absolute left-1 top-1 inline-flex items-center justify-center rounded bg-background/85 p-0.5 text-warning-foreground"
281 >
282 <CircleAlertIcon className="size-3" />
283 </span>
284 }
285 />
286 <TooltipPopup side="top">
287 <T>
288 Draft attachment could not be saved locally and may be lost on navigation.
289 </T>
290 </TooltipPopup>
291 </Tooltip>
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 <Tooltip>
306 <TooltipTrigger
307 render={
308 <Button
309 variant="overlay"
310 size="icon-xs"
311 className="absolute bottom-1 left-1"
312 onClick={() =>
313 retryAttachmentUpload({
314 environmentId,
315 image: ready,
316 draftTarget: attachmentDraftTarget,
317 })
318 }
319 disabled={!canOperateThread}
320 aria-label={gt("Retry upload for {name}", { name: image.name })}
321 />
322 }
323 >
324 <RefreshIcon />
325 </TooltipTrigger>
326 <TooltipPopup side="top">
327 {attachmentUploadFailureText(upload, messages)}
328 </TooltipPopup>
329 </Tooltip>
330 )}
331 <span
332 className={cn(
333 "absolute right-1 top-1 flex",
334 source?.kind === "snap-shot" &&
335 "opacity-0 transition-opacity pointer-coarse:opacity-100 group-hover/attachment:opacity-100 group-focus-within/attachment:opacity-100",
336 )}
337 >
338 <Button
339 variant="media-close"
340 size="icon-xs"
341 onClick={() => onRemoveImage(image.id)}
342 aria-label={gt("Remove {name}", { name: image.name })}
343 >
344 <XIcon />
345 </Button>
346 </span>
347 </SnapShotAttachmentFrame>
348 );
349 })
350 .concat(
351 uncommittedSnapShotIds.map((captureId) => (
352 <SnapShotAttachmentFrame
353 key={captureId}
354 aria-hidden="true"
355 animationId={captureId}
356 animationSource={
357 pendingSnapShotAnimations.find((capture) => capture.id === captureId)?.source
358 }
359 className={cn(
360 SNAP_SHOT_ATTACHMENT_FRAME_CLASS,
361 "invisible shrink-0 snap-start bg-background",
362 )}
363 />
364 )),
365 )}
366 {videos.map((file) => {
367 const fileCanUpload =
368 supportsAttachmentUploads &&
369 maxFileAttachmentBytes !== null &&
370 file.sizeBytes <= maxFileAttachmentBytes;
371 const upload = fileCanUpload ? uploadsByImageId[file.id] : undefined;
372 return (
373 <div
374 key={file.id}
375 className="relative h-16 w-16 shrink-0 snap-start overflow-hidden rounded-lg border border-border/80 bg-black"
376 >
377 <button
378 type="button"
379 className="flex h-full w-full cursor-zoom-in flex-col items-center justify-center gap-1 px-1 text-white"
380 aria-label={gt("Play {name}", { name: file.name })}
381 onClick={() => {
382 if (file.file !== null) {
383 const preview = buildExpandedImagePreview([file], file.id);
384 if (preview) onExpandImage(preview);
385 return;
386 }
387 if (!file.uploadedAttachmentId) return;
388 onFileOpen({ ...file, id: file.uploadedAttachmentId });
389 }}
390 >
391 {file.file && (
392 <>
393 <ComposerVideoThumbnail file={file.file} />
394 <span className="pointer-events-none absolute inset-0 bg-gradient-to-t from-black/70 via-black/10 to-black/10" />
395 </>
396 )}
397 <PlayIcon className="relative z-10 size-4 fill-current drop-shadow-md" />
398 </button>
399 {upload?.status === "uploading" && (
400 <span className="pointer-events-none absolute inset-x-0 bottom-0 bg-background/85 px-1 text-center text-3xs text-foreground">
401 <ComposerAttachmentUploadProgress id={file.id} upload={upload} />
402 </span>
403 )}
404 {upload?.status === "failed" && (
405 <Tooltip>
406 <TooltipTrigger
407 render={
408 <Button
409 variant="overlay"
410 size="icon-xs"
411 className="absolute bottom-1 left-1"
412 onClick={() =>
413 retryAttachmentUpload({
414 environmentId,
415 image: file,
416 draftTarget: attachmentDraftTarget,
417 })
418 }
419 disabled={!canOperateThread}
420 aria-label={gt("Retry upload for {name}", { name: file.name })}
421 />
422 }
423 >
424 <RefreshIcon />
425 </TooltipTrigger>
426 <TooltipPopup side="top">
427 {attachmentUploadFailureText(upload, messages)}
428 </TooltipPopup>
429 </Tooltip>
430 )}
431 <Button
432 variant="media-close"
433 size="icon-xs"
434 className="absolute right-1 top-1"
435 onClick={() => onRemoveFile(file.id)}
436 aria-label={gt("Remove {name}", { name: file.name })}
437 >
438 <XIcon />
439 </Button>
440 </div>
441 );
442 })}
443 </div>
444 );
445 }
446
447 /** Non-media file attachments, listed under the media row. */
448 export function ComposerAttachmentFileList({
449 files,
450 resolvedTheme,
451 supportsAttachmentUploads,
452 maxFileAttachmentBytes,
453 fileStagingLimit,
454 environmentId,
455 attachmentDraftTarget,
456 canOperateThread,
457 onPreviewFile,
458 onRemoveFile,
459 }: {
460 readonly files: ReadonlyArray<ComposerFileAttachment>;
461 readonly resolvedTheme: "light" | "dark";
462 readonly supportsAttachmentUploads: boolean;
463 readonly maxFileAttachmentBytes: number | null;
464 readonly fileStagingLimit: number | null;
465 readonly environmentId: EnvironmentId;
466 readonly attachmentDraftTarget: ScopedThreadRef | DraftId;
467 readonly canOperateThread: boolean;
468 readonly onPreviewFile: (fileId: string) => void;
469 readonly onRemoveFile: (fileId: string) => void;
470 }) {
471 const gt = useGT();
472 const messages = useMessages();
473 const uploadsByImageId = useAttachmentUploadStore((state) => state.uploadsByImageId);
474 return (
475 <div className="mb-3 flex flex-col gap-1">
476 {files.map((file) => {
477 const fileCanUpload =
478 supportsAttachmentUploads &&
479 maxFileAttachmentBytes !== null &&
480 file.sizeBytes <= maxFileAttachmentBytes;
481 const upload = fileCanUpload ? uploadsByImageId[file.id] : undefined;
482 const needsReattach = composerFileNeedsReattach(file);
483 const canReattachFile = fileStagingLimit !== null && file.sizeBytes <= fileStagingLimit;
484 return (
485 <div
486 key={file.id}
487 className="flex min-w-0 items-center gap-2 py-1 text-sm text-foreground"
488 >
489 <PierreEntryIcon pathValue={file.name} kind="file" theme={resolvedTheme} />
490 <button
491 type="button"
492 disabled={needsReattach}
493 className="min-w-0 flex-1 truncate text-left hover:underline focus-visible:outline-2"
494 onClick={() => onPreviewFile(file.id)}
495 >
496 {file.name}
497 </button>
498 <span className="shrink-0 text-xs text-secondary-label">
499 {needsReattach ? (
500 canReattachFile ? (
501 gt("Attach again")
502 ) : (
503 gt("Remove to send")
504 )
505 ) : upload?.status === "uploading" ? (
506 <ComposerAttachmentUploadProgress
507 id={file.id}
508 upload={upload}
509 fallback={formatAttachmentSize(file.sizeBytes, messages)}
510 />
511 ) : (
512 formatAttachmentSize(file.sizeBytes, messages)
513 )}
514 </span>
515 {!needsReattach && upload?.status === "failed" ? (
516 <Tooltip>
517 <TooltipTrigger
518 render={
519 <Button
520 variant="ghost"
521 size="icon-xs"
522 onClick={() =>
523 retryAttachmentUpload({
524 environmentId,
525 image: file,
526 draftTarget: attachmentDraftTarget,
527 })
528 }
529 disabled={!canOperateThread}
530 aria-label={gt("Retry upload for {name}", { name: file.name })}
531 />
532 }
533 >
534 <RefreshIcon />
535 </TooltipTrigger>
536 <TooltipPopup side="top">
537 {attachmentUploadFailureText(upload, messages)}
538 </TooltipPopup>
539 </Tooltip>
540 ) : null}
541 <Button
542 variant="ghost"
543 size="icon-xs"
544 onClick={() => onRemoveFile(file.id)}
545 aria-label={gt("Remove {name}", { name: file.name })}
546 >
547 <XIcon />
548 </Button>
549 </div>
550 );
551 })}
552 </div>
553 );
554 }
555
556 export function ComposerFilePreviewDialog({
557 file,
558 onRemove,
559 onPreviewFileIdChange,
560 }: {
561 readonly file: ComposerFileAttachment;
562 readonly onRemove: (fileId: string) => void;
563 readonly onPreviewFileIdChange: (fileId: string | null) => void;
564 }) {
565 const gt = useGT();
566 const onClose = () => onPreviewFileIdChange(null);
567 return (
568 <Dialog
569 open
570 onOpenChange={(open) => {
571 if (!open) onClose();
572 }}
573 >
574 <DialogPopup
575 {...composerFloatingLayerProps}
576 className="h-[min(85vh,52rem)] max-w-4xl overflow-hidden"
577 showCloseButton={false}
578 >
579 <DialogTitle className="sr-only">{file.name}</DialogTitle>
580 <AttachmentFilePreview
581 key={file.id}
582 name={file.name}
583 mimeType={file.mimeType}
584 sizeBytes={file.sizeBytes}
585 file={file.file}
586 origin={gt("Draft", { $context: "where an attachment comes from: the unsent message" })}
587 {...(file.uploadedAttachmentId && file.uploadEnvironmentId
588 ? {
589 asset: {
590 environmentId: file.uploadEnvironmentId,
591 attachmentId: file.uploadedAttachmentId,
592 },
593 }
594 : {})}
595 onRemove={() => {
596 onRemove(file.id);
597 onClose();
598 }}
599 onClose={onClose}
600 />
601 </DialogPopup>
602 </Dialog>
603 );
604 }
605
606 /** Thumbnails beside the single-line prompt while the composer rests. */
607 export function ComposerRestingImagePreviews({
608 images,
609 allImages,
610 resolvedTheme,
611 onExpandImage,
612 onCopySnapshot,
613 onShowMore,
614 }: {
615 readonly images: ReadonlyArray<ComposerImageAttachment>;
616 readonly allImages: ReadonlyArray<ComposerImageAttachment>;
617 readonly resolvedTheme: "light" | "dark";
618 readonly onCopySnapshot: (imageId: string) => Promise<void>;
619 readonly onExpandImage: (preview: ExpandedImagePreview) => void;
620 readonly onShowMore: () => void;
621 }) {
622 const gt = useGT();
623 const counts = getRestingComposerImagePreviewCounts(images.length);
624 const visibleImages = images.slice(0, counts.visibleCount);
625 return (
626 <div data-chat-composer-resting-images="true" className="flex shrink-0 items-center gap-1 ps-1">
627 {visibleImages.map((image) => (
628 <button
629 key={image.id}
630 type="button"
631 className="relative size-7 shrink-0 cursor-zoom-in overflow-hidden rounded-md border border-border/70 bg-muted/60"
632 aria-label={gt("Preview {name}", { name: image.name })}
633 onPointerDown={(event) => event.preventDefault()}
634 onClick={() => {
635 const preview = buildExpandedImagePreview(allImages, image.id, onCopySnapshot);
636 if (preview) onExpandImage(preview);
637 }}
638 >
639 {image.previewUrl ? (
640 <ComposerImageThumbnail
641 file={image.file}
642 alt=""
643 className="size-full object-cover"
644 fallback={
645 isHeicImageFile({ name: image.name, type: image.mimeType }) ? (
646 <AttachmentImage
647 name={image.name}
648 mimeType={image.mimeType}
649 src={image.previewUrl}
650 alt=""
651 className="size-full object-cover"
652 />
653 ) : (
654 <PierreEntryIcon
655 pathValue={image.name}
656 kind="file"
657 theme={resolvedTheme}
658 className="m-auto size-3.5"
659 />
660 )
661 }
662 />
663 ) : (
664 <PierreEntryIcon
665 pathValue={image.name}
666 kind="file"
667 theme={resolvedTheme}
668 className="m-auto size-3.5"
669 />
670 )}
671 </button>
672 ))}
673 {counts.overflowCount > 0 ? (
674 <button
675 type="button"
676 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"
677 aria-label={gt(
678 "{count, plural, one {Show {count} more image attachments} other {Show {count} more image attachments}}",
679 {
680 count: counts.overflowCount,
681 },
682 )}
683 onPointerDown={(event) => event.preventDefault()}
684 onClick={onShowMore}
685 >
686 +{counts.overflowCount}
687 </button>
688 ) : null}
689 </div>
690 );
691 }
692
693 /** Attachments of the queued message being edited; they are already uploaded. */
694 export function ComposerQueuedAttachmentRow({
695 attachments,
696 onRemove,
697 }: {
698 readonly attachments: ReadonlyArray<{
699 readonly attachment: ChatAttachment;
700 readonly url: string | null;
701 }>;
702 readonly onRemove: (attachmentId: string) => void;
703 }) {
704 const gt = useGT();
705 return (
706 <div className="mb-3 flex flex-wrap gap-2">
707 {attachments.map(({ attachment, url }) => (
708 <div
709 key={attachment.id}
710 className="relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
711 >
712 {attachment.type === "image" && url ? (
713 <img src={url} alt={attachment.name} className="h-full w-full object-cover" />
714 ) : (
715 <div className="flex h-full w-full items-center justify-center px-1 text-center text-3xs text-secondary-label">
716 {attachment.name}
717 </div>
718 )}
719 <Button
720 variant="media-close"
721 size="icon-xs"
722 className="absolute right-1 top-1"
723 onClick={() => onRemove(attachment.id)}
724 aria-label={gt("Remove {name}", { name: attachment.name })}
725 >
726 <XIcon />
727 </Button>
728 </div>
729 ))}
730 </div>
731 );
732 }
733
734 export function ComposerAttachButton({
735 addComposerAttachments,
736 focusComposer,
737 }: {
738 readonly addComposerAttachments: (files: File[]) => Promise<boolean>;
739 readonly focusComposer: () => void;
740 }) {
741 const gt = useGT();
742 const inputRef = useRef<HTMLInputElement>(null);
743 return (
744 <>
745 <input
746 ref={inputRef}
747 type="file"
748 multiple
749 className="hidden"
750 onChange={(event) => {
751 const files = Array.from(event.currentTarget.files ?? []);
752 event.currentTarget.value = "";
753 // Inserting a chip refocuses the editor after the draft renders;
754 // focusing synchronously here would report the editor's stale text
755 // over the prompt that was just written.
756 void addComposerAttachments(files).then((inserted) => {
757 if (!inserted) focusComposer();
758 });
759 }}
760 />
761 <Tooltip>
762 <TooltipTrigger
763 render={
764 <Button
765 type="button"
766 variant="ghost"
767 size="icon-sm"
768 onPointerDown={(event) => event.preventDefault()}
769 onClick={() => inputRef.current?.click()}
770 aria-label={gt("Attach files")}
771 />
772 }
773 >
774 {/* The clip's weight sits in its upper loop; 1px down reads as centered on the row. */}
775 <PaperclipIcon className="translate-y-px" />
776 </TooltipTrigger>
777 <TooltipPopup>
778 <T>Attach files</T>
779 </TooltipPopup>
780 </Tooltip>
781 </>
782 );
783 }