# Uploader

## Introduction

Uploader is a file upload component that provides a drag-and-drop zone along with a file browser for selecting files. It handles file type validation, individual and total file size limits, minimum and maximum file count constraints, and displays uploaded file previews with delete capabilities. The component automatically generates helper text based on its configuration and surfaces clear error messages when validation rules are violated.

Uploader is designed for forms where users need to attach documents, images, or other files. It supports both controlled error states via the `error` prop and internal validation that triggers automatically when files are added. A [Figma design guide](https://www.figma.com/design/NoAOnaPiP2H2lzvRhkBnGZ/CDS-v1.1?node-id=2600-3701\&t=WLh4JrGHlzDGMeV4-0) is available for reference.

```tsx
<Uploader
  accept=".png"
  maxFileTotalSize={31457280}
/>
```

| Field            | Description                                                                                                                                                                                                                                                            | Default  |
| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
| accept           | \['허용되는 파일의 확장자.', '\`image/\*\` = \`.jpeg,.jpg,.png,.gif,.bmp,.tiff,.svg,.webp,.heic,.ico\`', '\`video/\*\` = \`.mp4,.avi,.mkv,.mov,.wmv,.flv,.webm,.mpeg,.3gp,.m4v\`', '\`audio/\*\` = \`.mp3,.wav,.flac,.aac,.ogg,.m4a,.wma,.aiff,.alac,.midi,.mp4\`'].join('\n\n') | ".png"   |
| label            | Uploader에 대한 label                                                                                                                                                                                                                                                     | —        |
| error            | —                                                                                                                                                                                                                                                                      | —        |
| disabled         | —                                                                                                                                                                                                                                                                      | —        |
| minCount         | upload 해야하는 최소 파일 개수                                                                                                                                                                                                                                                   | —        |
| maxCount         | upload 가능한 최대 파일 개수                                                                                                                                                                                                                                                    | —        |
| maxFileSize      | upload 가능한 단일 파일 최대 사이즈(MiB)                                                                                                                                                                                                                                           | —        |
| maxFileTotalSize | upload 가능한 최대 사이즈(MiB)                                                                                                                                                                                                                                                 | 31457280 |
| helperText       | 모든 안내 메세지/에러 메세지보다 해당 메세지가 우선적으로 보여진다.                                                                                                                                                                                                                                 | —        |
| onChange         | —                                                                                                                                                                                                                                                                      | —        |
| onDelete         | —                                                                                                                                                                                                                                                                      | —        |

## Usage

```tsx
import { Uploader } from '@ceed/cds';

function MyForm() {
  return (
    <Uploader
      accept=".png,.jpg,.pdf"
      maxFileTotalSize={10 * 1024 * 1024}
      maxCount={5}
      label="Attachments"
      onChange={(files) => console.log('Files added:', files)}
      onDelete={(fileId) => console.log('File removed:', fileId)}
    />
  );
}
```

## Default

The most basic Uploader requires `accept` and `maxFileTotalSize` props. Helper text is automatically generated from these values.

```tsx
<Uploader
  accept=".png"
  maxFileTotalSize={31457280}
/>
```

## With Label

Adding a `label` prop displays a title above the dropzone.

```tsx
<Uploader
  accept=".png"
  maxFileTotalSize={31457280}
  label="Click to Upload or drag file"
/>
```

## Sizes

Two sizes are available: `sm` and `md`. Use the smaller size for compact form layouts.

```tsx
<Stack gap={4}>
    <Stack gap={2}>
      <Typography level="title-sm">SM</Typography>
      <Uploader {...args} size="sm" />
    </Stack>
    <Stack gap={2}>
      <Typography level="title-sm">MD</Typography>
      <Uploader {...args} size="md" />
    </Stack>
  </Stack>
```

## File Type Restriction (Accepts)

The `accept` prop controls which file types are allowed. You can specify individual extensions (`.png,.jpg`) or use wildcards (`image/*`, `video/*`, `audio/*`) that map to predefined extension sets.

```tsx
<Uploader
  accept="image/png, image/jpeg, .pdf,.word,.txt,.doc,.docx"
  maxFileTotalSize={31457280}
/>
```

## Min Count Validation

The `minCount` prop sets a minimum number of required files. Validation triggers on form submission.

```tsx
<>
    <form
      onSubmit={(e) => {
        e.preventDefault();
        console.log("Submitted");
      }}
    >
      <Stack gap={2}>
        <Uploader {...args} />
        <Button type="submit">Submit</Button>
      </Stack>
    </form>
  </>
```

## With Uploaded Files

Display pre-existing uploaded files and enforce `maxCount` limits. Try uploading additional files to trigger the limit error.

```tsx
<Uploader
  accept=".png"
  maxFileTotalSize={31457280}
  label="Click to Upload or drag file"
  maxCount={3}
  uploaded={[{
  id: '1',
  name: 'file1.jpg',
  size: 1024
}, {
  id: '2',
  name: 'file2.jpg',
  size: 0
}]}
/>
```

## Total File Size Limit

The `maxFileTotalSize` prop limits the combined size of all uploaded files.

```tsx
<Uploader
  accept=".png"
  maxFileTotalSize={1048576}
  label="Click to Upload or drag file"
  size="sm"
/>
```

## Individual File Size Limit

The `maxFileSize` prop limits the size of each individual file, independent of the total size limit.

```tsx
<Uploader
  accept="image/*, .txt"
  maxFileTotalSize={31457280}
  label="Click to Upload or drag file"
  size="sm"
  maxFileSize={1048576}
/>
```

## Error State

Use the `error` prop to externally control the error state, and `helperText` to display a custom error message.

```tsx
<Uploader
  accept=".png"
  maxFileTotalSize={31457280}
  label="Click to Upload or drag file"
  error
  helperText="This is an error state with custom helper text"
/>
```

## Validation Errors

Demonstrates automatic validation error messages for various rule violations (file type, size, count).

```tsx
<Stack gap={4}>
    <Stack gap={2}>
      <Typography level="title-sm">Try uploading files that violate validation rules:</Typography>
      <Typography level="body-sm">
        • Upload a file larger than 500KB (individual file size limit)
      </Typography>
      <Typography level="body-sm">• Upload multiple files exceeding 1MB total</Typography>
      <Typography level="body-sm">• Upload more than 2 files</Typography>
      <Typography level="body-sm">• Upload non-PNG/JPG files</Typography>
    </Stack>
    <Uploader {...args} />
  </Stack>
```

## Helper Text Variations

Comparison of auto-generated helper text, custom helper text, and error-state helper text.

```tsx
<Stack gap={4}>
    <Stack gap={2}>
      <Typography level="title-sm">Default Helper Text (Generated)</Typography>
      <Uploader
        {...args}
        label="Default helper text"
        accept=".png,.jpg,.pdf"
        maxFileTotalSize={5 * 1024 * 1024}
        maxCount={3}
      />
    </Stack>
    <Stack gap={2}>
      <Typography level="title-sm">Custom Helper Text</Typography>
      <Uploader
        {...args}
        label="Custom helper text"
        accept=".png,.jpg,.pdf"
        maxFileTotalSize={5 * 1024 * 1024}
        maxCount={3}
        helperText="Please upload your profile documents (PNG, JPG, or PDF only)"
      />
    </Stack>
    <Stack gap={2}>
      <Typography level="title-sm">Error State with Custom Helper Text</Typography>
      <Uploader
        {...args}
        label="Error state"
        accept=".png,.jpg,.pdf"
        maxFileTotalSize={5 * 1024 * 1024}
        maxCount={3}
        error={true}
        helperText="There was an error processing your files. Please try again."
      />
    </Stack>
  </Stack>
```

## Disabled State

The Uploader can be disabled to prevent file selection and drag-and-drop interactions.

```tsx
<Uploader
  accept=".png"
  maxFileTotalSize={31457280}
  label="Click to Upload or drag file"
  disabled
/>
```

## Common Use Cases

### Profile Photo Upload

```tsx
import { Uploader } from '@ceed/cds';

function ProfilePhotoUpload() {
  return (
    <Uploader
      label="Profile Photo"
      accept="image/*"
      maxFileTotalSize={5 * 1024 * 1024}
      maxCount={1}
      maxFileSize={5 * 1024 * 1024}
      helperText="Upload a profile photo (JPG, PNG, max 5MB)"
    />
  );
}
```

### Document Attachment in a Form

```tsx
import { Uploader, Stack, Button } from '@ceed/cds';

function DocumentForm() {
  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
      }}
    >
      <Stack gap={3}>
        <Uploader
          label="Supporting Documents"
          accept=".pdf,.doc,.docx"
          maxFileTotalSize={30 * 1024 * 1024}
          maxCount={10}
          minCount={1}
          maxFileSize={10 * 1024 * 1024}
        />
        <Button type="submit">Submit</Button>
      </Stack>
    </form>
  );
}
```

### Multi-Image Gallery Upload

```tsx
import { Uploader } from '@ceed/cds';

function GalleryUpload({ existingImages }) {
  return (
    <Uploader
      label="Gallery Images"
      accept="image/*"
      maxFileTotalSize={50 * 1024 * 1024}
      maxCount={20}
      maxFileSize={10 * 1024 * 1024}
      uploaded={existingImages}
      onChange={(files) => console.log('New files:', files)}
      onDelete={(id) => console.log('Removed:', id)}
    />
  );
}
```

## Best Practices

- **Always set `maxFileTotalSize`.** This is a required prop that protects against excessively large uploads and informs users of the limit via auto-generated helper text.

- **Be specific with `accept`.** Use explicit extensions (`.png,.jpg,.pdf`) rather than wildcards when possible, as wildcard-to-extension mapping may vary across devices.
  - ✔ `accept=".png,.jpg,.pdf"` -- clear and predictable
  - ✘ `accept="*"` -- allows any file type with no validation

- **Provide meaningful labels.** Use the `label` prop to clearly indicate what type of files the user should upload and in what context.

- **Set `maxFileSize` for individual limits.** Even if `maxFileTotalSize` is set, large individual files can cause upload failures. Use `maxFileSize` to catch oversized files early.

- **Use `minCount` with form validation.** The minimum count check triggers on form submission, not on file selection. Make sure the Uploader is inside a `<form>` element for this validation to work.

## Props and Customization

### Key Props

| Prop               | Type                                                      | Default    | Description                                                 |
| ------------------ | --------------------------------------------------------- | ---------- | ----------------------------------------------------------- |
| `accept`           | `string`                                                  | (required) | Accepted file types (e.g., `'image/*'`, `'.pdf,.doc'`)      |
| `maxFileTotalSize` | `number`                                                  | (required) | Maximum total size of all files in bytes                    |
| `onChange`         | `(event: { target: { name?, value: File[] } }) => void`   | -          | Callback when files are added                               |
| `onDelete`         | `(deletedFile: UserUpload) => void`                       | -          | Callback when an uploaded file is removed                   |
| `uploaded`         | `{ id: string \| number; name: string; size?: number }[]` | -          | Pre-existing uploaded files to display                      |
| `maxFileSize`      | `number`                                                  | -          | Maximum size per individual file in bytes                   |
| `maxCount`         | `number`                                                  | -          | Maximum number of files allowed                             |
| `minCount`         | `number`                                                  | -          | Minimum number of files required (validated on form submit) |
| `label`            | `string`                                                  | -          | Label displayed above the uploader                          |
| `helperText`       | `string`                                                  | -          | Helper text displayed below the uploader                    |
| `error`            | `boolean`                                                 | `false`    | Applies error styling                                       |
| `disabled`         | `boolean`                                                 | `false`    | Disables the uploader                                       |
| `name`             | `string`                                                  | -          | HTML name attribute for form submission                     |
| `size`             | `'sm' \| 'md'`                                            | `'md'`     | Uploader size                                               |

## Accessibility

- The dropzone is keyboard-accessible and can be activated via **Enter** or **Space** to open the file browser.
- Error messages and helper text are associated with the dropzone via ARIA attributes, ensuring screen readers announce validation feedback.
- Uploaded file items include accessible delete buttons with descriptive labels.
- The `label` prop renders as a visible label associated with the upload control for screen reader identification.
