Skip to content
Shaken UI
Sign in

Attachment

Save

File attachment chips and tiles with an image thumbnail or file type icon, name, size, upload progress, retry, and remove, for messages and composers.

Category
AI elements
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Attachment preview

In the composer

  • churn-dashboard.pngPNG, 471 KB
  • q3-retention.csvCSV, 1.8 MB
  • pricing-experiment.pdfUploading 64%
    x
  • cohorts.sqlOver the 5 MB limit

In a sent message

  • churn-dashboard.png

    PNG, 471 KB

  • CSV

    q3-retention.csv

    CSV, 1.8 MB

  • PDF

    pricing-experiment.pdf

    PDF, 3.2 MB

  • SQL

    cohorts.sql

    SQL, 7.0 KB

Installation

npx @shakenui/cli add attachment

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add attachment --dry-run

Usage

attachment-example.tsx
"use client";

import { useState } from "react";
import { Attachment, AttachmentList } from "@/components/shaken/agent/attachment";

// A small inline screenshot so the example has a real thumbnail without network requests.
const screenshot = `data:image/svg+xml,${encodeURIComponent(
  `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 160"><rect width="160" height="160" fill="#f4f4f5"/><rect x="12" y="14" width="56" height="8" rx="4" fill="#18181b"/><rect x="12" y="34" width="136" height="54" rx="6" fill="#fff" stroke="#e4e4e7"/><path d="M22 76l18-14 16 8 20-20 18 12 16-10 22 16" fill="none" stroke="#0ea5e9" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/><rect x="12" y="98" width="64" height="48" rx="6" fill="#fff" stroke="#e4e4e7"/><rect x="84" y="98" width="64" height="48" rx="6" fill="#fff" stroke="#e4e4e7"/><rect x="22" y="110" width="28" height="6" rx="3" fill="#a1a1aa"/><rect x="22" y="124" width="40" height="10" rx="3" fill="#18181b"/><rect x="94" y="110" width="28" height="6" rx="3" fill="#a1a1aa"/><rect x="94" y="124" width="36" height="10" rx="3" fill="#10b981"/></svg>`,
)}`;

const initial = [
  { id: "1", name: "churn-dashboard.png", type: "image/png", size: 482_113, previewUrl: screenshot },
  { id: "2", name: "q3-retention.csv", type: "text/csv", size: 1_920_448 },
  { id: "3", name: "pricing-experiment.pdf", type: "application/pdf", size: 3_404_002, status: "uploading" as const, progress: 64 },
  { id: "4", name: "cohorts.sql", size: 7_210, status: "error" as const, error: "Over the 5 MB limit" },
];

export default function AttachmentExample() {
  const [files, setFiles] = useState(initial);
  const remove = (id: string) => setFiles((current) => current.filter((file) => file.id !== id));

  return (
    <div className="grid w-full max-w-xl gap-8">
      <div className="grid gap-2">
        <p className="text-xs font-medium text-zinc-500">In the composer</p>
        <AttachmentList>
          {files.map(({ id, ...file }) => (
            <Attachment key={id} {...file} onRemove={() => remove(id)} onRetry={file.status === "error" ? () => remove(id) : undefined} />
          ))}
        </AttachmentList>
        {files.length < initial.length ? (
          <button
            type="button"
            onClick={() => setFiles(initial)}
            className="justify-self-start rounded-md text-xs text-zinc-500 underline-offset-2 hover:text-zinc-950 hover:underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500 dark:hover:text-white"
          >
            Restore attachments
          </button>
        ) : null}
      </div>
      <div className="grid gap-2">
        <p className="text-xs font-medium text-zinc-500">In a sent message</p>
        <AttachmentList layout="grid">
          <Attachment variant="tile" name="churn-dashboard.png" type="image/png" size={482_113} previewUrl={screenshot} />
          <Attachment variant="tile" name="q3-retention.csv" type="text/csv" size={1_920_448} />
          <Attachment variant="tile" name="pricing-experiment.pdf" type="application/pdf" size={3_404_002} />
          <Attachment variant="tile" name="cohorts.sql" size={7_210} />
        </AttachmentList>
      </div>
    </div>
  );
}

API

PropTypeDefaultDescription
name / size / type / previewUrlstring / number / string / string—The file. type and the extension pick the icon; previewUrl shows an image thumbnail.
status"uploading" | "ready" | "error""ready"Uploading shows a thin progress bar and percentage; error turns the border red and shows the reason.
progressnumber—0 to 100. Unset while uploading means indeterminate.
errorstring—Reason shown when the upload failed.
onRemove / onRetry() => void—Show the remove and retry buttons.
variant"chip" | "tile""chip"A compact row for composers, or a square tile for grids.
AttachmentList({ layout: "row" | "grid" }) => JSX—Lays attachments out as wrapping chips or a tile grid, as a labelled list.

Accessibility

  • Upload progress uses Base UI Progress (role progressbar with aria-valuenow, labelled Uploading and the file name); it is indeterminate when progress is unknown.
  • Remove and retry are buttons named with the file, such as Remove q3-retention.csv; on tiles they appear on hover and focus and are always visible on touch screens.
  • Upload errors are announced as alerts and shown in text, not only by the red border. Thumbnails are decorative; the name is the label.
  • New attachments scale in from 96% in 200ms and the progress bar moves with transform; both are instant with reduced motion.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/agent/attachment.tsxattachment
  • npm packages: @base-ui/react@^1.9.0React and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/attachment/0.1.0.json.

agent/attachment.tsxShow
agent/attachment.tsx
"use client";

import { Progress } from "@base-ui/react/progress";
import { Children, type ComponentProps, type ReactNode } from "react";

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

const ease = "ease-[cubic-bezier(0.23,1,0.32,1)]";

export type AttachmentStatus = "uploading" | "ready" | "error";
export type AttachmentKind = "image" | "pdf" | "document" | "spreadsheet" | "code" | "archive" | "audio" | "video" | "file";

export interface AttachmentFile {
  /** File name with its extension. */
  name: string;
  /** Size in bytes. */
  size?: number;
  /** MIME type. Used with the extension to pick the icon. */
  type?: string;
  /** Thumbnail URL for images, for example from `URL.createObjectURL`. */
  previewUrl?: string;
}

export interface AttachmentProps extends AttachmentFile, Omit<ComponentProps<"div">, "children"> {
  status?: AttachmentStatus;
  /** Upload progress from 0 to 100 while uploading. Leave unset for an indeterminate upload. */
  progress?: number;
  /** Shown instead of the size when the upload failed. */
  error?: string;
  /** Shows a remove button. */
  onRemove?: () => void;
  /** Shows a retry button when the upload failed. */
  onRetry?: () => void;
  /** chip is a compact row for composers and messages; tile is a square for grids. */
  variant?: "chip" | "tile";
}

const extensions: Record<string, AttachmentKind> = {
  png: "image", jpg: "image", jpeg: "image", gif: "image", webp: "image", svg: "image", avif: "image", heic: "image",
  pdf: "pdf",
  doc: "document", docx: "document", md: "document", txt: "document", rtf: "document", pages: "document",
  csv: "spreadsheet", xls: "spreadsheet", xlsx: "spreadsheet", numbers: "spreadsheet", tsv: "spreadsheet",
  ts: "code", tsx: "code", js: "code", jsx: "code", json: "code", py: "code", go: "code", rs: "code", css: "code", html: "code", sql: "code", yml: "code", yaml: "code", sh: "code",
  zip: "archive", gz: "archive", tar: "archive", rar: "archive", "7z": "archive",
  mp3: "audio", wav: "audio", m4a: "audio", ogg: "audio", flac: "audio",
  mp4: "video", mov: "video", webm: "video", mkv: "video",
};

function extensionOf(name: string): string {
  const dot = name.lastIndexOf(".");
  return dot > 0 ? name.slice(dot + 1).toLowerCase() : "";
}

/** Picks the icon family for a file from its MIME type, then its extension. */
export function attachmentKind(file: Pick<AttachmentFile, "name" | "type">): AttachmentKind {
  const type = file.type ?? "";
  if (type.startsWith("image/")) return "image";
  if (type.startsWith("audio/")) return "audio";
  if (type.startsWith("video/")) return "video";
  if (type === "application/pdf") return "pdf";
  return extensions[extensionOf(file.name)] ?? "file";
}

/** Bytes as a short size, e.g. 2.4 MB. */
export function formatBytes(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  const units = ["KB", "MB", "GB"];
  let value = bytes / 1024;
  let unit = 0;
  while (value >= 1024 && unit < units.length - 1) {
    value /= 1024;
    unit++;
  }
  return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`;
}

