# File upload

> Dashed drop area over a real file input; a small script lists the chosen files with a remove button and announces changes.

- Kind: ui · Category: Forms · Interactivity: script
- Install: `npx shadcn@latest add @haze/file-upload`
- File: `src/components/haze/ui/file-upload.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/ui/file-upload

## Use when
- Attaching invoices, screenshots or documents to a form
- Uploads where dragging files onto the page area should work as well as clicking

## Avoid when
- Uploads that need previews, progress bars or resumable transfers, which need an application-level uploader
- A single small avatar change; a button that opens the file picker is lighter

## Alternatives
- [input](https://hazeui.com/ui/input.md)
- [button](https://hazeui.com/ui/button.md)
- [field](https://hazeui.com/ui/field.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | File input id; the visible title is a label for it, the hint id is <id>-hint. |
| name | `string` | id | no | Form field name. |
| label | `string` |  | yes | Title inside the box and the accessible name of the input. |
| hint | `string` |  | no | Help text such as accepted types and the size limit; linked with aria-describedby. |
| accept | `string` |  | no | Comma-separated file types, as in the native accept attribute. |
| multiple | `boolean` |  | no | Allows choosing more than one file. |
| class | `string` |  | no | Extra classes on the wrapper. |
| ...rest | `attributes` |  | no | Any other input attribute, for example required or disabled. A passed aria-describedby is joined to the hint id, not a replacement for it. |

## Accessibility
- The invisible file input fills the whole box, so click, drag-and-drop and the operating system's file dialog are all native; the visible title is its label.
- With the script, chosen files are listed as rows, and a polite live region announces what was added or removed and how many files are selected. Without scripting the native file input is shown below the hint, so the browser itself displays the chosen file names.
- Each row has a remove button named "Remove <file name>". Removing a file returns focus to the file input.
- The focus outline is drawn on the box with has-focus-visible, because the input itself has no visible edge. While files are dragged over the box its border and tint change; this is a hint only, and dropping works the same either way.
- Type and size limits are written in the hint; accept only filters the picker, so validate files on the server.
- Key Tab: Focuses the file input
- Key Enter or Space: Opens the file dialog

## Agent prompts

### Install and use

Install the Haze UI component "File upload" with `npx shadcn@latest add @haze/file-upload`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import FileUpload from "@/components/haze/ui/file-upload.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/file-upload.md

### Customize with real content

Adapt the Haze file-upload ui for our product. Replace the demo values of these props with our real content: id, name, label, hint, accept, multiple, class, ...rest. Keep the layout, the heading level rules and these accessibility details: The invisible file input fills the whole box, so click, drag-and-drop and the operating system's file dialog are all native; the visible title is its label. With the script, chosen files are listed as rows, and a polite live region announces what was added or removed and how many files are selected. Without scripting the native file input is shown below the hint, so the browser itself displays the chosen file names. Each row has a remove button named "Remove <file name>". Removing a file returns focus to the file input. The focus outline is drawn on the box with has-focus-visible, because the input itself has no visible edge. While files are dragged over the box its border and tint change; this is a hint only, and dropping works the same either way. Type and size limits are written in the hint; accept only filters the picker, so validate files on the server. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using file-upload, check it fits: use it when attaching invoices, screenshots or documents to a form; uploads where dragging files onto the page area should work as well as clicking. Avoid it when uploads that need previews, progress bars or resumable transfers, which need an application-level uploader; a single small avatar change; a button that opens the file picker is lighter. Alternatives: @haze/input, @haze/button, @haze/field.

## Example requests that should lead here
- Add an invoice upload box that accepts PNG and PDF
- Make a multiple-file screenshot upload that lists the file names

## Source

```astro
---
import { Upload, X } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface Props {
  id: string;
  name?: string;
  /** Accessible name, shown as the title inside the drop area. */
  label: string;
  /** Short help text, for example "PNG or PDF, up to 10 MB". */
  hint?: string;
  /** Comma-separated types, as in the native accept attribute. */
  accept?: string;
  multiple?: boolean;
  class?: string;
  /** Any other input attribute, for example required or disabled. An aria-describedby is added after the hint id, not instead of it. */
  [key: string]: unknown;
}

const { id, name = id, label, hint, accept, multiple, class: className, ...rest } = Astro.props;
const { "aria-describedby": extraDescribedBy, ...inputRest } = rest;
const describedBy = [hint ? `${id}-hint` : undefined, typeof extraDescribedBy === "string" ? extraDescribedBy : undefined].filter(Boolean).join(" ") || undefined;
---

