# Attachment

> A file chip or card with a type icon, a middle-truncated name, size, upload progress, an error state and a remove button.

- Kind: ui · Category: Data display · Interactivity: none
- Install: `npx shadcn@latest add @haze/attachment`
- File: `src/components/haze/ui/attachment.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/placeholder, @haze/progress, @haze/utils
- Docs page: https://hazeui.com/ui/attachment

## Use when
- Files queued under a message box or attached to a sent message
- A list of downloadable documents, each with its size
- Showing one file's upload progress or error next to its name

## Avoid when
- The user still has to choose the files. Use file-upload or file-input.
- You show a person's profile picture. Use avatar or avatar-upload.

## Alternatives
- [file-upload](https://hazeui.com/ui/file-upload.md)
- [file-input](https://hazeui.com/ui/file-input.md)
- [chip](https://hazeui.com/ui/chip.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| name | `string` |  | yes | Full file name with extension; the accessible name and tooltip. The visible text is cut in the middle so the end stays readable. |
| bytes | `number` |  | no | Size in bytes, shown as B, KB or MB. |
| type | `string` | "" | no | MIME type; with the extension it picks the icon (image, document, sheet, code, archive or generic). |
| variant | `"chip" \| "card"` | "chip" | no | Compact inline chip or a larger card. |
| state | `"uploading" \| "ready" \| "error"` | "ready" | no | Uploading shows a progress bar, error shows the message in the destructive color with a warning icon. |
| progress | `number` |  | no | 0 to 100. Leave out while uploading for a bar with no value. |
| errorMessage | `string` | "Upload failed" | no | Text of the error state. |
| href | `string` |  | no | Turns the name into a download link. |
| removable | `boolean` | false | no | Adds a remove button with data-attachment-remove; the action is yours to wire. |
| removeLabel | `string` | "Remove {name}" | no | Accessible name of the remove button; {name} becomes the file name. |
| progressLabel | `string` | "Uploading {name}" | no | Accessible name of the progress bar. |
| preview | `boolean` |  | no | Card only: shows a picture placeholder on top. Defaults to true for images. |
| previewLabel | `string` | "" | no | Describes the real preview image; leave empty while it is a placeholder. |
| class | `string` |  | no | Extra classes on the root. |
| ...rest | `HTML attributes` |  | no | Passed to the root element. |

## Accessibility
- The full file name is in the accessible name and the tooltip; the visibly shortened text is hidden from assistive technology so it is not read twice.
- Upload progress is a progressbar named with the file name and shows the percentage as text, and the error state has an icon and a message, so neither relies on color.
- The remove button is named "Remove <file name>" so several chips stay distinguishable, and it is 28 px square.
- Key Tab: Move to the download link, then to the remove button.
- Key Enter: Follow the download link or activate the remove button.

## Agent prompts

### Install and use

Install the Haze UI component "Attachment" with `npx shadcn@latest add @haze/attachment`. 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 Attachment from "@/components/haze/ui/attachment.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/attachment.md

### Customize with real content

Adapt the Haze attachment ui for our product. Replace the demo values of these props with our real content: name, bytes, type, variant, state, progress, errorMessage, href, removable, removeLabel, progressLabel, preview, previewLabel, class, ...rest. Keep the layout, the heading level rules and these accessibility details: The full file name is in the accessible name and the tooltip; the visibly shortened text is hidden from assistive technology so it is not read twice. Upload progress is a progressbar named with the file name and shows the percentage as text, and the error state has an icon and a message, so neither relies on color. The remove button is named "Remove <file name>" so several chips stay distinguishable, and it is 28 px square. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using attachment, check it fits: use it when files queued under a message box or attached to a sent message; a list of downloadable documents, each with its size; showing one file's upload progress or error next to its name. Avoid it when the user still has to choose the files. use file-upload or file-input.; you show a person's profile picture. use avatar or avatar-upload.. Alternatives: @haze/file-upload, @haze/file-input, @haze/chip.

## Example requests that should lead here
- Show the files attached to a message as chips, one still uploading at 62 percent and one that failed.

## Source

```astro
---
import { CircleAlert, File, FileArchive, FileCode, FileImage, FileSpreadsheet, FileText, X } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Placeholder from "./placeholder.astro";
import Progress from "./progress.astro";

interface Props {
  /** Full file name with its extension. It is the accessible name and the tooltip. */
  name: string;
  /** Size in bytes; shown as B, KB or MB. Leave out to hide it. */
  bytes?: number;
  /** MIME type such as "application/pdf". Together with the extension it picks the icon. */
  type?: string;
  variant?: "chip" | "card";
  /** uploading shows the progress bar, error shows the message, ready shows the size. */
  state?: "uploading" | "ready" | "error";
  /** Upload progress from 0 to 100. Leave out while uploading for a bar with no value. */
  progress?: number;
  /** Text shown in the error state. */
  errorMessage?: string;
  /** Makes the name a download link. */
  href?: string;
  /** Adds a remove button. It is a plain type="button" with data-attachment-remove; wire the action yourself. */
  removable?: boolean;
  /** Accessible name of the remove button. `{name}` is replaced by the file name. */
  removeLabel?: string;
  /** Accessible name of the progress bar. `{name}` is replaced by the file name. */
  progressLabel?: string;
  /** Card only: shows a picture placeholder above the details. Defaults to true for images. */
  preview?: boolean;
  /** Card only: describes the real preview image. Leave empty while it is only a placeholder. */
  previewLabel?: string;
  class?: string;
  [key: string]: unknown;
}

