# File Input

A drop zone or button for choosing files, and a list of the files chosen.

Source: [file-input.tsx](https://github.com/jakejarvis/jarvis-ui/blob/main/src/components/ui/file-input.tsx)

```tsx
import {
  FileInput,
  FileInputDropzone,
  FileInputList,
  formatFileSize,
} from "@/components/ui/file-input";

const maxSize = 10_000_000;

export default function FileInputBasic() {
  return (
    <FileInput multiple accept="image/*,.pdf" maxSize={maxSize} className="max-w-sm">
      <FileInputDropzone>
        <span className="font-medium text-foreground">Drop files or click to browse</span>
        <span className="text-2xs">Images and PDFs, up to {formatFileSize(maxSize)}</span>
      </FileInputDropzone>
      <FileInputList />
    </FileInput>
  );
}
```

## Installation

Add the registry, once per project:

```bash
npx shadcn@latest registry add @jarvis=https://ui.jarv.is/r/{name}.json
```

Then add the component:

```bash
npx shadcn@latest add @jarvis/file-input
```

## Usage

```tsx
import { FileInput, FileInputDropzone, FileInputList } from "@/components/ui/file-input";

export function Attachments() {
  return (
    <FileInput multiple accept="image/*,.pdf">
      <FileInputDropzone>
        <span className="font-medium text-foreground">Drop files or click to browse</span>
      </FileInputDropzone>
      <FileInputList />
    </FileInput>
  );
}
```

`FileInput` holds the chosen files as `File` objects. It doesn't upload them: send them yourself,
or give it a `name` to submit them with a form.

`FileInputDropzone` accepts dropped files and opens the file picker on click. It's a button, so
use spans inside it. It renders an upload icon above its content: pass `icon` to replace the icon,
or `null` to remove it.

`FileInputList` renders a `FileInputItem` for each file, with a preview, the file's name and size,
and a button to remove it. `FileInputItemMetadata` truncates a long name in the middle with
[Truncate](https://ui.jarv.is/components/truncate.md), so the extension stays visible. To customize an item, such as to
show upload progress, pass `FileInputList` a function that renders each file, as in the example
below.

`accept`, `maxSize` and `maxFiles` limit which files are accepted. `onFileReject` is called with
each rejected file and the reason. Folders dropped on the dropzone are ignored.

Removing a file moves focus to the next file's remove button, or the previous one's. When the last
file is removed, focus moves to the dropzone or the trigger, or, if there's neither, to the next
focusable element on the page.

## Composition

- `FileInput`
  - `FileInputDropzone`
  - `FileInputTrigger`
  - `FileInputList`
    - `FileInputItem`
      - `FileInputItemPreview`
      - `FileInputItemMetadata`
      - `FileInputItemProgress`
      - `FileInputItemRemove`

## Examples

### Upload progress

Put a `FileInputItemProgress` in `FileInputItemMetadata` to show progress while a file uploads.

```tsx
"use client";

import * as React from "react";

import {
  FileInput,
  FileInputDropzone,
  FileInputItem,
  FileInputItemMetadata,
  FileInputItemPreview,
  FileInputItemProgress,
  FileInputItemRemove,
  FileInputList,
} from "@/components/ui/file-input";

// Stands in for a real upload, which would report progress from XMLHttpRequest's upload events.
function fakeUpload(onProgress: (percent: number) => void) {
  let percent = 0;
  const timer = setInterval(() => {
    percent = Math.min(percent + 6 + Math.random() * 14, 100);
    onProgress(Math.round(percent));
    if (percent === 100) clearInterval(timer);
  }, 300);
}

export default function FileInputWithProgress() {
  const [files, setFiles] = React.useState<File[]>([]);
  const [progress, setProgress] = React.useState(() => new Map<File, number>());

  function addFiles(next: File[]) {
    for (const file of next) {
      if (files.includes(file)) continue;
      fakeUpload((percent) => setProgress((current) => new Map(current).set(file, percent)));
    }
    setFiles(next);
  }

  return (
    <FileInput multiple value={files} onValueChange={addFiles} className="max-w-sm">
      <FileInputDropzone>
        <span className="font-medium text-foreground">Drop files or click to browse</span>
      </FileInputDropzone>
      <FileInputList>
        {(file) => {
          const percent = progress.get(file) ?? 0;
          return (
            <FileInputItem file={file}>
              <FileInputItemPreview />
              <FileInputItemMetadata>
                {percent < 100 ? <FileInputItemProgress value={percent} /> : null}
              </FileInputItemMetadata>
              <FileInputItemRemove />
            </FileInputItem>
          );
        }}
      </FileInputList>
    </FileInput>
  );
}
```

### With a label

In a [Field](https://ui.jarv.is/components/field.md), the `FieldLabel` labels the dropzone and the trigger. Set
`invalid` on the `Field` and explain a rejected file with a `FieldError`. The field's
`FieldDescription` and `FieldError` describe the dropzone and the trigger, which become invalid or
disabled along with the field.

```tsx
"use client";

import * as React from "react";

import { Field, FieldDescription, FieldError, FieldLabel } from "@/components/ui/field";
import { FileInput, FileInputDropzone, FileInputList } from "@/components/ui/file-input";

export default function FileInputWithLabel() {
  const [error, setError] = React.useState<string | null>(null);

  return (
    <Field invalid={!!error} className="w-full max-w-sm">
      <FieldLabel>Import contacts</FieldLabel>
      <FileInput
        accept=".csv"
        maxSize={5_000_000}
        onValueChange={() => setError(null)}
        onFileReject={(file, reason) =>
          setError(
            reason === "type" ? `${file.name} isn’t a CSV file.` : `${file.name} is over 5 MB.`,
          )
        }
      >
        <FileInputDropzone>
          <span className="font-medium text-foreground">Drop a CSV file or click to browse</span>
        </FileInputDropzone>
        <FileInputList />
      </FileInput>
      {error ? (
        <FieldError>{error}</FieldError>
      ) : (
        <FieldDescription>One contact per row, up to 5 MB.</FieldDescription>
      )}
    </Field>
  );
}
```

### In a form

Give a [`Field`](https://ui.jarv.is/components/field.md) or the `FileInput` a `name`, and the files are submitted under
it, each as a separate value, so `formData.getAll(name)` returns them all. When the `FileInput` is
outside the form, pass the form's `id` as `form`. With `required`, the form won't submit without a
file, and validation fails with `valueMissing`. A [Form](https://ui.jarv.is/components/form.md)'s `onFormSubmit`
receives the `File` objects as an array.

Resetting the form restores `defaultValue`, or clears the files if there isn't one. When that
changes the files, `onValueChange` is called with the reason `none`, so the parent of a controlled
`FileInput` decides whether to apply the change.

```tsx
"use client";

import { Button } from "@/components/ui/button";
import { Field, FieldDescription, FieldError, FieldLabel } from "@/components/ui/field";
import { FileInput, FileInputDropzone, FileInputList } from "@/components/ui/file-input";
import { Form } from "@/components/ui/form";
import { toast } from "@/components/ui/toast";

export default function FileInputForm() {
  return (
    <Form
      className="w-full max-w-sm"
      onFormSubmit={(values) => {
        const [resume] = values.resume as File[];
        toast.add({ title: "Application sent", description: `With ${resume?.name}.` });
      }}
    >
      <Field name="resume">
        <FieldLabel>Résumé</FieldLabel>
        <FileInput accept=".pdf" required>
          <FileInputDropzone>
            <span className="font-medium text-foreground">Drop a PDF or click to browse</span>
          </FileInputDropzone>
          <FileInputList />
        </FileInput>
        <FieldDescription>One PDF, sent with your application.</FieldDescription>
        <FieldError match="valueMissing">Add your résumé.</FieldError>
      </Field>
      <Button type="submit" variant="primary" className="self-start">
        Send application
      </Button>
    </Form>
  );
}
```

### With a button

`FileInputTrigger` opens the file picker from a button, when a drop zone would take too much room.

```tsx
import { PaperclipIcon } from "lucide-react";

import { FileInput, FileInputList, FileInputTrigger } from "@/components/ui/file-input";

export default function FileInputWithButton() {
  return (
    <FileInput multiple maxFiles={3} className="max-w-sm">
      <FileInputTrigger>
        <PaperclipIcon />
        Attach files
      </FileInputTrigger>
      <FileInputList />
    </FileInput>
  );
}
```

### Disabled

```tsx
import { FileInput, FileInputDropzone } from "@/components/ui/file-input";

export default function FileInputDisabled() {
  return (
    <FileInput disabled className="max-w-sm">
      <FileInputDropzone>
        <span className="font-medium text-foreground">Uploads are paused</span>
        <span className="text-2xs">Your workspace is out of storage.</span>
      </FileInputDropzone>
    </FileInput>
  );
}
```

## Props

The file also exports `formatFileSize(bytes, locale?)`, which formats a size such as "2.4 MB" for
`locale`, the same way `FileInput` formats each file's size with its own `locale`.

| Part | Extends |
| --- | --- |
| `FileInput` | `<div>` |
| `FileInputDropzone` | `<button>` |
| `FileInputTrigger` | [`Button`](https://ui.jarv.is/components/button.md) |
| `FileInputList` | `<ul>` |
| `FileInputItem` | `<li>` |
| `FileInputItemPreview` | `<span>` |
| `FileInputItemMetadata` | `<div>` |
| `FileInputItemProgress` | [`Progress`](https://ui.jarv.is/components/progress.md) |
| `FileInputItemRemove` | [`Button`](https://ui.jarv.is/components/button.md) |

Base UI's [styling](https://base-ui.com/react/handbook/styling) and [composition](https://base-ui.com/react/handbook/composition) guides say more about `className`, `style` and `render`.

### FileInput

| Prop             | Type                                                                   | Default   | Description                                                                                                                                                                               |
| ---------------- | ---------------------------------------------------------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `value?`         | `File[]`                                                               | —         | The chosen files.                                                                                                                                                                         |
| `defaultValue?`  | `File[]`                                                               | —         | The files chosen at first, and again when the form resets.                                                                                                                                |
| `onValueChange?` | `((files: File[], eventDetails: FileInputChangeEventDetails) => void)` | —         | Called with all the files after one is added or removed, and with `defaultValue` when a form reset changes the files. Calling `eventDetails.cancel()` keeps the files as they were.       |
| `accept?`        | `string`                                                               | —         | The file types to accept, as in a file input's `accept`: extensions such as `.pdf`, or MIME types such as `image/*`.                                                                      |
| `multiple?`      | `boolean`                                                              | `false`   | Whether users can choose more than one file. Otherwise, a new file replaces the current one.                                                                                              |
| `maxFiles?`      | `number`                                                               | —         | The maximum number of files to accept, with `multiple`.                                                                                                                                   |
| `maxSize?`       | `number`                                                               | —         | The maximum file size to accept, in bytes.                                                                                                                                                |
| `onFileReject?`  | `((file: File, reason: FileRejectReason) => void)`                     | —         | Called for each rejected file, with the reason: its `type`, its `size`, or the file `count`.                                                                                              |
| `disabled?`      | `boolean`                                                              | `false`   | Disables the dropzone, the trigger and each file's remove button. A disabled `Field` disables the input too.                                                                              |
| `name?`          | `string`                                                               | —         | The name the files are submitted under in a form. A `Field`'s `name` overrides it.                                                                                                        |
| `form?`          | `string`                                                               | —         | The `id` of the form to submit the files with, when the input isn't inside it.                                                                                                            |
| `required?`      | `boolean`                                                              | `false`   | Whether a form can't be submitted without a file.                                                                                                                                         |
| `locale?`        | `string`                                                               | `"en-US"` | The BCP 47 locale that formats each file's size.                                                                                                                                          |
| `className?`     | `string`                                                               | —         | CSS class applied to the element.                                                                                                                                                         |
| `style?`         | `React.CSSProperties`                                                  | —         | Style applied to the element.                                                                                                                                                             |
| `render?`        | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement`               | —         | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### FileInputDropzone

| Prop         | Type                                                     | Default          | Description                                                                                                                                                                               |
| ------------ | -------------------------------------------------------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `icon?`      | `React.ReactNode`                                        | `<UploadIcon />` | The icon above the text. Pass `null` for none.                                                                                                                                            |
| `className?` | `string`                                                 | —                | CSS class applied to the element.                                                                                                                                                         |
| `style?`     | `React.CSSProperties`                                    | —                | Style applied to the element.                                                                                                                                                             |
| `render?`    | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement` | —                | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### FileInputTrigger

| Prop                     | Type                                                                                 | Default       | Description                                                                                                                                                                               |
| ------------------------ | ------------------------------------------------------------------------------------ | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `focusableWhenDisabled?` | `boolean`                                                                            | `false`       | Whether the button should be focusable when disabled.                                                                                                                                     |
| `nativeButton?`          | `boolean`                                                                            | `true`        | Whether the component renders a native `<button>` element when replacing it via the `render` prop. Set to `false` if the rendered element is not a button (for example, `<div>`).         |
| `variant?`               | `"destructive" \| "ghost" \| "link" \| "outline" \| "primary" \| "secondary"`        | `"secondary"` |                                                                                                                                                                                           |
| `size?`                  | `"default" \| "icon" \| "icon-lg" \| "icon-sm" \| "icon-xs" \| "lg" \| "sm" \| "xs"` | `"default"`   |                                                                                                                                                                                           |
| `className?`             | `string \| ((state: ButtonState) => string \| undefined)`                            | —             | CSS class applied to the element, or a function that returns a class based on the component's state.                                                                                      |
| `style?`                 | `React.CSSProperties \| ((state: ButtonState) => React.CSSProperties \| undefined)`  | —             | Style applied to the element, or a function that returns a style object based on the component's state.                                                                                   |
| `render?`                | `ComponentRenderFn<HTMLProps, ButtonState> \| React.ReactElement`                    | —             | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### FileInputList

| Prop         | Type                                                     | Default                                   | Description                                                                                                                                                                               |
| ------------ | -------------------------------------------------------- | ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `children?`  | `((file: File, index: number) => React.ReactNode)`       | `(file) => <FileInputItem file={file} />` | Renders each file, usually as a `FileInputItem`.                                                                                                                                          |
| `className?` | `string`                                                 | —                                         | CSS class applied to the element.                                                                                                                                                         |
| `style?`     | `React.CSSProperties`                                    | —                                         | Style applied to the element.                                                                                                                                                             |
| `render?`    | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement` | —                                         | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### FileInputItem

| Prop         | Type                                                     | Default | Description                                                                                                                                                                               |
| ------------ | -------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `file`       | `File`                                                   | —       | The file this item shows.                                                                                                                                                                 |
| `className?` | `string`                                                 | —       | CSS class applied to the element.                                                                                                                                                         |
| `style?`     | `React.CSSProperties`                                    | —       | Style applied to the element.                                                                                                                                                             |
| `render?`    | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement` | —       | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### FileInputItemPreview

| Prop         | Type                                                     | Default | Description                                                                                                                                                                               |
| ------------ | -------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `className?` | `string`                                                 | —       | CSS class applied to the element.                                                                                                                                                         |
| `style?`     | `React.CSSProperties`                                    | —       | Style applied to the element.                                                                                                                                                             |
| `render?`    | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement` | —       | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### FileInputItemMetadata

| Prop         | Type                                                     | Default | Description                                                                                                                                                                               |
| ------------ | -------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `className?` | `string`                                                 | —       | CSS class applied to the element.                                                                                                                                                         |
| `style?`     | `React.CSSProperties`                                    | —       | Style applied to the element.                                                                                                                                                             |
| `render?`    | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement` | —       | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### FileInputItemProgress

| Prop                | Type                                                                                      | Default   | Description                                                                                                                                                                               |
| ------------------- | ----------------------------------------------------------------------------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `aria-valuetext?`   | `string`                                                                                  | —         | A string value that provides a user-friendly name for `aria-valuenow`, the current value of the progress bar.                                                                             |
| `format?`           | `Intl.NumberFormatOptions`                                                                | —         | Options to format the value.                                                                                                                                                              |
| `getAriaValueText?` | `((formattedValue: string, value: number \| null) => string)`                             | —         | Accepts a function which returns a string value that provides a human-readable text alternative for the current value of the progress bar.                                                |
| `locale?`           | `Intl.LocalesArgument`                                                                    | `"en-US"` | The locale used by `Intl.NumberFormat` when formatting the value. Defaults to the user's runtime locale.                                                                                  |
| `max?`              | `number`                                                                                  | `100`     | The maximum value.                                                                                                                                                                        |
| `min?`              | `number`                                                                                  | `0`       | The minimum value.                                                                                                                                                                        |
| `value`             | `number \| null`                                                                          | —         | The current value. The component is indeterminate when value is `null`.                                                                                                                   |
| `className?`        | `string \| ((state: ProgressRootState) => string \| undefined)`                           | —         | CSS class applied to the element, or a function that returns a class based on the component's state.                                                                                      |
| `style?`            | `React.CSSProperties \| ((state: ProgressRootState) => React.CSSProperties \| undefined)` | —         | Style applied to the element, or a function that returns a style object based on the component's state.                                                                                   |
| `render?`           | `ComponentRenderFn<HTMLProps, ProgressRootState> \| React.ReactElement`                   | —         | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### FileInputItemRemove

| Prop                     | Type                                                                                 | Default     | Description                                                                                                                                                                               |
| ------------------------ | ------------------------------------------------------------------------------------ | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `focusableWhenDisabled?` | `boolean`                                                                            | `false`     | Whether the button should be focusable when disabled.                                                                                                                                     |
| `nativeButton?`          | `boolean`                                                                            | `true`      | Whether the component renders a native `<button>` element when replacing it via the `render` prop. Set to `false` if the rendered element is not a button (for example, `<div>`).         |
| `variant?`               | `"destructive" \| "ghost" \| "link" \| "outline" \| "primary" \| "secondary"`        | `"ghost"`   |                                                                                                                                                                                           |
| `size?`                  | `"default" \| "icon" \| "icon-lg" \| "icon-sm" \| "icon-xs" \| "lg" \| "sm" \| "xs"` | `"icon-sm"` |                                                                                                                                                                                           |
| `className?`             | `string \| ((state: ButtonState) => string \| undefined)`                            | —           | CSS class applied to the element, or a function that returns a class based on the component's state.                                                                                      |
| `style?`                 | `React.CSSProperties \| ((state: ButtonState) => React.CSSProperties \| undefined)`  | —           | Style applied to the element, or a function that returns a style object based on the component's state.                                                                                   |
| `render?`                | `ComponentRenderFn<HTMLProps, ButtonState> \| React.ReactElement`                    | —           | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### useFileInput

`useFileInput()` reads the `FileInput` that your part renders in, and returns its files and
controls:

| Value      | Type                                                                          | Description                                                                                                                                                       |
| ---------- | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `files`    | `File[]`                                                                      | The files in the input, in the order they were added.                                                                                                             |
| `disabled` | `boolean`                                                                     | Whether the file input is disabled.                                                                                                                               |
| `open`     | `() => void`                                                                  | Opens the file picker, as `FileInputTrigger` does. Does nothing while the file input is disabled.                                                                 |
| `add`      | `(files: Iterable<File>, eventDetails?: FileInputChangeEventDetails) => void` | Adds files the same way a drop or the file picker does, rejecting any that the limits don't allow. `eventDetails` has the reason `none` unless you pass your own. |
| `remove`   | `(file: File, eventDetails?: FileInputChangeEventDetails) => boolean`         | Removes a file. Returns `false` when `onValueChange` cancels the change. `eventDetails` has the reason `none` unless you pass your own.                           |

To accept files dropped on your own element, pass its drop event's `dataTransfer` to
`getDroppedFiles(dataTransfer)`, then pass the result to `add`. `getDroppedFiles` returns the files
without any folders, which browsers list as empty files.
