# Upload (https://s3.dimah.dev/docs/ui/components/upload)

Upload files with a button, a dropzone, or a paste, and show their progress.
`Upload` holds one [`useUpload`](https://s3.dimah.dev/docs/react/hooks/upload) hook, and the parts
inside it render that hook.

For a form value, use [Upload Field](https://s3.dimah.dev/docs/ui/components/upload-field). For a
profile picture, use [Avatar Upload](https://s3.dimah.dev/docs/ui/components/avatar-upload).

```tsx title="upload-demo.tsx"
"use client";

import { useUpload } from "@dimah-s3/react";
import { Upload, UploadDropzone, UploadToasts } from "@dimah-s3/ui";

export function UploadDemo() {
  const upload = useUpload({
    route: "uploads",
    maxFiles: 4,
    maxFileSize: 75 * 1024 * 1024,
    append: true,
  });

  return (
    <div className="mx-auto w-full max-w-md">
      <Upload upload={upload}>
        <UploadDropzone />
      </Upload>
      <UploadToasts upload={upload} />
    </div>
  );
}
```

## Installation [#installation]

<Tabs items={["npm","shadcn"]}>
<Tab value="npm">
```tsx
import {
  Upload,
  UploadDropzone,
  UploadStatus,
  UploadToasts,
  UploadTrigger,
} from "@dimah-s3/ui";
```
</Tab>

<Tab value="shadcn">
```npm
npx shadcn@latest add @dimah-s3/upload
```

The parts land in `components/dimah-s3/upload/`, one file each, such as
`@/components/dimah-s3/upload/upload-dropzone`. `usePasteFiles` is in
`@/hooks/use-paste-files`, and `useUploadHints` in `@/lib/upload-hints`.
</Tab>
</Tabs>

Complete [Installation](https://s3.dimah.dev/docs/ui/installation) first: the package or registry
setup, the stylesheet, and one `<Toaster />` in your layout.

## Usage [#usage]

```tsx
"use client";

import { useUpload } from "@dimah-s3/react";
import { Upload, UploadDropzone, UploadToasts } from "@dimah-s3/ui";

export function Attachments() {
  const upload = useUpload({ route: "attachments", maxFiles: 5, append: true });

  return (
    <>
      <Upload upload={upload}>
        <UploadDropzone />
      </Upload>
      <UploadToasts upload={upload} />
    </>
  );
}
```

## Anatomy [#anatomy]

```tsx
<Upload upload={upload}>
  <UploadTrigger />
  <UploadDropzone>
    <UploadDropzoneTrigger />
    <UploadStatus />
  </UploadDropzone>
  <UploadFileList />
</Upload>
<UploadToasts upload={upload} />
```

| Part                    | Description                                                                  |
| ----------------------- | ---------------------------------------------------------------------------- |
| `Upload`                | Root. Holds the hook and the hidden file input. Renders no element           |
| `UploadTrigger`         | A `Button` that opens the file picker                                        |
| `UploadDropzone`        | A drop area. By default it holds a dropzone trigger and the status           |
| `UploadDropzoneTrigger` | The clickable part of a dropzone, with an icon, a title, and the limits      |
| `UploadStatus`          | Progress of the queue: one card for one file, a summary and rows for several |
| `UploadFileList`        | Every file in the queue, as rows or a grid. Render each file yourself        |
| `UploadToasts`          | Progress, results, and rejected files as toasts. Mount once per hook         |

Place the parts anywhere inside `Upload`. Several parts can share one hook,
such as a toolbar button and a dropzone.

## Examples [#examples]

### Button [#button]

A trigger with the status under it.

```tsx title="upload-button-demo.tsx"
"use client";

import { useUpload } from "@dimah-s3/react";
import {
  Upload,
  UploadStatus,
  UploadToasts,
  UploadTrigger,
} from "@dimah-s3/ui";

export function UploadButtonDemo() {
  const upload = useUpload({
    route: "uploads",
    maxFileSize: 75 * 1024 * 1024,
  });

  return (
    <div className="mx-auto flex w-full max-w-sm flex-col items-center gap-3">
      <Upload upload={upload}>
        <UploadTrigger />
        <UploadStatus />
      </Upload>
      <UploadToasts upload={upload} />
    </div>
  );
}
```

### Button styles [#button-styles]

`UploadTrigger` is a `Button`: pass `variant`, `size`, and `children` to
restyle it, and `tooltip` to add a tooltip. At an icon size it shows the icon
alone and keeps its accessible name.

```tsx title="upload-trigger-variants-demo.tsx"
"use client";

import { ImagePlusIcon, PaperclipIcon, PlusIcon } from "lucide-react";
import { useUpload } from "@dimah-s3/react";
import {
  Upload,
  UploadStatus,
  UploadToasts,
  UploadTrigger,
} from "@dimah-s3/ui";

export function UploadTriggerVariantsDemo() {
  const upload = useUpload({
    route: "uploads",
    maxFiles: 3,
    maxFileSize: 75 * 1024 * 1024,
    append: true,
  });

  return (
    <div className="mx-auto flex w-full max-w-md flex-col gap-4">
      <Upload upload={upload}>
        <div className="flex flex-wrap items-center justify-center gap-2">
          <UploadTrigger />
          <UploadTrigger variant="outline" />
          <UploadTrigger variant="secondary">
            <PaperclipIcon data-icon="inline-start" />
            Attach
          </UploadTrigger>
          <UploadTrigger variant="ghost" size="sm">
            <ImagePlusIcon data-icon="inline-start" />
            Add photos
          </UploadTrigger>
          <UploadTrigger
            variant="outline"
            size="icon"
            aria-label="Upload files"
            tooltip="Upload files"
          >
            <PlusIcon />
          </UploadTrigger>
        </div>
        <UploadStatus />
      </Upload>
      <UploadToasts upload={upload} />
    </div>
  );
}
```

### Image grid [#image-grid]

Give `UploadDropzone` children to arrange it yourself. `layout="grid"` shows
the files as tiles.

```tsx title="upload-gallery-demo.tsx"
"use client";

import { ImagesIcon } from "lucide-react";
import { useUpload } from "@dimah-s3/react";
import {
  Upload,
  UploadDropzone,
  UploadDropzoneTrigger,
  UploadStatus,
  UploadToasts,
} from "@dimah-s3/ui";

export function UploadGalleryDemo() {
  const upload = useUpload({
    route: "uploads",
    accept: ["image/*"],
    maxFiles: 8,
    maxFileSize: 10 * 1024 * 1024,
    append: true,
  });

  return (
    <div className="mx-auto w-full max-w-lg">
      <Upload upload={upload}>
        <UploadDropzone>
          <UploadDropzoneTrigger>
            <ImagesIcon
              className="size-8 text-muted-foreground"
              strokeWidth={1.5}
            />
            <div className="flex flex-col gap-1">
              <p className="text-sm font-medium">Add photos to the album</p>
              <p className="text-xs text-muted-foreground">
                Drop up to 8 images, or click to choose them.
              </p>
            </div>
          </UploadDropzoneTrigger>
          <UploadStatus layout="grid" />
        </UploadDropzone>
      </Upload>
      <UploadToasts upload={upload} />
    </div>
  );
}
```

### Compact dropzone [#compact-dropzone]

A one-line dropzone for a form, with the status outside it. `useUploadHints`
returns the route's limits as text.

```tsx title="upload-compact-demo.tsx"
"use client";

import { FileUpIcon } from "lucide-react";
import { useUpload } from "@dimah-s3/react";
import {
  Upload,
  UploadDropzone,
  UploadDropzoneTrigger,
  UploadStatus,
  UploadToasts,
  useUploadHints,
} from "@dimah-s3/ui";

export function UploadCompactDemo() {
  const upload = useUpload({
    route: "uploads",
    accept: ["application/pdf"],
    maxFileSize: 20 * 1024 * 1024,
  });
  // The route's limits as text, such as "Up to 20.0 MB."
  const hints = useUploadHints(upload.policy);

  return (
    <div className="mx-auto flex w-full max-w-md flex-col gap-2">
      <Upload upload={upload}>
        <UploadDropzone>
          <UploadDropzoneTrigger className="min-h-0 flex-row justify-start gap-3 p-3 text-start">
            <span className="flex size-9 shrink-0 items-center justify-center rounded-md bg-muted">
              <FileUpIcon className="size-4" />
            </span>
            <span className="flex min-w-0 flex-col">
              <span className="text-sm font-medium">
                Drop your contract, or{" "}
                <span className="text-primary underline underline-offset-4">
                  browse
                </span>
              </span>
              <span className="text-xs text-muted-foreground">
                PDF only. {hints.limits}
              </span>
            </span>
          </UploadDropzoneTrigger>
        </UploadDropzone>
        {/* Outside the dropzone, so it keeps its own place in the layout. */}
        <UploadStatus />
      </Upload>
      <UploadToasts upload={upload} />
    </div>
  );
}
```

### Custom file rows [#custom-file-rows]

Pass a function to `UploadFileList` to render each file from `upload.files`,
with its `phase`, `progress`, and `error`.

```tsx title="upload-file-list-demo.tsx"
"use client";

import { CheckIcon, XIcon } from "lucide-react";
import {
  useFormatFileSize,
  useUpload,
  type UploadFileState,
} from "@dimah-s3/react";
import {
  FileTypeGlyph,
  Upload,
  UploadFileList,
  UploadToasts,
  UploadTrigger,
} from "@dimah-s3/ui";
import { Button } from "@/components/ui/button";

export function UploadFileListDemo() {
  const upload = useUpload({
    route: "uploads",
    maxFiles: 5,
    maxFileSize: 75 * 1024 * 1024,
    append: true,
  });
  const formatFileSize = useFormatFileSize();

  function status(file: UploadFileState) {
    switch (file.phase) {
      case "success":
        return <CheckIcon className="size-4 text-green-600" />;
      case "error":
        return <span className="text-destructive">Failed</span>;
      case "uploading":
        return `${file.progress.percent}%`;
      default:
        return "Waiting…";
    }
  }

  return (
    <div className="mx-auto flex w-full max-w-md flex-col items-start gap-3">
      <Upload upload={upload}>
        <UploadTrigger variant="outline" size="sm" />
        <UploadFileList className="gap-0 divide-y rounded-lg border">
          {(file) => (
            <div className="relative flex items-center gap-3 px-3 py-2 text-sm">
              <FileTypeGlyph
                layout="icon"
                fileName={file.fileName}
                contentType={file.contentType}
              />
              <div className="flex min-w-0 flex-1 flex-col">
                <span className="truncate font-medium">{file.fileName}</span>
                <span className="text-xs text-muted-foreground">
                  {formatFileSize(file.fileSize)}
                </span>
              </div>
              <span className="text-xs text-muted-foreground tabular-nums">
                {status(file)}
              </span>
              {file.phase === "uploading" || file.phase === "queued" ? (
                <Button
                  variant="ghost"
                  size="icon-xs"
                  aria-label={`Cancel ${file.fileName}`}
                  onClick={() => upload.cancel(file.id)}
                >
                  <XIcon />
                </Button>
              ) : null}
              {/* A thin bar along the bottom edge of the row. */}
              <span
                aria-hidden
                className="absolute inset-x-0 bottom-0 h-0.5 origin-left bg-primary transition-transform rtl:origin-right"
                style={{
                  transform: `scaleX(${file.phase === "uploading" ? file.progress.percent / 100 : 0})`,
                }}
              />
            </div>
          )}
        </UploadFileList>
      </Upload>
      <UploadToasts upload={upload} />
    </div>
  );
}
```

### Paste [#paste]

`usePasteFiles` uploads files pasted anywhere on the page. Pastes into text
fields are left alone.

```tsx title="upload-paste-demo.tsx"
"use client";

import { useUpload } from "@dimah-s3/react";
import {
  Upload,
  UploadStatus,
  UploadToasts,
  UploadTrigger,
  usePasteFiles,
} from "@dimah-s3/ui";

export function UploadPasteDemo() {
  const upload = useUpload({
    route: "uploads",
    accept: ["image/*"],
    maxFiles: 4,
    maxFileSize: 10 * 1024 * 1024,
    append: true,
  });
  // Files pasted anywhere on the page upload, except into text fields.
  usePasteFiles(upload);

  return (
    <div className="mx-auto flex w-full max-w-md flex-col items-center gap-3 text-center">
      <p className="text-sm text-muted-foreground">
        Copy an image or a screenshot, then press{" "}
        <kbd className="rounded border bg-muted px-1.5 font-mono text-xs">
          Ctrl
        </kbd>{" "}
        +{" "}
        <kbd className="rounded border bg-muted px-1.5 font-mono text-xs">
          V
        </kbd>{" "}
        anywhere on this page.
      </p>
      <Upload upload={upload}>
        <UploadTrigger variant="outline" size="sm">
          Or choose images
        </UploadTrigger>
        <UploadStatus layout="grid" />
      </Upload>
      <UploadToasts upload={upload} />
    </div>
  );
}
```

### Disabled [#disabled]

Pass `disabled` to `useUpload`. Every part follows it: triggers and the
dropzone disable, and drops and pastes do nothing.

```tsx title="upload-disabled-demo.tsx"
"use client";

import { useState } from "react";
import { LockIcon, LockOpenIcon } from "lucide-react";
import { useUpload } from "@dimah-s3/react";
import {
  Upload,
  UploadDropzone,
  UploadToasts,
  UploadTrigger,
} from "@dimah-s3/ui";
import { Button } from "@/components/ui/button";

export function UploadDisabledDemo() {
  const [locked, setLocked] = useState(true);
  const upload = useUpload({
    route: "uploads",
    maxFiles: 2,
    maxFileSize: 75 * 1024 * 1024,
    // Every part follows the hook: the picker, drops, and pastes stop.
    disabled: locked,
  });

  return (
    <div className="mx-auto flex w-full max-w-md flex-col gap-3">
      <Upload upload={upload}>
        <div className="flex items-center justify-between gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={() => setLocked((value) => !value)}
          >
            {locked ? (
              <LockOpenIcon data-icon="inline-start" />
            ) : (
              <LockIcon data-icon="inline-start" />
            )}
            {locked ? "Unlock uploads" : "Lock uploads"}
          </Button>
          <UploadTrigger size="sm" />
        </div>
        <UploadDropzone />
      </Upload>
      <UploadToasts upload={upload} />
    </div>
  );
}
```

## Dropzone [#dropzone]

Without children, `UploadDropzone` renders this:

```tsx
<UploadDropzone>
  <UploadDropzoneTrigger />
  <UploadStatus />
</UploadDropzone>
```

Pass children to change the layout, such as moving `UploadStatus` outside.
`UploadDropzoneTrigger` is a button: put links and other buttons next to it,
not inside.

Style the drag states with data attributes:

| Attribute          | Set when                                       |
| ------------------ | ---------------------------------------------- |
| `data-drag-active` | Files are dragged over the dropzone            |
| `data-drag-reject` | The dragged files break `accept` or `maxFiles` |
| `data-disabled`    | The hook is disabled, or the root is full      |

## Status [#status]

- **One file** shows as its own card, with cancel, retry, or dismiss.
- **Several files** show a summary, with the overall progress, the count, and
  the time left, then a row for each file. The summary cancels every upload,
  retries the failed ones, and dismisses the list once it settles.
- **Pause** appears while a multipart upload is in flight (a file of at least
  50 MiB on a route with multipart), since it resumes from its uploaded parts.
  A paused file shows "Paused" and its own resume action. Once every file in
  flight is paused, the summary offers resume for all of them.

Call `upload.reset()` to clear the status from your own code.

## Toasts [#toasts]

Parts never toast. Mount `UploadToasts` once per hook. It shows:

- A progress toast with a cancel action while files upload, and a resume action while they are paused.
- The result once the queue settles. A failure has a retry action.
- The reason for each call that rejects files, such as a file that is too large.

## Per-call options [#per-call-options]

`call` on `UploadTrigger` or `UploadDropzone` applies to the files they take
in. Its `uploadOptions` merge over the hook's, and `maxFiles` lowers the
hook's limit for that call.

```tsx
<UploadTrigger
  call={{ uploadOptions: { clientMetadata: { albumId } } }}
  tooltip="Add photos"
/>
```

Inside an [`ObjectList`](https://s3.dimah.dev/docs/ui/components/object-list) with the same hook,
files go to the open folder, and your `call` merges over that.

## Accessibility [#accessibility]

- `UploadTrigger` is named "Upload file" or "Upload files". At an icon size the
  label is visually hidden and stays its accessible name.
- `UploadDropzoneTrigger` is a button: click, Enter, or Space opens the picker,
  and a paste while it has focus uploads. The route's limits are its
  description.
- A polite live region announces when dragged files can or cannot be dropped.

## API Reference [#api-reference]

### Upload [#upload]

| Prop           | Type              | Default  | Description                                                                         |
| -------------- | ----------------- | -------- | ----------------------------------------------------------------------------------- |
| `upload`       | `UseUploadReturn` | required | The `useUpload` return the parts read                                               |
| `isFull`       | `boolean`         | `false`  | Renders the triggers and retry actions as `aria-disabled`. The hook's limit decides |
| `hideUploaded` | `boolean`         | `false`  | Leaves finished files out of `UploadStatus` and `UploadFileList`                    |
| `children`     | `ReactNode`       | required | The parts                                                                           |

### UploadTrigger [#uploadtrigger]

Also accepts every `Button` prop.

| Prop       | Type                | Default                   | Description                                               |
| ---------- | ------------------- | ------------------------- | --------------------------------------------------------- |
| `call`     | `UploadCallOptions` | —                         | Options for the files picked through it                   |
| `tooltip`  | `ReactNode`         | —                         | Tooltip on hover and focus                                |
| `disabled` | `boolean`           | `upload.disabled`         | Disables this trigger only. The hook can still disable it |
| `children` | `ReactNode`         | Icon and "Upload file(s)" | Replaces the icon and label                               |

### UploadDropzone [#uploaddropzone]

Also accepts every `div` prop.

| Prop       | Type                | Default                    | Description                                                          |
| ---------- | ------------------- | -------------------------- | -------------------------------------------------------------------- |
| `call`     | `UploadCallOptions` | —                          | Options for dropped files, and files picked or pasted on its trigger |
| `children` | `ReactNode`         | Trigger and `UploadStatus` | The dropzone content                                                 |

### UploadDropzoneTrigger [#uploaddropzonetrigger]

Accepts every `div` prop. `children` replace the default icon, title, and
limits.

### UploadStatus [#uploadstatus]

Also accepts every `div` prop except `children`.

| Prop     | Type               | Default  | Description                        |
| -------- | ------------------ | -------- | ---------------------------------- |
| `layout` | `"list" \| "grid"` | `"list"` | Rows, or tiles with image previews |

### UploadFileList [#uploadfilelist]

Also accepts every `ul` prop except `children`.

| Prop       | Type                                   | Default          | Description                        |
| ---------- | -------------------------------------- | ---------------- | ---------------------------------- |
| `layout`   | `"list" \| "grid"`                     | `"list"`         | Rows, or tiles with image previews |
| `children` | `(file: UploadFileState) => ReactNode` | `UploadFileItem` | Renders one file                   |

### UploadFileItem [#uploadfileitem]

The default card of one file, with its progress, error, and cancel or retry.
Also accepts the [`FileAttachment`](https://s3.dimah.dev/docs/ui/components/attachment) props it
does not set itself, such as `actions` and `description`.

| Prop   | Type              | Default  | Description                 |
| ------ | ----------------- | -------- | --------------------------- |
| `file` | `UploadFileState` | required | One entry of `upload.files` |

### UploadToasts [#uploadtoasts]

| Prop     | Type              | Default  | Description               |
| -------- | ----------------- | -------- | ------------------------- |
| `upload` | `UseUploadReturn` | required | The hook return to report |

### usePasteFiles [#usepastefiles]

`usePasteFiles(upload, options?)` uploads files pasted anywhere on the page,
except into form fields, editable text, or a dropzone that already took the
paste.

| Option    | Type                | Default | Description                                        |
| --------- | ------------------- | ------- | -------------------------------------------------- |
| `call`    | `UploadCallOptions` | —       | Options for the pasted files                       |
| `enabled` | `boolean`           | `true`  | Listens for pastes. Off while the hook is disabled |

### useUploadHints [#useuploadhints]

`useUploadHints(upload.policy)` returns the route's limits as localized text,
the same lines the default dropzone shows.

| Property | Type             | Description                                       |
| -------- | ---------------- | ------------------------------------------------- |
| `limits` | `string \| null` | Count and size, such as "You can upload 3 files." |
| `accept` | `string \| null` | Accepted types, such as "Accepted PNG, JPEG."     |

### useUploadContext [#useuploadcontext]

Returns the root's values inside `Upload`, for parts of your own. See
[Custom UI](https://s3.dimah.dev/docs/ui/custom-ui).

| Property       | Type              | Description                               |
| -------------- | ----------------- | ----------------------------------------- |
| `upload`       | `UseUploadReturn` | The root's hook                           |
| `isFull`       | `boolean`         | The root takes no more files              |
| `hideUploaded` | `boolean`         | Status parts leave out the uploaded files |

## Frequently asked questions [#frequently-asked-questions]

<Accordions>
<Accordion title="How do I keep the picker closed in some cases?">
Call `event.preventDefault()` in the trigger's `onClick`:

```tsx
<UploadTrigger
  onClick={(event) => {
    if (!signedIn) event.preventDefault();
  }}
/>
```
</Accordion>

<Accordion title="How do I disable only one trigger?">
Pass `disabled` to that `UploadTrigger`. The hook stays enabled for the other
parts. While the hook itself is disabled, the picker stays closed whatever the
prop says.
</Accordion>

<Accordion title="Where did UploadButton and the 1.x UploadDropzone go?">
`UploadTrigger` is the button, and `UploadStatus` is the status it rendered
under it. `UploadDropzone` now goes inside `Upload` and reads its hook from
there. See [Upgrade to 2.0](https://s3.dimah.dev/docs/migration-2-0).
</Accordion>
</Accordions>