{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"qr-reveal","type":"registry:component","title":"QR reveal","description":"The code leaves the button as a cloud of ink dust that billows up and settles, grain by grain, into a QR you can scan.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/qr-reveal.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\nimport { AnimatePresence, animate, motion, useMotionValue } from \"motion/react\";\nimport { usePreviewPlay } from \"@/lib/preview-play\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\n// After bakai's QR code reveal (https://x.com/samakov0): the code leaves\n// the button as a cloud of ink dust that billows up and settles, grain by\n// grain, into its squares. Hiding blows it back in.\n\n// A real, scannable code for lab.xevrion.dev (version 2, 25 by 25, medium\n// error correction), worked out once and kept here so the piece needs no\n// QR library.\nconst CODE = [\n  \"1111111001001100101111111\",\n  \"1000001000001111101000001\",\n  \"1011101011000011001011101\",\n  \"1011101011010110001011101\",\n  \"1011101011101100101011101\",\n  \"1000001010010111001000001\",\n  \"1111111010101010101111111\",\n  \"0000000011010000000000000\",\n  \"1011111000001101101111100\",\n  \"0011110011010100100100010\",\n  \"0011101110001111001001011\",\n  \"1011100110101000111110001\",\n  \"1110101100011111111010111\",\n  \"1011110001100000100101010\",\n  \"1010101101011011101111011\",\n  \"1001000001010001100110001\",\n  \"1010111001110111111110100\",\n  \"0000000011001001100011000\",\n  \"1111111001000010101010111\",\n  \"1000001011001010100011010\",\n  \"1011101010001111111110111\",\n  \"1011101010000011001011111\",\n  \"1011101011111111100001101\",\n  \"1000001000010000110111001\",\n  \"1111111010111000000111111\",\n];\n\n// Layout, in CSS px. The code sits above the button and every square sets\n// off from the button's top edge.\nconst W = 300;\nconst H = 336;\nconst SIZE = 240;\nconst CELL = SIZE / CODE.length;\nconst LEFT = (W - SIZE) / 2;\nconst TOP = 12;\nconst ORIGIN = { x: W / 2, y: 292 };\n\n// One flight takes FLY of the timeline. Squares set off in order of their\n// distance from the button, so the code fills in as a wave rising out of\n// it, and each grain leaves a little after or before its square's turn.\nconst FLY = 0.46;\nconst JITTER = 0.1;\nconst SPREAD = 1 - FLY - JITTER;\n// Grains of ink per square: enough to read as a cloud, few enough to stay\n// smooth on a phone (about 2,500 in all).\nconst GRAINS = 8;\n// Loose dust that rides along in the cloud and never lands.\nconst STRAYS = 420;\nconst REVEAL = 1.45;\nconst HIDE = 0.95;\n\n// Seeded, so the cloud is the same every time and on every screen.\nfunction random(seed: number) {\n  return () => {\n    seed |= 0;\n    seed = (seed + 0x6d2b79f5) | 0;\n    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);\n    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\n\ntype Field = {\n  // Squares: where they land and when their turn comes.\n  squares: { x: number; y: number; at: number }[];\n  // Grains, flattened: start delay, a bend point in the cloud, the spot\n  // they land on, and their size. Strays fade out instead of landing.\n  at: Float32Array;\n  bx: Float32Array;\n  by: Float32Array;\n  tx: Float32Array;\n  ty: Float32Array;\n  size: Float32Array;\n  stray: Uint8Array;\n};\n\nfunction buildField(): Field {\n  const rand = random(7);\n  const gauss = () => (rand() + rand() + rand() - 1.5) / 1.5;\n  const cells: { x: number; y: number; d: number }[] = [];\n  CODE.forEach((row, r) =>\n    [...row].forEach((bit, c) => {\n      if (bit !== \"1\") return;\n      const x = LEFT + c * CELL;\n      const y = TOP + r * CELL;\n      cells.push({ x, y, d: Math.hypot(x + CELL / 2 - ORIGIN.x, y + CELL / 2 - ORIGIN.y) });\n    }),\n  );\n  const near = Math.min(...cells.map((c) => c.d));\n  const far = Math.max(...cells.map((c) => c.d));\n  const squares = cells.map((c) => ({\n    x: c.x,\n    y: c.y,\n    at: ((c.d - near) / (far - near)) * SPREAD,\n  }));\n\n  const count = squares.length * GRAINS + STRAYS;\n  const field: Field = {\n    squares,\n    at: new Float32Array(count),\n    bx: new Float32Array(count),\n    by: new Float32Array(count),\n    tx: new Float32Array(count),\n    ty: new Float32Array(count),\n    size: new Float32Array(count),\n    stray: new Uint8Array(count),\n  };\n  let i = 0;\n  const add = (tx: number, ty: number, at: number, stray: boolean) => {\n    field.tx[i] = tx;\n    field.ty[i] = ty;\n    field.at[i] = Math.max(0, at + (rand() - 0.5) * JITTER);\n    // The bend sits partway up and wide of the straight line, so grains\n    // billow out into a dome before they gather.\n    field.bx[i] = ORIGIN.x + (tx - ORIGIN.x) * 0.7 + gauss() * 46;\n    field.by[i] = ORIGIN.y + (ty - ORIGIN.y) * 0.55 - rand() * 46;\n    field.size[i] = stray ? 0.6 + rand() * 0.8 : 0.8 + rand() * 1.1;\n    field.stray[i] = stray ? 1 : 0;\n    i += 1;\n  };\n  for (const sq of squares) {\n    for (let g = 0; g < GRAINS; g++) {\n      add(sq.x + rand() * CELL, sq.y + rand() * CELL, sq.at, false);\n    }\n  }\n  for (let k = 0; k < STRAYS; k++) {\n    // Strays aim anywhere over the code and a little past its edges.\n    const tx = LEFT - 20 + rand() * (SIZE + 40);\n    const ty = TOP - 16 + rand() * (SIZE + 24);\n    const d = Math.hypot(tx - ORIGIN.x, ty - ORIGIN.y);\n    add(tx, ty, ((d - near) / (far - near)) * SPREAD, true);\n  }\n  return field;\n}\n\nlet field: Field | null = null;\n\nconst smooth = (a: number, b: number, t: number) => {\n  const k = Math.min(1, Math.max(0, (t - a) / (b - a)));\n  return k * k * (3 - 2 * k);\n};\n// Leaves the button quickly, slows as it gathers into place.\nconst glide = (t: number) => 1 - (1 - t) ** 2.4;\n\nfunction draw(canvas: HTMLCanvasElement, s: number, plain: boolean) {\n  const ctx = canvas.getContext(\"2d\");\n  if (!ctx) return;\n  const dpr = canvas.width / W;\n  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n  ctx.clearRect(0, 0, W, H);\n  const ink = getComputedStyle(canvas).color;\n\n  // A viewfinder's corners mark where the code will be, so the empty\n  // space reads as waiting rather than blank. They give way as it fills.\n  const frame = 0.22 * (1 - smooth(0, 0.35, s));\n  if (frame > 0.01) {\n    const pad = 6;\n    const arm = 24;\n    const x0 = LEFT - pad;\n    const y0 = TOP - pad;\n    const x1 = LEFT + SIZE + pad;\n    const y1 = TOP + SIZE + pad;\n    ctx.globalAlpha = frame;\n    ctx.strokeStyle = ink;\n    ctx.lineWidth = 2;\n    ctx.lineCap = \"round\";\n    ctx.lineJoin = \"round\";\n    ctx.beginPath();\n    ctx.moveTo(x0, y0 + arm);\n    ctx.arcTo(x0, y0, x0 + arm, y0, 8);\n    ctx.lineTo(x0 + arm, y0);\n    ctx.moveTo(x1 - arm, y0);\n    ctx.arcTo(x1, y0, x1, y0 + arm, 8);\n    ctx.lineTo(x1, y0 + arm);\n    ctx.moveTo(x1, y1 - arm);\n    ctx.arcTo(x1, y1, x1 - arm, y1, 8);\n    ctx.lineTo(x1 - arm, y1);\n    ctx.moveTo(x0 + arm, y1);\n    ctx.arcTo(x0, y1, x0, y1 - arm, 8);\n    ctx.lineTo(x0, y1 - arm);\n    ctx.stroke();\n  }\n  if (s <= 0) {\n    ctx.globalAlpha = 1;\n    return;\n  }\n  ctx.fillStyle = ink;\n  field ??= buildField();\n  const f = field;\n\n  if (!plain) {\n    for (let i = 0; i < f.at.length; i++) {\n      const local = (s - f.at[i]) / FLY;\n      if (local <= 0) continue;\n      const stray = f.stray[i] === 1;\n      // Landed grains hand over to the solid square; strays just fade.\n      if (local >= 1 && !stray) continue;\n      const e = glide(Math.min(1, local));\n      const u = 1 - e;\n      const x = u * u * ORIGIN.x + 2 * u * e * f.bx[i] + e * e * f.tx[i];\n      const y = u * u * ORIGIN.y + 2 * u * e * f.by[i] + e * e * f.ty[i];\n      const alpha = stray\n        ? Math.min(1, local * 4) * (1 - smooth(0.45, 1, local)) * 0.7\n        : Math.min(1, local * 4) * (1 - smooth(0.82, 1, local));\n      if (alpha <= 0.01) continue;\n      ctx.globalAlpha = alpha;\n      const r = f.size[i];\n      ctx.fillRect(x - r / 2, y - r / 2, r, r);\n    }\n  }\n\n  // The squares solidify as their grains arrive. A hair over a cell, so\n  // neighbours meet without a seam.\n  for (const sq of f.squares) {\n    const local = (s - sq.at) / FLY;\n    const alpha = plain ? Math.min(1, Math.max(0, local)) : smooth(0.72, 1.05, local);\n    if (alpha <= 0) continue;\n    ctx.globalAlpha = alpha;\n    ctx.fillRect(sq.x, sq.y, CELL + 0.4, CELL + 0.4);\n  }\n  ctx.globalAlpha = 1;\n}\n\nexport function QrReveal({\n  label = \"lab.xevrion.dev\",\n  className,\n}: {\n  // What the code points to, shown under it once it lands.\n  label?: string;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const play = usePreviewPlay();\n  const [own, setOwn] = useState(false);\n  const [show, setShow] = useState(false);\n  const shown = play ? show : own;\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n  // 0 is every square inside the button, 1 is the code complete.\n  const timeline = useMotionValue(0);\n  const [landed, setLanded] = useState(false);\n\n  // Sharp on any screen, and redrawn as the timeline moves.\n  useEffect(() => {\n    const canvas = canvasRef.current;\n    if (!canvas) return;\n    const dpr = Math.min(window.devicePixelRatio || 1, 3);\n    canvas.width = W * dpr;\n    canvas.height = H * dpr;\n    const paint = () => draw(canvas, timeline.get(), reduceMotion);\n    paint();\n    const stop = timeline.on(\"change\", paint);\n    // The ink follows the theme, so a theme switch repaints it.\n    const media = matchMedia(\"(prefers-color-scheme: dark)\");\n    media.addEventListener(\"change\", paint);\n    const observer = new MutationObserver(paint);\n    observer.observe(document.documentElement, {\n      attributes: true,\n      attributeFilter: [\"data-theme\", \"class\"],\n    });\n    return () => {\n      stop();\n      media.removeEventListener(\"change\", paint);\n      observer.disconnect();\n    };\n  }, [timeline, reduceMotion]);\n\n  useEffect(() => {\n    const from = timeline.get();\n    const to = shown ? 1 : 0;\n    if (from === to) return;\n    // Turning round halfway takes only as long as the way back.\n    const whole = shown ? REVEAL : HIDE;\n    const controls = animate(timeline, to, {\n      duration: whole * Math.abs(to - from),\n      ease: \"linear\",\n      onComplete: () => setLanded(shown),\n    });\n    return () => controls.stop();\n  }, [shown, timeline]);\n\n  // The card's show: reveal, hold, put away.\n  useEffect(() => {\n    if (!play) return;\n    const timers: ReturnType<typeof setTimeout>[] = [];\n    const loop = () => {\n      timers.push(setTimeout(() => setShow(true), 400));\n      timers.push(setTimeout(() => setShow(false), 2600));\n      timers.push(setTimeout(loop, 3600));\n    };\n    loop();\n    return () => {\n      timers.forEach(clearTimeout);\n      setShow(false);\n    };\n  }, [play]);\n\n  return (\n    <div\n      className={cn(\"relative max-w-full\", className)}\n      style={{ width: W, height: H }}\n    >\n      <canvas\n        ref={canvasRef}\n        role=\"img\"\n        aria-label={`QR code for ${label}`}\n        aria-hidden={!shown}\n        className=\"absolute inset-0 size-full text-foreground\"\n      />\n      <AnimatePresence>\n        {shown && landed && (\n          <motion.p\n            className=\"absolute inset-x-0 text-center font-mono text-[12px] text-muted-foreground\"\n            style={{ top: TOP + SIZE + 6 }}\n            initial={{ opacity: 0, y: -2, filter: \"blur(4px)\" }}\n            animate={{ opacity: 1, y: 0, filter: \"blur(0px)\" }}\n            exit={{ opacity: 0, transition: { duration: 0.12 } }}\n            transition={{ duration: 0.25, ease: [0.23, 1, 0.32, 1] }}\n          >\n            {label}\n          </motion.p>\n        )}\n      </AnimatePresence>\n      <button\n        type=\"button\"\n        aria-expanded={shown}\n        onClick={() => {\n          setLanded(false);\n          setOwn((o) => !o);\n        }}\n        className=\"absolute left-1/2 flex h-10 -translate-x-1/2 touch-manipulation items-center gap-2 rounded-full bg-background pr-4 pl-3 text-[14px] font-medium shadow-raised outline-hidden transition-[scale] duration-150 ease-out focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground active:scale-[0.96]\"\n        style={{ top: ORIGIN.y - 8 }}\n      >\n        <svg\n          viewBox=\"0 0 16 16\"\n          className=\"size-4\"\n          fill=\"currentColor\"\n          aria-hidden\n        >\n          <path d=\"M2 2h5v5H2V2Zm1.5 1.5v2h2v-2h-2ZM9 2h5v5H9V2Zm1.5 1.5v2h2v-2h-2ZM2 9h5v5H2V9Zm1.5 1.5v2h2v-2h-2ZM9 9h2v2H9V9Zm3 0h2v2h-2V9Zm-3 3h2v2H9v-2Zm3 0h2v2h-2v-2Z\" />\n        </svg>\n        <span className=\"grid\">\n          {/* Both labels share a cell, so the button keeps its width. */}\n          <span className={cn(\"col-start-1 row-start-1 transition-[opacity] duration-150\", shown && \"opacity-0\")}>\n            Show code\n          </span>\n          <span className={cn(\"col-start-1 row-start-1 transition-[opacity] duration-150\", !shown && \"opacity-0\")}>\n            Hide code\n          </span>\n        </span>\n      </button>\n    </div>\n  );\n}\n\nexport default function QrRevealDemo() {\n  return <QrReveal />;\n}\n"},{"path":"lib/preview-play.ts","type":"registry:lib","target":"lib/preview-play.ts","content":"\"use client\";\n\nimport { createContext, useContext } from \"react\";\n\n// Lets a demo know whether it's showing in an index card, and whether that\n// card is hovered or focused. Demos use it to act themselves out on hover:\n// a star button stars itself, a checkbox scribbles, and so on.\n//\n// null: not in a preview (the component's own page, or real use).\n// false: in a preview, at rest.\n// true: in a preview, being hovered or focused: play the show.\nexport const PreviewPlayContext = createContext<boolean | null>(null);\n\nexport function usePreviewPlay() {\n  return useContext(PreviewPlayContext);\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["cards"],"docs":"From ui lab: https://lab.xevrion.dev/lab/qr-reveal"}