{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"qr-code","type":"registry:component","title":"QR Code","description":"A rounded-dot QR code on canvas that builds itself piece by piece. Dots and finder eyes fly in on curved paths, pop in behind a spreading ring, drop in behind a bar sweeping down, or rise as smoke and condense into place. Hiding plays the build backwards, and a press mid-build turns it around in place.","author":"Saurabh <saurabh10102@gmail.com>","dependencies":["clsx","motion","tailwind-merge","uqr"],"registryDependencies":[],"docs":"QR Code: usage, props and types at https://beui.dev/components/motion/qr-code.md","files":[{"path":"components/motion/qr-code.tsx","type":"registry:component","target":"@components/motion/qr-code.tsx","content":"\"use client\";\n// beui.dev/components/motion/qr-code\n\nimport { useReducedMotion } from \"motion/react\";\nimport { useEffect, useLayoutEffect, useMemo, useRef } from \"react\";\nimport { encode } from \"uqr\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\nexport type QrCodeVariant = \"swarm\" | \"ripple\" | \"scan\" | \"smoke\";\n\nexport const qrCodeMessages = {\n  label: \"QR code for {value}\",\n};\n\nexport type QrCodeMessages = typeof qrCodeMessages;\n\nexport interface QrCodeOrigin {\n  /** Horizontal position as a fraction of the canvas width, 0 is the left edge. */\n  x: number;\n  /** Vertical position as a fraction of the canvas height, 0 is the top edge. */\n  y: number;\n}\n\nexport interface AnimatedQrCodeProps {\n  /** Text or URL the code encodes. */\n  value: string;\n  /** Whether the code is drawn. Turning it on builds the code; turning it off plays the build backwards from wherever it is. */\n  shown: boolean;\n  /** How the code builds: every piece flies in on a curved path, pops in place behind a spreading ring, drops into place behind a bar sweeping down, or rises as smoke and condenses from the bottom row up. Default: \"swarm\" */\n  variant?: QrCodeVariant;\n  /** Side of the square canvas, in px, quiet zone included. Default: 296 */\n  size?: number;\n  /** Where swarm pieces fly from and where the ripple ring starts. Scan and smoke ignore it. Default: bottom centre for swarm, centre for ripple */\n  origin?: QrCodeOrigin;\n  /** Dot colour, any CSS colour. Default: \"#0a0a0a\" */\n  ink?: string;\n  /** Background colour, any CSS colour. Keep it light so cameras can read the code. Default: \"#ffffff\" */\n  paper?: string;\n  /** Called when a build or teardown finishes, with the `shown` value it ended on. */\n  onSettled?: (shown: boolean) => void;\n  /** Translated strings, merged over the English defaults. */\n  labels?: Partial<QrCodeMessages>;\n  /** Classes merged onto the canvas. */\n  className?: string;\n}\n\n/** Empty modules kept around the code on every side. */\nconst QUIET = 2;\n/** Gap between the first and the last piece starting, in ms. */\nconst SPREAD = 600;\n/** One piece's own arrival, in ms. */\nconst PIECE_IN = 500;\nconst TOTAL = SPREAD + PIECE_IN;\n/** Taking the code down runs this much faster than building it. */\nconst EXIT_RATE = 1.6;\n/** Time constant for the clock turning around after a press mid-run, in ms. */\nconst TURN_MS = 90;\n/** Reduced motion keeps only an opacity fade of this length, in ms. */\nconst REDUCED_MS = 200;\n/** Random offset added to each swarm piece's start, in ms, so the order is not mechanical. */\nconst JITTER = 70;\n/** How far a swarm path bows outward, as a share of its length; each piece adds up to BEND_SPREAD more. */\nconst BEND = 0.14;\nconst BEND_SPREAD = 0.12;\n/** Extra length of a piece at top speed on the longest flight, as a share of its size. Width shrinks to keep its area. */\nconst STRETCH = 1.3;\n/** Share of that stretch an eye takes. */\nconst EYE_STRETCH = 0.2;\n/** How far a scan piece drops into place, in modules. */\nconst DROP = 1.6;\n/** Height of the soft trail behind the scan bar, in px. */\nconst SCAN_TRAIL = 28;\n/** Soft puffs in the smoke plume. */\nconst PUFFS = 90;\n/** Life of one puff, in ms. Puffs are released over SMOKE_EMIT so the last fades out as the build ends. */\nconst PUFF_LIFE = 560;\nconst SMOKE_EMIT = SPREAD * 0.9;\n/** Width of the band puffs rise from, as a share of the canvas. */\nconst SMOKE_BAND = 0.75;\n/** A puff's radius at birth and at the end of its life, in modules. */\nconst PUFF_START = 1.4;\nconst PUFF_END = 3.6;\n/** Peak opacity of one puff. Overlap builds the density. Fewer, smaller puffs keep the fill cost near 3ms a frame. */\nconst PUFF_ALPHA = 0.22;\n/** How far a condensing piece drifts up into place, in modules. */\nconst SMOKE_DRIFT = 1;\nconst TAU = Math.PI * 2;\n\n/**\n * One soft puff: a radial falloff tinted with the ink colour, drawn scaled\n * per puff. A sprite is far cheaper than a gradient or a blur per draw, and\n * blur filters would re-render every frame.\n */\nconst puffSprites = new Map<string, HTMLCanvasElement>();\nfunction puffSprite(ink: string) {\n  const cached = puffSprites.get(ink);\n  if (cached) return cached;\n  const s = 96;\n  const sprite = document.createElement(\"canvas\");\n  sprite.width = s;\n  sprite.height = s;\n  const g = sprite.getContext(\"2d\");\n  if (g) {\n    const fall = g.createRadialGradient(s / 2, s / 2, 0, s / 2, s / 2, s / 2);\n    fall.addColorStop(0, \"rgba(0,0,0,1)\");\n    fall.addColorStop(0.45, \"rgba(0,0,0,0.55)\");\n    fall.addColorStop(1, \"rgba(0,0,0,0)\");\n    g.fillStyle = fall;\n    g.fillRect(0, 0, s, s);\n    g.globalCompositeOperation = \"source-in\";\n    g.fillStyle = ink;\n    g.fillRect(0, 0, s, s);\n  }\n  puffSprites.set(ink, sprite);\n  return sprite;\n}\n\n/**\n * Smoke is soft, so it is drawn at half the canvas resolution in CSS px (a\n * quarter of the device pixels on a 2x screen) and scaled up in one draw.\n * The puffs overlap heavily, and filling them at full resolution cost\n * several ms a frame.\n */\nconst SMOKE_RES = 0.5;\nconst smokeLayers = new Map<number, CanvasRenderingContext2D | null>();\nfunction smokeLayer(size: number) {\n  if (!smokeLayers.has(size)) {\n    const layer = document.createElement(\"canvas\");\n    layer.width = Math.ceil(size * SMOKE_RES);\n    layer.height = layer.width;\n    const lctx = layer.getContext(\"2d\");\n    lctx?.scale(SMOKE_RES, SMOKE_RES);\n    smokeLayers.set(size, lctx);\n  }\n  return smokeLayers.get(size) ?? null;\n}\n\nfunction drawSmoke(ctx: CanvasRenderingContext2D, layout: Layout, clock: number, ink: string) {\n  const { size, cell, pieces } = layout;\n  const lctx = smokeLayer(size);\n  if (!lctx) return;\n  const sprite = puffSprite(ink);\n  lctx.clearRect(0, 0, size, size);\n\n  // A soft haze where each condensing piece is gathering.\n  for (const p of pieces) {\n    const t = (clock - pieceStart(p, \"smoke\", size)) / PIECE_IN;\n    if (t <= 0 || t >= 1) continue;\n    const k = settle(t);\n    const half = p.side / 2;\n    const haze = (p.eye ? half * 1.3 : cell * 1.6) * (1.4 - k);\n    lctx.globalAlpha = 0.35 * Math.min(1, t * 4) * (1 - k);\n    lctx.drawImage(sprite, p.x + half - haze, p.y + half - haze + (1 - k) * cell * SMOKE_DRIFT, haze * 2, haze * 2);\n  }\n\n  for (let i = 0; i < PUFFS; i++) {\n    const age = clock - (i / PUFFS) * SMOKE_EMIT;\n    const u = age / PUFF_LIFE;\n    if (u <= 0 || u >= 1) continue;\n    const h1 = hash(i * 3 + 1);\n    const h2 = hash(i * 3 + 2);\n    const h3 = hash(i * 3 + 3);\n    // Rises fast, then slows and spreads as it cools.\n    const rise = size * (0.55 + 0.6 * h2) * (1 - (1 - u) ** 2);\n    const curl = Math.sin(h3 * TAU + u * 4) * cell * 2.4 * u;\n    const x = size / 2 + (h1 - 0.5) * size * SMOKE_BAND + curl;\n    const y = size + cell * 2 - rise;\n    const r = cell * (PUFF_START + (PUFF_END - PUFF_START) * u);\n    lctx.globalAlpha = PUFF_ALPHA * Math.min(1, u * 6) * (1 - u) ** 1.5;\n    lctx.drawImage(sprite, x - r, y - r, r * 2, r * 2);\n  }\n  ctx.globalAlpha = 1;\n  ctx.drawImage(lctx.canvas, 0, 0, size, size);\n}\nconst QUARTER = Math.PI / 2;\n\n/**\n * Each piece moves like a critically damped spring pulled to its cell: it\n * leaves at rest, speeds up, and eases in with no overshoot. An ease-out\n * curve would start at full speed, which reads as a jolt at launch. The\n * curve is scaled to land exactly at t = 1. Local because it has to run per\n * piece on a canvas, where the shared motion tokens cannot.\n */\nconst OMEGA = 7;\nconst SETTLE_END = 1 - (1 + OMEGA) * Math.exp(-OMEGA);\nconst settle = (t: number) => (1 - (1 + OMEGA * t) * Math.exp(-OMEGA * t)) / SETTLE_END;\n/** Speed of `settle` at t, 0 to 1, peaking at t = 1 / OMEGA. */\nconst speedAt = (t: number) => OMEGA * t * Math.exp(1 - OMEGA * t);\nconst DEFAULT_ORIGIN: Record<\"swarm\" | \"ripple\", QrCodeOrigin> = {\n  swarm: { x: 0.5, y: 1 },\n  ripple: { x: 0.5, y: 0.5 },\n};\n\nconst clamp01 = (v: number) => (v < 0 ? 0 : v > 1 ? 1 : v);\n\nfunction hash(n: number) {\n  let t = Math.imul(n ^ 0x9e3779b9, 0x85ebca6b);\n  t ^= t >>> 13;\n  t = Math.imul(t, 0xc2b2ae35);\n  return ((t ^ (t >>> 16)) >>> 0) / 4294967296;\n}\n\n/** One thing that arrives: a data dot, or a whole finder eye. */\ninterface Piece {\n  eye: boolean;\n  /** Top-left corner, in px. */\n  x: number;\n  y: number;\n  /** Side, in px. */\n  side: number;\n  /** Distance of its centre from the origin, 0 to 1. */\n  d: number;\n  /** Small per-piece random value, 0 to 1. */\n  r: number;\n}\n\ninterface Layout {\n  cell: number;\n  dot: number;\n  radius: number;\n  pieces: Piece[];\n  /** Largest origin distance, in px, so the ripple ring meets each piece as it starts. */\n  reach: number;\n  ox: number;\n  oy: number;\n  size: number;\n}\n\nfunction isEye(x: number, y: number, n: number) {\n  return (x < 7 && y < 7) || (x >= n - 7 && y < 7) || (x < 7 && y >= n - 7);\n}\n\nfunction buildLayout(value: string, size: number, origin: QrCodeOrigin): Layout {\n  const { data, size: n } = encode(value || \" \", { ecc: \"M\", border: 0 });\n  const cell = Math.max(2, Math.floor(size / (n + QUIET * 2)));\n  const gap = Math.max(1, Math.round(cell * 0.12));\n  const dot = cell - gap;\n  const start = Math.round((size - n * cell) / 2);\n  const ox = origin.x * size;\n  const oy = origin.y * size;\n\n  const pieces: Piece[] = [];\n  const add = (eye: boolean, x: number, y: number, side: number, seed: number) => {\n    pieces.push({ eye, x, y, side, d: Math.hypot(x + side / 2 - ox, y + side / 2 - oy), r: hash(seed) });\n  };\n  const eyeSide = cell * 7 - gap;\n  const far = start + (n - 7) * cell;\n  add(true, start, start, eyeSide, -1);\n  add(true, far, start, eyeSide, -2);\n  add(true, start, far, eyeSide, -3);\n  data.forEach((row, y) => {\n    row.forEach((dark, x) => {\n      if (dark && !isEye(x, y, n)) add(false, start + x * cell, start + y * cell, dot, y * n + x);\n    });\n  });\n  const reach = Math.max(1, ...pieces.map((p) => p.d));\n  for (const p of pieces) p.d /= reach;\n\n  return { cell, dot, radius: dot * 0.32, pieces, reach, ox, oy, size };\n}\n\n/** A finder eye: a rounded ring and a rounded core, radii concentric. */\nfunction drawEye(ctx: CanvasRenderingContext2D, x: number, y: number, side: number, cell: number, radius: number) {\n  const r = cell * 2;\n  ctx.beginPath();\n  ctx.roundRect(x, y, side, side, r);\n  ctx.roundRect(x + cell, y + cell, side - cell * 2, side - cell * 2, r - cell);\n  ctx.fill(\"evenodd\");\n  ctx.beginPath();\n  ctx.roundRect(x + cell * 2, y + cell * 2, side - cell * 4, side - cell * 4, Math.max(radius, r - cell * 2));\n  ctx.fill();\n}\n\nfunction pieceStart(p: Piece, variant: QrCodeVariant, size: number) {\n  if (variant === \"scan\") return clamp01((p.y + p.side / 2) / size) * SPREAD;\n  if (variant === \"smoke\") return (1 - clamp01((p.y + p.side / 2) / size)) * (SPREAD - JITTER) + p.r * JITTER;\n  if (variant === \"ripple\") return p.d * SPREAD;\n  return p.d * (SPREAD - JITTER) + p.r * JITTER;\n}\n\nfunction draw(\n  ctx: CanvasRenderingContext2D,\n  layout: Layout,\n  clock: number,\n  variant: QrCodeVariant,\n  reduce: boolean,\n  ink: string,\n  paper: string,\n) {\n  const { cell, dot, radius, pieces, reach, ox, oy, size } = layout;\n  ctx.globalAlpha = 1;\n  ctx.fillStyle = paper;\n  ctx.fillRect(0, 0, size, size);\n  ctx.fillStyle = ink;\n\n  if (reduce) {\n    ctx.globalAlpha = clock / TOTAL;\n    ctx.beginPath();\n    for (const p of pieces) if (!p.eye) ctx.roundRect(p.x, p.y, dot, dot, radius);\n    ctx.fill();\n    for (const p of pieces) if (p.eye) drawEye(ctx, p.x, p.y, p.side, cell, radius);\n    ctx.globalAlpha = 1;\n    return;\n  }\n\n  // Landed pieces sit on whole pixels with no transform. Dots share one fill.\n  ctx.beginPath();\n  for (const p of pieces) {\n    if (!p.eye && clock - pieceStart(p, variant, size) >= PIECE_IN) ctx.roundRect(p.x, p.y, dot, dot, radius);\n  }\n  ctx.fill();\n  for (const p of pieces) {\n    if (p.eye && clock - pieceStart(p, variant, size) >= PIECE_IN) drawEye(ctx, p.x, p.y, p.side, cell, radius);\n  }\n\n  // The wavefront each piece waits for, drawn faintly while it moves.\n  const q = clock / SPREAD;\n  if (q > 0 && q < 1 && (variant === \"ripple\" || variant === \"scan\")) {\n    ctx.save();\n    const fade = Math.sin(Math.PI * q);\n    if (variant === \"ripple\") {\n      ctx.strokeStyle = ink;\n      ctx.lineWidth = 1.5;\n      ctx.globalAlpha = 0.22 * fade;\n      ctx.beginPath();\n      ctx.arc(ox, oy, q * reach, 0, Math.PI * 2);\n      ctx.stroke();\n    } else {\n      const y = q * size;\n      const trail = ctx.createLinearGradient(0, y - SCAN_TRAIL, 0, y);\n      trail.addColorStop(0, \"transparent\");\n      trail.addColorStop(1, ink);\n      ctx.globalAlpha = 0.08 * fade;\n      ctx.fillStyle = trail;\n      ctx.fillRect(0, y - SCAN_TRAIL, size, SCAN_TRAIL);\n      ctx.globalAlpha = 0.3 * fade;\n      ctx.fillStyle = ink;\n      ctx.fillRect(0, y - 1, size, 1.5);\n    }\n    ctx.restore();\n  }\n\n  for (const p of pieces) {\n    const t = (clock - pieceStart(p, variant, size)) / PIECE_IN;\n    if (t <= 0 || t >= 1) continue;\n    const k = settle(t);\n    const half = p.side / 2;\n    const cx = p.x + half;\n    const cy = p.y + half;\n    ctx.save();\n\n    if (variant === \"ripple\") {\n      // Pops in place from a round seed.\n      ctx.globalAlpha = Math.min(1, t * 4);\n      ctx.translate(cx, cy);\n      if (p.eye) {\n        ctx.scale(k, k);\n        drawEye(ctx, -half, -half, p.side, cell, radius);\n      } else {\n        const s = dot * k;\n        ctx.beginPath();\n        ctx.roundRect(-s / 2, -s / 2, s, s, s / 2 + (radius - s / 2) * k);\n        ctx.fill();\n      }\n    } else if (variant === \"smoke\") {\n      // Condenses out of the plume: the solid piece firms up as it drifts up\n      // into place, under a haze drawn with the smoke layer.\n      ctx.globalAlpha = k ** 1.4;\n      ctx.translate(0, (1 - k) * cell * SMOKE_DRIFT);\n      if (p.eye) drawEye(ctx, p.x, p.y, p.side, cell, radius);\n      else {\n        ctx.beginPath();\n        ctx.roundRect(p.x, p.y, dot, dot, radius);\n        ctx.fill();\n      }\n    } else if (variant === \"scan\") {\n      // Drops a little way into place as the bar passes over it.\n      ctx.globalAlpha = Math.min(1, t * 3);\n      ctx.translate(0, -(1 - k) * cell * DROP);\n      if (p.eye) drawEye(ctx, p.x, p.y, p.side, cell, radius);\n      else {\n        ctx.beginPath();\n        ctx.roundRect(p.x, p.y, dot, dot, radius);\n        ctx.fill();\n      }\n    } else {\n      // Swarm: a curved flight from the origin, bowing away from the centre\n      // line so the paths fan out like a fountain instead of crossing.\n      const dx = cx - ox;\n      const dy = cy - oy;\n      const side = dx < 0 ? 1 : -1;\n      const bend = (BEND + BEND_SPREAD * p.r) * side;\n      const qx = ox + dx / 2 + dy * bend;\n      const qy = oy + dy / 2 - dx * bend;\n      const u = 1 - k;\n      const x = u * u * ox + 2 * u * k * qx + k * k * cx;\n      const y = u * u * oy + 2 * u * k * qy + k * k * cy;\n      const angle = Math.atan2(u * (qy - oy) + k * (cy - qy), u * (qx - ox) + k * (cx - qx));\n      const rest = Math.round(angle / QUARTER) * QUARTER;\n      // Real speed along the curve, so it stretches most where it moves\n      // fastest, and longer flights move faster. 0 at launch and on landing.\n      const v = speedAt(t) * p.d;\n      // Eyes are seven modules wide, so the same stretch would turn them into long bars.\n      const along = 1 + STRETCH * v * (p.eye ? EYE_STRETCH : 1);\n      const across = 1 / along;\n      ctx.globalAlpha = Math.min(1, t * 6);\n      ctx.translate(x, y);\n      // Faces its heading in flight and turns square as it settles.\n      ctx.rotate(rest + (angle - rest) * (1 - k) ** 2);\n      if (p.eye) {\n        ctx.scale(along, across);\n        drawEye(ctx, -half, -half, p.side, cell, radius);\n      } else {\n        const l = dot * along;\n        const w = dot * across;\n        ctx.beginPath();\n        ctx.roundRect(-l / 2, -w / 2, l, w, Math.min(w / 2, radius + (w / 2 - radius) * Math.min(1, v * 2)));\n        ctx.fill();\n      }\n    }\n    ctx.restore();\n  }\n  // The plume drifts over the code, so the dots seem to come out of it.\n  if (variant === \"smoke\") drawSmoke(ctx, layout, clock, ink);\n  ctx.globalAlpha = 1;\n}\n\n/**\n * A QR code drawn on a canvas that builds itself piece by piece: the dots and\n * the three finder eyes fly in on curved paths, pop in behind a spreading\n * ring, or drop in behind a bar sweeping down. One reversible clock runs it,\n * so hiding plays the build backwards and a press mid-run turns around from\n * where it is.\n */\nexport function AnimatedQrCode({\n  value,\n  shown,\n  variant = \"swarm\",\n  size = 296,\n  origin,\n  ink = \"#0a0a0a\",\n  paper = \"#ffffff\",\n  onSettled,\n  labels,\n  className,\n}: AnimatedQrCodeProps) {\n  const t = useMessages(\"AnimatedQrCode\", qrCodeMessages, labels);\n  const reduce = useReducedMotion() ?? false;\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n  const ctxRef = useRef<CanvasRenderingContext2D | null>(null);\n  // Read from the first render only. The clock must never be reset by a\n  // change of `shown`, or a press would skip straight to the end.\n  const clockRef = useRef(shown ? TOTAL : 0);\n  /** Clock ms per real ms, signed. Eased toward its goal on a turnaround. */\n  const rateRef = useRef(0);\n  const fallback = DEFAULT_ORIGIN[variant === \"ripple\" ? \"ripple\" : \"swarm\"];\n  const ox = origin?.x ?? fallback.x;\n  const oy = origin?.y ?? fallback.y;\n  const layout = useMemo(() => buildLayout(value, size, { x: ox, y: oy }), [value, size, ox, oy]);\n\n  const live = useRef({ layout, variant, reduce, ink, paper, onSettled });\n  useLayoutEffect(() => {\n    live.current = { layout, variant, reduce, ink, paper, onSettled };\n  });\n\n  // Backing store at device resolution, scaled once. Draws only push and pop\n  // their own transforms, so the scale is never lost.\n  useLayoutEffect(() => {\n    const canvas = canvasRef.current;\n    if (!canvas) return;\n    const dpr = Math.max(1, window.devicePixelRatio || 1);\n    canvas.width = Math.round(size * dpr);\n    canvas.height = Math.round(size * dpr);\n    const ctx = canvas.getContext(\"2d\");\n    if (!ctx) return;\n    ctx.scale(dpr, dpr);\n    ctxRef.current = ctx;\n  }, [size]);\n\n  // Repaint at the current time when the look changes, without moving it.\n  useLayoutEffect(() => {\n    const ctx = ctxRef.current;\n    if (ctx) draw(ctx, layout, clockRef.current, variant, reduce, ink, paper);\n  }, [layout, variant, reduce, ink, paper]);\n\n  // Run the clock toward the end `shown` asks for, from wherever it is.\n  useEffect(() => {\n    const target = shown ? TOTAL : 0;\n    if (clockRef.current === target) return;\n    // From rest, start at full rate: each piece already eases out of rest.\n    if (clockRef.current === 0 || clockRef.current === TOTAL) rateRef.current = shown ? 1 : -EXIT_RATE;\n    let frame = 0;\n    let last = performance.now();\n    const tick = (now: number) => {\n      // Real time, so slow frames drop instead of slowing the build. The cap\n      // only stops a long stall, like a background tab, from skipping to the end.\n      const dt = Math.min(250, now - last);\n      last = now;\n      const cur = live.current;\n      // A press mid-run eases the clock's rate into the new direction\n      // instead of flipping it, so every piece slows, stops and turns back.\n      const goal = shown ? 1 : -EXIT_RATE;\n      rateRef.current += (goal - rateRef.current) * (1 - Math.exp(-dt / TURN_MS));\n      const scale = cur.reduce ? TOTAL / REDUCED_MS : 1;\n      const next = Math.min(TOTAL, Math.max(0, clockRef.current + dt * rateRef.current * scale));\n      clockRef.current = next;\n      const ctx = ctxRef.current;\n      if (ctx) draw(ctx, cur.layout, next, cur.variant, cur.reduce, cur.ink, cur.paper);\n      if (next === target) {\n        cur.onSettled?.(shown);\n        return;\n      }\n      frame = requestAnimationFrame(tick);\n    };\n    frame = requestAnimationFrame(tick);\n    return () => cancelAnimationFrame(frame);\n  }, [shown]);\n\n  return (\n    <canvas\n      ref={canvasRef}\n      role=\"img\"\n      aria-label={shown ? t(\"label\", { value }) : undefined}\n      aria-hidden={shown ? undefined : true}\n      width={size}\n      height={size}\n      // A ring, not a border, so the canvas keeps its exact pixel size.\n      className={cn(\"aspect-square h-auto max-w-full rounded-2xl ring-1 ring-border\", className)}\n      style={{ width: size, backgroundColor: paper }}\n    />\n  );\n}\n"},{"path":"lib/i18n.tsx","type":"registry:lib","target":"@lib/i18n.tsx","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useMemo,\n} from \"react\";\n\n/**\n * A component's messages. Plain strings with `{name}` placeholders, so a\n * dictionary stays JSON-serializable and can be passed from a server layout.\n * There are no plural forms: write messages that read correctly for any count.\n */\nexport type Messages = Record<string, string>;\n\n/** A language file: component namespace → any subset of that component's messages. */\nexport type LocaleMessages = Record<string, Partial<Messages>>;\n\ntype LocaleContextValue = {\n  locale?: string;\n  messages: LocaleMessages;\n};\n\nconst NO_MESSAGES: LocaleMessages = {};\n\nconst LocaleContext = createContext<LocaleContextValue>({ messages: NO_MESSAGES });\n\n/** Without a locale, digits stay plain so server and client render the same text. */\nexport function formatNumber(value: number, locale?: string) {\n  return locale ? new Intl.NumberFormat(locale).format(value) : String(value);\n}\n\nexport interface LocaleProviderProps {\n  /** BCP 47 tag, e.g. `de`, `pt-BR`. Drives `Intl` number formatting. */\n  locale: string;\n  /**\n   * Component namespace → translated strings. Missing keys fall back to English.\n   * Pass a stable object (a module constant, imported JSON or a memoized value):\n   * a new object each render gives every translated component a new `t`.\n   */\n  messages?: LocaleMessages;\n  children: ReactNode;\n}\n\nexport function LocaleProvider({ locale, messages = NO_MESSAGES, children }: LocaleProviderProps) {\n  const value = useMemo(() => ({ locale, messages }), [locale, messages]);\n  return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;\n}\n\nexport function useLocale(): { locale?: string } {\n  return { locale: useContext(LocaleContext).locale };\n}\n\n/**\n * Resolves a component's strings: `labels` prop, then the provider's\n * messages for `namespace`, then the component's English `defaults`.\n * Numbers passed as values are formatted for the provider's locale.\n */\nexport function useMessages<T extends Messages>(\n  namespace: string,\n  defaults: T,\n  labels?: Partial<T>,\n) {\n  const { locale, messages } = useContext(LocaleContext);\n  const provided = messages[namespace];\n  // Inline `labels={{ … }}` is a new object every render. Keying it by content\n  // keeps `t` one identity until a label changes, so effects and memos that\n  // depend on `t` don't re-run per render, and render-time reads never lag.\n  const labelsKey = labels ? JSON.stringify(labels) : \"\";\n  const stableLabels = useMemo(\n    () => (labelsKey ? (JSON.parse(labelsKey) as Partial<T>) : undefined),\n    [labelsKey],\n  );\n\n  return useCallback(\n    (key: keyof T & string, values?: Record<string, string | number>) => {\n      const template = stableLabels?.[key] ?? provided?.[key] ?? defaults[key];\n      if (!values) return template;\n      return template.replace(/\\{(\\w+)\\}/g, (match, name: string) => {\n        const value = values[name];\n        if (value === undefined) return match;\n        return typeof value === \"number\" ? formatNumber(value, locale) : value;\n      });\n    },\n    [defaults, stableLabels, locale, provided],\n  );\n}\n"},{"path":"lib/utils.ts","type":"registry:lib","target":"@lib/utils.ts","content":"import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n"}]}