AI Attachments

Files on the way into a prompt: chips with an upload ring, a fanned image stack, and a drop zone that reacts as files hover.

Installation

Installation

One command adds ai-attachments and the shared AI Kit layer it is built on (tokens, faces, marks and brand icons). No animation library, light and dark built in.

$npx shadcn@latest add https://tweenui.dev/r/ai-attachments.json
ai-attachments-demo
components/ui/ai-attachments-demo.tsx
"use client"

import * as React from "react"

import { AiDemo } from "@/lib/ai-demo"
import { useAiLoop } from "@/lib/ai-kit"
import {
  AiDropzone,
  AiFileChips,
  AiImageStack,
  type AiAttachment,
  type AiStackImage,
} from "@/registry/tween/ai-attachments"

const frame: React.CSSProperties = {
  display: "grid",
  justifyItems: "center",
  width: "100%",
}

const FILES: AiAttachment[] = [
  { id: "hero", name: "hero.tsx", size: "4 KB", kind: "code" },
  { id: "ref", name: "reference.png", size: "1.8 MB", kind: "image" },
  { id: "copy", name: "launch-copy.pdf", size: "640 KB", kind: "file" },
  { id: "plans", name: "pricing.csv", size: "12 KB", kind: "sheet" },
]

function Chips() {
  const root = React.useRef<HTMLDivElement>(null)
  const [files, setFiles] = React.useState<AiAttachment[]>([
    FILES[0]!,
    { ...FILES[1]!, progress: 0.62 },
    FILES[2]!,
  ])
  const [hands, setHands] = React.useState(false)

  const patch = (id: string, change: Partial<AiAttachment>) =>
    setFiles((list) =>
      list.map((file) => (file.id === id ? { ...file, ...change } : file))
    )

  useAiLoop(
    root,
    async ({ sleep }) => {
      const upload = async (file: AiAttachment, failAt?: number) => {
        setFiles((list) => [...list, { ...file, progress: 0 }])
        for (let step = 1; step <= 10; step++) {
          await sleep(170)
          if (failAt && step === failAt)
            return patch(file.id, { error: "Upload dropped" })
          patch(file.id, { progress: step / 10 })
        }
        await sleep(200)
        patch(file.id, { progress: undefined })
      }
      setFiles([])
      await sleep(600)
      await upload(FILES[0]!)
      await sleep(250)
      await Promise.all([
        upload(FILES[1]!),
        sleep(500).then(() => upload(FILES[2]!, 6)),
      ])
      await sleep(1200)
      patch("copy", { error: undefined, progress: 0.5 })
      for (let step = 6; step <= 10; step++) {
        await sleep(170)
        patch("copy", { progress: step / 10 })
      }
      await sleep(200)
      patch("copy", { progress: undefined })
      await sleep(900)
      await upload(FILES[3]!)
      await sleep(2000)
    },
    { gap: 400, enabled: !hands }
  )

  return (
    <div ref={root} style={frame} onPointerDown={() => setHands(true)}>
      <AiFileChips
        files={files}
        onRemove={(id) =>
          setFiles((list) => list.filter((file) => file.id !== id))
        }
        onRetry={(id) => patch(id, { error: undefined, progress: undefined })}
      />
    </div>
  )
}

const SHOTS: AiStackImage[] = [
  { id: "dunes", name: "Dunes at dusk", art: 0 },
  { id: "board", name: "Dashboard mock", art: 1 },
  { id: "orbit", name: "Orbit study", art: 2 },
  { id: "tide", name: "Tide lines", art: 3 },
  { id: "dunes-2", name: "Dunes, wide crop", art: 0 },
  { id: "orbit-2", name: "Orbit, second pass", art: 2 },
]

function Stack() {
  const root = React.useRef<HTMLDivElement>(null)
  const [images, setImages] = React.useState(SHOTS)
  const [open, setOpen] = React.useState(false)
  const [hands, setHands] = React.useState(false)

  useAiLoop(
    root,
    async ({ sleep }) => {
      setImages(SHOTS)
      setOpen(false)
      await sleep(1500)
      setOpen(true)
      await sleep(2600)
      setOpen(false)
      await sleep(900)
    },
    { gap: 300, enabled: !hands, still: () => setOpen(true) }
  )

  return (
    <div
      ref={root}
      style={frame}
      onPointerDown={() => setHands(true)}
      onKeyDown={() => setHands(true)}
    >
      <AiImageStack
        images={images}
        expanded={open}
        onExpandedChange={setOpen}
        onRemove={(id) =>
          setImages((list) => list.filter((image) => image.id !== id))
        }
      />
    </div>
  )
}

