{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "paint-reveal",
  "type": "registry:ui",
  "title": "Paint Reveal",
  "description": "Two pictures in one frame. The pointer paints the second one in with a soft brush, and the stroke closes back behind it.",
  "author": "KeyframeUI <https://keyframeui.com>",
  "categories": [
    "image",
    "hover",
    "canvas"
  ],
  "docs": "Live preview, examples and props: https://keyframeui.com/components/paint-reveal",
  "dependencies": [
    "clsx",
    "tailwind-merge"
  ],
  "registryDependencies": [
    "utils"
  ],
  "files": [
    {
      "path": "components/ui/paint-reveal.tsx",
      "type": "registry:ui",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/**\n * Keep:\n * - The brush, the stroke and the flood live in `createPainter`, outside React, on one rAF loop\n *   that stops when nothing moves; props reach it through `set()`, never a re-render per frame.\n * - Every dab fills the mask as one shadow-feathered shape, so overlapping dabs never stack into\n *   darker spots and a stroke's edge stays as soft as a resting brush.\n * - The canvas redraws `object-fit: cover` at `objectPosition` by hand, so the paint lines up\n *   pixel for pixel with the `<img>` beneath it.\n * - A flip floods out from the brush or the pressed button, then swaps the base picture; a\n *   resting pointer's brush stays shut until it moves again (`armed`).\n * - Under reduced motion there's no brush or drift: the toggle always shows and a flip crossfades\n *   the whole frame.\n */\nconst TIMING = {\n  /** A stroke closing back, in ms (the `fadeMs` prop). */\n  fadeMs: 600,\n  /** The brush trailing the pointer, as the time constant of its follow, in ms (the `lagMs` prop). */\n  lagMs: 40,\n  /** The brush trailing the drift, as the time constant of its follow, in seconds. */\n  drift: 0.2,\n  /** How fast the drift wanders, as a multiple of its base loop. */\n  driftSpeed: 0.7,\n  /** The brush opening and closing, as a time constant in seconds. */\n  open: 0.09,\n  /** The brush's measured speed catching up, as a time constant in seconds; the swell reads it. */\n  speedFollow: 0.08,\n  /** The brush speed where the swell tops out, in px/s. */\n  swellSpeed: 2600,\n  /** The longest step one frame advances by, in seconds, so a stalled tab doesn't leap. */\n  maxStep: 0.05,\n  /** A flip covering the frame, in ms. */\n  flood: 950,\n  /** A flip with reduced motion, crossfading, in ms. */\n  crossfade: 260,\n  /** After a finger lifts, before the drift comes back, in ms. */\n  resume: 1800,\n  /** After the pointer leaves, before the drift comes back with autoPlay={true}, in ms. */\n  resumeMouse: 700,\n  /** The toggle's thumb sliding across, as Tailwind classes. */\n  thumb: \"duration-300 ease-[cubic-bezier(0.2,0.8,0.2,1)]\",\n  /** A toggle label's color change, as a Tailwind class. */\n  label: \"duration-200\",\n} as const;\n\n/* ─────────────────────────────────────────────────────────\n * PAINT REVEAL STORYBOARD\n *\n *  rest     `src` fills the frame. `revealSrc` waits under it,\n *           lined up pixel for pixel\n *  enter    the brush opens under the pointer: a soft circle of\n *           `revealSrc` grows to `brushSize`\n *  paint    the brush trails the pointer by a few ms and leaves a\n *           stroke behind. Quick strokes paint a little wider.\n *           Where the pointer rests, the picture stays open\n *  fade     each part of the stroke closes back over `fadeMs`,\n *           holding its width at first, then thinning to nothing,\n *           oldest first, so the stroke tapers like a comet\n *  leave    the brush closes where the pointer left the frame\n *  idle     on touch screens (or everywhere, with autoPlay) the\n *           brush drifts over the frame by itself while it's in\n *           view. A finger drag takes over; the drift comes back\n *           when the finger lifts\n *  flip     `revealed`, or the toggle, floods `revealSrc` across\n *           the frame from the brush or the toggle. From then on\n *           the brush paints `src` back. Flipping again mid-flood\n *           pulls the flood back in\n *  reduced  no brush or drift: the toggle crossfades the pictures\n * ───────────────────────────────────────────────────────── */\n\nconst PAINT = {\n  spacing: 0.2, // dab spacing along a stroke, as a fraction of the brush radius\n  maxDpr: 2,\n  maskScale: 0.5, // mask pixels per CSS pixel; the mask is soft, so it's drawn small\n  bake: 600, // with fadeMs={Infinity}, older dabs are flattened into a bitmap past this count\n} as const;\n\ntype Dab = { x: number; y: number; r: number; t: number };\ntype Box = { x0: number; y0: number; x1: number; y1: number };\n\ntype Options = {\n  brushSize: number;\n  softness: number;\n  fadeMs: number;\n  lagMs: number;\n  swell: number;\n  autoPlay: boolean | \"touch\";\n  objectPosition: string;\n  reduced: boolean;\n};\n\nconst clamp01 = (t: number) => Math.min(1, Math.max(0, t));\nconst easeOut = (t: number) => 1 - Math.pow(1 - t, 3);\n\n/** Reads an object-position like \"50% 30%\", \"left\" or \"right top\" as 0–1 fractions. */\nfunction parsePosition(value: string): [number, number] {\n  const words: Record<string, number> = { left: 0, top: 0, center: 0.5, right: 1, bottom: 1 };\n  const read = (part = \"center\") =>\n    part in words ? words[part] : part.endsWith(\"%\") ? clamp01(parseFloat(part) / 100) : 0.5;\n  const [a, b] = value.trim().split(/\\s+/);\n  // \"top\", \"bottom\" and \"top left\" name the vertical position first.\n  if (a === \"top\" || a === \"bottom\" || b === \"left\" || b === \"right\") return [read(b), read(a)];\n  return [read(a), read(b)];\n}\n\n/** A slow loop that wanders over the frame, as 0–1 fractions. */\nfunction driftAt(t: number): [number, number] {\n  return [\n    0.5 + 0.3 * Math.sin(t * 0.83) + 0.1 * Math.sin(t * 2.1 + 1.3),\n    0.5 + 0.24 * Math.sin(t * 1.17 + 0.6) + 0.1 * Math.sin(t * 2.7 + 2.1),\n  ];\n}\n\n/**\n * Everything that changes per frame lives here, outside React: the brush, the\n * stroke, the flood and both canvases. The component hands it the elements in\n * an effect and its options after each render.\n */\nfunction createPainter(els: {\n  root: HTMLDivElement;\n  canvas: HTMLCanvasElement;\n  base: HTMLImageElement;\n  top: HTMLImageElement;\n  revealed: boolean;\n}) {\n  const { root, canvas, base, top } = els;\n  const view = canvas.getContext(\"2d\");\n  // The stroke's shape, drawn at half resolution and feathered, then stretched over the picture.\n  const mask = document.createElement(\"canvas\");\n  const mctx = mask.getContext(\"2d\");\n  let bake: HTMLCanvasElement | null = null;\n  let baked = false;\n\n  let opts: Options = {\n    brushSize: 180,\n    softness: 0.5,\n    fadeMs: TIMING.fadeMs,\n    lagMs: TIMING.lagMs,\n    swell: 0.2,\n    autoPlay: \"touch\",\n    objectPosition: \"50% 50%\",\n    reduced: false,\n  };\n  let anchor: [number, number] = [0.5, 0.5];\n\n  let w = 0;\n  let h = 0;\n  let dpr = 1;\n  let dabs: Dab[] = [];\n\n  // The pointer in client px. `inside` while it's over the frame (or a finger is down);\n  // `armed` once it has moved since the last flip.\n  const pointer = { x: 0, y: 0, touch: false, inside: false, armed: false };\n  // The brush in local px. `open` runs 0–1; `r` is its radius right now.\n  const brush = { x: 0, y: 0, open: 0, r: 0, speed: 0, carry: 0, live: false };\n  // 0: `src` is the base and the brush paints `revealSrc`. 1: the other way round.\n  let side: 0 | 1 = els.revealed ? 1 : 0;\n  let want = side;\n  top.style.opacity = side === 1 ? \"1\" : \"0\";\n  // How far the other picture has flooded the frame, 0–1.\n  const flood = { f: 0, from: 0, to: 0, start: 0, x: 0, y: 0, active: false };\n  const drift = { t: Math.random() * 40, on: false, resumeAt: 0 };\n  let inView = false;\n  let canHover = true;\n\n  let raf = 0;\n  let last = 0;\n  let dirty = true;\n  let drawn: Box | null = null; // the part of the view canvas painted last frame\n\n  const radius = () => opts.brushSize / 2;\n  const painted = () => (side === 0 ? top : base);\n  const ready = (img: HTMLImageElement) => img.complete && img.naturalWidth > 0;\n  const finite = () => Number.isFinite(opts.fadeMs);\n\n  /** Feathering in mask px. shadowBlur is about 2σ, so the edge fades over roughly twice this either side. */\n  const feather = () => Math.max(0.6, opts.softness * radius() * 0.5 * PAINT.maskScale);\n\n  function resize() {\n    w = root.clientWidth;\n    h = root.clientHeight;\n    dpr = Math.min(window.devicePixelRatio || 1, PAINT.maxDpr);\n    canvas.width = Math.max(1, Math.round(w * dpr));\n    canvas.height = Math.max(1, Math.round(h * dpr));\n    const mw = Math.max(1, Math.ceil(w * PAINT.maskScale));\n    const mh = Math.max(1, Math.ceil(h * PAINT.maskScale));\n    if (bake && baked && (bake.width !== mw || bake.height !== mh)) {\n      // Keep paint that's meant to stay, stretched to the new size.\n      const copy = document.createElement(\"canvas\");\n      copy.width = mw;\n      copy.height = mh;\n      copy.getContext(\"2d\")?.drawImage(bake, 0, 0, mw, mh);\n      bake = copy;\n    }\n    mask.width = mw;\n    mask.height = mh;\n    drawn = null;\n    dirty = true;\n    kick();\n  }\n\n  /** The pointer in local px. Divides out any CSS transform on the frame. */\n  function local() {\n    const rect = root.getBoundingClientRect();\n    return {\n      x: ((pointer.x - rect.left) * w) / (rect.width || 1),\n      y: ((pointer.y - rect.top) * h) / (rect.height || 1),\n    };\n  }\n\n  /** Moves the brush without painting the way there. If it's open, it leaves a dab that closes with the stroke. */\n  function jump(x: number, y: number, now: number) {\n    if (brush.r > 1) dabs.push({ x: brush.x, y: brush.y, r: brush.r, t: now });\n    brush.x = x;\n    brush.y = y;\n    brush.open = 0;\n    brush.r = 0;\n    brush.speed = 0;\n    brush.carry = 0;\n  }\n\n  /** Lays dabs every few px along the brush's path this frame, carrying the leftover distance over. */\n  function stamp(x0: number, y0: number, r0: number, now: number) {\n    const dist = Math.hypot(brush.x - x0, brush.y - y0);\n    const step = Math.max(2, radius() * PAINT.spacing);\n    let d = step - brush.carry;\n    for (; d <= dist; d += step) {\n      const k = d / dist;\n      const r = r0 + (brush.r - r0) * k;\n      if (r > 0.5) dabs.push({ x: x0 + (brush.x - x0) * k, y: y0 + (brush.y - y0) * k, r, t: now });\n    }\n    brush.carry = dist - (d - step);\n  }\n\n  function driftAllowed(now: number) {\n    if (opts.reduced || !inView || pointer.inside || now < drift.resumeAt) return false;\n    return opts.autoPlay === true || (opts.autoPlay === \"touch\" && !canHover);\n  }\n\n  /** Advances one frame. Returns whether anything is still moving. */\n  function update(now: number, dt: number) {\n    let busy = false;\n\n    // Where the brush is headed: the pointer, the drift, or nowhere (it closes).\n    let target: { x: number; y: number } | null = null;\n    let follow = opts.lagMs / 1000;\n    if (pointer.inside) {\n      if (pointer.armed && !opts.reduced) target = local();\n      drift.on = false;\n    } else if (driftAllowed(now)) {\n      drift.t += dt * TIMING.driftSpeed;\n      const [fx, fy] = driftAt(drift.t);\n      target = { x: fx * w, y: fy * h };\n      if (!drift.on) jump(target.x, target.y, now);\n      drift.on = true;\n      follow = TIMING.drift;\n      busy = true;\n    } else {\n      drift.on = false;\n    }\n    brush.live = target !== null;\n\n    const x0 = brush.x;\n    const y0 = brush.y;\n    const r0 = brush.r;\n    let speed = 0;\n    if (target) {\n      const k = 1 - Math.exp(-dt / follow);\n      brush.x += (target.x - brush.x) * k;\n      brush.y += (target.y - brush.y) * k;\n      speed = Math.hypot(brush.x - x0, brush.y - y0) / Math.max(dt, 1e-3);\n      if (Math.hypot(target.x - brush.x, target.y - brush.y) > 0.25) busy = true;\n    }\n    brush.speed += (speed - brush.speed) * (1 - Math.exp(-dt / TIMING.speedFollow));\n    if (brush.speed < 1) brush.speed = 0;\n    else busy = true;\n\n    const openTo = brush.live ? 1 : 0;\n    brush.open += (openTo - brush.open) * (1 - Math.exp(-dt / TIMING.open));\n    if (Math.abs(openTo - brush.open) < 0.002) brush.open = openTo;\n    else busy = true;\n    brush.r = radius() * brush.open * (1 + opts.swell * clamp01(brush.speed / TIMING.swellSpeed));\n\n    if (brush.x !== x0 || brush.y !== y0) stamp(x0, y0, r0, now);\n    if (brush.x !== x0 || brush.y !== y0 || brush.r !== r0) dirty = true;\n\n    // Drop the parts of the stroke that have closed.\n    if (finite()) {\n      const fade = Math.max(1, opts.fadeMs);\n      let gone = 0;\n      while (gone < dabs.length && now - dabs[gone].t >= fade) gone++;\n      if (gone) dabs = dabs.slice(gone);\n      if (gone || dabs.length) dirty = true;\n      if (dabs.length) busy = true;\n    } else if (dabs.length > PAINT.bake) {\n      flatten(dabs.splice(0, dabs.length - 40));\n    }\n\n    // Flood toward the side that's wanted, or back out of it.\n    if (want !== side || flood.f > 0) {\n      const to = want !== side ? 1 : 0;\n      if (to !== flood.to || !flood.active) {\n        flood.from = flood.f;\n        flood.to = to;\n        flood.start = now;\n        flood.active = true;\n      }\n      const span = (opts.reduced ? TIMING.crossfade : TIMING.flood) * Math.abs(flood.to - flood.from);\n      const p = span > 0 ? clamp01((now - flood.start) / span) : 1;\n      flood.f = flood.from + (flood.to - flood.from) * easeOut(p);\n      dirty = true;\n      if (p < 1) busy = true;\n      else {\n        flood.active = false;\n        flood.f = flood.to;\n        if (flood.to === 1) swap();\n      }\n    }\n\n    return busy;\n  }\n\n  /** The flood covers the frame: the other picture becomes the base and the brush starts over. */\n  function swap() {\n    side = side === 0 ? 1 : 0;\n    top.style.opacity = side === 1 ? \"1\" : \"0\";\n    flood.f = flood.from = flood.to = 0;\n    dabs = [];\n    clearBake();\n    brush.open = brush.r = brush.carry = 0;\n    // A brush resting where it was would show the old picture again; it waits for the pointer to move.\n    pointer.armed = false;\n    dirty = true;\n  }\n\n  function clearBake() {\n    baked = false;\n    bake?.getContext(\"2d\")?.clearRect(0, 0, bake.width, bake.height);\n  }\n\n  function flatten(list: Dab[]) {\n    bake ??= document.createElement(\"canvas\");\n    if (bake.width !== mask.width || bake.height !== mask.height) {\n      bake.width = mask.width;\n      bake.height = mask.height;\n    }\n    const ctx = bake.getContext(\"2d\");\n    if (ctx && fill(ctx, (add) => list.forEach((d) => add(d.x, d.y, d.r)))) baked = true;\n  }\n\n  /**\n   * Fills circles (local px) into a mask as one shape, feathered by its\n   * shadow. One fill means overlapping dabs never stack into darker spots,\n   * so a stroke's edge is exactly as soft as a resting brush. Returns the\n   * bounds it touched, in local px.\n   */\n  function fill(ctx: CanvasRenderingContext2D, each: (add: (x: number, y: number, r: number) => void) => void) {\n    const s = PAINT.maskScale;\n    // The shape is drawn off the canvas and only its shadow lands on it.\n    const away = (ctx.canvas.width + ctx.canvas.height) * 2;\n    const box: Box = { x0: Infinity, y0: Infinity, x1: -Infinity, y1: -Infinity };\n    ctx.save();\n    ctx.setTransform(1, 0, 0, 1, 0, 0);\n    ctx.globalCompositeOperation = \"source-over\";\n    ctx.shadowColor = \"#000\";\n    ctx.shadowBlur = feather();\n    ctx.shadowOffsetX = away;\n    ctx.beginPath();\n    each((x, y, r) => {\n      if (r < 0.25) return;\n      ctx.moveTo((x + r) * s - away, y * s);\n      ctx.arc(x * s - away, y * s, r * s, 0, Math.PI * 2);\n      box.x0 = Math.min(box.x0, x - r);\n      box.y0 = Math.min(box.y0, y - r);\n      box.x1 = Math.max(box.x1, x + r);\n      box.y1 = Math.max(box.y1, y + r);\n    });\n    const any = box.x1 > box.x0;\n    if (any) ctx.fill();\n    ctx.restore();\n    if (!any) return null;\n    const pad = (feather() * 1.6) / s + 2;\n    return { x0: box.x0 - pad, y0: box.y0 - pad, x1: box.x1 + pad, y1: box.y1 + pad };\n  }\n\n  function shape(now: number) {\n    if (!mctx) return null;\n    mctx.setTransform(1, 0, 0, 1, 0, 0);\n    mctx.clearRect(0, 0, mask.width, mask.height);\n    const fade = Math.max(1, opts.fadeMs);\n    let box = fill(mctx, (add) => {\n      for (const d of dabs) {\n        // Holds its width at first, then closes quickly: the stroke keeps its body and thins toward the tail.\n        const k = finite() ? clamp01((now - d.t) / fade) : 0;\n        add(d.x, d.y, d.r * (1 - k * k * (0.35 + 0.65 * k)));\n      }\n      add(brush.x, brush.y, brush.r);\n      if (flood.f > 0 && !opts.reduced) {\n        const far = Math.max(\n          Math.hypot(flood.x, flood.y),\n          Math.hypot(w - flood.x, flood.y),\n          Math.hypot(flood.x, h - flood.y),\n          Math.hypot(w - flood.x, h - flood.y),\n        );\n        add(flood.x, flood.y, flood.f * (far + (feather() * 2) / PAINT.maskScale));\n      }\n    });\n    if (baked && bake) {\n      mctx.drawImage(bake, 0, 0);\n      box = { x0: 0, y0: 0, x1: w, y1: h };\n    }\n    return box;\n  }\n\n  function render(now: number) {\n    if (!view) return;\n    dirty = false;\n    view.setTransform(1, 0, 0, 1, 0, 0);\n    view.globalCompositeOperation = \"source-over\";\n    view.globalAlpha = 1;\n    if (drawn) view.clearRect(drawn.x0, drawn.y0, drawn.x1 - drawn.x0, drawn.y1 - drawn.y0);\n    drawn = null;\n\n    const img = painted();\n    if (!ready(img) || !w || !h) return;\n    const fading = opts.reduced && flood.f > 0;\n    const box = fading ? { x0: 0, y0: 0, x1: w, y1: h } : shape(now);\n    if (!box) return;\n\n    // Only the part with paint in it is touched, in device px.\n    const x0 = Math.max(0, Math.floor(box.x0 * dpr));\n    const y0 = Math.max(0, Math.floor(box.y0 * dpr));\n    const x1 = Math.min(canvas.width, Math.ceil(box.x1 * dpr));\n    const y1 = Math.min(canvas.height, Math.ceil(box.y1 * dpr));\n    if (x1 <= x0 || y1 <= y0) return;\n    drawn = { x0, y0, x1, y1 };\n\n    view.save();\n    view.beginPath();\n    view.rect(x0, y0, x1 - x0, y1 - y0);\n    view.clip();\n    if (fading) {\n      view.globalAlpha = flood.f;\n      view.fillRect(x0, y0, x1 - x0, y1 - y0);\n      view.globalAlpha = 1;\n    } else {\n      view.imageSmoothingEnabled = true;\n      const k = dpr / PAINT.maskScale;\n      view.drawImage(mask, 0, 0, mask.width * k, mask.height * k);\n    }\n    // Keep the picture only where the mask is.\n    view.globalCompositeOperation = \"source-in\";\n    view.imageSmoothingQuality = \"high\";\n    const iw = img.naturalWidth;\n    const ih = img.naturalHeight;\n    const scale = Math.max(canvas.width / iw, canvas.height / ih);\n    // object-fit: cover, at objectPosition.\n    view.drawImage(\n      img,\n      (canvas.width - iw * scale) * anchor[0],\n      (canvas.height - ih * scale) * anchor[1],\n      iw * scale,\n      ih * scale,\n    );\n    view.restore();\n  }\n\n  function frame(now: number) {\n    raf = 0;\n    const dt = last ? Math.min(TIMING.maxStep, (now - last) / 1000) : 1 / 60;\n    last = now;\n    const busy = update(now, dt);\n    if (dirty) render(now);\n    if (busy) raf = requestAnimationFrame(frame);\n    else last = 0;\n  }\n\n  function kick() {\n    if (!raf) raf = requestAnimationFrame(frame);\n  }\n\n  // ── Input ──\n\n  function enter(e: PointerEvent) {\n    pointer.x = e.clientX;\n    pointer.y = e.clientY;\n    if (!pointer.inside || !pointer.armed) {\n      const p = local();\n      jump(p.x, p.y, performance.now());\n    }\n    pointer.inside = true;\n    pointer.armed = true;\n    kick();\n  }\n\n  function onMove(e: PointerEvent) {\n    // A finger paints only while it's down; a mouse or pen paints whenever it's over the frame.\n    if (e.pointerType === \"touch\" ? !pointer.touch : false) return;\n    enter(e);\n  }\n\n  function onDown(e: PointerEvent) {\n    if (e.pointerType !== \"touch\") return;\n    if (e.target instanceof Element && e.target.closest(\"[data-paint-reveal-toggle]\")) return;\n    pointer.touch = true;\n    enter(e);\n  }\n\n  function onUp(e: PointerEvent) {\n    if (e.pointerType !== \"touch\" || !pointer.touch) return;\n    pointer.touch = false;\n    pointer.inside = false;\n    drift.resumeAt = performance.now() + TIMING.resume;\n    kick();\n  }\n\n  function onLeave(e: PointerEvent) {\n    if (e.pointerType === \"touch\") return;\n    pointer.inside = false;\n    drift.resumeAt = performance.now() + TIMING.resumeMouse;\n    kick();\n  }\n\n  function onScroll() {\n    // The page moved under a resting pointer.\n    if (pointer.inside) kick();\n  }\n\n  root.addEventListener(\"pointermove\", onMove);\n  root.addEventListener(\"pointerdown\", onDown);\n  root.addEventListener(\"pointerup\", onUp);\n  root.addEventListener(\"pointercancel\", onUp);\n  root.addEventListener(\"pointerleave\", onLeave);\n  window.addEventListener(\"scroll\", onScroll, { capture: true, passive: true });\n\n  const hover = window.matchMedia(\"(hover: hover) and (pointer: fine)\");\n  canHover = hover.matches;\n  const onHover = () => {\n    canHover = hover.matches;\n    kick();\n  };\n  hover.addEventListener(\"change\", onHover);\n\n  const sized = new ResizeObserver(resize);\n  sized.observe(root);\n  const seen = new IntersectionObserver(([entry]) => {\n    inView = entry.isIntersecting;\n    kick();\n  });\n  seen.observe(root);\n\n  const onLoad = (e: Event) => {\n    // Decode now, so the first stroke doesn't stall on it.\n    (e.target as HTMLImageElement).decode?.().catch(() => {});\n    dirty = true;\n    kick();\n  };\n  base.addEventListener(\"load\", onLoad);\n  top.addEventListener(\"load\", onLoad);\n\n  return {\n    set(next: Options) {\n      if (finite() !== Number.isFinite(next.fadeMs) && baked) clearBake();\n      opts = next;\n      anchor = parsePosition(next.objectPosition);\n      dirty = true;\n      kick();\n    },\n    /** Floods the frame with `revealSrc` (1) or `src` (0), from a point in local px, or the brush. */\n    flip(to: 0 | 1, from?: { x: number; y: number }) {\n      if (to === want) return;\n      if (!flood.active && flood.f === 0) {\n        const origin = from ?? (brush.open > 0.2 ? brush : { x: w / 2, y: h / 2 });\n        flood.x = origin.x;\n        flood.y = origin.y;\n      }\n      want = to;\n      kick();\n    },\n    destroy() {\n      cancelAnimationFrame(raf);\n      root.removeEventListener(\"pointermove\", onMove);\n      root.removeEventListener(\"pointerdown\", onDown);\n      root.removeEventListener(\"pointerup\", onUp);\n      root.removeEventListener(\"pointercancel\", onUp);\n      root.removeEventListener(\"pointerleave\", onLeave);\n      window.removeEventListener(\"scroll\", onScroll, { capture: true });\n      hover.removeEventListener(\"change\", onHover);\n      base.removeEventListener(\"load\", onLoad);\n      top.removeEventListener(\"load\", onLoad);\n      sized.disconnect();\n      seen.disconnect();\n    },\n  };\n}\n\ntype Painter = ReturnType<typeof createPainter>;\n\nconst REDUCED = \"(prefers-reduced-motion: reduce)\";\nconst subscribeReduced = (onChange: () => void) => {\n  const query = window.matchMedia(REDUCED);\n  query.addEventListener(\"change\", onChange);\n  return () => query.removeEventListener(\"change\", onChange);\n};\n\n/** Reduced motion, read so the server and the first client render agree. */\nfunction useReduced() {\n  return React.useSyncExternalStore(\n    subscribeReduced,\n    () => window.matchMedia(REDUCED).matches,\n    () => false,\n  );\n}\n\n/* ── PaintReveal ────────────────────────────────────────── */\n\nexport interface PaintRevealProps extends React.HTMLAttributes<HTMLDivElement> {\n  /** The picture shown at rest. */\n  src: string;\n  /** Alt text for `src`. */\n  alt: string;\n  /** The picture the brush paints in. Give it the same size and framing as `src` so the two line up. */\n  revealSrc: string;\n  /** Alt text for `revealSrc`. Leave it empty when it only restyles `src`. */\n  revealAlt?: string;\n  /** Responsive candidates for `src`, as in `<img srcSet>`. */\n  srcSet?: string;\n  /** Responsive candidates for `revealSrc`. Offer the same widths as `srcSet`. */\n  revealSrcSet?: string;\n  /** How wide the frame is drawn, as in `<img sizes>`, for picking from the candidates. */\n  sizes?: string;\n  /** `\"lazy\"` waits to fetch both pictures until the frame nears the screen. */\n  loading?: \"eager\" | \"lazy\";\n  /** Diameter of the brush, in px. */\n  brushSize?: number;\n  /** Edge of the brush, from 0 (crisp) to 1 (very soft). */\n  softness?: number;\n  /** How long a stroke takes to close back, in ms. `0` leaves no trail, `Infinity` keeps the paint until the next flip. */\n  fadeMs?: number;\n  /** How far the brush trails the pointer, as the time constant of its follow, in ms. */\n  lagMs?: number;\n  /** How much wider a quick stroke paints, as a share of `brushSize`. `0` keeps every stroke the same width. */\n  swell?: number;\n  /** Let the brush drift by itself while the frame is in view: `\"touch\"` on touch screens only, `true` everywhere, `false` never. */\n  autoPlay?: boolean | \"touch\";\n  /** Floods `revealSrc` over the whole frame. Leave unset to let the toggle manage it. */\n  revealed?: boolean;\n  /** Whether `revealSrc` starts out covering the frame. */\n  defaultRevealed?: boolean;\n  /** Called when the toggle flips the pictures. */\n  onRevealedChange?: (revealed: boolean) => void;\n  /** Show a two-way switch in the bottom-right corner. It's always shown with reduced motion, where it crossfades. */\n  toggle?: boolean;\n  /** The switch's labels: `src` first, then `revealSrc`. */\n  labels?: [string, string];\n  /** Classes for the switch, e.g. to move it to another corner. */\n  toggleClassName?: string;\n  /** Where both pictures are anchored when they're cropped, like CSS `object-position`. */\n  objectPosition?: string;\n}\n\n/**\n * Two pictures in one frame. Moving the pointer paints the second one in with\n * a soft brush, and the stroke closes back behind it.\n */\nexport function PaintReveal({\n  src,\n  alt,\n  revealSrc,\n  revealAlt = \"\",\n  srcSet,\n  revealSrcSet,\n  sizes,\n  loading,\n  brushSize = 180,\n  softness = 0.5,\n  fadeMs = TIMING.fadeMs,\n  lagMs = TIMING.lagMs,\n  swell = 0.2,\n  autoPlay = \"touch\",\n  revealed,\n  defaultRevealed = false,\n  onRevealedChange,\n  toggle = false,\n  labels = [\"Before\", \"After\"],\n  toggleClassName,\n  objectPosition = \"50% 50%\",\n  className,\n  children,\n  ...props\n}: PaintRevealProps) {\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const canvasRef = React.useRef<HTMLCanvasElement>(null);\n  const baseRef = React.useRef<HTMLImageElement>(null);\n  const topRef = React.useRef<HTMLImageElement>(null);\n  const painterRef = React.useRef<Painter | null>(null);\n  const originRef = React.useRef<{ x: number; y: number } | undefined>(undefined);\n\n  const [own, setOwn] = React.useState(defaultRevealed);\n  const shown = revealed ?? own;\n  // The markup starts on this side; the painter draws every flip after it.\n  const [initial] = React.useState(shown);\n  const shownRef = React.useRef(shown);\n  const reduced = useReduced();\n\n  const options: Options = {\n    brushSize,\n    softness: clamp01(softness),\n    fadeMs,\n    lagMs,\n    swell,\n    autoPlay,\n    objectPosition,\n    reduced,\n  };\n  const optionsRef = React.useRef(options);\n  React.useLayoutEffect(() => {\n    optionsRef.current = options;\n    painterRef.current?.set(options);\n  });\n\n  React.useEffect(() => {\n    const root = rootRef.current;\n    const canvas = canvasRef.current;\n    const base = baseRef.current;\n    const top = topRef.current;\n    if (!root || !canvas || !base || !top) return;\n    const painter = createPainter({ root, canvas, base, top, revealed: shownRef.current });\n    painter.set(optionsRef.current);\n    painterRef.current = painter;\n    return () => {\n      painter.destroy();\n      painterRef.current = null;\n    };\n  }, []);\n\n  React.useEffect(() => {\n    shownRef.current = shown;\n    painterRef.current?.flip(shown ? 1 : 0, originRef.current);\n    originRef.current = undefined;\n  }, [shown]);\n\n  const choose = (next: boolean, event: React.MouseEvent<HTMLButtonElement>) => {\n    if (next === shown) return;\n    const root = rootRef.current;\n    if (root) {\n      // Flood from the button that was pressed.\n      const frame = root.getBoundingClientRect();\n      const button = event.currentTarget.getBoundingClientRect();\n      originRef.current = {\n        x: ((button.left + button.width / 2 - frame.left) * root.clientWidth) / (frame.width || 1),\n        y: ((button.top + button.height / 2 - frame.top) * root.clientHeight) / (frame.height || 1),\n      };\n    }\n    if (revealed === undefined) setOwn(next);\n    onRevealedChange?.(next);\n  };\n\n  return (\n    <div ref={rootRef} className={cn(\"relative isolate touch-pan-y overflow-hidden\", className)} {...props}>\n      {/* eslint-disable-next-line @next/next/no-img-element -- a remote picture in an installable component */}\n      <img\n        ref={baseRef}\n        src={src}\n        srcSet={srcSet}\n        sizes={sizes}\n        alt={alt}\n        loading={loading}\n        decoding=\"async\"\n        draggable={false}\n        className=\"pointer-events-none absolute inset-0 -z-10 size-full object-cover\"\n        style={{ objectPosition }}\n      />\n      {/* eslint-disable-next-line @next/next/no-img-element -- a remote picture in an installable component */}\n      <img\n        ref={topRef}\n        src={revealSrc}\n        srcSet={revealSrcSet}\n        sizes={sizes}\n        alt={revealAlt}\n        loading={loading}\n        decoding=\"async\"\n        draggable={false}\n        className={cn(\n          \"pointer-events-none absolute inset-0 -z-10 size-full object-cover\",\n          initial ? \"opacity-100\" : \"opacity-0\",\n        )}\n        style={{ objectPosition }}\n      />\n      <canvas ref={canvasRef} aria-hidden className=\"pointer-events-none absolute inset-0 -z-10 size-full\" />\n      {children}\n      {(toggle || reduced) && (\n        <div\n          data-paint-reveal-toggle=\"\"\n          role=\"group\"\n          aria-label=\"Compare pictures\"\n          className={cn(\n            \"absolute right-3 bottom-3 z-10 grid grid-cols-2 rounded-full bg-black/45 p-1 text-xs font-medium text-white ring-1 ring-white/15 backdrop-blur-md\",\n            toggleClassName,\n          )}\n        >\n          <span\n            aria-hidden\n            className={cn(\n              `absolute inset-y-1 left-1 w-[calc(50%-0.25rem)] rounded-full bg-white shadow-sm transition-transform ${TIMING.thumb} motion-reduce:transition-none`,\n              shown && \"translate-x-full\",\n            )}\n          />\n          {labels.map((label, i) => {\n            const active = shown === (i === 1);\n            return (\n              <button\n                key={i}\n                type=\"button\"\n                aria-pressed={active}\n                onClick={(event) => choose(i === 1, event)}\n                className={cn(\n                  `relative rounded-full px-3 py-1.5 whitespace-nowrap transition-colors ${TIMING.label} outline-none focus-visible:ring-2 focus-visible:ring-white/70`,\n                  active ? \"text-zinc-950\" : \"text-white/80 hover:text-white\",\n                )}\n              >\n                {label}\n              </button>\n            );\n          })}\n        </div>\n      )}\n    </div>\n  );\n}\n"
    }
  ]
}