/**
 * One attached file: an image thumbnail or a file type icon, the name, the size, and while
 * uploading a thin progress bar. A remove button sits on the chip, and a failed upload offers retry.
 */
export function Attachment({
  name,
  size,
  type,
  previewUrl,
  status = "ready",
  progress,
  error,
  onRemove,
  onRetry,
  variant = "chip",
  className,
  ...props
}: AttachmentProps) {
  const kind = attachmentKind({ name, type });
  const extension = extensionOf(name).toUpperCase();
  const uploading = status === "uploading";
  const failed = status === "error";
  const meta = failed
    ? (error ?? "Upload failed")
    : uploading
      ? progress != null
        ? `Uploading ${Math.round(progress)}%`
        : "Uploading"
      : [extension || null, size != null ? formatBytes(size) : null].filter(Boolean).join(", ");

  const thumb =
    kind === "image" && previewUrl ? (
      <img src={previewUrl} alt="" className={cx("size-full object-cover", uploading && "opacity-60")} />
    ) : (
      <FileIcon kind={kind} />
    );

  const actions = (
    <>
      {failed && onRetry ? <IconButton label={`Retry uploading ${name}`} onClick={onRetry} icon="retry" tile={variant === "tile"} /> : null}
      {onRemove ? <IconButton label={`Remove ${name}`} onClick={onRemove} icon="remove" tile={variant === "tile"} /> : null}
    </>
  );

  if (variant === "tile") {
    return (
      <div
        data-status={status}
        className={cx("group relative w-28 transition-[opacity,scale] duration-200 starting:scale-96 starting:opacity-0 motion-reduce:transition-none", ease, className)}
        {...props}
      >
        <div
          className={cx(
            "relative flex aspect-square items-center justify-center overflow-hidden rounded-xl border bg-white text-zinc-500 dark:bg-black dark:text-zinc-400",
            "transition-[border-color] duration-150 motion-reduce:transition-none",
            failed ? "border-red-500/35" : "border-zinc-950/10 dark:border-white/10",
            kind !== "image" || !previewUrl ? "[&>svg]:size-7" : "",
          )}
        >
          {thumb}
          {kind !== "image" || !previewUrl ? (
            <span className="absolute bottom-2 font-mono text-[10px] font-medium text-zinc-500">{extension || "FILE"}</span>
          ) : null}
          {uploading ? <UploadBar progress={progress} name={name} className="absolute inset-x-2 bottom-2" /> : null}
          <div
            className={cx(
              "absolute top-1.5 right-1.5 flex gap-1",
              "transition-opacity duration-150 ease-out motion-reduce:transition-none",
              "opacity-0 group-focus-within:opacity-100 group-hover:opacity-100 [@media(hover:none)]:opacity-100",
              failed && "opacity-100",
            )}
          >
            {actions}
          </div>
        </div>
        <p className="mt-1.5 truncate text-xs font-medium text-zinc-950 dark:text-white" title={name}>
          {name}
        </p>
        <p className={cx("truncate text-[11px] tabular-nums", failed ? "text-red-600 dark:text-red-400" : "text-zinc-500")} role={failed ? "alert" : undefined}>
          {meta}
        </p>
      </div>
    );
  }

  return (
    <div
      data-status={status}
      className={cx(
        "relative flex h-11 w-64 max-w-full items-center gap-2.5 overflow-hidden rounded-lg border bg-white py-1.5 pr-1.5 pl-1.5 text-left dark:bg-black",
        "shadow-[0_1px_2px_rgb(0_0_0/0.04)] dark:shadow-none",
        `transition-[border-color,opacity,scale] duration-200 ${ease} starting:scale-96 starting:opacity-0 motion-reduce:transition-none`,
        failed ? "border-red-500/35" : "border-zinc-950/10 dark:border-white/12",
        className,
      )}
      {...props}
    >
      <span
        className={cx(
          "flex size-8 shrink-0 items-center justify-center overflow-hidden rounded-md text-zinc-500 dark:text-zinc-400",
          "shadow-[inset_0_0_0_1px_rgb(9_9_11/0.07)] dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.1)]",
          "[&>svg]:size-4",
        )}
      >
        {thumb}
      </span>
      <span className="min-w-0 flex-1">
        <span className="block truncate text-[13px] leading-4 font-medium text-zinc-950 dark:text-white" title={name}>
          {name}
        </span>
        <span
          role={failed ? "alert" : undefined}
          className={cx("mt-0.5 block truncate text-[11px] leading-4 tabular-nums", failed ? "text-red-600 dark:text-red-400" : "text-zinc-500")}
        >
          {meta}
        </span>
      </span>
      {onRemove || (failed && onRetry) ? <span className="flex shrink-0 items-center">{actions}</span> : null}
      {uploading ? <UploadBar progress={progress} name={name} className="absolute inset-x-0 bottom-0" flush /> : null}
    </div>
  );
}

