# File upload

A drop zone that is also a real file input, and a list of chosen files with a type icon, size, simulated progress with a `Spinner`, and a quiet remove button. A file over the 10 MB limit shows an error row, and an “Upload 3 files” `Button` counts only the files that can go.

**Example: Upload survey files** (`examples/recipes/file-upload.tsx`)

```tsx
'use client'

import { BodySmall, Button, Card, Heading, Spinner, Stack, Text, toastSuccess } from '@blocks/design-system'
import { CircleAlert, CircleCheck, CloudUpload, File, FileImage, FilePlay, FileSpreadsheet, FileText, X } from 'lucide-react'
import { type ChangeEvent, type DragEvent, useEffect, useId, useRef, useState } from 'react'
import styles from './file-upload.module.css'

const sizeLimit = 10 * 1024 * 1024
// A non-breaking space keeps "10 MB" together when the text wraps.
const sizeLimitLabel = '10\u00a0MB'

type Status = 'queued' | 'uploading' | 'done' | 'too-large'

interface Upload {
  id: number
  name: string
  type: string
  size: number
  status: Status
  progress: number
}

// Four files already chosen, one of them over the limit.
const initialUploads: Upload[] = [
  { id: 1, name: 'north-ridge-site-survey.pdf', type: 'application/pdf', size: 2_516_582, status: 'queued', progress: 0 },
  { id: 2, name: 'trailhead-elevation.png', type: 'image/png', size: 880_640, status: 'queued', progress: 0 },
  { id: 3, name: 'trail-counts-2026.csv', type: 'text/csv', size: 49_152, status: 'queued', progress: 0 },
  { id: 4, name: 'drone-flyover-raw.mov', type: 'video/quicktime', size: 155_189_248, status: 'too-large', progress: 0 },
]

function formatSize(bytes: number) {
  if (bytes < 1024) return `${bytes} B`
  if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`
  return `${(bytes / 1024 / 1024).toFixed(1)} MB`
}

// "drone-flyover-raw.mov" → ["drone-flyover-raw", ".mov"], so a long name
// can truncate in the middle and keep its extension.
function splitName(name: string): [string, string] {
  const dot = name.lastIndexOf('.')
  return dot > 0 ? [name.slice(0, dot), name.slice(dot)] : [name, '']
}

function FileIcon({ type }: { type: string }) {
  if (type.startsWith('image/')) return <FileImage aria-hidden size={20} />
  if (type.startsWith('video/')) return <FilePlay aria-hidden size={20} />
  if (type === 'text/csv' || type.includes('spreadsheet')) return <FileSpreadsheet aria-hidden size={20} />
  if (type === 'application/pdf' || type.startsWith('text/')) return <FileText aria-hidden size={20} />
  return <File aria-hidden size={20} />
}

