Attachment Upload

Drop in files, images and audio, with previews, retry and removal.

Preview

"use client";

import { useEffect, useRef, useState } from "react";
import {
  AttachmentUpload,
  type AttachmentUploadItem,
} from "@/components/motion/attachment-upload";

const INITIAL_ITEMS: AttachmentUploadItem[] = [
  {
    id: "brief",
    name: "launch-brief.pdf",
    kind: "file",
    size: 32_400_000,
    href: "data:application/pdf,beUI%20launch%20brief",
    status: "failed",
    error: "Upload failed",
  },
  {
    id: "flowers",
    name: "orange-flowers.jpg",
    kind: "image",
    size: 9_800_000,
    previewUrl:
      "https://images.unsplash.com/photo-1490750967868-88aa4486c946?auto=format&fit=crop&w=1200&q=85",
  },
  {
    id: "voice-note",
    name: "launch-note.m4a",
    kind: "audio",
    currentTime: 12,
    duration: 48,
  },
];

export function AttachmentUploadPreview() {
  const [items, setItems] = useState(INITIAL_ITEMS);
  const [playingId, setPlayingId] = useState<string>();
  const retryTimersRef = useRef<number[]>([]);

  useEffect(
    () => () => {
      for (const timer of retryTimersRef.current) {
        window.clearTimeout(timer);
      }
    },
    [],
  );

  useEffect(() => {
    if (!playingId) return;

    const timer = window.setInterval(() => {
      setItems((current) =>
        current.map((item) => {
          if (item.id !== playingId || !item.duration) return item;
          const nextTime = Math.min(
            item.duration,
            (item.currentTime ?? 0) + 1,
          );
          return { ...item, currentTime: nextTime };
        }),
      );
    }, 1000);

    return () => window.clearInterval(timer);
  }, [playingId]);

  useEffect(() => {
    if (!playingId) return;
    const playingItem = items.find((item) => item.id === playingId);
    if (
      playingItem?.duration &&
      (playingItem.currentTime ?? 0) >= playingItem.duration
    ) {
      setPlayingId(undefined);
    }
  }, [items, playingId]);

  return (
    <div className="w-full max-w-2xl px-3 py-6 sm:px-6">
      <AttachmentUpload
        value={items}
        onValueChange={setItems}
        onRetry={(retryItem) => {
          setItems((current) =>
            current.map((item) =>
              item.id === retryItem.id
                ? { ...item, status: "uploading", error: undefined }
                : item,
            ),
          );

          const completeTimer = window.setTimeout(() => {
            setItems((current) =>
              current.map((item) =>
                item.id === retryItem.id
                  ? { ...item, status: "complete" }
                  : item,
              ),
            );
          }, 900);
          const readyTimer = window.setTimeout(() => {
            setItems((current) =>
              current.map((item) =>
                item.id === retryItem.id
                  ? { ...item, status: "idle" }
                  : item,
              ),
            );
          }, 1900);
          retryTimersRef.current.push(completeTimer, readyTimer);
        }}
        playingId={playingId}
        onAudioToggle={(item) => {
          setPlayingId((current) =>
            current === item.id ? undefined : item.id,
          );
        }}
        attachmentsLabel="Attachments:"
      />
    </div>
  );
}

Install

Add it with the shadcn CLI, or copy the source manually.

$ bunx --bun shadcn add @beui/attachment-upload

API Reference

value?
AttachmentUploadItem[]

The attachment list, for controlled use.

Default—
defaultValue?
AttachmentUploadItem[]

The initial attachment list when uncontrolled.

Default—
onValueChange?
((items: AttachmentUploadItem[]) => void)

Called with the full list when attachments are added or removed.

Default—
onFilesAdded?
((items: AttachmentUploadItem[], files: File[]) => void)

Called with the new items and their files after files are accepted.

Default—
onFilesRejected?
((files: File[], reason: AttachmentRejectReason) => void)

Called with files turned away for being too large or over `maxFiles`.

Default—
onRemove?
((item: AttachmentUploadItem) => void)

Called with the item after its remove animation finishes.

Default—
onRetry?
((item: AttachmentUploadItem) => void)

Called with a failed item when its retry button is pressed. Shows the button.

Default—
playingId?
string

Id of the audio attachment that shows as playing.

Default—
onAudioToggle?
((item: AttachmentUploadItem) => void)

Called with an audio item when its play or pause button is pressed.

Default—
accept?
string

File types the picker allows, as in the input `accept` attribute.

Default—
multiple?
boolean

Allows picking or dropping more than 1 file at a time. Default: true

Defaulttrue
maxFiles?
number

Most attachments allowed. The dropzone locks once reached. Default: 12

Default12
maxFileSize?
number

Largest file size allowed, in bytes. Default: 500 MB

Default500 * 1024 * 1024
disabled?
boolean

Turns off the dropzone and file picker. Default: false

Defaultfalse
title?
string

Heading inside the dropzone. Default: "Drag and drop or browse files"

Default—
description?
string

Line under the dropzone heading. Defaults to the max file size.

Default—
attachmentsLabel?
string

Heading above the attachment list. Default: "Attachments"

Default—
labels?
Partial<{ title: string; description: string; attachments: string; input: string; limitTitle: string; limitDescription: string; uploading: string; uploadComplete: string; uploadCompleteFor: string; ... 15 more ...; web: string; }>

Override any built-in string. `{name}` fills the per-attachment labels; `{count}` and `{max}` fill `limitDescription`; `{size}` fills `description`.

Default—
className?
string

Classes merged onto the root element.

Default—
classNames?
AttachmentUploadClassNames

Classes for the dropzone, list and each row.

Default—

More in File Upload

Keep in mind

Some components on this site are inspired by or recreated from existing work across the web. I'm not here to take credit; just to learn, experiment, and sometimes push things a bit further. If something looks familiar and I forgot to mention you, reach out and I'll fix that right away.

Updated