const {
  name,
  bytes,
  type = "",
  variant = "chip",
  state = "ready",
  progress,
  errorMessage = "Upload failed",
  href,
  removable = false,
  removeLabel = "Remove {name}",
  progressLabel = "Uploading {name}",
  preview,
  previewLabel = "",
  class: className,
  ...rest
} = Astro.props;

const ext = (name.includes(".") ? name.split(".").pop() ?? "" : "").toLowerCase();
const is = (mime: RegExp, exts: string[]) => mime.test(type) || exts.includes(ext);
const kind = is(/^image\//, ["png", "jpg", "jpeg", "gif", "webp", "svg", "avif", "heic"])
  ? "image"
  : is(/spreadsheet|excel|csv/, ["xls", "xlsx", "csv", "tsv", "ods", "numbers"])
    ? "sheet"
    : is(/pdf|msword|wordprocessing|^text\/(plain|markdown)/, ["pdf", "doc", "docx", "txt", "md", "rtf", "odt"])
      ? "document"
      : is(/zip|compressed|tar|gzip|7z|rar/, ["zip", "tar", "gz", "7z", "rar", "tgz"])
        ? "archive"
        : is(/json|javascript|typescript|xml|html|css|x-sh/, ["js", "ts", "tsx", "jsx", "json", "html", "css", "py", "go", "rs", "sh", "xml", "yml", "yaml"])
          ? "code"
          : "file";
const icons = { image: FileImage, sheet: FileSpreadsheet, document: FileText, archive: FileArchive, code: FileCode, file: File };
const Icon = state === "error" ? CircleAlert : icons[kind];

function formatSize(n: number) {
  if (n < 1024) return `${n} B`;
  if (n < 1024 * 1024) return `${Math.round(n / 1024)} KB`;
  return `${(n / (1024 * 1024)).toFixed(1).replace(/\.0$/, "")} MB`;
}
const sizeText = typeof bytes === "number" && Number.isFinite(bytes) && bytes >= 0 ? formatSize(bytes) : "";

// Middle truncation: the tail (end of the stem plus the extension) never shrinks, the head gives way with an ellipsis.
const tailLength = Math.min(name.length > 14 ? 9 : 0, name.length);
const head = name.slice(0, name.length - tailLength);
const tail = name.slice(name.length - tailLength);

const uploading = state === "uploading";
const percent = typeof progress === "number" ? Math.round(Math.min(Math.max(progress, 0), 100)) : undefined;
const meta = state === "error" ? errorMessage : uploading ? (percent === undefined ? "" : `${percent}%`) : sizeText;
const card = variant === "card";
const showPreview = card && (preview ?? kind === "image");
const fill = (text: string) => text.replaceAll("{name}", name);
---

<div
  title={name}
  class={cn(
    "min-w-0 border bg-card",
    card
      ? "flex w-full flex-col overflow-hidden rounded-xl border-border"
      : "inline-flex max-w-full flex-col gap-1.5 rounded-lg border-frame bg-field px-2.5 py-1.5",
    state === "error" && "border-frame-destructive",
    className,
  )}
  {...rest}
>
  {showPreview && <Placeholder variant="photo" label={previewLabel} class="h-24 rounded-none border-0 border-b border-border" />}
  <div class={cn("flex min-w-0 items-center gap-2.5", card ? "p-3" : "gap-2")}>
    <span
      class={cn(
        "inline-flex shrink-0 items-center justify-center",
        card ? "size-9 rounded-lg bg-foreground/5 inset-ring inset-ring-frame" : "size-5",
        state === "error" ? "text-destructive" : "text-muted-foreground",
      )}
    >
      <Icon aria-hidden="true" class={card ? "size-[1.125rem]" : "size-4"} />
    </span>
    <div class="min-w-0 flex-1">
      {
        href ? (
          <a
            href={href}
            download={name}
            class="flex min-h-6 min-w-0 items-center rounded-sm text-[0.8125rem]/5 font-medium text-foreground underline-offset-4 hover:underline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
          >
            <span class="sr-only">{name}</span>
            <span aria-hidden="true" class="truncate">{head}</span>
            <span aria-hidden="true" class="shrink-0">{tail}</span>
          </a>
        ) : (
          <p class="flex min-w-0 text-[0.8125rem]/5 font-medium text-foreground">
            <span class="sr-only">{name}</span>
            <span aria-hidden="true" class="truncate">{head}</span>
            <span aria-hidden="true" class="shrink-0">{tail}</span>
          </p>
        )
      }
      {meta && <p class={cn("truncate text-xs/4 tabular-nums", state === "error" ? "text-destructive" : "text-muted-foreground")}>{meta}</p>}
    </div>
    {
      removable && (
        <button
          type="button"
          data-attachment-remove
          aria-label={fill(removeLabel)}
          class="inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-md border border-transparent 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"
        >
          <X aria-hidden="true" class="size-4" />
        </button>
      )
    }
  </div>
  {
    uploading && (
      <div class={cn(card ? "px-3 pb-3" : "w-full")}>
        <Progress value={percent} label={fill(progressLabel)} hideLabel size="sm" />
      </div>
    )
  }
</div>
```