function Drop() {
  const root = React.useRef<HTMLDivElement>(null)
  const [status, setStatus] = React.useState<
    "idle" | "over" | "done" | undefined
  >("over")
  const [title, setTitle] = React.useState<string | undefined>(undefined)
  const [hands, setHands] = React.useState(false)

  useAiLoop(
    root,
    async ({ sleep }) => {
      setTitle(undefined)
      setStatus("idle")
      await sleep(1500)
      setStatus("over")
      await sleep(1900)
      setStatus("done")
      setTitle("3 files attached")
      await sleep(2200)
    },
    { gap: 300, enabled: !hands, still: () => setStatus("over") }
  )

  const take = () => {
    if (hands) return
    setHands(true)
    setStatus(undefined)
    setTitle(undefined)
  }

  return (
    <div
      ref={root}
      style={frame}
      onPointerDown={take}
      onDragEnter={take}
      onKeyDown={take}
    >
      <AiDropzone
        status={status}
        title={title}
        onFiles={(files) => {
          setStatus("done")
          setTitle(
            `${files.length} file${files.length === 1 ? "" : "s"} attached`
          )
        }}
      />
    </div>
  )
}

export function AiAttachmentsDemo({ only }: { only?: string }) {
  return (
    <AiDemo
      only={only}
      tabs={[
        { name: "File chips", node: <Chips /> },
        { name: "Image stack", node: <Stack /> },
        { name: "Drop zone", node: <Drop /> },
      ]}
    />
  )
}

Installation

pnpm dlx shadcn@latest add https://tweenui.dev/r/ai-attachments.json

Usage

import {
  AiDropzone,
  AiFileChips,
  AiImageStack,
} from "@/components/ui/ai-attachments"
const [files, setFiles] = useState([
  { id: "hero", name: "hero.tsx", size: "4 KB", kind: "code" },
  { id: "ref", name: "reference.png", size: "1.8 MB", kind: "image", progress: 0.4 },
])
 
<AiFileChips
  files={files}
  onRemove={(id) => setFiles(files.filter((file) => file.id !== id))}
/>
 
<AiDropzone accept="image/*,.pdf" onFiles={(dropped) => upload(dropped)} />

Set progress (0 to 1) while a file uploads and clear it when the upload finishes. Set error to show the failed state with a retry button.

Versions

  • AiFileChips shows attached files as chips. A ring fills around the icon while a file uploads, then the tile squares off. Failed files turn red and offer retry.
  • AiImageStack shows images as a fanned stack. Press it and the cards slide apart into a row with remove buttons. Past max, the last card carries a count.
  • AiDropzone reacts to real drag events: the frame turns solid, three files rise above the face, and the headline changes. Click, Enter or Space opens the file picker.

AiThumbArt is also exported: four original SVG thumbnails for demos and placeholders.

Props

AiFileChips

PropTypeDefaultDescription
filesAiAttachment[]{ id, name, size?, kind?, progress?, error? } each.
onRemove(id: string) => voidCalled from a chip's remove button.
onRetry(id: string) => voidCalled from the retry button of a failed file.
emptyLabelstring"No files attached"Shown when there are no files.

kind is "file", "code", "image" or "sheet" and picks the icon.

AiImageStack

PropTypeDefaultDescription
imagesAiStackImage[]{ id, name, src?, art? } each.
expandedbooleanControls the spread. Omit to let the stack manage it.
onExpandedChange(expanded: boolean) => voidCalled when the stack opens or closes.
onRemove(id: string) => voidCalled from a card's remove button.
maxnumber4Cards shown before the rest fold into a count.

AiDropzone

PropTypeDefaultDescription
onFiles(files: File[]) => voidCalled with dropped or chosen files.
acceptstringPassed to the file input.
multiplebooleantrueAllow more than one file.
disabledbooleanfalseDims the zone and ignores input.
status"idle" | "over" | "done"Overrides the state. Omit to follow real drag events.
title, hintstringThe headline and the line under it.
tone, shapeface look"blue", "blob"The face in the zone.