<div data-haze-file-upload class={cn("grid w-full min-w-0 grid-cols-1 gap-3", className)}>
  <div
    data-dropzone
    class="relative flex flex-col items-center gap-1.5 rounded-xl border border-dashed border-input bg-card px-6 py-8 text-center transition-[border-color,background-color] duration-150 ease-snappy hover:border-border-strong hover:bg-muted data-[dragging]:border-foreground data-[dragging]:bg-muted has-focus-visible:outline-2 has-focus-visible:outline-offset-1 has-focus-visible:outline-ring has-disabled:cursor-not-allowed has-disabled:[&>label]:opacity-50 has-disabled:[&>span]:opacity-50 has-disabled:hover:border-input has-disabled:hover:bg-card"
  >
    <span class="mb-1 grid size-10 place-items-center rounded-lg bg-muted text-muted-foreground inset-ring inset-ring-frame">
      <Upload class="size-5" aria-hidden="true" />
    </span>
    <label for={id} class="text-[0.8125rem]/5 font-medium text-foreground">{label}</label>
    {hint && <p id={`${id}-hint`} class="text-xs text-muted-foreground">{hint}</p>}
    <input
      id={id}
      name={name}
      type="file"
      accept={accept}
      multiple={multiple}
      aria-describedby={describedBy}
      class="absolute inset-0 size-full cursor-pointer opacity-0 disabled:cursor-not-allowed noscript:static noscript:inset-auto noscript:h-auto noscript:w-full noscript:opacity-100 noscript:text-[0.8125rem]/5 noscript:text-muted-foreground noscript:file:mr-3 noscript:file:rounded-md noscript:file:border noscript:file:border-border noscript:file:bg-field noscript:file:px-2.5 noscript:file:py-1 noscript:file:text-[0.8125rem]/5 noscript:file:font-medium noscript:file:text-foreground"
      {...inputRest}
    />
  </div>
  <ul data-file-list class="grid min-w-0 grid-cols-1 gap-2 empty:hidden"></ul>
  <p data-file-status aria-live="polite" class="sr-only"></p>
  <template data-file-row>
    <li class="flex animate-rise items-center gap-3 rounded-lg border border-border bg-card px-3 py-2 text-[0.8125rem]">
      <span data-file-name class="min-w-0 flex-1 truncate font-medium text-foreground"></span>
      <span data-file-size class="shrink-0 text-[0.8125rem]/5 text-muted-foreground tabular-nums"></span>
      <button
        type="button"
        data-file-remove
        class="grid size-7 shrink-0 cursor-pointer place-items-center rounded-md text-muted-foreground transition-[background-color,color,scale] duration-150 ease-snappy hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-90 active:duration-75 motion-reduce:transition-none motion-reduce:active:scale-100"
      >
        <X class="size-4" aria-hidden="true" />
      </button>
    </li>
  </template>
</div>

<script>
  // Enhancement. Without it, clicking the box or dropping files on it still works because the native
  // file input covers the whole box. With scripting off the native input is shown below the hint, so the
  // browser lists the chosen file; with scripting on but this script missing, no names are shown.
  // With it: a highlight while files are dragged over, a row per chosen file with a remove button,
  // and a polite announcement of every addition and removal.
  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`;
  }

  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const input = root.querySelector<HTMLInputElement>("input[type=file]");
    const zone = root.querySelector<HTMLElement>("[data-dropzone]");
    const list = root.querySelector<HTMLElement>("[data-file-list]");
    const status = root.querySelector<HTMLElement>("[data-file-status]");
    const template = root.querySelector<HTMLTemplateElement>("template[data-file-row]");
    if (!input || !zone || !list || !status || !template) return;
    root.setAttribute("data-enhanced", "");

    const key = (file: File) => `${file.name}|${file.size}|${file.lastModified}`;
    let known = new Set<string>();

    const count = (n: number) => (n === 1 ? "1 file" : `${n} files`);

    function render() {
      list!.replaceChildren();
      Array.from(input!.files ?? []).forEach((file, index) => {
        const row = template!.content.cloneNode(true) as DocumentFragment;
        row.querySelector("[data-file-name]")!.textContent = file.name;
        row.querySelector("[data-file-size]")!.textContent = formatSize(file.size);
        const remove = row.querySelector<HTMLButtonElement>("[data-file-remove]")!;
        remove.setAttribute("aria-label", `Remove ${file.name}`);
        remove.disabled = input!.disabled;
        remove.addEventListener("click", () => {
          const kept = new DataTransfer();
          Array.from(input!.files ?? []).forEach((f, i) => i !== index && kept.items.add(f));
          input!.files = kept.files;
          known = new Set(Array.from(input!.files).map(key));
          render();
          status!.textContent = `Removed ${file.name}. ${input!.files.length ? `${count(input!.files.length)} selected.` : "No files selected."}`;
          input!.focus();
        });
        list!.appendChild(row);
      });
    }

    input.addEventListener("change", () => {
      const files = Array.from(input.files ?? []);
      const added = files.filter((file) => !known.has(key(file)));
      const removed = known.size - (files.length - added.length);
      known = new Set(files.map(key));
      render();
      if (added.length) status.textContent = `Added ${added.map((file) => file.name).join(", ")}. ${count(files.length)} selected.`;
      else if (removed > 0) status.textContent = files.length ? `${count(files.length)} selected.` : "All files removed.";
    });

    const hasFiles = (event: DragEvent) => Array.from(event.dataTransfer?.types ?? []).includes("Files");
    ["dragenter", "dragover"].forEach((type) =>
      zone.addEventListener(type, (event) => {
        if (!input.disabled && hasFiles(event as DragEvent)) zone.setAttribute("data-dragging", "");
      }),
    );
    zone.addEventListener("dragleave", (event) => {
      if (!zone.contains(event.relatedTarget as Node | null)) zone.removeAttribute("data-dragging");
    });
    zone.addEventListener("drop", () => zone.removeAttribute("data-dragging"));
  }

  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-file-upload]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-file-upload-listener")) {
    document.documentElement.setAttribute("data-haze-file-upload-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