// A drop zone that's also a real file input: the input is visually hidden
// inside its label, so clicking, Enter or Space opens the picker and the
// zone shows the input's focus ring.
export default function FileUpload() {
  const titleId = useId()
  const inputId = useId()
  const hintId = useId()
  const nextId = useRef(initialUploads.length + 1)
  const fileInput = useRef<HTMLInputElement>(null)
  const list = useRef<HTMLUListElement>(null)
  const [uploads, setUploads] = useState(initialUploads)
  const [dragging, setDragging] = useState(false)
  const [announcement, setAnnouncement] = useState('')

  const uploading = uploads.some((upload) => upload.status === 'uploading')
  const ready = uploads.filter((upload) => upload.status === 'queued')
  const uploaded = uploads.filter((upload) => upload.status === 'done').length
  const rejected = uploads.filter((upload) => upload.status === 'too-large').length
  const uploadable = uploads.length - rejected

  // Simulated progress: one interval while anything uploads, cleared when
  // the last file finishes or the component unmounts.
  useEffect(() => {
    if (!uploading) return
    const timer = setInterval(() => {
      setUploads((current) =>
        current.map((upload) => {
          if (upload.status !== 'uploading') return upload
          // Smaller files finish sooner.
          const step = Math.max(3, Math.round(24 - Math.log2(upload.size)))
          const progress = Math.min(100, upload.progress + step)
          return { ...upload, progress, status: progress === 100 ? 'done' : 'uploading' }
        }),
      )
    }, 150)
    return () => clearInterval(timer)
  }, [uploading])

  // Confirm once when a batch finishes.
  const wasUploading = useRef(false)
  useEffect(() => {
    if (wasUploading.current && !uploading) {
      toastSuccess(`${uploaded} ${uploaded === 1 ? 'file' : 'files'} uploaded`, {
        description: 'Saved to the North Ridge survey.',
      })
    }
    wasUploading.current = uploading
  }, [uploading, uploaded])

  function addFiles(files: FileList | null) {
    if (!files || files.length === 0) return
    const added = Array.from(files, (file): Upload => ({
      id: nextId.current++,
      name: file.name,
      type: file.type,
      size: file.size,
      status: file.size > sizeLimit ? 'too-large' : 'queued',
      progress: 0,
    }))
    setUploads((current) => [...current, ...added])
    const tooLarge = added.filter((upload) => upload.status === 'too-large').length
    const count = `${added.length} ${added.length === 1 ? 'file' : 'files'} added`
    setAnnouncement(tooLarge ? `${count}, ${tooLarge} over the ${sizeLimitLabel} limit.` : `${count}.`)
  }

  function choose(event: ChangeEvent<HTMLInputElement>) {
    addFiles(event.currentTarget.files)
    // Clear the input so choosing the same file again still fires a change.
    event.currentTarget.value = ''
  }

  function drop(event: DragEvent<HTMLLabelElement>) {
    event.preventDefault()
    setDragging(false)
    addFiles(event.dataTransfer.files)
  }

  // The row's button disappears, so move focus to a neighbouring row's
  // remove button, or back to the drop zone after the last one.
  function remove(upload: Upload, button: HTMLButtonElement) {
    const buttons = Array.from(list.current?.querySelectorAll('button') ?? [])
    const index = buttons.indexOf(button)
    const neighbour = buttons[index + 1] ?? buttons[index - 1]
    ;(neighbour ?? fileInput.current)?.focus()
    setUploads((current) => current.filter((item) => item.id !== upload.id))
    setAnnouncement(`Removed ${upload.name}.`)
  }

  function startUpload() {
    setAnnouncement(`Uploading ${ready.length} ${ready.length === 1 ? 'file' : 'files'}.`)
    setUploads((current) =>
      current.map((upload) => (upload.status === 'queued' ? { ...upload, status: 'uploading' } : upload)),
    )
  }

  return (
    <Card as="section" aria-labelledby={titleId} padding="lg" borderRadius="xl">
      <Stack gap="lg">
        <Stack gap="xs">
          <Heading as="h3" id={titleId} fontSize="lg" margin="none">
            Upload survey files
          </Heading>
          <BodySmall color="text-muted" margin="none">
            Attach reports, photos and data to the North Ridge survey.
          </BodySmall>
        </Stack>

        <label
          htmlFor={inputId}
          className={styles.dropzone}
          data-dragging={dragging || undefined}
          onDragOver={(event) => {
            event.preventDefault()
            setDragging(true)
          }}
          onDragLeave={(event) => {
            // Moving onto a child also fires dragleave; only leaving the zone counts.
            if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setDragging(false)
          }}
          onDrop={drop}
        >
          <input
            ref={fileInput}
            id={inputId}
            type="file"
            multiple
            className={styles.visuallyHidden}
            aria-describedby={hintId}
            onChange={choose}
          />
          <span className={styles.dropIcon}>
            <CloudUpload aria-hidden size={24} />
          </span>
          <Text fontWeight="semibold">
            Drop files here or <span className={styles.browse}>browse</span>
          </Text>
          <Text id={hintId} fontSize="xs" color="text-muted">
            PDF, images, CSV or video. Up to {sizeLimitLabel} each.
          </Text>
        </label>

        <p className={styles.visuallyHidden} aria-live="polite">
          {announcement}
        </p>

        {uploads.length > 0 && (
          <ul ref={list} className={styles.files} aria-label="Chosen files">
            {uploads.map((upload) => {
              const [base, extension] = splitName(upload.name)
              return (
                <li key={upload.id} className={styles.file} data-status={upload.status}>
                  <span className={styles.fileIcon}>
                    <FileIcon type={upload.type} />
                  </span>
                  <div className={styles.fileBody}>
                    <Text fontSize="sm" fontWeight="medium" dangerouslySetClassName={styles.fileName}>
                      <span className={styles.base}>{base}</span>
                      <span>{extension}</span>
                    </Text>
                    {upload.status === 'too-large' ? (
                      <Text fontSize="xs" color="danger-text" dangerouslySetClassName={styles.status}>
                        <CircleAlert aria-hidden size={12} />
                        <span>
                          {formatSize(upload.size)} · Over the {sizeLimitLabel} limit
                        </span>
                      </Text>
                    ) : upload.status === 'done' ? (
                      <Text fontSize="xs" color="success-text" dangerouslySetClassName={styles.status}>
                        <CircleCheck aria-hidden size={12} />
                        <span>{formatSize(upload.size)} · Uploaded</span>
                      </Text>
                    ) : (
                      <Text fontSize="xs" color="text-muted">
                        {formatSize(upload.size)} · {upload.status === 'uploading' ? `${upload.progress}%` : 'Ready'}
                      </Text>
                    )}
                    {upload.status === 'uploading' && (
                      <div
                        className={styles.progress}
                        role="progressbar"
                        aria-label={`Uploading ${upload.name}`}
                        aria-valuenow={upload.progress}
                        aria-valuemin={0}
                        aria-valuemax={100}
                      >
                        <span style={{ inlineSize: `${upload.progress}%` }} />
                      </div>
                    )}
                  </div>
                  {upload.status === 'uploading' ? (
                    <Spinner size="sm" aria-hidden />
                  ) : (
                    // A quiet icon button: the file, not its remove action, leads the row.
                    <button
                      type="button"
                      className={styles.remove}
                      aria-label={`Remove ${upload.name}`}
                      onClick={(event) => remove(upload, event.currentTarget)}
                    >
                      <X aria-hidden size={16} />
                    </button>
                  )}
                </li>
              )
            })}
          </ul>
        )}

        <Stack direction="row" justify="space-between" align="center" gap="md" wrap="wrap">
          <Text fontSize="sm" color="text-muted">
            {uploaded} of {uploadable} uploaded
            {rejected > 0 && ` · ${rejected} can’t be uploaded`}
          </Text>
          {/* aria-disabled keeps focus on the button after it starts the upload. */}
          <Button
            type="button"
            variant="primary"
            aria-disabled={ready.length === 0 || uploading}
            onClick={() => ready.length > 0 && !uploading && startUpload()}
          >
            {uploading
              ? 'Uploading…'
              : ready.length === 0
                ? 'Upload files'
                : `Upload ${ready.length} ${ready.length === 1 ? 'file' : 'files'}`}
          </Button>
        </Stack>
      </Stack>
    </Card>
  )
}
```

## How it works

- **The drop zone is a label.** The file input is visually hidden inside it, so clicking, Enter or Space opens the picker and the zone draws the input’s focus ring with `:has(:focus-visible)`. Dropped files and chosen files go through the same function.
- **Progress is simulated with one interval.** An effect starts a single `setInterval` while anything is uploading and clears it when the last file finishes or the component unmounts. Each bar is a `role="progressbar"` with its value; the spinner beside it is decorative.
- **Changes are announced.** A polite live region reports files added (and how many were over the limit) and removed. Removing a row moves focus to a neighbouring row’s button, or back to the drop zone.
- **Errors don’t rely on color.** The oversized file has an alert icon and says “Over the 10 MB limit” in words, the summary reads “0 of 3 uploaded · 1 can’t be uploaded”, and the Upload button counts only the files that can go. It stays `aria-disabled`, not `disabled`, while uploading so focus stays on it.

- **Long names keep their extension.** The name is split at its last dot and only the base truncates, so “north-ridge-permit-appli… .pdf” still says what kind of file it is. The remove buttons are borderless icon buttons; the oversized file’s keeps a frame, since removing it is that row’s only next step.

## App-owned CSS

The drop zone, file rows, quiet remove buttons and progress bars.

`examples/recipes/file-upload.module.css`:

```css
/* The drop zone, file rows and their progress bars. */