export interface AttachmentListProps extends ComponentProps<"ul"> {
  /** row wraps chips (composers, messages); grid lays out tiles. */
  layout?: "row" | "grid";
  children: ReactNode;
}

/** Lays out attachments as wrapping chips or a grid of tiles, as a labelled list. */
export function AttachmentList({ layout = "row", className, children, "aria-label": label = "Attachments", ...props }: AttachmentListProps) {
  return (
    <ul
      aria-label={label}
      className={cx(layout === "grid" ? "grid grid-cols-[repeat(auto-fill,7rem)] gap-3" : "flex flex-wrap gap-2", className)}
      {...props}
    >
      {Children.map(children, (child) => (child == null || child === false ? null : <li>{child}</li>))}
    </ul>
  );
}

/** A thin progress bar. Indeterminate (a still, faint track) when progress is unknown. */
function UploadBar({ progress, name, className, flush = false }: { progress?: number; name: string; className?: string; flush?: boolean }) {
  return (
    <Progress.Root value={progress ?? null} aria-label={`Uploading ${name}`} className={className}>
      <Progress.Track className={cx("h-0.5 overflow-hidden bg-zinc-950/[0.08] dark:bg-white/[0.12]", !flush && "rounded-full")}>
        <span
          className={cx(
            "block h-full origin-left bg-sky-500 transition-transform duration-300 ease-out motion-reduce:transition-none",
            progress == null && "opacity-40",
          )}
          style={{ transform: `scaleX(${progress == null ? 1 : Math.max(0, Math.min(100, progress)) / 100})` }}
        />
      </Progress.Track>
    </Progress.Root>
  );
}

