About
An image upload where the picture itself is the progress.
Built with React and Tailwind. Copy the prompt and paste it into Claude Code, Cursor or Lovable: your agent adds Dither upload to your project and fits it to your theme.
Code
How Dither upload is used: the demo's code. The component's own source comes with a free account.
Usage.tsx
"use client"
import * as React from "react"
import { DitherUpload, DitherUploadFile } from "@/components/ui/dither-upload"
const FIT_CSS = "html,body{overflow:hidden}[data-fit-small] [data-fit-hide]{display:none!important}"
/**
* 21st shows a demo in a small frame: about 674 by 421 on a component page, 358 by 224 on a
* phone and 245 by 139 on a profile card. A demo taller than its frame gets scrollbars, which
* render white on dark pages. FitFrame fills the frame exactly instead.
*
* - "scale": the content shrinks until it fits, centered. For visuals such as orbs.
* - "crop": the content stays at full size from the top and fades out at the bottom. For text
* that streams in, where a changing scale would make the page breathe.
*
* `minWidth` lays out a wide demo (a table, a two column panel) at that width and scales it down
* to the frame, instead of letting it collapse to a narrow layout. The frame centers it, so it
* shrinks evenly on both sides.
*
* Anything marked `data-fit-hide` (state buttons, the chatcn.dev line) drops out in frames
* shorter than `hideBelow`, so a profile card shows the visual alone.
*/
function FitFrame({
children,
mode = "scale",
hideBelow = 360,
minWidth,
maxScale = 1,
}: {
children: React.ReactNode
mode?: "scale" | "crop"
hideBelow?: number
minWidth?: string
/** Above 1, a small demo grows until its first child fills most of the frame. */
maxScale?: number
}) {
const content = React.useRef<HTMLDivElement>(null)
const [cropped, setCropped] = React.useState(false)
React.useLayoutEffect(() => {
const el = content.current
if (!el) return
const measure = () => {
const vw = window.innerWidth
const vh = window.innerHeight
el.toggleAttribute("data-fit-small", vh < hideBelow)
// Layout sizes ignore the transform, so measuring never feeds back.
const w = Math.max(el.offsetWidth, el.scrollWidth)
const h = Math.max(el.offsetHeight, el.scrollHeight)
let scale = mode === "scale" ? Math.min(1, vw / w, vh / h) : 1
const child = el.firstElementChild as HTMLElement | null
if (mode === "scale" && maxScale > 1 && scale === 1 && child) {
// A full width wrapper says nothing about the demo's size: measure its widest child.
let cw = child.offsetWidth
if (cw >= el.offsetWidth - 1) {
cw = 0
for (const c of Array.from(child.children)) cw = Math.max(cw, (c as HTMLElement).offsetWidth)
}
const grow = Math.min(maxScale, (vw * 0.9) / Math.max(cw, 1), (vh * 0.9) / child.offsetHeight)
if (grow > 1) scale = grow
}
el.style.transform = scale !== 1 ? `scale(${scale})` : ""
setCropped(mode === "crop" && h > vh + 1)
}
measure()
const observer = new ResizeObserver(measure)
observer.observe(el)
// Content that changes inside a fixed width box (a headline that cycles words) never resizes
// the box itself, so changes below it measure again on the next frame.
let frame = 0
const mutations = new MutationObserver(() => {
cancelAnimationFrame(frame)
frame = requestAnimationFrame(measure)
})
mutations.observe(el, { subtree: true, childList: true, characterData: true })
window.addEventListener("resize", measure)
return () => {
observer.disconnect()
mutations.disconnect()
cancelAnimationFrame(frame)
window.removeEventListener("resize", measure)
}
}, [mode, hideBelow, maxScale])
const fade = "linear-gradient(to bottom, #000 calc(100% - 40px), transparent)"
return (
<div
className="flex w-full justify-center overflow-hidden"
style={{
height: "100dvh",
alignItems: mode === "crop" ? "flex-start" : "center",
maskImage: cropped ? fade : undefined,
WebkitMaskImage: cropped ? fade : undefined,
}}
>
<style>{FIT_CSS}</style>
<div
ref={content}
className="w-full shrink-0"
style={{ transformOrigin: mode === "crop" ? "top center" : "center", minWidth }}
>
{children}
</div>
</div>
)
}
// Uneven but steady progress, like a real upload over a real network.
const KEYS: [number, number][] = [
[0, 0],
[0.35, 0.04],
[1.0, 0.21],
[1.4, 0.25],
[2.2, 0.5],
[2.6, 0.57],
[3.4, 0.84],
[3.9, 0.94],
[4.4, 1],
]
function progressAt(s: number) {
const lastKey = KEYS[KEYS.length - 1]
if (!lastKey || s >= lastKey[0]) return 1
let i = 0
while ((KEYS[i + 1]?.[0] ?? 0) < s) i++
const [t0, p0] = KEYS[i] ?? [0, 0]
const [t1, p1] = KEYS[i + 1] ?? [1, 1]
const k = (s - t0) / (t1 - t0)
return p0 + (p1 - p0) * (k * k * (3 - 2 * k))
}
/** A colour of the painted picture. It is a photograph's paint, not interface, so no token fits. */
const paint = (hex: number, alpha = 1) =>
// design-lint-ignore-next-line a painted photograph, not interface colour
`rgba(${hex >> 16}, ${(hex >> 8) & 255}, ${hex & 255}, ${alpha})`
// A minimal studio still life, painted procedurally: a terracotta vase on a plaster plinth,
// a dark stone sphere on the floor, soft window light from the left. No assets.
function paintStudio(w: number, h: number) {
const cv = document.createElement("canvas")
cv.width = w
cv.height = h
const c = cv.getContext("2d")
if (!c) return cv
const X = (v: number) => v * w
const Y = (v: number) => v * h
const hz = 0.66 // horizon where the backdrop sweeps into the floor
// backdrop + floor, with a soft sweep rather than a hard horizon
let g = c.createLinearGradient(0, 0, 0, h)
g.addColorStop(0, paint(0xbfa58c))
g.addColorStop(hz - 0.12, paint(0xd6c0a8))
g.addColorStop(hz, paint(0xdcc7b0))
g.addColorStop(hz + 0.06, paint(0xd2b99f))
g.addColorStop(1, paint(0xbb9c80))
c.fillStyle = g
c.fillRect(0, 0, w, h)
// window light from the upper left, falling off to the right
g = c.createRadialGradient(X(0.12), Y(0.18), 0, X(0.12), Y(0.18), X(0.95))
g.addColorStop(0, paint(0xfff6e8, 0.55))
g.addColorStop(0.5, paint(0xfff6e8, 0.12))
g.addColorStop(1, paint(0x3c2819, 0.18))
c.fillStyle = g
c.fillRect(0, 0, w, h)
// plinth geometry
const px0 = X(0.17)
const px1 = X(0.47)
const ptop = Y(0.5)
const pdepth = Y(0.05)
const pbot = Y(0.9)
// long soft shadows thrown to the right
c.save()
c.filter = `blur(${Math.round(w * 0.018)}px)`
c.fillStyle = paint(0x462d1c, 0.32)
c.beginPath()
c.moveTo(px1 - X(0.01), pbot)
c.lineTo(px1 + X(0.2), pbot - Y(0.02))
c.lineTo(px1 + X(0.16), ptop + Y(0.16))
c.lineTo(px1 - X(0.01), ptop + pdepth)
c.closePath()
c.fill()
c.restore()
// sphere and its shadow
const sx = X(0.7)
const sr = Y(0.105)
const sy = Y(0.86) - sr
c.save()
c.filter = `blur(${Math.round(w * 0.012)}px)`
c.fillStyle = paint(0x372316, 0.42)
c.beginPath()
c.ellipse(sx + sr * 1.15, sy + sr * 0.92, sr * 1.7, sr * 0.28, -0.06, 0, Math.PI * 2)
c.fill()
c.restore()
c.save()
c.filter = `blur(${Math.max(1, Math.round(w * 0.003))}px)`
c.fillStyle = paint(0x28190f, 0.55)
c.beginPath()
c.ellipse(sx + sr * 0.15, sy + sr * 0.97, sr * 0.8, sr * 0.12, 0, 0, Math.PI * 2)
c.fill()
c.restore()
g = c.createRadialGradient(sx - sr * 0.45, sy - sr * 0.5, sr * 0.05, sx, sy, sr * 1.05)
g.addColorStop(0, paint(0x7d8a80))
g.addColorStop(0.35, paint(0x46524b))
g.addColorStop(0.85, paint(0x1f2723))
g.addColorStop(1, paint(0x2c2a24))
c.fillStyle = g
c.beginPath()
c.arc(sx, sy, sr, 0, Math.PI * 2)
c.fill()
// warm bounce light from the floor on the sphere"s underside
g = c.createRadialGradient(sx, sy + sr * 1.1, 0, sx, sy + sr * 1.1, sr * 0.9)
g.addColorStop(0, paint(0xbe8c64, 0.35))
g.addColorStop(1, paint(0xbe8c64, 0))
c.fillStyle = g
c.beginPath()
c.arc(sx, sy, sr, 0, Math.PI * 2)
c.fill()
// plinth: front face, top face
g = c.createLinearGradient(px0, 0, px1, 0)
g.addColorStop(0, paint(0xf1ebe2))
g.addColorStop(0.6, paint(0xe2d8cb))
g.addColorStop(1, paint(0xcdbfae))
c.fillStyle = g
c.fillRect(px0, ptop + pdepth, px1 - px0, pbot - ptop - pdepth)
g = c.createLinearGradient(px0, ptop, px1, ptop)
g.addColorStop(0, paint(0xfbf7f1))
g.addColorStop(1, paint(0xece3d7))
c.fillStyle = g
c.beginPath()
c.moveTo(px0, ptop + pdepth)
c.lineTo(px0 + X(0.03), ptop)
c.lineTo(px1 + X(0.03), ptop)
c.lineTo(px1, ptop + pdepth)
c.closePath()
c.fill()
c.fillStyle = paint(0xc4b4a1)
c.beginPath()
c.moveTo(px1, ptop + pdepth)
c.lineTo(px1 + X(0.03), ptop)
c.lineTo(px1 + X(0.03), pbot - pdepth * 0.9)
c.lineTo(px1, pbot)
c.closePath()
c.fill()
// contact shade where the plinth meets the floor
c.save()
c.filter = `blur(${Math.max(1, Math.round(w * 0.004))}px)`
c.fillStyle = paint(0x3c2819, 0.35)
c.fillRect(px0 - X(0.005), pbot - Y(0.008), px1 - px0 + X(0.04), Y(0.016))
c.restore()
// vase on the plinth
const vx = X(0.315)
const vb = ptop + pdepth * 0.55
const vh = Y(0.36)
const vw = X(0.085)
c.save()
c.filter = `blur(${Math.round(w * 0.01)}px)`
c.fillStyle = paint(0x5a371e, 0.3)
c.beginPath()
c.ellipse(vx + vw * 1.1, vb - Y(0.005), vw * 1.6, Y(0.02), 0, 0, Math.PI * 2)
c.fill()
c.restore()
const vase = new Path2D()
vase.moveTo(vx - vw * 0.55, vb)
vase.bezierCurveTo(
vx - vw * 1.25,
vb - vh * 0.25,
vx - vw * 1.1,
vb - vh * 0.62,
vx - vw * 0.42,
vb - vh * 0.8,
)
vase.bezierCurveTo(
vx - vw * 0.3,
vb - vh * 0.88,
vx - vw * 0.3,
vb - vh * 0.95,
vx - vw * 0.45,
vb - vh,
)
vase.lineTo(vx + vw * 0.45, vb - vh)
vase.bezierCurveTo(
vx + vw * 0.3,
vb - vh * 0.95,
vx + vw * 0.3,
vb - vh * 0.88,
vx + vw * 0.42,
vb - vh * 0.8,
)
vase.bezierCurveTo(
vx + vw * 1.1,
vb - vh * 0.62,
vx + vw * 1.25,
vb - vh * 0.25,
vx + vw * 0.55,
vb,
)
vase.closePath()
g = c.createLinearGradient(vx - vw * 1.2, 0, vx + vw * 1.2, 0)
g.addColorStop(0, paint(0x9a5332))
g.addColorStop(0.28, paint(0xd88a5a))
g.addColorStop(0.45, paint(0xc8754a))
g.addColorStop(0.8, paint(0x8a4528))
g.addColorStop(1, paint(0x6e361f))
c.fillStyle = g
c.fill(vase)
// mouth
c.fillStyle = paint(0x5a2c18)
c.beginPath()
c.ellipse(vx, vb - vh, vw * 0.45, vh * 0.025, 0, 0, Math.PI * 2)
c.fill()
// a dry branch in the vase
c.strokeStyle = paint(0x5b4632)
c.lineCap = "round"
c.lineWidth = Math.max(1, w * 0.0035)
c.beginPath()
c.moveTo(vx + vw * 0.05, vb - vh)
c.bezierCurveTo(
vx + vw * 0.2,
vb - vh * 1.35,
vx + vw * 0.9,
vb - vh * 1.55,
vx + vw * 1.6,
vb - vh * 1.72,
)
c.moveTo(vx + vw * 0.5, vb - vh * 1.4)
c.bezierCurveTo(
vx + vw * 0.7,
vb - vh * 1.62,
vx + vw * 0.6,
vb - vh * 1.8,
vx + vw * 0.9,
vb - vh * 1.95,
)
c.moveTo(vx - vw * 0.05, vb - vh)
c.bezierCurveTo(
vx - vw * 0.3,
vb - vh * 1.3,
vx - vw * 0.9,
vb - vh * 1.45,
vx - vw * 1.3,
vb - vh * 1.5,
)
c.stroke()
// film grain: one small tile of noise, laid over the picture
const tile = document.createElement("canvas")
tile.width = tile.height = 96
const tc = tile.getContext("2d")
if (tc) {
const img = tc.createImageData(96, 96)
let s = 99
for (let i = 0; i < img.data.length; i += 4) {
s = (s * 16807) % 2147483647
const v = s / 2147483647 > 0.5 ? 255 : 0
img.data[i] = img.data[i + 1] = img.data[i + 2] = v
img.data[i + 3] = 7
}
tc.putImageData(img, 0, 0)
const grain = c.createPattern(tile, "repeat")
if (grain) {
c.fillStyle = grain
c.fillRect(0, 0, w, h)
}
}
return cv
}
const SIZE = 8.4e6
function DitherUploadDemo() {
const ref = React.useRef<HTMLDivElement>(null)
const chipRef = React.useRef<HTMLDivElement>(null)
const [photo, setPhoto] = React.useState("")
const [file, setFile] = React.useState<DitherUploadFile | null>(null)
const [progress, setProgress] = React.useState(0)
const [rate, setRate] = React.useState(0)
const [idle, setIdle] = React.useState(false)
const uploadRaf = React.useRef(0)
const picked = React.useRef("")
// One pretend upload. It runs to the end even after someone takes over, as a real one would.
const upload = React.useCallback((next: DitherUploadFile) => {
cancelAnimationFrame(uploadRaf.current)
setFile(next)
setProgress(0)
const t0 = performance.now()
let prev = 0
let r = 1.8e6
const tick = (now: number) => {
const p = progressAt((now - t0) / 1000)
r += ((p - prev) * next.size * 60 - r) * 0.05
prev = p
setProgress(p)
setRate(Math.max(0.1e6, r))
if (p < 1) uploadRaf.current = requestAnimationFrame(tick)
}
uploadRaf.current = requestAnimationFrame(tick)
}, [])
React.useEffect(
() => () => {
cancelAnimationFrame(uploadRaf.current)
if (picked.current) URL.revokeObjectURL(picked.current)
},
[],
)
React.useEffect(() => {
// Encoded off the main thread, and only as large as the card can show it.
let url = ""
let gone = false
paintStudio(1000, 625).toBlob(
(blob) => {
if (!blob || gone) return
url = URL.createObjectURL(blob)
setPhoto(url)
},
"image/jpeg",
0.92,
)
return () => {
gone = true
if (url) URL.revokeObjectURL(url)
}
}, [])
// Carries a photo in, drops it, uploads it, removes it, and again, until someone uses it.
React.useEffect(() => {
if (idle || !photo) return
let raf = 0
const timers: number[] = []
const at = (ms: number, fn: () => void) => timers.push(window.setTimeout(fn, ms))
const zone = () => ref.current?.querySelector<HTMLElement>("[data-dither-zone]")
const fire = (type: string, x: number, y: number) =>
zone()?.dispatchEvent(
new DragEvent(type, { bubbles: true, cancelable: true, clientX: x, clientY: y }),
)
const carry = (ms: number, from: [number, number], to: [number, number], done: () => void) => {
const t0 = performance.now()
const step = (now: number) => {
const t = Math.min(1, (now - t0) / ms)
const e = t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2
const x = from[0] + (to[0] - from[0]) * e
const y = from[1] + (to[1] - from[1]) * e - Math.sin(Math.PI * t) * 24
const box = ref.current?.getBoundingClientRect()
const chip = chipRef.current
if (chip && box) {
chip.style.opacity = String(Math.min(1, t * 4))
chip.style.transform = `translate(${x - box.left + 12}px, ${y - box.top + 14}px) rotate(-4deg)`
}
fire("dragover", x, y)
if (t < 1) raf = requestAnimationFrame(step)
else done()
}
raf = requestAnimationFrame(step)
}
const cycle = () => {
const z = zone()?.getBoundingClientRect()
if (!z) return
const target: [number, number] = [z.left + z.width * 0.5, z.top + z.height * 0.5]
carry(1300, [z.right + 60, z.bottom + 120], target, () => {
fire("drop", target[0], target[1])
if (chipRef.current) chipRef.current.style.opacity = "0"
upload({ name: "studio-shoot-04.jpg", size: SIZE, src: photo, dimensions: "4032 × 2520" })
at(4400 + 2600, () =>
ref.current
?.querySelector<HTMLButtonElement>(
"[data-slot=dither-upload] button[aria-label^=Remove]",
)
?.click(),
)
})
}
at(700, cycle)
const loop = window.setInterval(() => at(0, cycle), 10400)
const chip = chipRef.current
return () => {
cancelAnimationFrame(raf)
window.clearInterval(loop)
for (const id of timers) window.clearTimeout(id)
// Taken over mid carry: the carried photo goes away and the spotlight goes out.
if (chip) chip.style.opacity = "0"
zone()?.dispatchEvent(new DragEvent("dragleave", { bubbles: true }))
}
}, [idle, photo, upload])
return (
<div
ref={ref}
// Tall enough for the open card, so nothing around it moves; it opens both ways from the middle.
className="relative flex min-h-[22.5rem] w-full items-center justify-center overflow-x-clip px-0 py-2 sm:px-4"
onPointerDownCapture={(e) => {
if (e.isTrusted) setIdle(true)
}}
onKeyDownCapture={(e) => {
if (e.isTrusted) setIdle(true)
}}
onDragEnterCapture={(e) => {
if (e.isTrusted) setIdle(true)
}}
>
<DitherUpload
className="max-w-[392px]"
file={file}
progress={progress}
rate={progress < 1 ? rate : undefined}
onFiles={(files) => {
const f = files[0]
if (!f) return
setIdle(true)
if (picked.current) URL.revokeObjectURL(picked.current)
picked.current = URL.createObjectURL(f)
upload({ name: f.name, size: f.size, src: picked.current })
}}
onRemove={() => {
cancelAnimationFrame(uploadRaf.current)
setFile(null)
setProgress(0)
}}
/>
<div
ref={chipRef}
aria-hidden="true"
className="bg-(color:--chatcn-card) text-(color:--chatcn-fg) shadow-(--chatcn-shadow-lg) rounded-(--chatcn-radius-md) text-[0.8125rem]/[1.25rem] pointer-events-none absolute top-0 left-0 z-10 flex items-center gap-2 py-1 ps-1 pe-3 font-mono font-medium whitespace-nowrap opacity-0"
>
{photo ? (
<img src={photo} alt="" className="rounded-(--chatcn-radius-sm) size-9 object-cover" />
) : null}
studio-shoot-04.jpg
</div>
</div>
)
}
/** The line under each 21st demo that points back to the kit. */
function MoreOn({ slug, children }: { slug: string; children: React.ReactNode }) {
return (
<p data-fit-hide className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-faint) text-center text-balance">
{children}{" "}
<a
href={`https://chatcn.dev/docs/components/${slug}`}
target="_blank"
rel="noopener"
className="text-(color:--chatcn-fg-subtle) hover:text-(color:--chatcn-fg) underline underline-offset-2"
>
chatcn.dev
</a>
</p>
)
}
/** Dither upload, playing on its own, with the line back to its chatcn page. */
export default function DitherUploadPreview() {
return (
<FitFrame maxScale={1.6}>
<div className="mx-auto flex w-[26rem] max-w-full flex-col items-center gap-2 py-4">
<DitherUploadDemo />
<MoreOn slug="dither-upload">One of 30 free microinteractions on</MoreOn>
</div>
</FitFrame>
)
}
