.dropzone {
  position: relative;
  display: grid;
  justify-items: center;
  gap: var(--ds-space-sm);
  padding: var(--ds-space-xl) var(--ds-space-lg);
  text-align: center;
  background: var(--ds-color-bg-subtle);
  border: var(--ds-border-width-md) dashed var(--ds-color-border);
  border-radius: var(--ds-border-radius-xl);
  cursor: pointer;
  transition:
    border-color var(--ds-duration-fast) var(--ds-easing-standard),
    background-color var(--ds-duration-fast) var(--ds-easing-standard);

  &:hover {
    border-color: var(--ds-color-border-strong);
  }

  /* The hidden input has focus; the zone draws the ring. */
  &:has(input:focus-visible) {
    outline: var(--ds-border-width-md) solid var(--ds-color-focus-ring);
    outline-offset: var(--ds-border-width-md);
  }

  &[data-dragging] {
    background: var(--ds-color-accent-subtle);
    border-color: var(--ds-color-accent);
  }
}

.dropIcon {
  display: grid;
  place-items: center;
  width: var(--ds-control-height-lg);
  height: var(--ds-control-height-lg);
  margin-bottom: var(--ds-space-sm);
  color: var(--ds-color-accent-text);
  background: var(--ds-color-bg);
  border: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
  border-radius: var(--ds-border-radius-circle);
}

