{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"reeded-reveal","type":"registry:component","title":"Reeded reveal","description":"A generated image seen through reeded glass: each reed bends its slice, then the glass clears from the centre outward.","author":"Hairline UI","dependencies":[],"registryDependencies":["https://hairlineui.com/r/number-roll.json?as=dependency"],"files":[{"path":"registry/reeded-reveal.tsx","type":"registry:component","content":"// Hairline UI · reeded-reveal · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\n/* ─────────────────────────────────────────────────────────\n * REEDED REVEAL: the image behind reeded glass\n *\n * While your generation runs, the well is a pane of reeded\n * glass with colour behind it and a glint that crosses the\n * reeds. When the image has loaded, you see it through the\n * glass: each reed bends its own slice and softens it, then the\n * reeds relax from the centre outward, the glint sweeping once,\n * until the picture is sharp. Works with any image host.\n * ───────────────────────────────────────────────────────── */\n\nimport * as React from \"react\";\nimport { clamp01, drawFitted } from \"./image-grains\";\nimport { Announce, ErrorFace, ProgressTag, frameClass, useArrival, useReducedMotion, type RevealProps } from \"./image-arrival\";\n\nexport type { GenerationStatus, RevealLabels } from \"./image-arrival\";\nexport interface ReededRevealProps extends RevealProps {\n  /** How many reeds across the glass. */\n  reeds?: number;\n}\n\nconst CLEAR = 1500;\n\n/** How strongly reed i (of n) still refracts at time p: all of them at first, then clearing from the centre out. */\nfunction refraction(i: number, n: number, p: number) {\n  if (p >= 1) return 0;\n  const centre = (n - 1) / 2;\n  const fromCentre = Math.abs(i - centre) / Math.max(1, centre);\n  const local = clamp01((p - (0.18 + fromCentre * 0.36)) / 0.4);\n  return Math.pow(1 - local, 2.4);\n}\n\nconst BEHIND =\n  \"radial-gradient(50% 55% at 30% 45%, color-mix(in oklab, var(--chart-2) 38%, transparent), transparent 72%), radial-gradient(45% 50% at 72% 58%, color-mix(in oklab, var(--chart-4) 34%, transparent), transparent 72%)\";\nconst reedsOf = (n: number) =>\n  `repeating-linear-gradient(90deg, color-mix(in oklab, var(--background) 34%, transparent) 0, transparent calc(100% / ${n} * 0.18), transparent calc(100% / ${n} * 0.62), color-mix(in oklab, var(--foreground) 10%, transparent) calc(100% / ${n}))`;\n\nexport function ReededReveal({ src, status, progress, alt, crossOrigin, onReady, onRetry, labels, className, reeds = 14 }: ReededRevealProps) {\n  const reduced = useReducedMotion();\n  const { phase, onLoad, onError, imageRef, finish } = useArrival(src, status, onReady);\n  const figure = React.useRef<HTMLElement>(null);\n  const image = React.useRef<HTMLImageElement>(null);\n  const canvas = React.useRef<HTMLCanvasElement>(null);\n  const revealing = phase === \"revealing\";\n  const n = Math.max(4, Math.min(40, Math.round(reeds)));\n\n  React.useEffect(() => {\n    if (!revealing) return;\n    const el = canvas.current;\n    const box = figure.current;\n    const img = image.current;\n    if (reduced || !el || !box || !img) {\n      const id = window.setTimeout(finish, 0);\n      return () => window.clearTimeout(id);\n    }\n    const dpr = Math.min(window.devicePixelRatio || 1, 2);\n    const w = box.clientWidth;\n    const h = box.clientHeight;\n    el.width = Math.round(w * dpr);\n    el.height = Math.round(h * dpr);\n    const ctx = el.getContext(\"2d\");\n    if (!ctx) return;\n    const fit = getComputedStyle(img).objectFit || \"cover\";\n    // Both copies at device resolution, so the hand-over to the real image never sharpens with a jump.\n    const W = el.width;\n    const H = el.height;\n    const sharp = document.createElement(\"canvas\");\n    sharp.width = W;\n    sharp.height = H;\n    const sctx = sharp.getContext(\"2d\");\n    if (sctx) drawFitted(sctx, img, img.naturalWidth, img.naturalHeight, 0, 0, W, H, fit);\n    // Frosted: a tenth-size copy scaled back up is soft without a canvas filter (which Safari lacks).\n    const tiny = document.createElement(\"canvas\");\n    tiny.width = Math.max(4, Math.round(w / 10));\n    tiny.height = Math.max(4, Math.round(h / 10));\n    tiny.getContext(\"2d\")?.drawImage(sharp, 0, 0, tiny.width, tiny.height);\n    const frost = document.createElement(\"canvas\");\n    frost.width = W;\n    frost.height = H;\n    const fctx = frost.getContext(\"2d\");\n    if (fctx) {\n      fctx.imageSmoothingQuality = \"high\";\n      fctx.drawImage(tiny, -8 * dpr, -8 * dpr, W + 16 * dpr, H + 16 * dpr);\n    }\n\n    const reedW = w / n;\n    let frame = 0;\n    const start = performance.now();\n    const step = (now: number) => {\n      const p = clamp01((now - start) / CLEAR);\n      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n      ctx.drawImage(sharp, 0, 0, w, h);\n      const glint = -0.25 + p * 1.6;\n      for (let i = 0; i < n; i++) {\n        const r = refraction(i, n, p);\n        if (r <= 0.005) continue;\n        const x = i * reedW;\n        const rw = i === n - 1 ? w - x : reedW + 0.5;\n        // Each reed shows its slice shifted and squeezed, as a cylinder lens would.\n        const shift = ((i % 2 ? -1 : 1) * 11 + Math.sin(p * 6.9 + i * 0.62) * 5) * r;\n        const sx = Math.max(0, Math.min(w - rw, x + shift));\n        const sw = Math.max(4, rw * (1 - 0.34 * r));\n        ctx.globalAlpha = Math.min(1, r * 1.15);\n        ctx.drawImage(frost, sx * dpr, 0, sw * dpr, H, x, 0, rw, h);\n        const lit = Math.max(0, 1 - Math.abs(i / (n - 1) - glint) * 3.6);\n        const g = ctx.createLinearGradient(x, 0, x + rw, 0);\n        g.addColorStop(0, `rgba(255,255,255,${(r * (0.26 + lit * 0.3)).toFixed(3)})`);\n        g.addColorStop(0.16, `rgba(255,255,255,${(r * (0.08 + lit * 0.12)).toFixed(3)})`);\n        g.addColorStop(0.52, \"rgba(255,255,255,0)\");\n        g.addColorStop(1, `rgba(0,0,0,${(r * 0.36).toFixed(3)})`);\n        ctx.globalAlpha = 1;\n        ctx.fillStyle = g;\n        ctx.fillRect(x, 0, rw, h);\n      }\n      ctx.globalAlpha = 1;\n      if (p < 1) frame = requestAnimationFrame(step);\n      else finish();\n    };\n    frame = requestAnimationFrame(step);\n    return () => cancelAnimationFrame(frame);\n  }, [revealing, reduced, finish, n]);\n\n  const waiting = phase === \"waiting\";\n  return (\n    <figure ref={figure} className={frameClass(className)} aria-busy={waiting}>\n      {waiting && (\n        <div aria-hidden=\"true\" className=\"pointer-events-none absolute inset-0 overflow-clip\">\n          <div className=\"absolute inset-0\" style={{ background: BEHIND }} />\n          <div className=\"absolute inset-0\" style={{ background: reedsOf(n) }} />\n          <div\n            className=\"absolute inset-y-0 left-0 w-1/3\"\n            style={{\n              background: \"linear-gradient(90deg, transparent, color-mix(in oklab, var(--background) 40%, transparent), transparent)\",\n              animation: reduced ? \"none\" : \"ui-reed-glint 3.2s cubic-bezier(0.45,0,0.25,1) infinite\",\n              opacity: reduced ? 0 : 1,\n            }}\n          />\n        </div>\n      )}\n      {src && (\n        // eslint-disable-next-line @next/next/no-img-element\n        <img\n          ref={(el) => {\n            image.current = el;\n            imageRef(el);\n          }}\n          key={src}\n          src={src}\n          alt={alt}\n          crossOrigin={crossOrigin}\n          onLoad={onLoad}\n          onError={onError}\n          draggable={false}\n          className=\"absolute inset-0 size-full object-cover\"\n          style={{ opacity: phase === \"shown\" ? 1 : 0 }}\n        />\n      )}\n      {revealing && <canvas ref={canvas} aria-hidden=\"true\" className=\"pointer-events-none absolute inset-0 size-full\" />}\n      {waiting && <ProgressTag progress={progress} label={labels?.generating ?? \"Generating\"} />}\n      {phase === \"error\" && <ErrorFace labels={labels} onRetry={onRetry} />}\n      <Announce phase={phase} labels={labels} />\n    </figure>\n  );\n}\n"},{"path":"registry/image-arrival.tsx","type":"registry:component","content":"// Hairline UI · reeded-reveal · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\n/* ─────────────────────────────────────────────────────────\n * IMAGE ARRIVAL: what the four reveals share.\n *\n * A reveal follows your app's real state, never a timer: it\n * waits while `status` is \"generating\", and it only plays once\n * `status` is \"ready\" and the picture has actually loaded and\n * decoded. An image that was already there when the page loaded\n * is simply shown. \"error\", or a picture that fails to load,\n * shows a failure with Try again.\n * ───────────────────────────────────────────────────────── */\n\nimport * as React from \"react\";\nimport { RotateCcw } from \"lucide-react\";\nimport { NumberRoll } from \"./number-roll\";\n\nexport type GenerationStatus = \"generating\" | \"ready\" | \"error\";\n\nexport interface RevealLabels {\n  generating?: string;\n  ready?: string;\n  failed?: string;\n  retry?: string;\n}\n\nexport interface RevealProps {\n  /** The generated image. It can arrive before or with status \"ready\". */\n  src?: string;\n  /** Your generation's real state. */\n  status: GenerationStatus;\n  /** 0 to 1, if your API reports it. Without it no figure is shown and nothing pretends to know. */\n  progress?: number;\n  alt: string;\n  /** Pass \"anonymous\" when your image host sends CORS headers (needed for pixel effects; others work without). */\n  crossOrigin?: \"anonymous\" | \"use-credentials\";\n  /** Called once the reveal has played (or the image is shown). */\n  onReady?: () => void;\n  /** Shows Try again on failure. */\n  onRetry?: () => void;\n  labels?: RevealLabels;\n  /** Size the frame here, e.g. \"aspect-square w-72\". */\n  className?: string;\n}\n\nexport type ArrivalPhase = \"waiting\" | \"revealing\" | \"shown\" | \"error\";\n\nconst reducedQuery = \"(prefers-reduced-motion: reduce)\";\nconst subscribeReduced = (onChange: () => void) => {\n  const query = window.matchMedia(reducedQuery);\n  query.addEventListener(\"change\", onChange);\n  return () => query.removeEventListener(\"change\", onChange);\n};\nexport const useReducedMotion = () => React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);\n\n/** The phase a reveal is in, and the handlers its <img> needs. Call `finish` when the reveal has played. */\nexport function useArrival(src: string | undefined, status: GenerationStatus, onReady?: () => void) {\n  const [loaded, setLoaded] = React.useState<string | null>(null);\n  const [broken, setBroken] = React.useState<string | null>(null);\n  const [played, setPlayed] = React.useState<string | null>(null);\n  // Only an image seen generating in this mount is revealed; one that was already there is just shown.\n  const [armed, setArmed] = React.useState(status === \"generating\");\n  const [seen, setSeen] = React.useState(status);\n  if (status !== seen) {\n    setSeen(status);\n    if (status === \"generating\") {\n      setArmed(true);\n      setPlayed(null);\n    }\n  }\n\n  const failed = status === \"error\" || (status === \"ready\" && !!src && broken === src);\n  const arrived = status === \"ready\" && !!src && loaded === src;\n  const phase: ArrivalPhase = failed ? \"error\" : !arrived ? \"waiting\" : !armed || played === src ? \"shown\" : \"revealing\";\n\n  const ready = React.useRef(onReady);\n  React.useLayoutEffect(() => {\n    ready.current = onReady;\n  });\n  React.useEffect(() => {\n    if (phase === \"shown\") ready.current?.();\n  }, [phase]);\n\n  const settle = React.useCallback(\n    (img: HTMLImageElement) => {\n      const url = src ?? null;\n      (img.decode ? img.decode() : Promise.resolve()).catch(() => undefined).then(() => setLoaded(url));\n    },\n    [src],\n  );\n  const onLoad = (event: React.SyntheticEvent<HTMLImageElement>) => settle(event.currentTarget);\n  const onError = () => setBroken(src ?? null);\n  // A server-rendered image can finish loading before React attaches onLoad; catch that when the element arrives.\n  const imageRef = React.useCallback(\n    (img: HTMLImageElement | null) => {\n      if (!img || !img.complete) return;\n      if (img.naturalWidth) settle(img);\n      else setBroken(src ?? null);\n    },\n    [settle, src],\n  );\n  const finish = React.useCallback(() => setPlayed(src ?? null), [src]);\n  return { phase, onLoad, onError, imageRef, finish };\n}\n\n/** Two frames later, so a starting state is painted before it changes. */\nexport function useNextFrame(active: boolean) {\n  const [go, setGo] = React.useState(false);\n  if (!active && go) setGo(false);\n  React.useEffect(() => {\n    if (!active) return;\n    let second = 0;\n    const first = requestAnimationFrame(() => {\n      second = requestAnimationFrame(() => setGo(true));\n    });\n    return () => {\n      cancelAnimationFrame(first);\n      cancelAnimationFrame(second);\n    };\n  }, [active]);\n  return active && go;\n}\n\n/** The figure's progress, in a small tag at its foot, only when your API reports a number. */\nexport function ProgressTag({ progress, label }: { progress?: number; label: string }) {\n  if (progress == null || !Number.isFinite(progress)) return null;\n  const pct = Math.round(Math.min(1, Math.max(0, progress)) * 100);\n  return (\n    <span className=\"pointer-events-none absolute bottom-3 left-3 z-10 inline-flex h-6 items-center gap-1.5 rounded-full bg-background/90 px-2.5 text-[11.5px] font-medium text-foreground ring-1 ring-border tabular-nums\">\n      {label}\n      <span aria-hidden=\"true\" className=\"text-muted-foreground\">\n        <NumberRoll value={pct} suffix=\"%\" duration={500} />\n      </span>\n    </span>\n  );\n}\n\n/** What a failed generation shows: what happened, and Try again when the app can retry. */\nexport function ErrorFace({ labels, onRetry }: { labels?: RevealLabels; onRetry?: () => void }) {\n  return (\n    <div className=\"absolute inset-0 z-10 flex flex-col items-center justify-center gap-3 bg-muted p-6 text-center\">\n      <p className=\"max-w-[16rem] text-[13px] leading-snug text-muted-foreground\">{labels?.failed ?? \"This image couldn’t be created.\"}</p>\n      {onRetry && (\n        <button\n          type=\"button\"\n          onClick={onRetry}\n          className=\"inline-flex h-8 cursor-pointer items-center gap-1.5 rounded-full bg-background px-3 text-[12.5px] font-medium text-foreground ring-1 ring-border transition-[background-color,scale] duration-150 hover:bg-accent active:scale-[0.97] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50\"\n        >\n          <RotateCcw className=\"size-3.5\" aria-hidden=\"true\" />\n          {labels?.retry ?? \"Try again\"}\n        </button>\n      )}\n    </div>\n  );\n}\n\n/** The sentence a screen reader hears when the phase changes. */\nexport function Announce({ phase, labels }: { phase: ArrivalPhase; labels?: RevealLabels }) {\n  const text = phase === \"waiting\" ? labels?.generating ?? \"Generating image\" : phase === \"error\" ? labels?.failed ?? \"This image couldn’t be created.\" : labels?.ready ?? \"Image ready\";\n  return (\n    <span role=\"status\" className=\"sr-only\">\n      {text}\n    </span>\n  );\n}\n\n/** The frame: full width unless your className sets one (the default has no specificity, so any width class wins). */\nexport const frameClass = (className = \"\") => `relative isolate [:where(&)]:w-full overflow-hidden rounded-[18px] bg-muted ${className}`;\n"},{"path":"registry/image-grains.ts","type":"registry:component","content":"// Hairline UI · reeded-reveal · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n/* ─────────────────────────────────────────────────────────\n * IMAGE GRAINS: the engine under sand-away, burn-away,\n * shatter-away, drain-away, grain-reveal and variant-pick.\n *\n * An element is cut into a grid of grains that carry its real\n * colours. Each grain lets go when a front reaches it (the front\n * is what tells the four styles apart: wind from one side, a burn\n * from a corner, shards from the bottom, a drain into the middle)\n * and then moves on its own path. Time runs both ways, so every\n * removal can be played back to undo it.\n *\n * Pictures (an <img>, <canvas> or <video>, or an element holding\n * one) are read pixel by pixel. Anything else, or a picture from\n * another origin without CORS, keeps its own element on screen\n * behind a moving mask, and its grains take the element's own\n * colours: nothing fails silently.\n * ───────────────────────────────────────────────────────── */\n\nexport type GrainStyle = \"sand\" | \"burn\" | \"shatter\" | \"drain\";\n\nexport interface AwayOptions {\n  /** Milliseconds for the whole removal. Defaults by style, and shorter on rows. */\n  duration?: number;\n}\n\n/* ── noise ─────────────────────────────────────────────── */\n\nexport const hash2 = (x: number, y: number) => {\n  const n = Math.sin(x * 127.1 + y * 311.7) * 43758.5453123;\n  return n - Math.floor(n);\n};\n\nexport function noise2(x: number, y: number) {\n  const xi = Math.floor(x);\n  const yi = Math.floor(y);\n  const xf = x - xi;\n  const yf = y - yi;\n  const u = xf * xf * (3 - 2 * xf);\n  const v = yf * yf * (3 - 2 * yf);\n  const a = hash2(xi, yi);\n  const b = hash2(xi + 1, yi);\n  const c = hash2(xi, yi + 1);\n  const d = hash2(xi + 1, yi + 1);\n  return a + (b - a) * u + (c + (d - c) * u - (a + (b - a) * u)) * v;\n}\n\nexport const clamp01 = (n: number) => (n < 0 ? 0 : n > 1 ? 1 : n);\nconst clamp = (n: number, lo: number, hi: number) => (n < lo ? lo : n > hi ? hi : n);\n\nexport function reducedMotion() {\n  return typeof window !== \"undefined\" && !!window.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches;\n}\n\n/* ── where each grain lets go, and how it moves ────────── */\n\n/** When (0 to 0.58 of the run) the grain at nx, ny lets go. */\nexport function releaseAt(style: GrainStyle | \"gather\", nx: number, ny: number, n: number) {\n  const centre = Math.min(1, Math.hypot(nx - 0.5, ny - 0.5) * 1.42);\n  let raw: number;\n  if (style === \"sand\") raw = nx * 0.58 + ny * 0.1 + n * 0.24;\n  else if (style === \"burn\") raw = (1 - nx) * 0.42 + (1 - ny) * 0.34 + n * 0.22;\n  else if (style === \"drain\") raw = (1 - centre) * 0.54 + n * 0.24;\n  else if (style === \"shatter\") raw = hash2(Math.floor(nx * 7), Math.floor(ny * 9)) * 0.42 + (1 - ny) * 0.28 + n * 0.14;\n  else raw = centre * 0.38 + n * 0.32;\n  return (clamp(raw, 0, 0.78) / 0.78) * 0.58;\n}\n\nexport interface Motion {\n  dx: number;\n  dy: number;\n  alpha: number;\n  scale: number;\n  heat: number;\n}\n\nconst MOTION: Motion = { dx: 0, dy: 0, alpha: 1, scale: 1, heat: 0 };\n\n/** Where a grain is at `life` (0 just let go, 1 gone), written into one shared object (no allocation per grain). */\nexport function move(style: GrainStyle | \"gather\", life: number, nx: number, ny: number, a: number, b: number): Motion {\n  const t = clamp01(life);\n  const out = MOTION;\n  out.heat = 0;\n  if (style === \"sand\") {\n    const ease = 1 - Math.pow(1 - t, 2.4);\n    // The front crosses left to right; grains blow back behind it, never over what is still whole.\n    out.dx = (-18 - a * 46) * ease + Math.sin(t * 5 + b * 6.28) * 7 * t;\n    out.dy = (-24 - b * 60) * Math.pow(t, 1.35);\n    out.alpha = t < 0.14 ? 1 : Math.max(0, 1 - Math.pow((t - 0.14) / 0.86, 1.25));\n    out.scale = 1 - t * 0.42;\n  } else if (style === \"burn\") {\n    const ease = 1 - Math.pow(1 - t, 2.4);\n    out.dx = (a - 0.5) * 34 * ease + Math.sin(t * 7 + b * 10) * 7 * t;\n    out.dy = (-34 - b * 84) * Math.pow(t, 1.45);\n    out.heat = t < 0.5 ? Math.sin((t / 0.5) * Math.PI) : 0;\n    out.alpha = Math.max(0, 1 - Math.pow(t, 1.35));\n    out.scale = 1 + out.heat * 0.3 - t * 0.5;\n  } else if (style === \"shatter\") {\n    const ease = 1 - Math.pow(1 - t, 2.4);\n    out.dx = (nx - 0.5) * 64 * ease + (a - 0.5) * 26 * t;\n    out.dy = -12 * ease + (90 + b * 80) * t * t;\n    out.alpha = Math.max(0, 1 - Math.pow(t, 1.6));\n    out.scale = 1;\n  } else if (style === \"drain\") {\n    const pull = t * t * 0.97;\n    const relX = (0.5 - nx) * 2;\n    const relY = (0.5 - ny) * 2;\n    const angle = t * t * (2.4 + a * 1.2);\n    const cos = Math.cos(angle) - 1;\n    const sin = Math.sin(angle);\n    const restX = relX * (1 - pull);\n    const restY = relY * (1 - pull);\n    // relX/relY are in half-sizes; the caller scales dx/dy by the element's half width and height.\n    out.dx = relX * pull + (restX * cos - restY * sin) * 0.35;\n    out.dy = relY * pull + (restX * sin + restY * cos) * 0.35;\n    out.alpha = Math.max(0, 1 - Math.pow(t, 1.7));\n    out.scale = Math.max(0.25, 1 - t * 0.68);\n  } else {\n    // gather: from scattered (t = 0) to home (t = 1), inside the frame.\n    const inv = 1 - t;\n    const spread = Math.pow(inv, 2.15);\n    const angle = a * Math.PI * 2 + inv * 1.9;\n    const radius = (18 + b * 44) * spread;\n    out.dx = Math.cos(angle) * radius;\n    out.dy = Math.sin(angle) * radius;\n    out.alpha = clamp01(0.24 + t * 0.82);\n    out.scale = 0.68 + t * 0.32;\n  }\n  return out;\n}\n\n/* ── reading an element's pixels ───────────────────────── */\n\ntype Media = HTMLImageElement | HTMLCanvasElement | HTMLVideoElement;\n\nexport function findMedia(el: Element): Media | null {\n  if (el instanceof HTMLImageElement || el instanceof HTMLCanvasElement || el instanceof HTMLVideoElement) return el;\n  return el.querySelector<Media>(\"img, canvas, video\");\n}\n\nconst naturalSize = (m: Media) =>\n  m instanceof HTMLImageElement ? [m.naturalWidth, m.naturalHeight] : m instanceof HTMLVideoElement ? [m.videoWidth, m.videoHeight] : [m.width, m.height];\n\n/** Draws a picture into a box the way object-fit (cover or contain) and object-position would. */\nexport function drawFitted(ctx: CanvasRenderingContext2D, m: Media | CanvasImageSource, iw: number, ih: number, x: number, y: number, w: number, h: number, fit = \"cover\") {\n  if (!iw || !ih) return;\n  const scale = fit === \"contain\" ? Math.min(w / iw, h / ih) : fit === \"fill\" ? 0 : Math.max(w / iw, h / ih);\n  if (!scale) {\n    ctx.drawImage(m as CanvasImageSource, x, y, w, h);\n    return;\n  }\n  const dw = iw * scale;\n  const dh = ih * scale;\n  ctx.drawImage(m as CanvasImageSource, x + (w - dw) / 2, y + (h - dh) / 2, dw, dh);\n}\n\nfunction roundedPath(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number) {\n  const rr = Math.min(r, w / 2, h / 2);\n  ctx.beginPath();\n  ctx.moveTo(x + rr, y);\n  ctx.arcTo(x + w, y, x + w, y + h, rr);\n  ctx.arcTo(x + w, y + h, x, y + h, rr);\n  ctx.arcTo(x, y + h, x, y, rr);\n  ctx.arcTo(x, y, x + w, y, rr);\n  ctx.closePath();\n}\n\nfunction parseColour(value: string): [number, number, number, number] | null {\n  const m = value.match(/rgba?\\(([^)]+)\\)/);\n  if (!m) return null;\n  const parts = m[1].split(/[\\s,/]+/).filter(Boolean).map(Number);\n  if (parts.length < 3 || parts.some((p) => Number.isNaN(p))) return null;\n  return [parts[0], parts[1], parts[2], parts[3] ?? 1];\n}\n\n/** Turns any CSS colour (oklch, a variable…) into rgb through the browser. */\nfunction resolveColour(value: string): [number, number, number, number] | null {\n  const direct = parseColour(value);\n  if (direct) return direct;\n  const probe = document.createElement(\"canvas\").getContext(\"2d\");\n  if (!probe) return null;\n  probe.fillStyle = \"#000\";\n  probe.fillStyle = value;\n  probe.fillRect(0, 0, 1, 1);\n  const d = probe.getImageData(0, 0, 1, 1).data;\n  return [d[0], d[1], d[2], d[3] / 255];\n}\n\n/** The colours an element shows without a picture: its own background (or the first one behind it), its text and its edge. */\nexport function elementPalette(el: Element): [number, number, number][] {\n  let bg: [number, number, number, number] | null = null;\n  for (let node: Element | null = el; node && !bg; node = node.parentElement) {\n    const c = resolveColour(getComputedStyle(node).backgroundColor);\n    if (c && c[3] > 0.5) bg = c;\n  }\n  const style = getComputedStyle(el);\n  const fg = resolveColour(style.color);\n  const edge = resolveColour(style.borderTopColor);\n  const base: [number, number, number] = bg ? [bg[0], bg[1], bg[2]] : [128, 128, 128];\n  const ink: [number, number, number] = fg ? [fg[0], fg[1], fg[2]] : [60, 60, 60];\n  const line: [number, number, number] = edge ? [edge[0], edge[1], edge[2]] : ink;\n  return [base, base, base, ink, line];\n}\n\nexport interface Snapshot {\n  w: number;\n  h: number;\n  radius: number;\n  /** The element's picture at device resolution, rounded like the element; null when it couldn't be read. */\n  sharp: HTMLCanvasElement | null;\n  /** Colours per grain cell, row by row, or null to use the palette. */\n  cells: Uint8ClampedArray | null;\n  palette: [number, number, number][];\n  cols: number;\n  rows: number;\n  step: number;\n}\n\nconst MAX_GRAINS = 7000;\n\nexport function gridFor(w: number, h: number, minStep = 3) {\n  const step = Math.max(minStep, Math.sqrt((w * h) / MAX_GRAINS));\n  return { step, cols: Math.max(4, Math.round(w / step)), rows: Math.max(2, Math.round(h / step)) };\n}\n\n/** Reads an element into grains: its picture's real colours where it can, its own colours where it can't. */\nexport function snapshot(el: HTMLElement, dpr = Math.min(window.devicePixelRatio || 1, 2)): Snapshot {\n  const rect = el.getBoundingClientRect();\n  const w = Math.max(1, rect.width);\n  const h = Math.max(1, rect.height);\n  const radius = parseFloat(getComputedStyle(el).borderTopLeftRadius) || 0;\n  const { step, cols, rows } = gridFor(w, h, h < 90 ? 2.5 : 3);\n  const palette = elementPalette(el);\n  const media = findMedia(el);\n  const shot: Snapshot = { w, h, radius, sharp: null, cells: null, palette, cols, rows, step };\n  if (!media) return shot;\n  // A thumbnail inside a row isn't the row: only a picture that fills most of the element is drawn from its pixels.\n  const area = media.getBoundingClientRect();\n  if (area.width * area.height < w * h * 0.6) return shot;\n  const [iw, ih] = naturalSize(media);\n  if (!iw || !ih) return shot;\n\n  const sharp = document.createElement(\"canvas\");\n  sharp.width = Math.round(w * dpr);\n  sharp.height = Math.round(h * dpr);\n  const ctx = sharp.getContext(\"2d\");\n  if (!ctx) return shot;\n  ctx.scale(dpr, dpr);\n  roundedPath(ctx, 0, 0, w, h, radius);\n  ctx.clip();\n  const [r, g, b] = palette[0];\n  ctx.fillStyle = `rgb(${r},${g},${b})`;\n  ctx.fillRect(0, 0, w, h);\n  const mr = media.getBoundingClientRect();\n  const fit = getComputedStyle(media).objectFit || \"fill\";\n  drawFitted(ctx, media, iw, ih, mr.left - rect.left, mr.top - rect.top, mr.width, mr.height, media instanceof HTMLCanvasElement ? \"fill\" : fit);\n\n  const small = document.createElement(\"canvas\");\n  small.width = cols;\n  small.height = rows;\n  const sctx = small.getContext(\"2d\", { willReadFrequently: true });\n  if (!sctx) return shot;\n  sctx.drawImage(sharp, 0, 0, cols, rows);\n  try {\n    shot.cells = sctx.getImageData(0, 0, cols, rows).data;\n    shot.sharp = sharp;\n  } catch {\n    // Another origin without CORS: the canvas is tainted. Fall back to the element's own colours and its own pixels on screen.\n  }\n  return shot;\n}\n\n/* ── grains ────────────────────────────────────────────── */\n\nexport interface Grain {\n  x: number;\n  y: number;\n  nx: number;\n  ny: number;\n  gx: number;\n  gy: number;\n  release: number;\n  a: number;\n  b: number;\n  /** fillStyle strings: the grain's colour, then hotter steps for a burn. */\n  colours: string[];\n}\n\nconst HOT: [number, number, number] = [255, 168, 62];\n\nexport function makeGrains(shot: Snapshot, style: GrainStyle | \"gather\"): Grain[] {\n  const { cols, rows, w, h, radius, cells, palette } = shot;\n  const cw = w / cols;\n  const ch = h / rows;\n  const out: Grain[] = [];\n  for (let gy = 0; gy < rows; gy++) {\n    for (let gx = 0; gx < cols; gx++) {\n      const x = (gx + 0.5) * cw;\n      const y = (gy + 0.5) * ch;\n      if (radius > 0 && outsideCorner(x, y, w, h, radius)) continue;\n      const nx = cols > 1 ? gx / (cols - 1) : 0.5;\n      const ny = rows > 1 ? gy / (rows - 1) : 0.5;\n      let r: number;\n      let g: number;\n      let b: number;\n      if (cells) {\n        const i = (gy * cols + gx) * 4;\n        r = cells[i];\n        g = cells[i + 1];\n        b = cells[i + 2];\n      } else {\n        [r, g, b] = palette[Math.floor(hash2(gx * 3.7, gy * 5.1) * palette.length)];\n      }\n      const colours = [`rgb(${r},${g},${b})`];\n      if (style === \"burn\") {\n        for (let k = 1; k <= 4; k++) {\n          const t = k / 4;\n          colours.push(`rgb(${Math.round(r + (HOT[0] - r) * t)},${Math.round(g + (HOT[1] - g) * t)},${Math.round(b * (1 - t * 0.7) + 40 * t)})`);\n        }\n      }\n      // Shards move as one: every grain in a shard shares its seeds.\n      const sa = style === \"shatter\" ? hash2(Math.floor(nx * 7) * 1.7 + 3, Math.floor(ny * 9) * 2.3 + 11) : hash2(gx * 1.7 + 3, gy * 2.3 + 11);\n      const sb = style === \"shatter\" ? hash2(Math.floor(nx * 7) * 3.1 + 19, Math.floor(ny * 9) * 1.3 + 5) : hash2(gx * 3.1 + 19, gy * 1.3 + 5);\n      out.push({ x, y, nx, ny, gx, gy, release: releaseAt(style, nx, ny, noise2(nx * 6.5, ny * 8)), a: sa, b: sb, colours });\n    }\n  }\n  return out;\n}\n\nfunction outsideCorner(x: number, y: number, w: number, h: number, r: number) {\n  const cx = x < r ? r : x > w - r ? w - r : x;\n  const cy = y < r ? r : y > h - r ? h - r : y;\n  if (cx === x || cy === y) return false;\n  return Math.hypot(x - cx, y - cy) > r;\n}\n\n/** Draws every grain that has let go at time t (0 to 1), offset by ox, oy. */\nexport function drawGrains(ctx: CanvasRenderingContext2D, grains: Grain[], style: GrainStyle | \"gather\", t: number, shot: Snapshot, ox: number, oy: number, span = 0.42) {\n  // Shards are solid pieces (grains meet, the cracks open as shards part); everything else is loose grain with a hairline gap.\n  const size = Math.max(1.2, (shot.w / shot.cols) * (style === \"shatter\" ? 1.06 : 0.92));\n  const hw = shot.w / 2;\n  const hh = shot.h / 2;\n  for (let i = 0; i < grains.length; i++) {\n    const g = grains[i];\n    if (t < g.release) continue;\n    const life = (t - g.release) / span;\n    if (life >= 1) continue;\n    const m = move(style, life, g.nx, g.ny, g.a, g.b);\n    if (m.alpha <= 0.02) continue;\n    const dx = style === \"drain\" ? m.dx * hw : m.dx;\n    const dy = style === \"drain\" ? m.dy * hh : m.dy;\n    const s = size * m.scale;\n    ctx.globalAlpha = m.alpha;\n    ctx.fillStyle = m.heat > 0.08 ? g.colours[Math.min(4, Math.max(1, Math.round(m.heat * 4)))] ?? g.colours[0] : g.colours[0];\n    ctx.fillRect(ox + g.x + dx - s / 2, oy + g.y + dy - s / 2, s, s);\n  }\n  ctx.globalAlpha = 1;\n}\n\n/** Draws what is still whole at time t: the sharp picture through a mask of the grains that haven't let go. */\nexport function drawRemaining(ctx: CanvasRenderingContext2D, shot: Snapshot, grains: Grain[], t: number, ox: number, oy: number, scratch: { mask: HTMLCanvasElement; img: ImageData; out: HTMLCanvasElement }) {\n  if (!shot.sharp) return;\n  const d = scratch.img.data;\n  d.fill(0);\n  let any = false;\n  for (let i = 0; i < grains.length; i++) {\n    const g = grains[i];\n    if (t < g.release) {\n      const k = (g.gy * shot.cols + g.gx) * 4;\n      d[k] = d[k + 1] = d[k + 2] = d[k + 3] = 255;\n      any = true;\n    }\n  }\n  if (!any) return;\n  const mctx = scratch.mask.getContext(\"2d\");\n  const octx = scratch.out.getContext(\"2d\");\n  if (!mctx || !octx) return;\n  mctx.putImageData(scratch.img, 0, 0);\n  octx.globalCompositeOperation = \"copy\";\n  octx.drawImage(shot.sharp, 0, 0);\n  octx.globalCompositeOperation = \"destination-in\";\n  octx.imageSmoothingEnabled = false;\n  octx.drawImage(scratch.mask, 0, 0, scratch.out.width, scratch.out.height);\n  octx.globalCompositeOperation = \"source-over\";\n  ctx.drawImage(scratch.out, ox, oy, shot.w, shot.h);\n}\n\nexport function makeScratch(shot: Snapshot) {\n  const mask = document.createElement(\"canvas\");\n  mask.width = shot.cols;\n  mask.height = shot.rows;\n  const out = document.createElement(\"canvas\");\n  out.width = shot.sharp?.width ?? 1;\n  out.height = shot.sharp?.height ?? 1;\n  const img = new ImageData(shot.cols, shot.rows);\n  return { mask, img, out };\n}\n\n/* ── removals: one call on any element ─────────────────── */\n\nconst DURATION: Record<GrainStyle, number> = { sand: 1000, burn: 1250, shatter: 1050, drain: 1000 };\nconst PAD = 150;\nconst BACK_SPEED = 1.3;\n\ninterface Run {\n  el: HTMLElement;\n  style: GrainStyle;\n  shot: Snapshot;\n  grains: Grain[];\n  scratch: ReturnType<typeof makeScratch>;\n  canvas: HTMLCanvasElement;\n  dpr: number;\n  t: number;\n  dir: 1 | -1;\n  duration: number;\n  last: number;\n  frame: number;\n  visibility: string;\n  mask: string;\n  waiting: { dir: 1 | -1; resolve: (done: boolean) => void }[];\n}\n\nconst runs = new WeakMap<HTMLElement, Run>();\n\nlet layer: HTMLDivElement | null = null;\nfunction topLayer() {\n  if (layer && layer.isConnected) return layer;\n  layer = document.createElement(\"div\");\n  layer.setAttribute(\"aria-hidden\", \"true\");\n  layer.style.cssText = \"position:fixed;inset:0;pointer-events:none;z-index:2147483000;contain:layout style;overflow:clip;\";\n  document.body.appendChild(layer);\n  return layer;\n}\n\n/** The mask that hides an element up to the front at time t, for elements drawn by the page itself (rows, cards, pictures from another origin). */\nfunction frontMask(style: GrainStyle, t: number) {\n  const p = clamp01(t / 0.58);\n  const soft = 9;\n  if (style === \"sand\") {\n    const x = p * (100 + soft) - soft;\n    return `linear-gradient(90deg, transparent ${x}%, #000 ${x + soft}%)`;\n  }\n  if (style === \"burn\") {\n    const x = p * (100 + soft) - soft;\n    return `linear-gradient(315deg, transparent ${x}%, #000 ${x + soft}%)`;\n  }\n  if (style === \"shatter\") {\n    const x = p * (100 + soft) - soft;\n    return `linear-gradient(0deg, transparent ${x}%, #000 ${x + soft}%)`;\n  }\n  const r = (1 - p) * (100 + soft);\n  return `radial-gradient(farthest-corner, #000 ${Math.max(0, r - soft)}%, transparent ${r}%)`;\n}\n\nfunction paint(run: Run) {\n  const { el, canvas, shot, dpr } = run;\n  // Follow the element through scrolling and layout; if the app has already removed it, stay where it was.\n  if (el.isConnected) {\n    const rect = el.getBoundingClientRect();\n    canvas.style.transform = `translate(${rect.left - PAD}px, ${rect.top - PAD}px)`;\n  }\n  const ctx = canvas.getContext(\"2d\");\n  if (!ctx) return;\n  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n  ctx.clearRect(0, 0, shot.w + PAD * 2, shot.h + PAD * 2);\n  if (shot.sharp) {\n    drawRemaining(ctx, shot, run.grains, run.t, PAD, PAD, run.scratch);\n  } else {\n    const m = run.t <= 0 ? run.mask : frontMask(run.style, run.t);\n    el.style.setProperty(\"mask-image\", m);\n    el.style.setProperty(\"-webkit-mask-image\", m);\n  }\n  drawGrains(ctx, run.grains, run.style, run.t, shot, PAD, PAD);\n}\n\nfunction settle(run: Run, done: boolean, dir: 1 | -1) {\n  const ready = run.waiting.filter((w) => w.dir === dir);\n  run.waiting = run.waiting.filter((w) => w.dir !== dir);\n  ready.forEach((w) => w.resolve(done));\n}\n\nfunction tick(run: Run, now: number) {\n  const dt = Math.min(48, now - run.last);\n  run.last = now;\n  run.t += (run.dir * dt * (run.dir < 0 ? BACK_SPEED : 1)) / run.duration;\n  if (run.dir > 0 && run.t >= 1) {\n    run.t = 1;\n    paint(run);\n    run.canvas.remove();\n    run.frame = 0;\n    settle(run, true, 1);\n    return;\n  }\n  if (run.dir < 0 && run.t <= 0) {\n    run.t = 0;\n    run.canvas.remove();\n    run.el.style.visibility = run.visibility;\n    run.el.style.setProperty(\"mask-image\", run.mask);\n    run.el.style.setProperty(\"-webkit-mask-image\", run.mask);\n    runs.delete(run.el);\n    run.frame = 0;\n    settle(run, true, -1);\n    return;\n  }\n  paint(run);\n  run.frame = requestAnimationFrame((n) => tick(run, n));\n}\n\nfunction start(run: Run) {\n  if (!run.canvas.isConnected) topLayer().appendChild(run.canvas);\n  if (run.frame) return;\n  run.last = performance.now();\n  run.frame = requestAnimationFrame((n) => tick(run, n));\n}\n\nfunction fade(el: HTMLElement, out: boolean) {\n  const anim = el.animate([{ opacity: out ? 1 : 0 }, { opacity: out ? 0 : 1 }], { duration: 160, easing: \"ease-out\", fill: \"forwards\" });\n  return anim.finished.then(() => {\n    if (!out) anim.cancel();\n    return true;\n  });\n}\n\nconst faded = new WeakSet<HTMLElement>();\n\n/**\n * Plays a removal on any element and resolves true once it has gone (it stays hidden in the page until you remove it\n * from your state), or false if undoAway turned it back first.\n */\nexport function playAway(el: HTMLElement | null | undefined, style: GrainStyle, options: AwayOptions = {}): Promise<boolean> {\n  if (!el) return Promise.resolve(false);\n  if (reducedMotion()) {\n    faded.add(el);\n    return fade(el, true);\n  }\n  let run = runs.get(el);\n  if (!run) {\n    const shot = snapshot(el);\n    const dpr = Math.min(window.devicePixelRatio || 1, 2);\n    const canvas = document.createElement(\"canvas\");\n    canvas.width = Math.round((shot.w + PAD * 2) * dpr);\n    canvas.height = Math.round((shot.h + PAD * 2) * dpr);\n    canvas.style.cssText = `position:absolute;left:0;top:0;width:${shot.w + PAD * 2}px;height:${shot.h + PAD * 2}px;will-change:transform;`;\n    const base = DURATION[style] * (shot.h < 90 ? 0.6 : 1);\n    run = {\n      el,\n      style,\n      shot,\n      grains: makeGrains(shot, style),\n      scratch: makeScratch(shot),\n      canvas,\n      dpr,\n      t: 0,\n      dir: 1,\n      duration: options.duration ?? base,\n      last: 0,\n      frame: 0,\n      visibility: el.style.visibility,\n      mask: el.style.getPropertyValue(\"mask-image\"),\n      waiting: [],\n    };\n    runs.set(el, run);\n    topLayer().appendChild(canvas);\n    paint(run);\n    // Drawn pictures take over from the element in the same frame, so nothing blinks.\n    if (shot.sharp) el.style.visibility = \"hidden\";\n  } else if (run.dir === 1 && run.t >= 1) {\n    return Promise.resolve(true);\n  }\n  run.dir = 1;\n  settle(run, false, -1);\n  const r = run;\n  const done = new Promise<boolean>((resolve) => r.waiting.push({ dir: 1, resolve }));\n  start(run);\n  return done;\n}\n\n/** Plays back whatever removal ran on the element, from wherever it is, and shows it again. Resolves true once it's back. */\nexport function undoAway(el: HTMLElement | null | undefined): Promise<boolean> {\n  if (!el) return Promise.resolve(false);\n  if (faded.has(el)) {\n    faded.delete(el);\n    return fade(el, false);\n  }\n  const run = runs.get(el);\n  if (!run) return Promise.resolve(false);\n  run.dir = -1;\n  settle(run, false, 1);\n  const done = new Promise<boolean>((resolve) => run.waiting.push({ dir: -1, resolve }));\n  start(run);\n  return done;\n}\n\n/** True while the element has been removed (or is being removed) and not brought back. */\nexport function isAway(el: HTMLElement | null | undefined) {\n  if (!el) return false;\n  if (faded.has(el)) return true;\n  const run = runs.get(el);\n  return !!run && run.dir === 1;\n}\n"}],"css":{"@keyframes ui-reed-glint":{"from":{"transform":"translate3d(-140%, 0, 0)"},"to":{"transform":"translate3d(260%, 0, 0)"}}},"docs":"Docs and live preview: https://hairlineui.com/ui/reeded-reveal. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}