@devries-cameron20 / t3code Mirror · read-only / commits / 7781e5209b
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 22, 20:45 UTC

refactor(web): composer attachment tiles live in their own component (#22689)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 21, 2026 at 01:24 UTC 7781e5209bde99e7dbaeb87b0209a99eef3c2ebf
2 files changed +589 -441
apps/web/src/components/chat/ChatComposer.tsx
+54 -441
@@ -6,15 +6,12 @@ import { runtimeModeConfig, runtimeModeOptions as runtimeModes } from "./runtime
6 import { isLocalEnvironmentDisabled } from "../../localEnvironment";
7 import { usePrimaryEnvironmentId } from "../../state/environments";
8 import { useRightPanelStore } from "~/rightPanelStore";
9 -import { AttachmentFilePreview } from "../files/AttachmentFilePreview";
10 -import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog";
9 import {
10 composerPullRequestsFromLinks,
11 filterComposerPullRequestMatches,
12 } from "@t3tools/shared/composerPullRequestMatches";
13 import { importPastedComposerText, readPastedComposerContext } from "../composerInlineTokenPaste";
14 import { elementContextToPreviewAnnotation } from "../../lib/elementContext";
17 -import { RefreshIcon } from "~/components/ui/refresh-icon";
15 import {
16 questionAttachmentDraftId,
17 countQuestionAttachments,
@@ -41,7 +38,6 @@ import type {
38 ScopedThreadRef,
39 ServerProvider,
40 ThreadId,
44 - SnapShotSource,
41 } from "@t3tools/contracts";
42 import {
43 EnvironmentRequestInvalidError,
@@ -69,7 +65,6 @@ import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model"
65 import { USAGE_LIMITS_COMMAND } from "@t3tools/shared/usageLimits";
66 import {
67 memo,
72 - type ComponentProps,
68 type ReactNode,
69 useEffect,
70 useEffectEvent,
@@ -110,7 +105,6 @@ import {
105 makeComposerMentionDragHandlers,
106 } from "./composerMentionDrag";
107 import {
113 - composerFloatingLayerProps,
108 useComposerMenuProps,
109 isInsideCollapsedComposerControls,
110 isInsideRestingComposerControlScope,
@@ -189,15 +183,11 @@ import {
183 releaseAttachmentUpload,
184 releaseDraftAttachment,
185 releasePersistedAttachmentUpload,
192 - retryAttachmentUpload,
186 startAttachmentUpload,
187 useAttachmentUploadStore,
188 verifyStashedAttachmentUpload,
189 } from "../../lib/attachmentUploadQueue";
197 -import {
198 - attachmentUploadBlockReason,
199 - formatAttachmentUploadProgress,
200 -} from "../../lib/attachmentUploadState";
190 +import { attachmentUploadBlockReason } from "../../lib/attachmentUploadState";
191 import { isCommandPaletteOpen } from "../../commandPaletteBus";
192 import { getTerminalFocusOwner } from "../../lib/terminalFocus";
193 import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
@@ -297,6 +287,11 @@ import {
287 import { ComposerPendingApprovalActions } from "./ComposerPendingApprovalActions";
288 import { CompactComposerControlsMenu } from "./CompactComposerControlsMenu";
289 import { ComposerImageThumbnail } from "./ComposerImageThumbnail";
290 +import {
291 + ComposerAttachmentFileList,
292 + ComposerAttachmentMediaRow,
293 + ComposerFilePreviewDialog,
294 +} from "./ComposerAttachmentStrip";
295 import { ComposerPrimaryActions } from "./ComposerPrimaryActions";
296 import { ComposerPendingApprovalPanel } from "./ComposerPendingApprovalPanel";
297 import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
@@ -331,21 +326,13 @@ import {
326 shouldReserveContextWindowMeter,
327 } from "./ContextWindowMeter.logic";
328 import {
334 - attachVideoThumbnail,
329 buildAttachmentVideoPreview,
330 buildExpandedImagePreview,
331 type ExpandedImagePreview,
332 } from "./ExpandedImagePreview";
339 -import {
340 - SNAP_SHOT_ATTACHMENT_FRAME_CLASS,
341 - SnapShotAttachmentDetails,
342 -} from "./SnapShotAttachmentDetails";
333 import {
334 getPendingSnapShotAnimations,
335 pendingSnapShotAnimationIdsForTarget,
346 - scheduleSnapShotAnimationDestination,
347 - setSnapShotAnimationDestination,
348 - shouldAnimateSnapShotArrival,
336 subscribeToPendingSnapShotAnimations,
337 } from "../../lib/snapShotAnimation";
338 import { resizeSnapShotSource } from "../../lib/snapShotSource";
@@ -371,28 +358,8 @@ import {
358 resetComposerScrollGesture,
359 suppressActiveComposerScrollGesture,
360 } from "./composerScrollGesture";
374 -import { prepareVideoFirstFrame } from "../../lib/videoFirstFrame";
361 import { observeResize } from "~/lib/observeResize";
362
377 -function ComposerVideoThumbnail({ file }: { file: File }) {
378 - const setVideo = (video: HTMLVideoElement | null) => {
379 - if (!video) return;
380 - return attachVideoThumbnail(video, file);
381 - };
382 -
383 - return (
384 - <video
385 - ref={setVideo}
386 - muted
387 - playsInline
388 - preload="metadata"
389 - aria-hidden="true"
390 - onLoadedMetadata={(event) => prepareVideoFirstFrame(event.currentTarget)}
391 - className="pointer-events-none absolute inset-0 size-full object-cover"
392 - />
393 - );
394 -}
395 -
363 type ComposerCommandMenuPosition = {
364 bottom: number;
365 left: number;
@@ -400,46 +367,6 @@ type ComposerCommandMenuPosition = {
367 width: number;
368 };
369
403 -function SnapShotAttachmentFrame({
404 - animationId,
405 - animationSource,
406 - arrival,
407 - animateArrival,
408 - className,
409 - ...props
410 -}: ComponentProps<"div"> & {
411 - readonly animationId?: string | undefined;
412 - readonly animationSource?: SnapShotSource | undefined;
413 - readonly arrival?: boolean | undefined;
414 - readonly animateArrival?: boolean | undefined;
415 -}) {
416 - const frameRef = useRef<HTMLDivElement>(null);
417 -
418 - useLayoutEffect(() => {
419 - const frame = frameRef.current;
420 - if (!frame || (!animationId && !arrival)) return;
421 - frame.scrollIntoView({ block: "nearest", inline: "nearest" });
422 - if (!animationId) return;
423 -
424 - return scheduleSnapShotAnimationDestination(animationId, () =>
425 - setSnapShotAnimationDestination(animationId, frame, animationSource),
426 - );
427 - }, [animationId, animationSource, arrival]);
428 -
429 - return (
430 - <div
431 - ref={frameRef}
432 - className={cn(
433 - animateArrival &&
434 - !animationId &&
435 - "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",
436 - className,
437 - )}
438 - {...props}
439 - />
440 - );
441 -}
442 -
370 const COMPOSER_PULL_REQUEST_LIST_LIMIT = 99;
371 const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidError);
372 const COMPOSER_PULL_REQUEST_RESULT_LIMIT = 12;
@@ -6404,6 +6331,47 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6331 ],
6332 );
6333
6334 + // Built outside the form's JSX so typing, which rebuilds that JSX, leaves them cached.
6335 + const composerAttachmentMediaRow =
6336 + !isComposerCollapsedMobile &&
6337 + (uncommittedSnapShotIds.length > 0 ||
6338 + composerVideos.length > 0 ||
6339 + expandedComposerImages.length > 0) ? (
6340 + <ComposerAttachmentMediaRow
6341 + images={composerImages}
6342 + expandedImages={expandedComposerImages}
6343 + videos={composerVideos}
6344 + pendingSnapShotAnimations={pendingSnapShotAnimations}
6345 + pendingSnapShotIds={pendingSnapShotIds}
6346 + uncommittedSnapShotIds={uncommittedSnapShotIds}
6347 + nonPersistedImageIds={nonPersistedComposerImageIds}
6348 + snapShotAnimations={settings.snapShotAnimations}
6349 + supportsAttachmentUploads={supportsAttachmentUploads}
6350 + maxFileAttachmentBytes={maxFileAttachmentBytes}
6351 + environmentId={environmentId}
6352 + attachmentDraftTarget={attachmentDraftTarget}
6353 + canOperateThread={canOperateThread}
6354 + onExpandImage={onExpandImage}
6355 + onFileOpen={onFileOpen}
6356 + onRemoveImage={removeComposerImage}
6357 + onRemoveFile={removeComposerFileFromDraft}
6358 + />
6359 + ) : null;
6360 + const composerAttachmentFileList =
6361 + !isComposerCollapsedMobile && composerOtherFiles.length > 0 ? (
6362 + <ComposerAttachmentFileList
6363 + files={composerOtherFiles}
6364 + resolvedTheme={resolvedTheme}
6365 + supportsAttachmentUploads={supportsAttachmentUploads}
6366 + maxFileAttachmentBytes={maxFileAttachmentBytes}
6367 + fileStagingLimit={fileStagingLimit}
6368 + environmentId={environmentId}
6369 + attachmentDraftTarget={attachmentDraftTarget}
6370 + canOperateThread={canOperateThread}
6371 + onPreviewFile={setPreviewFileId}
6372 + onRemoveFile={removeComposerFileFromDraft}
6373 + />
6374 + ) : null;
6375 return (
6376 <form
6377 ref={composerFormRef}
@@ -6758,334 +6726,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6726 </div>
6727 )}
6728
6761 - {!isComposerCollapsedMobile &&
6762 - (uncommittedSnapShotIds.length > 0 ||
6763 - composerVideos.length > 0 ||
6764 - expandedComposerImages.length > 0) && (
6765 - <div
6766 - className={cn(
6767 - "mb-3 flex max-w-full gap-2",
6768 - pendingSnapShotIds.length > 0 ||
6769 - expandedComposerImages.some((image) => image.source?.kind === "snap-shot")
6770 - ? "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"
6771 - : "flex-wrap",
6772 - )}
6773 - >
6774 - {expandedComposerImages
6775 - .map((image) => {
6776 - const upload = supportsAttachmentUploads
6777 - ? uploadsByImageId[image.id]
6778 - : undefined;
6779 - const snapShotAnimationPending =
6780 - image.source?.kind === "snap-shot" && pendingSnapShotIdSet.has(image.id);
6781 - const snapShotArrival =
6782 - image.source?.kind === "snap-shot" &&
6783 - shouldAnimateSnapShotArrival(image.source.capturedAt);
6784 - return (
6785 - <SnapShotAttachmentFrame
6786 - key={image.id}
6787 - data-chat-composer-expanded-image="true"
6788 - aria-hidden={snapShotAnimationPending || undefined}
6789 - inert={snapShotAnimationPending || undefined}
6790 - arrival={snapShotArrival}
6791 - animateArrival={
6792 - settings.snapShotAnimations &&
6793 - !snapShotAnimationPending &&
6794 - snapShotArrival
6795 - }
6796 - animationId={snapShotAnimationPending ? image.id : undefined}
6797 - animationSource={snapShotAnimationPending ? image.source : undefined}
6798 - className={cn(
6799 - "group/attachment shrink-0 snap-start bg-background",
6800 - image.source?.kind === "snap-shot"
6801 - ? SNAP_SHOT_ATTACHMENT_FRAME_CLASS
6802 - : "relative h-16 w-16 overflow-hidden rounded-lg border border-border/80",
6803 - snapShotAnimationPending && "invisible",
6804 - )}
6805 - >
6806 - {image.previewUrl ? (
6807 - <button
6808 - type="button"
6809 - className="h-full w-full cursor-zoom-in"
6810 - aria-label={`Preview ${image.name}`}
6811 - onClick={() => {
6812 - const preview = buildExpandedImagePreview(
6813 - composerImages,
6814 - image.id,
6815 - );
6816 - if (!preview) return;
6817 - onExpandImage(preview);
6818 - }}
6819 - >
6820 - <ComposerImageThumbnail
6821 - file={image.file}
6822 - alt={image.name}
6823 - className="h-full w-full object-cover"
6824 - fallback={
6825 - isHeicImageFile({ name: image.name, type: image.mimeType }) ? (
6826 - <AttachmentImage
6827 - name={image.name}
6828 - mimeType={image.mimeType}
6829 - src={image.previewUrl}
6830 - alt={image.name}
6831 - className="h-full w-full object-cover"
6832 - />
6833 - ) : (
6834 - <span className="flex h-full items-center justify-center px-1 text-3xs text-secondary-label">
6835 - {image.name}
6836 - </span>
6837 - )
6838 - }
6839 - />
6840 - </button>
6841 - ) : (
6842 - <div className="flex h-full w-full items-center justify-center px-1 text-center text-3xs text-secondary-label">
6843 - {image.name}
6844 - </div>
6845 - )}
6846 - {image.source?.kind === "snap-shot" ? (
6847 - <SnapShotAttachmentDetails
6848 - source={image.source}
6849 - className={cn(
6850 - upload?.status === "uploading" && "bottom-4",
6851 - upload?.status === "failed" && "bottom-8",
6852 - )}
6853 - />
6854 - ) : null}
6855 - {nonPersistedComposerImageIdSet.has(image.id) && (
6856 - <Tooltip>
6857 - <TooltipTrigger
6858 - render={
6859 - <span
6860 - role="img"
6861 - aria-label="Draft attachment may not persist"
6862 - className="absolute left-1 top-1 inline-flex items-center justify-center rounded bg-background/85 p-0.5 text-warning-foreground"
6863 - >
6864 - <CircleAlertIcon className="size-3" />
6865 - </span>
6866 - }
6867 - />
6868 - <TooltipPopup side="top">
6869 - Draft attachment could not be saved locally and may be lost on
6870 - navigation.
6871 - </TooltipPopup>
6872 - </Tooltip>
6873 - )}
6874 - {upload?.status === "uploading" && (
6875 - <span className="pointer-events-none absolute inset-x-0 bottom-0 bg-background/85 px-1 text-center text-3xs text-foreground">
6876 - {formatAttachmentUploadProgress(upload.progress)}
6877 - </span>
6878 - )}
6879 - {upload?.status === "failed" && (
6880 - <Tooltip>
6881 - <TooltipTrigger
6882 - render={
6883 - <Button
6884 - variant="overlay"
6885 - size="icon-xs"
6886 - className="absolute bottom-1 left-1"
6887 - onClick={() =>
6888 - retryAttachmentUpload({
6889 - environmentId,
6890 - image,
6891 - draftTarget: attachmentDraftTarget,
6892 - })
6893 - }
6894 - disabled={!canOperateThread}
6895 - aria-label={`Retry upload for ${image.name}`}
6896 - />
6897 - }
6898 - >
6899 - <RefreshIcon />
6900 - </TooltipTrigger>
6901 - <TooltipPopup side="top">{upload.reason}</TooltipPopup>
6902 - </Tooltip>
6903 - )}
6904 - <span
6905 - className={cn(
6906 - "absolute right-1 top-1 flex",
6907 - image.source?.kind === "snap-shot" &&
6908 - "opacity-0 transition-opacity pointer-coarse:opacity-100 group-hover/attachment:opacity-100 group-focus-within/attachment:opacity-100",
6909 - )}
6910 - >
6911 - <Button
6912 - variant="media-close"
6913 - size="icon-xs"
6914 - onClick={() => removeComposerImage(image.id)}
6915 - aria-label={`Remove ${image.name}`}
6916 - >
6917 - <XIcon />
6918 - </Button>
6919 - </span>
6920 - </SnapShotAttachmentFrame>
6921 - );
6922 - })
6923 - .concat(
6924 - uncommittedSnapShotIds.map((captureId) => (
6925 - <SnapShotAttachmentFrame
6926 - key={captureId}
6927 - aria-hidden="true"
6928 - animationId={captureId}
6929 - animationSource={
6930 - pendingSnapShotAnimations.find((capture) => capture.id === captureId)
6931 - ?.source
6932 - }
6933 - className={cn(
6934 - SNAP_SHOT_ATTACHMENT_FRAME_CLASS,
6935 - "invisible shrink-0 snap-start bg-background",
6936 - )}
6937 - />
6938 - )),
6939 - )}
6940 - {composerVideos.map((file) => {
6941 - const fileCanUpload =
6942 - supportsAttachmentUploads &&
6943 - maxFileAttachmentBytes !== null &&
6944 - file.sizeBytes <= maxFileAttachmentBytes;
6945 - const upload = fileCanUpload ? uploadsByImageId[file.id] : undefined;
6946 - return (
6947 - <div
6948 - key={file.id}
6949 - className="relative h-16 w-16 shrink-0 snap-start overflow-hidden rounded-lg border border-border/80 bg-black"
6950 - >
6951 - <button
6952 - type="button"
6953 - className="flex h-full w-full cursor-zoom-in flex-col items-center justify-center gap-1 px-1 text-white"
6954 - aria-label={`Play ${file.name}`}
6955 - onClick={() => {
6956 - if (file.file !== null) {
6957 - const preview = buildExpandedImagePreview([file], file.id);
6958 - if (preview) onExpandImage(preview);
6959 - return;
6960 - }
6961 - if (!file.uploadedAttachmentId) return;
6962 - onFileOpen({ ...file, id: file.uploadedAttachmentId });
6963 - }}
6964 - >
6965 - {file.file && (
6966 - <>
6967 - <ComposerVideoThumbnail file={file.file} />
6968 - <span className="pointer-events-none absolute inset-0 bg-gradient-to-t from-black/70 via-black/10 to-black/10" />
6969 - </>
6970 - )}
6971 - <PlayIcon className="relative z-10 size-4 fill-current drop-shadow-md" />
6972 - </button>
6973 - {upload?.status === "uploading" && (
6974 - <span className="pointer-events-none absolute inset-x-0 bottom-0 bg-background/85 px-1 text-center text-3xs text-foreground">
6975 - {formatAttachmentUploadProgress(upload.progress)}
6976 - </span>
6977 - )}
6978 - {upload?.status === "failed" && (
6979 - <Tooltip>
6980 - <TooltipTrigger
6981 - render={
6982 - <Button
6983 - variant="overlay"
6984 - size="icon-xs"
6985 - className="absolute bottom-1 left-1"
6986 - onClick={() =>
6987 - retryAttachmentUpload({
6988 - environmentId,
6989 - image: file,
6990 - draftTarget: attachmentDraftTarget,
6991 - })
6992 - }
6993 - disabled={!canOperateThread}
6994 - aria-label={`Retry upload for ${file.name}`}
6995 - />
6996 - }
6997 - >
6998 - <RefreshIcon />
6999 - </TooltipTrigger>
7000 - <TooltipPopup side="top">{upload.reason}</TooltipPopup>
7001 - </Tooltip>
7002 - )}
7003 - <Button
7004 - variant="media-close"
7005 - size="icon-xs"
7006 - className="absolute right-1 top-1"
7007 - onClick={() => removeComposerFileFromDraft(file.id)}
7008 - aria-label={`Remove ${file.name}`}
7009 - >
7010 - <XIcon />
7011 - </Button>
7012 - </div>
7013 - );
7014 - })}
7015 - </div>
7016 - )}
6729 + {composerAttachmentMediaRow}
6730
7018 - {!isComposerCollapsedMobile && composerOtherFiles.length > 0 && (
7019 - <div className="mb-3 flex flex-col gap-1">
7020 - {composerOtherFiles.map((file) => {
7021 - const fileCanUpload =
7022 - supportsAttachmentUploads &&
7023 - maxFileAttachmentBytes !== null &&
7024 - file.sizeBytes <= maxFileAttachmentBytes;
7025 - const upload = fileCanUpload ? uploadsByImageId[file.id] : undefined;
7026 - const needsReattach = composerFileNeedsReattach(file);
7027 - const canReattachFile =
7028 - fileStagingLimit !== null && file.sizeBytes <= fileStagingLimit;
7029 - return (
7030 - <div
7031 - key={file.id}
7032 - className="flex min-w-0 items-center gap-2 py-1 text-sm text-foreground"
7033 - >
7034 - <PierreEntryIcon pathValue={file.name} kind="file" theme={resolvedTheme} />
7035 - <button
7036 - type="button"
7037 - disabled={needsReattach}
7038 - className="min-w-0 flex-1 truncate text-left hover:underline focus-visible:outline-2"
7039 - onClick={() => setPreviewFileId(file.id)}
7040 - >
7041 - {file.name}
7042 - </button>
7043 - <span className="shrink-0 text-xs text-secondary-label">
7044 - {needsReattach
7045 - ? canReattachFile
7046 - ? "Attach again"
7047 - : "Remove to send"
7048 - : upload?.status === "uploading"
7049 - ? formatAttachmentUploadProgress(upload.progress)
7050 - : formatAttachmentSize(file.sizeBytes)}
7051 - </span>
7052 - {!needsReattach && upload?.status === "failed" ? (
7053 - <Tooltip>
7054 - <TooltipTrigger
7055 - render={
7056 - <Button
7057 - variant="ghost"
7058 - size="icon-xs"
7059 - onClick={() =>
7060 - retryAttachmentUpload({
7061 - environmentId,
7062 - image: file,
7063 - draftTarget: attachmentDraftTarget,
7064 - })
7065 - }
7066 - disabled={!canOperateThread}
7067 - aria-label={`Retry upload for ${file.name}`}
7068 - />
7069 - }
7070 - >
7071 - <RefreshIcon />
7072 - </TooltipTrigger>
7073 - <TooltipPopup side="top">{upload.reason}</TooltipPopup>
7074 - </Tooltip>
7075 - ) : null}
7076 - <Button
7077 - variant="ghost"
7078 - size="icon-xs"
7079 - onClick={() => removeComposerFileFromDraft(file.id)}
7080 - aria-label={`Remove ${file.name}`}
7081 - >
7082 - <XIcon />
7083 - </Button>
7084 - </div>
7085 - );
7086 - })}
7087 - </div>
7088 - )}
6731 + {composerAttachmentFileList}
6732
6733 <div
6734 className={cn("relative", isComposerResting && "flex min-w-0 items-center gap-1")}
@@ -7096,41 +6739,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
6739 }
6740 >
6741 {previewFile ? (
7099 - <Dialog
7100 - open
7101 - onOpenChange={(open) => {
7102 - if (!open) setPreviewFileId(null);
7103 - }}
7104 - >
7105 - <DialogPopup
7106 - {...composerFloatingLayerProps}
7107 - className="h-[min(85vh,52rem)] max-w-4xl overflow-hidden"
7108 - showCloseButton={false}
7109 - >
7110 - <DialogTitle className="sr-only">{previewFile.name}</DialogTitle>
7111 - <AttachmentFilePreview
7112 - key={previewFile.id}
7113 - name={previewFile.name}
7114 - mimeType={previewFile.mimeType}
7115 - sizeBytes={previewFile.sizeBytes}
7116 - file={previewFile.file}
7117 - origin="Draft"
7118 - {...(previewFile.uploadedAttachmentId && previewFile.uploadEnvironmentId
7119 - ? {
7120 - asset: {
7121 - environmentId: previewFile.uploadEnvironmentId,
7122 - attachmentId: previewFile.uploadedAttachmentId,
7123 - },
7124 - }
7125 - : {})}
7126 - onRemove={() => {
7127 - removeComposerFileFromDraft(previewFile.id);
7128 - setPreviewFileId(null);
7129 - }}
7130 - onClose={() => setPreviewFileId(null)}
7131 - />
7132 - </DialogPopup>
7133 - </Dialog>
6742 + <ComposerFilePreviewDialog
6743 + file={previewFile}
6744 + onRemove={removeComposerFileFromDraft}
6745 + onPreviewFileIdChange={setPreviewFileId}
6746 + />
6747 ) : null}
6748 <ComposerContextActionsContext value={composerContextActions}>
6749 <ComposerPromptEditor
apps/web/src/components/chat/ComposerAttachmentStrip.tsx new
+535
@@ -0,0 +1,535 @@
1 +import type {
2 + ChatFileAttachment,
3 + EnvironmentId,
4 + ScopedThreadRef,
5 + SnapShotSource,
6 +} from "@t3tools/contracts";
7 +import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
8 +import { CircleAlertIcon, PlayIcon, XIcon } from "lucide-react";
9 +import { type ComponentProps, useLayoutEffect, useRef } from "react";
10 +
11 +import {
12 + type ComposerFileAttachment,
13 + type ComposerImageAttachment,
14 + type DraftId,
15 + composerFileNeedsReattach,
16 +} from "../../composerDraftStore";
17 +import { retryAttachmentUpload, useAttachmentUploadStore } from "../../lib/attachmentUploadQueue";
18 +import { formatAttachmentUploadProgress } from "../../lib/attachmentUploadState";
19 +import { isHeicImageFile } from "../../lib/imageCompression";
20 +import {
21 + type PendingSnapShotAnimation,
22 + scheduleSnapShotAnimationDestination,
23 + setSnapShotAnimationDestination,
24 + shouldAnimateSnapShotArrival,
25 +} from "../../lib/snapShotAnimation";
26 +import { cn } from "~/lib/utils";
27 +import { RefreshIcon } from "~/components/ui/refresh-icon";
28 +import { AttachmentFilePreview } from "../files/AttachmentFilePreview";
29 +import { AttachmentImage } from "../media/AttachmentImage";
30 +import { Button } from "../ui/button";
31 +import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog";
32 +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
33 +import { ComposerImageThumbnail } from "./ComposerImageThumbnail";
34 +import { composerFloatingLayerProps } from "./composerEventScope";
35 +import {
36 + attachVideoThumbnail,
37 + buildExpandedImagePreview,
38 + type ExpandedImagePreview,
39 +} from "./ExpandedImagePreview";
40 +import { PierreEntryIcon } from "./PierreEntryIcon";
41 +import {
42 + SNAP_SHOT_ATTACHMENT_FRAME_CLASS,
43 + SnapShotAttachmentDetails,
44 +} from "./SnapShotAttachmentDetails";
45 +import { prepareVideoFirstFrame } from "../../lib/videoFirstFrame";
46 +
47 +function ComposerVideoThumbnail({ file }: { file: File }) {
48 + const setVideo = (video: HTMLVideoElement | null) => {
49 + if (!video) return;
50 + return attachVideoThumbnail(video, file);
51 + };
52 +
53 + return (
54 + <video
55 + ref={setVideo}
56 + muted
57 + playsInline
58 + preload="metadata"
59 + aria-hidden="true"
60 + onLoadedMetadata={(event) => prepareVideoFirstFrame(event.currentTarget)}
61 + className="pointer-events-none absolute inset-0 size-full object-cover"
62 + />
63 + );
64 +}
65 +
66 +function SnapShotAttachmentFrame({
67 + animationId,
68 + animationSource,
69 + arrival,
70 + animateArrival,
71 + className,
72 + ...props
73 +}: ComponentProps<"div"> & {
74 + readonly animationId?: string | undefined;
75 + readonly animationSource?: SnapShotSource | undefined;
76 + readonly arrival?: boolean | undefined;
77 + readonly animateArrival?: boolean | undefined;
78 +}) {
79 + const frameRef = useRef<HTMLDivElement>(null);
80 +
81 + useLayoutEffect(() => {
82 + const frame = frameRef.current;
83 + if (!frame || (!animationId && !arrival)) return;
84 + frame.scrollIntoView({ block: "nearest", inline: "nearest" });
85 + if (!animationId) return;
86 +
87 + return scheduleSnapShotAnimationDestination(animationId, () =>
88 + setSnapShotAnimationDestination(animationId, frame, animationSource),
89 + );
90 + }, [animationId, animationSource, arrival]);
91 +
92 + return (
93 + <div
94 + ref={frameRef}
95 + className={cn(
96 + animateArrival &&
97 + !animationId &&
98 + "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",
99 + className,
100 + )}
101 + {...props}
102 + />
103 + );
104 +}
105 +
106 +/** Image, SnapShot and video tiles above the composer editor. */
107 +export function ComposerAttachmentMediaRow({
108 + images,
109 + expandedImages,
110 + videos,
111 + pendingSnapShotAnimations,
112 + pendingSnapShotIds,
113 + uncommittedSnapShotIds,
114 + nonPersistedImageIds,
115 + snapShotAnimations,
116 + supportsAttachmentUploads,
117 + maxFileAttachmentBytes,
118 + environmentId,
119 + attachmentDraftTarget,
120 + canOperateThread,
121 + onExpandImage,
122 + onFileOpen,
123 + onRemoveImage,
124 + onRemoveFile,
125 +}: {
126 + readonly images: ReadonlyArray<ComposerImageAttachment>;
127 + readonly expandedImages: ReadonlyArray<ComposerImageAttachment>;
128 + readonly videos: ReadonlyArray<ComposerFileAttachment>;
129 + readonly pendingSnapShotAnimations: ReadonlyArray<PendingSnapShotAnimation>;
130 + readonly pendingSnapShotIds: ReadonlyArray<string>;
131 + readonly uncommittedSnapShotIds: ReadonlyArray<string>;
132 + readonly nonPersistedImageIds: ReadonlyArray<string>;
133 + readonly snapShotAnimations: boolean;
134 + readonly supportsAttachmentUploads: boolean;
135 + readonly maxFileAttachmentBytes: number | null;
136 + readonly environmentId: EnvironmentId;
137 + readonly attachmentDraftTarget: ScopedThreadRef | DraftId;
138 + readonly canOperateThread: boolean;
139 + readonly onExpandImage: (preview: ExpandedImagePreview) => void;
140 + readonly onFileOpen: (attachment: ChatFileAttachment) => void;
141 + readonly onRemoveImage: (imageId: string) => void;
142 + readonly onRemoveFile: (fileId: string) => void;
143 +}) {
144 + const uploadsByImageId = useAttachmentUploadStore((state) => state.uploadsByImageId);
145 + const pendingSnapShotIdSet = new Set(pendingSnapShotIds);
146 + const nonPersistedImageIdSet = new Set(nonPersistedImageIds);
147 + return (
148 + <div
149 + className={cn(
150 + "mb-3 flex max-w-full gap-2",
151 + pendingSnapShotIds.length > 0 ||
152 + expandedImages.some((image) => image.source?.kind === "snap-shot")
153 + ? "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"
154 + : "flex-wrap",
155 + )}
156 + >
157 + {expandedImages
158 + .map((image) => {
159 + const upload = supportsAttachmentUploads ? uploadsByImageId[image.id] : undefined;
160 + const snapShotAnimationPending =
161 + image.source?.kind === "snap-shot" && pendingSnapShotIdSet.has(image.id);
162 + const snapShotArrival =
163 + image.source?.kind === "snap-shot" &&
164 + shouldAnimateSnapShotArrival(image.source.capturedAt);
165 + return (
166 + <SnapShotAttachmentFrame
167 + key={image.id}
168 + data-chat-composer-expanded-image="true"
169 + aria-hidden={snapShotAnimationPending || undefined}
170 + inert={snapShotAnimationPending || undefined}
171 + arrival={snapShotArrival}
172 + animateArrival={snapShotAnimations && !snapShotAnimationPending && snapShotArrival}
173 + animationId={snapShotAnimationPending ? image.id : undefined}
174 + animationSource={snapShotAnimationPending ? image.source : undefined}
175 + className={cn(
176 + "group/attachment shrink-0 snap-start bg-background",
177 + image.source?.kind === "snap-shot"
178 + ? SNAP_SHOT_ATTACHMENT_FRAME_CLASS
179 + : "relative h-16 w-16 overflow-hidden rounded-lg border border-border/80",
180 + snapShotAnimationPending && "invisible",
181 + )}
182 + >
183 + {image.previewUrl ? (
184 + <button
185 + type="button"
186 + className="h-full w-full cursor-zoom-in"
187 + aria-label={`Preview ${image.name}`}
188 + onClick={() => {
189 + const preview = buildExpandedImagePreview(images, image.id);
190 + if (!preview) return;
191 + onExpandImage(preview);
192 + }}
193 + >
194 + <ComposerImageThumbnail
195 + file={image.file}
196 + alt={image.name}
197 + className="h-full w-full object-cover"
198 + fallback={
199 + isHeicImageFile({ name: image.name, type: image.mimeType }) ? (
200 + <AttachmentImage
201 + name={image.name}
202 + mimeType={image.mimeType}
203 + src={image.previewUrl}
204 + alt={image.name}
205 + className="h-full w-full object-cover"
206 + />
207 + ) : (
208 + <span className="flex h-full items-center justify-center px-1 text-3xs text-secondary-label">
209 + {image.name}
210 + </span>
211 + )
212 + }
213 + />
214 + </button>
215 + ) : (
216 + <div className="flex h-full w-full items-center justify-center px-1 text-center text-3xs text-secondary-label">
217 + {image.name}
218 + </div>
219 + )}
220 + {image.source?.kind === "snap-shot" ? (
221 + <SnapShotAttachmentDetails
222 + source={image.source}
223 + className={cn(
224 + upload?.status === "uploading" && "bottom-4",
225 + upload?.status === "failed" && "bottom-8",
226 + )}
227 + />
228 + ) : null}
229 + {nonPersistedImageIdSet.has(image.id) && (
230 + <Tooltip>
231 + <TooltipTrigger
232 + render={
233 + <span
234 + role="img"
235 + aria-label="Draft attachment may not persist"
236 + className="absolute left-1 top-1 inline-flex items-center justify-center rounded bg-background/85 p-0.5 text-warning-foreground"
237 + >
238 + <CircleAlertIcon className="size-3" />
239 + </span>
240 + }
241 + />
242 + <TooltipPopup side="top">
243 + Draft attachment could not be saved locally and may be lost on navigation.
244 + </TooltipPopup>
245 + </Tooltip>
246 + )}
247 + {upload?.status === "uploading" && (
248 + <span className="pointer-events-none absolute inset-x-0 bottom-0 bg-background/85 px-1 text-center text-3xs text-foreground">
249 + {formatAttachmentUploadProgress(upload.progress)}
250 + </span>
251 + )}
252 + {upload?.status === "failed" && (
253 + <Tooltip>
254 + <TooltipTrigger
255 + render={
256 + <Button
257 + variant="overlay"
258 + size="icon-xs"
259 + className="absolute bottom-1 left-1"
260 + onClick={() =>
261 + retryAttachmentUpload({
262 + environmentId,
263 + image,
264 + draftTarget: attachmentDraftTarget,
265 + })
266 + }
267 + disabled={!canOperateThread}
268 + aria-label={`Retry upload for ${image.name}`}
269 + />
270 + }
271 + >
272 + <RefreshIcon />
273 + </TooltipTrigger>
274 + <TooltipPopup side="top">{upload.reason}</TooltipPopup>
275 + </Tooltip>
276 + )}
277 + <span
278 + className={cn(
279 + "absolute right-1 top-1 flex",
280 + image.source?.kind === "snap-shot" &&
281 + "opacity-0 transition-opacity pointer-coarse:opacity-100 group-hover/attachment:opacity-100 group-focus-within/attachment:opacity-100",
282 + )}
283 + >
284 + <Button
285 + variant="media-close"
286 + size="icon-xs"
287 + onClick={() => onRemoveImage(image.id)}
288 + aria-label={`Remove ${image.name}`}
289 + >
290 + <XIcon />
291 + </Button>
292 + </span>
293 + </SnapShotAttachmentFrame>
294 + );
295 + })
296 + .concat(
297 + uncommittedSnapShotIds.map((captureId) => (
298 + <SnapShotAttachmentFrame
299 + key={captureId}
300 + aria-hidden="true"
301 + animationId={captureId}
302 + animationSource={
303 + pendingSnapShotAnimations.find((capture) => capture.id === captureId)?.source
304 + }
305 + className={cn(
306 + SNAP_SHOT_ATTACHMENT_FRAME_CLASS,
307 + "invisible shrink-0 snap-start bg-background",
308 + )}
309 + />
310 + )),
311 + )}
312 + {videos.map((file) => {
313 + const fileCanUpload =
314 + supportsAttachmentUploads &&
315 + maxFileAttachmentBytes !== null &&
316 + file.sizeBytes <= maxFileAttachmentBytes;
317 + const upload = fileCanUpload ? uploadsByImageId[file.id] : undefined;
318 + return (
319 + <div
320 + key={file.id}
321 + className="relative h-16 w-16 shrink-0 snap-start overflow-hidden rounded-lg border border-border/80 bg-black"
322 + >
323 + <button
324 + type="button"
325 + className="flex h-full w-full cursor-zoom-in flex-col items-center justify-center gap-1 px-1 text-white"
326 + aria-label={`Play ${file.name}`}
327 + onClick={() => {
328 + if (file.file !== null) {
329 + const preview = buildExpandedImagePreview([file], file.id);
330 + if (preview) onExpandImage(preview);
331 + return;
332 + }
333 + if (!file.uploadedAttachmentId) return;
334 + onFileOpen({ ...file, id: file.uploadedAttachmentId });
335 + }}
336 + >
337 + {file.file && (
338 + <>
339 + <ComposerVideoThumbnail file={file.file} />
340 + <span className="pointer-events-none absolute inset-0 bg-gradient-to-t from-black/70 via-black/10 to-black/10" />
341 + </>
342 + )}
343 + <PlayIcon className="relative z-10 size-4 fill-current drop-shadow-md" />
344 + </button>
345 + {upload?.status === "uploading" && (
346 + <span className="pointer-events-none absolute inset-x-0 bottom-0 bg-background/85 px-1 text-center text-3xs text-foreground">
347 + {formatAttachmentUploadProgress(upload.progress)}
348 + </span>
349 + )}
350 + {upload?.status === "failed" && (
351 + <Tooltip>
352 + <TooltipTrigger
353 + render={
354 + <Button
355 + variant="overlay"
356 + size="icon-xs"
357 + className="absolute bottom-1 left-1"
358 + onClick={() =>
359 + retryAttachmentUpload({
360 + environmentId,
361 + image: file,
362 + draftTarget: attachmentDraftTarget,
363 + })
364 + }
365 + disabled={!canOperateThread}
366 + aria-label={`Retry upload for ${file.name}`}
367 + />
368 + }
369 + >
370 + <RefreshIcon />
371 + </TooltipTrigger>
372 + <TooltipPopup side="top">{upload.reason}</TooltipPopup>
373 + </Tooltip>
374 + )}
375 + <Button
376 + variant="media-close"
377 + size="icon-xs"
378 + className="absolute right-1 top-1"
379 + onClick={() => onRemoveFile(file.id)}
380 + aria-label={`Remove ${file.name}`}
381 + >
382 + <XIcon />
383 + </Button>
384 + </div>
385 + );
386 + })}
387 + </div>
388 + );
389 +}
390 +
391 +/** Non-media file attachments, listed under the media row. */
392 +export function ComposerAttachmentFileList({
393 + files,
394 + resolvedTheme,
395 + supportsAttachmentUploads,
396 + maxFileAttachmentBytes,
397 + fileStagingLimit,
398 + environmentId,
399 + attachmentDraftTarget,
400 + canOperateThread,
401 + onPreviewFile,
402 + onRemoveFile,
403 +}: {
404 + readonly files: ReadonlyArray<ComposerFileAttachment>;
405 + readonly resolvedTheme: "light" | "dark";
406 + readonly supportsAttachmentUploads: boolean;
407 + readonly maxFileAttachmentBytes: number | null;
408 + readonly fileStagingLimit: number | null;
409 + readonly environmentId: EnvironmentId;
410 + readonly attachmentDraftTarget: ScopedThreadRef | DraftId;
411 + readonly canOperateThread: boolean;
412 + readonly onPreviewFile: (fileId: string) => void;
413 + readonly onRemoveFile: (fileId: string) => void;
414 +}) {
415 + const uploadsByImageId = useAttachmentUploadStore((state) => state.uploadsByImageId);
416 + return (
417 + <div className="mb-3 flex flex-col gap-1">
418 + {files.map((file) => {
419 + const fileCanUpload =
420 + supportsAttachmentUploads &&
421 + maxFileAttachmentBytes !== null &&
422 + file.sizeBytes <= maxFileAttachmentBytes;
423 + const upload = fileCanUpload ? uploadsByImageId[file.id] : undefined;
424 + const needsReattach = composerFileNeedsReattach(file);
425 + const canReattachFile = fileStagingLimit !== null && file.sizeBytes <= fileStagingLimit;
426 + return (
427 + <div
428 + key={file.id}
429 + className="flex min-w-0 items-center gap-2 py-1 text-sm text-foreground"
430 + >
431 + <PierreEntryIcon pathValue={file.name} kind="file" theme={resolvedTheme} />
432 + <button
433 + type="button"
434 + disabled={needsReattach}
435 + className="min-w-0 flex-1 truncate text-left hover:underline focus-visible:outline-2"
436 + onClick={() => onPreviewFile(file.id)}
437 + >
438 + {file.name}
439 + </button>
440 + <span className="shrink-0 text-xs text-secondary-label">
441 + {needsReattach
442 + ? canReattachFile
443 + ? "Attach again"
444 + : "Remove to send"
445 + : upload?.status === "uploading"
446 + ? formatAttachmentUploadProgress(upload.progress)
447 + : formatAttachmentSize(file.sizeBytes)}
448 + </span>
449 + {!needsReattach && upload?.status === "failed" ? (
450 + <Tooltip>
451 + <TooltipTrigger
452 + render={
453 + <Button
454 + variant="ghost"
455 + size="icon-xs"
456 + onClick={() =>
457 + retryAttachmentUpload({
458 + environmentId,
459 + image: file,
460 + draftTarget: attachmentDraftTarget,
461 + })
462 + }
463 + disabled={!canOperateThread}
464 + aria-label={`Retry upload for ${file.name}`}
465 + />
466 + }
467 + >
468 + <RefreshIcon />
469 + </TooltipTrigger>
470 + <TooltipPopup side="top">{upload.reason}</TooltipPopup>
471 + </Tooltip>
472 + ) : null}
473 + <Button
474 + variant="ghost"
475 + size="icon-xs"
476 + onClick={() => onRemoveFile(file.id)}
477 + aria-label={`Remove ${file.name}`}
478 + >
479 + <XIcon />
480 + </Button>
481 + </div>
482 + );
483 + })}
484 + </div>
485 + );
486 +}
487 +
488 +export function ComposerFilePreviewDialog({
489 + file,
490 + onRemove,
491 + onPreviewFileIdChange,
492 +}: {
493 + readonly file: ComposerFileAttachment;
494 + readonly onRemove: (fileId: string) => void;
495 + readonly onPreviewFileIdChange: (fileId: string | null) => void;
496 +}) {
497 + const onClose = () => onPreviewFileIdChange(null);
498 + return (
499 + <Dialog
500 + open
501 + onOpenChange={(open) => {
502 + if (!open) onClose();
503 + }}
504 + >
505 + <DialogPopup
506 + {...composerFloatingLayerProps}
507 + className="h-[min(85vh,52rem)] max-w-4xl overflow-hidden"
508 + showCloseButton={false}
509 + >
510 + <DialogTitle className="sr-only">{file.name}</DialogTitle>
511 + <AttachmentFilePreview
512 + key={file.id}
513 + name={file.name}
514 + mimeType={file.mimeType}
515 + sizeBytes={file.sizeBytes}
516 + file={file.file}
517 + origin="Draft"
518 + {...(file.uploadedAttachmentId && file.uploadEnvironmentId
519 + ? {
520 + asset: {
521 + environmentId: file.uploadEnvironmentId,
522 + attachmentId: file.uploadedAttachmentId,
523 + },
524 + }
525 + : {})}
526 + onRemove={() => {
527 + onRemove(file.id);
528 + onClose();
529 + }}
530 + onClose={onClose}
531 + />
532 + </DialogPopup>
533 + </Dialog>
534 + );
535 +}