.browse {
  color: var(--ds-color-accent-text);
  text-decoration: underline;
  text-underline-offset: 0.2em;
}

.visuallyHidden {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

.files {
  display: grid;
  gap: var(--ds-space-sm);
  margin: 0;
  padding: 0;
  list-style: none;
}

.file {
  display: flex;
  align-items: center;
  gap: var(--ds-space-md);
  padding: var(--ds-space-md);
  border: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
  border-radius: var(--ds-border-radius-md);

  &[data-status="too-large"] {
    background: var(--ds-color-danger-subtle);
    border-color: color-mix(in srgb, var(--ds-color-danger) 40%, transparent);
  }
}

.fileIcon {
  display: grid;
  place-items: center;
  flex: none;
  width: var(--ds-control-height-lg);
  height: var(--ds-control-height-lg);
  color: var(--ds-color-text-muted);
  background: var(--ds-color-bg-subtle);
  border-radius: var(--ds-border-radius-md);

  [data-status="too-large"] & {
    color: var(--ds-color-danger-text);
    background: var(--ds-color-bg);
  }
}

.fileBody {
  display: grid;
  gap: var(--ds-space-xs);
  flex: 1;
  min-width: 0;
}

.fileName {
  display: flex;
  min-width: 0;
  white-space: nowrap;

  & span:last-child {
    flex: none;
  }
}

/* The name's base truncates; its extension stays visible. */
.base {
  overflow: hidden;
  text-overflow: ellipsis;
}

/* The icon lines up with the first line when the status wraps. */
.status {
  display: inline-flex;
  align-items: flex-start;
  gap: var(--ds-space-sm);

  & svg {
    flex: none;
    margin-top: calc(var(--ds-space-xs) * 1.5);
  }
}

.remove {
  display: grid;
  place-items: center;
  flex: none;
  width: var(--ds-control-height-sm);
  height: var(--ds-control-height-sm);
  padding: 0;
  color: var(--ds-color-text-muted);
  background: transparent;
  border: var(--ds-border-width-sm) solid transparent;
  border-radius: var(--ds-border-radius-sm);
  cursor: pointer;

  &:hover {
    color: var(--ds-color-text);
    background: var(--ds-color-surface-hover);
  }

  &:focus-visible {
    outline: var(--ds-border-width-md) solid var(--ds-color-focus-ring);
  }

  /* The rejected file's remove is the row's one action, so it keeps a frame. */
  [data-status="too-large"] & {
    color: var(--ds-color-danger-text);
    background: var(--ds-color-bg);
    border-color: color-mix(in srgb, var(--ds-color-danger) 40%, transparent);
  }
}

.progress {
  height: var(--ds-space-sm);
  overflow: hidden;
  background: var(--ds-color-border-subtle);
  border-radius: var(--ds-border-radius-pill);

  & span {
    display: block;
    height: 100%;
    background: var(--ds-color-accent);
    border-radius: inherit;
    transition: inline-size var(--ds-duration-normal) var(--ds-easing-linear);
  }
}

@media (prefers-reduced-motion: reduce) {
  .dropzone,
  .progress span {
    transition: none;
  }
}
```