function IconButton({ label, onClick, icon, tile }: { label: string; onClick: () => void; icon: "remove" | "retry"; tile: boolean }) {
  return (
    <button
      type="button"
      aria-label={label}
      onClick={onClick}
      className={cx(
        "inline-flex size-7 cursor-pointer items-center justify-center rounded-md text-zinc-500",
        "transition-[background-color,color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.97] motion-reduce:transition-none",
        "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500",
        tile
          ? "size-6 rounded-full border border-zinc-950/10 bg-white text-zinc-600 shadow-[0_1px_2px_rgb(0_0_0/0.08)] hover:text-zinc-950 dark:border-white/15 dark:bg-black dark:text-zinc-300 dark:hover:text-white"
          : "hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:hover:bg-white/[0.06] dark:hover:text-white",
      )}
    >
      <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className={tile ? "size-3" : "size-3.5"}>
        {icon === "remove" ? <path d="m4.5 4.5 7 7m0-7-7 7" /> : <path d="M12.5 8a4.5 4.5 0 1 1-1.32-3.18M12.5 2.75v2.5H10" />}
      </svg>
    </button>
  );
}

/** Stroke file icons, one per kind, at 16px in a 16 unit box. */
export function FileIcon({ kind, className }: { kind: AttachmentKind; className?: string }) {
  return (
    <svg
      aria-hidden="true"
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.25"
      strokeLinecap="round"
      strokeLinejoin="round"
      data-kind={kind}
      className={cx("size-4 shrink-0", className)}
    >
      {kind === "image" ? (
        <>
          <rect x="2" y="2.5" width="12" height="11" rx="1.75" />
          <circle cx="6" cy="6.25" r="1.1" />
          <path d="m2.5 12 3.6-3.6a1 1 0 0 1 1.4 0L13.5 14" />
        </>
      ) : kind === "audio" ? (
        <path d="M6 12.25V3.5l7-1.25v8.5M6 12.25a1.75 1.75 0 1 1-3.5 0 1.75 1.75 0 0 1 3.5 0Zm7-1.5a1.75 1.75 0 1 1-3.5 0 1.75 1.75 0 0 1 3.5 0Z" />
      ) : kind === "video" ? (
        <>
          <rect x="1.75" y="3.5" width="9" height="9" rx="1.75" />
          <path d="m10.75 7 3.5-2v6l-3.5-2" />
        </>
      ) : kind === "archive" ? (
        <>
          <path d="M3.5 1.75h9v12.5h-9z" />
          <path d="M8 1.75v1.5m0 1.5v1.5m0 1.5v1.5" />
          <rect x="6.75" y="9.75" width="2.5" height="2.25" rx=".5" />
        </>
      ) : (
        <>
          <path d="M4 1.75h5l3 3v9.5H4V1.75Z" />
          <path d="M9 1.75v3h3" />
          {kind === "pdf" || kind === "document" ? <path d="M6.25 8.25h3.5M6.25 10.75h3.5" /> : null}
          {kind === "spreadsheet" ? <path d="M6 8h4v4H6zM8 8v4M6 10h4" /> : null}
          {kind === "code" ? <path d="m6.75 8.25-1.25 1.5 1.25 1.5m2.5-3 1.25 1.5-1.25 1.5" /> : null}
        </>
      )}
    </svg>
  );
}