{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"live-qr","type":"registry:component","title":"Live QR","description":"A QR code that re-issues itself in place: only the tiles that change turn over, an expired code becomes its Refresh button, and a scan draws a check from its own tiles.","author":"Hairline UI","dependencies":["lucide-react"],"registryDependencies":["https://hairlineui.com/r/status-button.json?as=dependency"],"files":[{"path":"registry/live-qr.tsx","type":"registry:component","content":"// Hairline UI · live-qr · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { RotateCw } from \"lucide-react\";\nimport { StatusButton, type ActionStatus } from \"./status-button\";\nimport { encodeQr, type QrLevel } from \"./live-qr-encode\";\n\n/* ─────────────────────────────────────────────────────────\n * LIVE QR: a QR code that re-issues itself in place\n *\n *   arrive    the three eyes open, then the dark tiles turn\n *             over in a wave that runs out from them\n *   re-issue  a new value never blanks the code: only the tiles\n *             that differ turn over, in the same wave, tinted\n *             with your colour while they're edge-on\n *   expired   the tiles sink to a faint grain from the middle\n *             out and the code becomes its Refresh button\n *   scanned   the code clears and its own tiles fly in from all\n *             around to draw a check, in stroke order\n *\n * One canvas draws it, tile by tile; each tile turns on its own\n * spring and only ever turns forward, so typing fast re-aims it\n * instead of making it flicker back.\n * ───────────────────────────────────────────────────────── */\n\nexport type LiveQRStatus = \"live\" | \"expired\" | \"scanned\";\n\nexport interface LiveQRProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"children\" | \"color\"> {\n  /** What the code holds: a link, a payment request, an otpauth:// secret, any text. An empty string shows no code. */\n  value: string;\n  status?: LiveQRStatus;\n  /** Shown as a button on an expired code. Throw or reject to keep it expired and say so. */\n  onRefresh?: () => Promise<unknown> | void;\n  /** Error correction. Defaults to M, or H when there's a logo. */\n  level?: QrLevel;\n  /** A mark in the middle of the code. */\n  logo?: React.ReactNode;\n  /** What the code is, for screen readers (\"Scan to pay Kept\"). */\n  label?: string;\n  /** Width in px; it shrinks with its container. */\n  size?: number;\n  /** The colour of the turning tiles and the check: any CSS colour. */\n  color?: string;\n  labels?: Partial<Record<\"refresh\" | \"refreshing\" | \"expired\" | \"scanned\", string>>;\n}\n\nconst LABELS = { refresh: \"Refresh code\", refreshing: \"Refreshing\", expired: \"Code expired\", scanned: \"Scanned\" };\nconst QUIET = 3; // light modules around the code\nconst PI = Math.PI;\nconst EASE = \"cubic-bezier(0.16,1,0.3,1)\";\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};\nconst useReducedMotion = () => React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);\n\nconst clamp01 = (t: number) => (t < 0 ? 0 : t > 1 ? 1 : t);\nconst easeOut = (t: number) => 1 - (1 - t) ** 3;\nconst inOut = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2);\n/** Thrown: a slight overshoot, then settles. */\nconst thrown = (t: number) => 1 + 2.2 * (t - 1) ** 3 + 1.2 * (t - 1) ** 2;\n\n/* ── The engine: plain data the frame loop reads and writes ── */\n\n/** Per-tile progress from `from` to `to`, linear; each tile has its own delay and duration. Eased when drawn. */\ntype Track = { from: Float32Array; to: number; start: number; delay: Float32Array; dur: Float32Array; end: number };\ntype Scalar = { from: number; to: number; start: number; dur: number };\n\ninterface Engine {\n  canvas: HTMLCanvasElement | null;\n  frame: number;\n  last: number;\n  reduced: boolean;\n  ink: string;\n  tint: string;\n  width: number; // css px\n  dpr: number;\n  n: number; // modules per side, 0 before the first code\n  level: QrLevel;\n  minVersion: number;\n  hasLogo: boolean;\n  logoCells: number;\n  arrived: boolean;\n  status: LiveQRStatus;\n  want: Uint8Array; // the bits of the current value\n  // Per tile: its face at angle 0, its angle, speed and aim (a multiple of π), and when it may start turning.\n  base: Uint8Array;\n  angle: Float32Array;\n  speed: Float32Array;\n  aim: Float32Array;\n  startAt: Float64Array;\n  tile: Uint8Array; // 1 if drawn as a tile (not an eye, not under the logo)\n  axis: Uint8Array; // 1: turns about a vertical axis (narrows), 0: about a horizontal one (flattens)\n  wave: Float32Array; // ms after the eyes\n  centre: Float32Array; // ms after the middle\n  dim: Track;\n  gather: Track;\n  assigned: Uint8Array; // tiles that fly into the check\n  toRow: Float32Array;\n  toCol: Float32Array;\n  eyesIn: Scalar;\n  eyesDim: Scalar;\n  eyesGather: Scalar;\n  prev: { n: number; bits: Uint8Array; start: number } | null;\n}\n\nconst scalar = (value: number): Scalar => ({ from: value, to: value, start: 0, dur: 1 });\nconst scalarAt = (s: Scalar, now: number) => s.from + (s.to - s.from) * clamp01((now - s.start) / s.dur);\nfunction aimScalar(s: Scalar, to: number, now: number, dur: number) {\n  s.from = scalarAt(s, now);\n  s.to = to;\n  s.start = now;\n  s.dur = Math.max(1, dur);\n}\n\nfunction makeTrack(count: number, value: number): Track {\n  const from = new Float32Array(count).fill(value);\n  return { from, to: value, start: 0, delay: new Float32Array(count), dur: new Float32Array(count).fill(1), end: 0 };\n}\nconst trackAt = (t: Track, i: number, now: number) => {\n  const p = (now - t.start - t.delay[i]) / t.dur[i];\n  return p <= 0 ? t.from[i] : p >= 1 ? t.to : t.from[i] + (t.to - t.from[i]) * p;\n};\nfunction aimTrack(t: Track, to: number, now: number, delay: Float32Array, dur: Float32Array, reduced: boolean) {\n  let end = 0;\n  for (let i = 0; i < t.from.length; i++) {\n    t.from[i] = reduced ? to : trackAt(t, i, now);\n    end = Math.max(end, delay[i] + dur[i]);\n  }\n  t.to = to;\n  t.start = now;\n  t.delay = delay;\n  t.dur = reduced ? new Float32Array(t.from.length).fill(1) : dur;\n  t.end = reduced ? 0 : end;\n}\n\nfunction createEngine(): Engine {\n  const empty = new Uint8Array(0);\n  return {\n    canvas: null,\n    frame: 0,\n    last: 0,\n    reduced: false,\n    ink: \"#111\",\n    tint: \"#305dde\",\n    width: 0,\n    dpr: 1,\n    n: 0,\n    level: \"M\",\n    minVersion: 1,\n    hasLogo: false,\n    logoCells: 0,\n    arrived: false,\n    status: \"live\",\n    want: empty,\n    base: empty,\n    angle: new Float32Array(0),\n    speed: new Float32Array(0),\n    aim: new Float32Array(0),\n    startAt: new Float64Array(0),\n    tile: empty,\n    axis: empty,\n    wave: new Float32Array(0),\n    centre: new Float32Array(0),\n    dim: makeTrack(0, 0),\n    gather: makeTrack(0, 0),\n    assigned: empty,\n    toRow: new Float32Array(0),\n    toCol: new Float32Array(0),\n    eyesIn: scalar(0),\n    eyesDim: scalar(0),\n    eyesGather: scalar(0),\n    prev: null,\n  };\n}\n\nconst isEye = (row: number, col: number, n: number) => (row < 8 && col < 8) || (row < 8 && col >= n - 8) || (row >= n - 8 && col < 8);\nconst faceAt = (base: number, angle: number) => base ^ (Math.floor(angle / PI + 0.5) & 1);\n\n/** Sets up the arrays for a grid of n × n and works out each tile's place in the waves. */\nfunction layout(e: Engine, n: number) {\n  const count = n * n;\n  e.n = n;\n  e.base = new Uint8Array(count);\n  e.angle = new Float32Array(count);\n  e.speed = new Float32Array(count);\n  e.aim = new Float32Array(count);\n  e.startAt = new Float64Array(count);\n  e.tile = new Uint8Array(count);\n  e.axis = new Uint8Array(count);\n  e.wave = new Float32Array(count);\n  e.centre = new Float32Array(count);\n  e.assigned = new Uint8Array(count);\n  e.toRow = new Float32Array(count);\n  e.toCol = new Float32Array(count);\n  const eyes = [[3, 3], [3, n - 4], [n - 4, 3]];\n  const mid = (n - 1) / 2;\n  const farthest = Math.hypot(n - 7, n - 7);\n  const perModule = Math.min(14, 380 / farthest);\n  markTiles(e);\n  for (let row = 0; row < n; row++) {\n    for (let col = 0; col < n; col++) {\n      const i = row * n + col;\n      let best = Infinity;\n      let dx = 0;\n      let dy = 0;\n      for (const [r, c] of eyes) {\n        const d = Math.hypot(row - r, col - c);\n        if (d < best) [best, dx, dy] = [d, col - c, row - r];\n      }\n      e.axis[i] = Math.abs(dx) > Math.abs(dy) ? 1 : 0;\n      e.wave[i] = best * perModule;\n      e.centre[i] = (Math.hypot(row - mid, col - mid) / (mid * Math.SQRT2)) * 200;\n    }\n  }\n  e.dim = makeTrack(count, e.status === \"expired\" ? 1 : 0);\n  e.gather = makeTrack(count, e.status === \"scanned\" ? 1 : 0);\n}\n\n/** Which modules are drawn as tiles: not the eyes (drawn whole) and not the hole under a logo. */\nfunction markTiles(e: Engine) {\n  const n = e.n;\n  const cells = e.hasLogo ? Math.round(n * 0.23) | 1 : 0;\n  const from = (n - cells) / 2;\n  e.logoCells = cells;\n  for (let row = 0; row < n; row++) {\n    for (let col = 0; col < n; col++) {\n      const underLogo = cells > 0 && row >= from && row < from + cells && col >= from && col < from + cells;\n      e.tile[row * n + col] = isEye(row, col, n) || underLogo ? 0 : 1;\n    }\n  }\n}\n\n/** Puts new bits on the grid. Animated: tiles that differ turn over in the wave; else they're simply there. */\nfunction applyBits(e: Engine, bits: Uint8Array, now: number, animate: boolean) {\n  e.want = bits;\n  for (let i = 0; i < bits.length; i++) {\n    if (!animate) {\n      e.base[i] = bits[i];\n      e.angle[i] = e.aim[i] = e.speed[i] = 0;\n      e.startAt[i] = 0;\n      continue;\n    }\n    if (faceAt(e.base[i], e.aim[i]) === bits[i]) continue;\n    // Always onward: a tile heading for the wrong face turns a further half-turn, never back.\n    const resting = e.angle[i] === e.aim[i] && e.speed[i] === 0;\n    e.aim[i] += PI;\n    if (resting || e.startAt[i] > now) e.startAt[i] = now + e.wave[i];\n    if (e.reduced) {\n      e.angle[i] = e.aim[i];\n      e.speed[i] = 0;\n    }\n  }\n}\n\n/** Installs a value: same grid size re-issues in place; a new size fades the old grid out and arrives fresh. */\nfunction install(e: Engine, value: string, now: number) {\n  const code = value ? encodeQr(value, e.level, e.minVersion) : null;\n  if (value && !code && process.env.NODE_ENV !== \"production\") console.warn(\"LiveQR: the value is too long for a QR code.\");\n  if (code) e.minVersion = Math.max(e.minVersion, code.version);\n  const n = code ? code.size : e.n;\n  if (!n) return;\n  const bits = code ? code.modules : new Uint8Array(n * n);\n  if (n !== e.n) {\n    if (e.n && e.arrived && !e.reduced) e.prev = { n: e.n, bits: shownBits(e), start: now };\n    layout(e, n);\n    if (e.arrived) arrive(e, bits, now);\n    else applyBits(e, bits, now, false);\n    if (e.status === \"scanned\") {\n      planCheck(e);\n      aimTrack(e.gather, 1, now, e.gather.delay, e.gather.dur, true);\n    }\n    return;\n  }\n  if (e.logoCells !== (e.hasLogo ? Math.round(n * 0.23) | 1 : 0)) markTiles(e);\n  applyBits(e, bits, now, e.arrived);\n}\n\nfunction shownBits(e: Engine) {\n  const bits = new Uint8Array(e.n * e.n);\n  for (let i = 0; i < bits.length; i++) bits[i] = faceAt(e.base[i], e.angle[i]);\n  return bits;\n}\n\n/** First time on screen: the eyes open, then every dark tile turns over from blank. */\nfunction arrive(e: Engine, bits: Uint8Array, now: number) {\n  e.arrived = true;\n  e.base.fill(0);\n  e.angle.fill(0);\n  e.speed.fill(0);\n  e.aim.fill(0);\n  e.want = bits;\n  for (let i = 0; i < bits.length; i++) {\n    if (!bits[i]) continue;\n    e.aim[i] = PI;\n    e.startAt[i] = now + 140 + e.wave[i];\n    if (e.reduced) e.angle[i] = PI;\n  }\n  e.eyesIn = { from: e.reduced ? 1 : 0, to: 1, start: now, dur: 460 };\n}\n\n/** Which tiles draw the check, where each lands, and when. */\nfunction planCheck(e: Engine) {\n  const n = e.n;\n  const span = n - 1;\n  const points = [[0.5, 0.21], [0.72, 0.41], [0.27, 0.8]].map(([r, c]) => [r * span, c * span]);\n  const half = Math.max(1.3, n * 0.054);\n  const lengths = [Math.hypot(points[1][0] - points[0][0], points[1][1] - points[0][1]), Math.hypot(points[2][0] - points[1][0], points[2][1] - points[1][1])];\n  const cells: { row: number; col: number; along: number }[] = [];\n  for (let row = 0; row < n; row++) {\n    for (let col = 0; col < n; col++) {\n      let near = Infinity;\n      let along = 0;\n      for (let s = 0; s < 2; s++) {\n        const [ar, ac] = points[s];\n        const [br, bc] = points[s + 1];\n        const t = clamp01(((row - ar) * (br - ar) + (col - ac) * (bc - ac)) / lengths[s] ** 2);\n        const d = Math.hypot(row - (ar + (br - ar) * t), col - (ac + (bc - ac) * t));\n        if (d < near) [near, along] = [d, (s ? lengths[0] : 0) + t * lengths[s]];\n      }\n      if (near <= half) cells.push({ row, col, along });\n    }\n  }\n  cells.sort((a, b) => a.along - b.along);\n\n  // Sources: dark tiles, ordered counter-clockwise from the side the check starts on, so the sweep follows the stroke.\n  const mid = span / 2;\n  const startAngle = Math.atan2(points[0][0] - mid, points[0][1] - mid);\n  const sources: { i: number; key: number }[] = [];\n  for (let i = 0; i < n * n; i++) {\n    if (!e.tile[i] || !faceAt(e.base[i], e.aim[i])) continue;\n    const angle = Math.atan2(Math.floor(i / n) - mid, (i % n) - mid);\n    sources.push({ i, key: (startAngle - angle + 4 * PI) % (2 * PI) });\n  }\n  sources.sort((a, b) => a.key - b.key);\n  const count = Math.min(cells.length, sources.length);\n  const delay = new Float32Array(n * n);\n  const dur = new Float32Array(n * n);\n  e.assigned.fill(0);\n  for (let i = 0; i < n * n; i++) {\n    delay[i] = (e.centre[i] / 200) * 140;\n    dur[i] = 260;\n  }\n  for (let k = 0; k < count; k++) {\n    const { i } = sources[Math.floor((k * sources.length) / count)];\n    e.assigned[i] = 1;\n    e.toRow[i] = cells[k].row;\n    e.toCol[i] = cells[k].col;\n    delay[i] = 60 + (k / count) * 320;\n    dur[i] = 470;\n  }\n  e.gather.delay = delay;\n  e.gather.dur = dur;\n}\n\nfunction setStatus(e: Engine, status: LiveQRStatus, now: number) {\n  const was = e.status;\n  e.status = status;\n  if (!e.n || was === status) return;\n  const count = e.n * e.n;\n  const reduced = e.reduced;\n  // Expiring sinks from the middle out (where the button lands); coming back grows with the re-issue wave.\n  const dimDur = new Float32Array(count).fill(380);\n  aimTrack(e.dim, status === \"expired\" ? 1 : 0, now, status === \"expired\" ? e.centre : e.wave, dimDur, reduced);\n  aimScalar(e.eyesDim, status === \"expired\" ? 1 : 0, now, reduced ? 1 : 380);\n  // A new plan only from a whole code; a scan that comes back mid-return keeps its tiles and their places.\n  const settled = e.gather.to === 0 && now >= e.gather.start + e.gather.end;\n  if (status === \"scanned\" && settled) planCheck(e);\n  aimTrack(e.gather, status === \"scanned\" ? 1 : 0, now, e.gather.delay, e.gather.dur, reduced);\n  aimScalar(e.eyesGather, status === \"scanned\" ? 1 : 0, now, reduced ? 1 : 260);\n}\n\n/** Moves every turning tile on; returns whether anything is still moving. */\nfunction step(e: Engine, now: number) {\n  const dt = Math.min(1 / 30, Math.max(0, (now - e.last) / 1000));\n  e.last = now;\n  let busy = false;\n  // About 380ms a turn, settling without a bounce.\n  const k = 200;\n  const c = 24;\n  for (let i = 0; i < e.angle.length; i++) {\n    if (e.angle[i] === e.aim[i] && e.speed[i] === 0) continue;\n    busy = true;\n    if (now < e.startAt[i]) continue;\n    for (let sub = 0; sub < 2; sub++) {\n      const h = dt / 2;\n      e.speed[i] += (k * (e.aim[i] - e.angle[i]) - c * e.speed[i]) * h;\n      e.angle[i] += e.speed[i] * h;\n    }\n    if (Math.abs(e.aim[i] - e.angle[i]) < 0.002 && Math.abs(e.speed[i]) < 0.03) {\n      // Keep angles small; a whole turn shows the same face.\n      const turns = Math.floor(e.aim[i] / (2 * PI)) * 2 * PI;\n      e.aim[i] -= turns;\n      e.angle[i] = e.aim[i];\n      e.speed[i] = 0;\n    }\n  }\n  if (now < e.dim.start + e.dim.end || now < e.gather.start + e.gather.end) busy = true;\n  for (const s of [e.eyesIn, e.eyesDim, e.eyesGather]) if (now < s.start + s.dur) busy = true;\n  if (e.prev && now - e.prev.start < 200) busy = true;\n  else e.prev = null;\n  return busy;\n}\n\ntype Box = { u: number; origin: number; gap: number };\nfunction grid(e: Engine, n: number): Box {\n  const size = Math.round(e.width * e.dpr);\n  const u = Math.max(1, Math.floor(size / (n + QUIET * 2)));\n  const origin = Math.round((size - u * n) / 2);\n  return { u, origin, gap: Math.floor(u * 0.1 + 0.3) };\n}\n\nfunction roundRect(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number) {\n  if (w <= 0.2 || h <= 0.2) return;\n  if (\"roundRect\" in ctx) ctx.roundRect(x, y, w, h, Math.max(0, Math.min(r, w / 2, h / 2)));\n  else (ctx as CanvasRenderingContext2D).rect(x, y, w, h);\n}\n\nfunction drawEyes(ctx: CanvasRenderingContext2D, n: number, box: Box, scale: number) {\n  const { u, origin, gap } = box;\n  for (const [row, col] of [[0, 0], [0, n - 7], [n - 7, 0]]) {\n    const cx = origin + (col + 3.5) * u;\n    const cy = origin + (row + 3.5) * u;\n    const at = (cells: number) => (cells * u - gap) * scale;\n    const outer = at(7);\n    const hole = (5 * u + gap) * scale;\n    const pupil = at(3);\n    ctx.beginPath();\n    roundRect(ctx, cx - outer / 2, cy - outer / 2, outer, outer, 2.1 * u * scale);\n    roundRect(ctx, cx - hole / 2, cy - hole / 2, hole, hole, 1.35 * u * scale);\n    ctx.fill(\"evenodd\");\n    ctx.beginPath();\n    roundRect(ctx, cx - pupil / 2, cy - pupil / 2, pupil, pupil, 0.95 * u * scale);\n    ctx.fill();\n  }\n}\n\nfunction draw(e: Engine, now: number) {\n  const canvas = e.canvas;\n  const ctx = canvas?.getContext(\"2d\");\n  if (!canvas || !ctx) return;\n  ctx.clearRect(0, 0, canvas.width, canvas.height);\n  if (!e.n || !e.arrived) return;\n\n  // The old grid, when the code just changed size, fades out under the new one.\n  if (e.prev) {\n    const fade = 1 - clamp01((now - e.prev.start) / 200);\n    const box = grid(e, e.prev.n);\n    ctx.globalAlpha = fade;\n    ctx.fillStyle = e.ink;\n    ctx.beginPath();\n    for (let row = 0; row < e.prev.n; row++) {\n      for (let col = 0; col < e.prev.n; col++) {\n        if (!e.prev.bits[row * e.prev.n + col] || isEye(row, col, e.prev.n)) continue;\n        roundRect(ctx, box.origin + col * box.u + box.gap / 2, box.origin + row * box.u + box.gap / 2, box.u - box.gap, box.u - box.gap, (box.u - box.gap) * 0.22);\n      }\n    }\n    ctx.fill();\n    drawEyes(ctx, e.prev.n, box, 1);\n    ctx.globalAlpha = 1;\n  }\n\n  const n = e.n;\n  const box = grid(e, n);\n  const { u, origin, gap } = box;\n  const size = u - gap;\n  const half = gap / 2;\n  const radius = size * 0.22;\n\n  // Eyes: they open on arrival, dim with the code, and close when it's scanned.\n  const opened = thrown(clamp01(scalarAt(e.eyesIn, now)));\n  const eyeDim = inOut(clamp01(scalarAt(e.eyesDim, now)));\n  const eyeGone = inOut(clamp01(scalarAt(e.eyesGather, now)));\n  const eyeScale = (0.55 + 0.45 * opened) * (1 - 0.08 * eyeDim) * (1 - eyeGone);\n  ctx.fillStyle = e.ink;\n  ctx.globalAlpha = clamp01(scalarAt(e.eyesIn, now) * 2.5) * (1 - 0.72 * eyeDim);\n  if (eyeScale > 0.01) drawEyes(ctx, n, box, eyeScale);\n\n  // Tiles at rest go into one path; anything turning, dimmed or flying is drawn on its own.\n  ctx.globalAlpha = 1;\n  ctx.beginPath();\n  const moving: number[] = [];\n  for (let i = 0; i < n * n; i++) {\n    if (!e.tile[i]) continue;\n    const still = e.angle[i] === e.aim[i] && e.speed[i] === 0;\n    const quiet = still && e.dim.to === 0 && trackAt(e.dim, i, now) === 0 && trackAt(e.gather, i, now) === 0;\n    if (!quiet) {\n      moving.push(i);\n      continue;\n    }\n    if (!faceAt(e.base[i], e.angle[i])) continue;\n    roundRect(ctx, origin + (i % n) * u + half, origin + Math.floor(i / n) * u + half, size, size, radius);\n  }\n  ctx.fill();\n\n  for (const i of moving) {\n    const row = Math.floor(i / n);\n    const col = i % n;\n    const a = e.angle[i];\n    const face = faceAt(e.base[i], a);\n    const turn = Math.abs(Math.cos(a));\n    const edge = Math.abs(Math.sin(a));\n    const dim = easeOut(clamp01(trackAt(e.dim, i, now)));\n    const g = clamp01(trackAt(e.gather, i, now));\n    const flies = e.assigned[i] === 1 && g > 0;\n    let x = col;\n    let y = row;\n    let scale = 1 - 0.55 * dim;\n    let alpha = 1 - 0.72 * dim;\n    // Your colour is the tile's edge: it shows as the tile turns away and is gone once it lies flat again.\n    let tint = inOut(clamp01((edge - 0.18) / 0.55));\n    if (flies) {\n      const p = thrown(g);\n      x = col + (e.toCol[i] - col) * p;\n      y = row + (e.toRow[i] - row) * p;\n      scale = scale + (1 - scale) * clamp01(g * 2);\n      alpha = alpha + (1 - alpha) * clamp01(g * 2);\n      tint = Math.max(tint * (1 - g), clamp01(g * 1.6));\n    } else {\n      scale *= 1 - inOut(g);\n    }\n    if (!flies && !face && tint < 0.02) continue;\n    if (scale < 0.02) continue;\n    // A tile turned edge-on narrows (vertical axis) or flattens (horizontal axis), away from the eye nearest it. It keeps\n    // some thickness edge-on, so the turn reads as a tile with an edge rather than a line.\n    const flat = flies && g > 0.5 ? 1 : 0.2 + 0.8 * turn;\n    const w = size * scale * (e.axis[i] ? flat : 1);\n    const h = size * scale * (e.axis[i] ? 1 : flat);\n    const cx = origin + x * u + u / 2;\n    const cy = origin + y * u + u / 2;\n    ctx.beginPath();\n    roundRect(ctx, cx - w / 2, cy - h / 2, w, h, radius * scale);\n    if (face || flies) {\n      ctx.globalAlpha = alpha;\n      ctx.fillStyle = e.ink;\n      ctx.fill();\n    }\n    if (tint > 0.02) {\n      ctx.globalAlpha = alpha * tint;\n      ctx.fillStyle = e.tint;\n      ctx.fill();\n    }\n  }\n  ctx.globalAlpha = 1;\n}\n\nfunction frame(e: Engine, now: number) {\n  e.frame = 0;\n  const busy = step(e, now);\n  draw(e, now);\n  if (busy) e.frame = requestAnimationFrame((t) => frame(e, t));\n}\nfunction kick(e: Engine) {\n  if (e.frame || !e.canvas) return;\n  e.last = performance.now();\n  e.frame = requestAnimationFrame((t) => frame(e, t));\n}\n\nexport function LiveQR({\n  value,\n  status = \"live\",\n  onRefresh,\n  level,\n  logo,\n  label = \"QR code\",\n  size = 224,\n  color,\n  labels,\n  className = \"\",\n  style,\n  ...props\n}: LiveQRProps) {\n  const reduced = useReducedMotion();\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const canvasRef = React.useRef<HTMLCanvasElement>(null);\n  const inkRef = React.useRef<HTMLSpanElement>(null);\n  const tintRef = React.useRef<HTMLSpanElement>(null);\n  const engineRef = React.useRef<Engine | null>(null);\n  const [logoPx, setLogoPx] = React.useState(0);\n  const [refresh, setRefresh] = React.useState<ActionStatus>(\"idle\");\n  const [arrived, setArrived] = React.useState(false);\n  const resolvedLevel: QrLevel = level ?? (logo ? \"H\" : \"M\");\n  const hasLogo = Boolean(logo);\n  const text = { ...LABELS, ...labels };\n\n  const engine = React.useCallback(() => {\n    if (!engineRef.current) engineRef.current = createEngine();\n    return engineRef.current;\n  }, []);\n\n  // Canvas, size and the logo's hole, measured from the rendered width.\n  React.useEffect(() => {\n    const e = engine();\n    const root = rootRef.current;\n    const canvas = canvasRef.current;\n    if (!root || !canvas) return;\n    e.canvas = canvas;\n    const measure = () => {\n      e.width = root.clientWidth;\n      e.dpr = Math.min(3, window.devicePixelRatio || 1);\n      const px = Math.round(e.width * e.dpr);\n      if (canvas.width !== px) canvas.width = canvas.height = px;\n      if (e.n) {\n        const box = grid(e, e.n);\n        const next = e.logoCells ? (e.logoCells * box.u - box.gap) / e.dpr : 0;\n        setLogoPx((was) => (Math.abs(was - next) < 0.25 ? was : next));\n      }\n      draw(e, performance.now());\n    };\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(root);\n    return () => {\n      observer.disconnect();\n      cancelAnimationFrame(e.frame);\n      e.frame = 0;\n      e.canvas = null;\n    };\n  }, [engine]);\n\n  // The theme's colours, read again whenever the theme changes.\n  React.useEffect(() => {\n    const e = engine();\n    const read = () => {\n      const probe = document.createElement(\"canvas\").getContext(\"2d\");\n      const usable = (css: string, fallback: string) => {\n        if (!probe || !css) return fallback;\n        probe.fillStyle = \"#010203\";\n        probe.fillStyle = css;\n        return probe.fillStyle === \"#010203\" ? fallback : css;\n      };\n      e.ink = usable(inkRef.current ? getComputedStyle(inkRef.current).color : \"\", \"#111111\");\n      e.tint = usable(tintRef.current ? getComputedStyle(tintRef.current).color : \"\", \"#305dde\");\n      draw(e, performance.now());\n      kick(e);\n    };\n    read();\n    const observer = new MutationObserver(read);\n    observer.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\", \"style\", \"data-theme\"] });\n    const media = window.matchMedia(\"(prefers-color-scheme: dark)\");\n    media.addEventListener(\"change\", read);\n    return () => {\n      observer.disconnect();\n      media.removeEventListener(\"change\", read);\n    };\n  }, [engine, color]);\n\n  React.useEffect(() => {\n    engine().reduced = reduced;\n  }, [engine, reduced]);\n\n  // A new value, level or logo: re-issue in place (or rebuild when the level or logo changes the grid).\n  React.useEffect(() => {\n    const e = engine();\n    const now = performance.now();\n    if (e.level !== resolvedLevel) {\n      e.level = resolvedLevel;\n      e.minVersion = 1;\n    }\n    e.hasLogo = hasLogo;\n    install(e, value, now);\n    if (e.n && e.canvas) {\n      const box = grid(e, e.n);\n      const next = e.logoCells ? (e.logoCells * box.u - box.gap) / e.dpr : 0;\n      requestAnimationFrame(() => setLogoPx((was) => (Math.abs(was - next) < 0.25 ? was : next)));\n    }\n    kick(e);\n  }, [engine, value, resolvedLevel, hasLogo]);\n\n  React.useEffect(() => {\n    const e = engine();\n    setStatus(e, status, performance.now());\n    kick(e);\n  }, [engine, status]);\n\n  // Arrives the first time it's on screen.\n  React.useEffect(() => {\n    const e = engine();\n    const root = rootRef.current;\n    if (!root) return;\n    const observer = new IntersectionObserver(([entry]) => {\n      if (!entry.isIntersecting || e.arrived || !e.n) return;\n      arrive(e, e.want, performance.now());\n      kick(e);\n      setArrived(true);\n      observer.disconnect();\n    });\n    observer.observe(root);\n    return () => observer.disconnect();\n  }, [engine, value]);\n\n  const expired = status === \"expired\";\n  const scanned = status === \"scanned\";\n  const runRefresh = async () => {\n    if (!onRefresh || refresh === \"pending\") return;\n    setRefresh(\"pending\");\n    try {\n      await onRefresh();\n      setRefresh(\"idle\");\n    } catch {\n      setRefresh(\"error\");\n    }\n  };\n\n  return (\n    <div\n      ref={rootRef}\n      className={`relative aspect-square max-w-full bg-background dark:bg-foreground shadow-[0_0_0_1px_var(--border)] ${className}`}\n      style={{ width: size, borderRadius: \"8%\", ...style }}\n      {...props}\n    >\n      <canvas ref={canvasRef} role=\"img\" aria-label={label} className=\"absolute inset-0 size-full\" />\n      <span ref={inkRef} hidden className=\"text-foreground dark:text-background\" />\n      <span ref={tintRef} hidden style={{ color: color ?? \"var(--primary)\" }} />\n\n      {logo && (\n        <div\n          aria-hidden\n          className=\"pointer-events-none absolute inset-0 m-auto grid place-items-center overflow-clip text-foreground dark:text-background [&_svg]:size-[64%]\"\n          style={{\n            width: logoPx,\n            height: logoPx,\n            borderRadius: \"22%\",\n            opacity: logoPx && arrived && !scanned ? (expired ? 0.28 : 1) : 0,\n            transform: arrived && !scanned ? \"none\" : \"scale(0.6)\",\n            transition: reduced ? \"none\" : `opacity 260ms ${EASE} ${arrived && !scanned ? 280 : 0}ms, transform 420ms ${EASE} ${arrived && !scanned ? 280 : 0}ms`,\n          }}\n        >\n          {logo}\n        </div>\n      )}\n\n      <div\n        inert={!expired}\n        className=\"absolute inset-0 grid place-items-center\"\n        style={{\n          opacity: expired ? 1 : 0,\n          transform: expired ? \"none\" : \"scale(0.92)\",\n          filter: expired ? \"blur(0px)\" : \"blur(4px)\",\n          transition: reduced ? \"none\" : `opacity 260ms ${EASE} ${expired ? 160 : 0}ms, transform 420ms ${EASE} ${expired ? 160 : 0}ms, filter 260ms ${EASE} ${expired ? 160 : 0}ms`,\n        }}\n      >\n        {onRefresh ? (\n          <StatusButton\n            status={refresh}\n            icon={<RotateCw />}\n            labels={{ idle: text.refresh, pending: text.refreshing, success: text.refresh, error: \"Try again\" }}\n            onClick={runRefresh}\n          />\n        ) : (\n          <span className=\"inline-flex h-8 items-center rounded-full bg-background px-3 text-[13px] text-foreground shadow-[0_0_0_1px_var(--border)]\">{text.expired}</span>\n        )}\n      </div>\n\n      <span className=\"sr-only\" role=\"status\" aria-live=\"polite\">\n        {expired ? text.expired : scanned ? text.scanned : \"\"}\n      </span>\n    </div>\n  );\n}\n"},{"path":"registry/live-qr-encode.ts","type":"registry:component","content":"// Hairline UI · live-qr · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n/* ─────────────────────────────────────────────────────────\n * A QR code encoder for Live QR: any text in byte mode (UTF-8),\n * versions 1 to 40, the four error-correction levels, and the\n * mask with the lowest penalty. No dependencies.\n *\n * The result is a square of modules (1 = dark), row by row, and a\n * second square marking the fixed patterns, so the renderer can\n * draw the three finder \"eyes\" as shapes of their own.\n * ───────────────────────────────────────────────────────── */\n\nexport type QrLevel = \"L\" | \"M\" | \"Q\" | \"H\";\n\nexport interface QrCode {\n  version: number;\n  /** Modules per side: 17 + 4 × version. */\n  size: number;\n  /** size × size, row by row; 1 is dark. */\n  modules: Uint8Array;\n  /** size × size; 1 where the module belongs to a fixed pattern (finders, timing, alignment, format, version). */\n  fixed: Uint8Array;\n}\n\n// Per version 1–40: error-correction codewords in each block, then the number of blocks (ISO/IEC 18004, table 9).\nconst EC_PER_BLOCK: Record<QrLevel, number[]> = {\n  L: [7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],\n  M: [10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28],\n  Q: [13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],\n  H: [17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],\n};\nconst BLOCKS: Record<QrLevel, number[]> = {\n  L: [1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25],\n  M: [1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49],\n  Q: [1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68],\n  H: [1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81],\n};\n// The two bits each level writes into the format information.\nconst LEVEL_BITS: Record<QrLevel, number> = { L: 1, M: 0, Q: 3, H: 2 };\n\n/* ── Arithmetic in GF(256), modulo x⁸ + x⁴ + x³ + x² + 1 ── */\n\nconst EXP = new Uint8Array(512);\nconst LOG = new Uint8Array(256);\n{\n  let x = 1;\n  for (let i = 0; i < 255; i++) {\n    EXP[i] = x;\n    LOG[x] = i;\n    x <<= 1;\n    if (x & 0x100) x ^= 0x11d;\n  }\n  for (let i = 255; i < 512; i++) EXP[i] = EXP[i - 255];\n}\nconst gfMul = (a: number, b: number) => (a === 0 || b === 0 ? 0 : EXP[LOG[a] + LOG[b]]);\n\n// The generator (x − α⁰)(x − α¹)…(x − αⁿ⁻¹), highest power first, cached by degree.\nconst generators = new Map<number, Uint8Array>();\nfunction generator(degree: number) {\n  const cached = generators.get(degree);\n  if (cached) return cached;\n  let poly = new Uint8Array([1]);\n  for (let i = 0; i < degree; i++) {\n    const next = new Uint8Array(poly.length + 1);\n    for (let j = 0; j < poly.length; j++) {\n      next[j] ^= poly[j];\n      next[j + 1] ^= gfMul(poly[j], EXP[i]);\n    }\n    poly = next;\n  }\n  generators.set(degree, poly);\n  return poly;\n}\n\n/** The Reed–Solomon check bytes for one block: the remainder of data × xⁿ divided by the generator. */\nfunction checkBytes(data: Uint8Array, count: number) {\n  const gen = generator(count);\n  const rest = new Uint8Array(count);\n  for (const byte of data) {\n    const factor = byte ^ rest[0];\n    rest.copyWithin(0, 1);\n    rest[count - 1] = 0;\n    for (let k = 0; k < count; k++) rest[k] ^= gfMul(gen[k + 1], factor);\n  }\n  return rest;\n}\n\n/* ── The fixed patterns ── */\n\nfunction alignmentCentres(version: number) {\n  if (version === 1) return [];\n  const size = version * 4 + 17;\n  const count = Math.floor(version / 7) + 2;\n  const step = version === 32 ? 26 : Math.ceil((size - 13) / (count * 2 - 2)) * 2;\n  const centres = [6];\n  for (let at = size - 7; centres.length < count; at -= step) centres.splice(1, 0, at);\n  return centres;\n}\n\n/** A blank symbol with every fixed pattern drawn and marked; format and version areas are reserved (marked, light). */\nfunction blankSymbol(version: number) {\n  const size = version * 4 + 17;\n  const modules = new Uint8Array(size * size);\n  const fixed = new Uint8Array(size * size);\n  const put = (row: number, col: number, dark: boolean) => {\n    if (row < 0 || col < 0 || row >= size || col >= size) return;\n    modules[row * size + col] = dark ? 1 : 0;\n    fixed[row * size + col] = 1;\n  };\n\n  // Timing lines first, so the finders and alignment patterns draw over their ends.\n  for (let i = 0; i < size; i++) {\n    put(6, i, i % 2 === 0);\n    put(i, 6, i % 2 === 0);\n  }\n  // Finders with their light separators: rings at distance 0–1 dark, 2 light, 3 dark, 4 light (the separator).\n  for (const [top, left] of [[0, 0], [0, size - 7], [size - 7, 0]]) {\n    for (let dr = -1; dr <= 7; dr++) {\n      for (let dc = -1; dc <= 7; dc++) {\n        const ring = Math.max(Math.abs(dr - 3), Math.abs(dc - 3));\n        put(top + dr, left + dc, ring !== 2 && ring !== 4);\n      }\n    }\n  }\n  // Alignment patterns, except where a finder already sits.\n  const centres = alignmentCentres(version);\n  const last = centres.length - 1;\n  centres.forEach((row, i) =>\n    centres.forEach((col, j) => {\n      if ((i === 0 && j === 0) || (i === 0 && j === last) || (i === last && j === 0)) return;\n      for (let dr = -2; dr <= 2; dr++) for (let dc = -2; dc <= 2; dc++) put(row + dr, col + dc, Math.max(Math.abs(dr), Math.abs(dc)) !== 1);\n    }),\n  );\n  // Reserve the format areas (filled in once the mask is chosen) and the always-dark module.\n  for (let i = 0; i < 9; i++) {\n    if (i === 6) continue; // the timing lines cross here\n    put(8, i, false);\n    put(i, 8, false);\n  }\n  for (let i = 0; i < 8; i++) {\n    put(8, size - 1 - i, false);\n    put(size - 1 - i, 8, false);\n  }\n  put(size - 8, 8, true);\n  // Version information, from version 7: two 6 × 3 blocks.\n  if (version >= 7) {\n    let rest = version;\n    for (let i = 0; i < 12; i++) rest = (rest << 1) ^ ((rest >> 11) * 0x1f25);\n    const bits = (version << 12) | rest;\n    for (let i = 0; i < 18; i++) {\n      const dark = ((bits >> i) & 1) === 1;\n      const a = size - 11 + (i % 3);\n      const b = Math.floor(i / 3);\n      put(b, a, dark);\n      put(a, b, dark);\n    }\n  }\n  return { size, modules, fixed };\n}\n\n/** Writes the 15 format bits (level and mask, BCH-protected) in both copies. */\nfunction writeFormat(modules: Uint8Array, size: number, level: QrLevel, mask: number) {\n  const data = (LEVEL_BITS[level] << 3) | mask;\n  let rest = data;\n  for (let i = 0; i < 10; i++) rest = (rest << 1) ^ ((rest >> 9) * 0x537);\n  const bits = ((data << 10) | rest) ^ 0x5412;\n  const bit = (i: number) => (bits >> i) & 1;\n  const set = (row: number, col: number, value: number) => (modules[row * size + col] = value);\n  // Around the top-left finder.\n  for (let i = 0; i <= 5; i++) set(i, 8, bit(i));\n  set(7, 8, bit(6));\n  set(8, 8, bit(7));\n  set(8, 7, bit(8));\n  for (let i = 9; i < 15; i++) set(8, 14 - i, bit(i));\n  // Split between the other two finders.\n  for (let i = 0; i < 8; i++) set(8, size - 1 - i, bit(i));\n  for (let i = 8; i < 15; i++) set(size - 15 + i, 8, bit(i));\n  set(size - 8, 8, 1);\n}\n\nconst MASKS: ((row: number, col: number) => boolean)[] = [\n  (r, c) => (r + c) % 2 === 0,\n  (r) => r % 2 === 0,\n  (_, c) => c % 3 === 0,\n  (r, c) => (r + c) % 3 === 0,\n  (r, c) => (Math.floor(r / 2) + Math.floor(c / 3)) % 2 === 0,\n  (r, c) => ((r * c) % 2) + ((r * c) % 3) === 0,\n  (r, c) => (((r * c) % 2) + ((r * c) % 3)) % 2 === 0,\n  (r, c) => (((r + c) % 2) + ((r * c) % 3)) % 2 === 0,\n];\n\n/** The four penalty rules of the standard; the mask with the lowest total wins. */\nfunction penalty(modules: Uint8Array, size: number) {\n  let score = 0;\n  const at = (row: number, col: number) => modules[row * size + col];\n  const lines = (horizontal: boolean) => {\n    for (let a = 0; a < size; a++) {\n      let run = 1;\n      let line = \"0000\";\n      for (let b = 0; b < size; b++) {\n        const value = horizontal ? at(a, b) : at(b, a);\n        line += value;\n        if (b > 0 && value === (horizontal ? at(a, b - 1) : at(b - 1, a))) run++;\n        else {\n          if (run >= 5) score += run - 2;\n          run = 1;\n        }\n      }\n      if (run >= 5) score += run - 2;\n      // A finder look-alike, 1:1:3:1:1, with four light modules on either side (the quiet zone counts as light).\n      line += \"0000\";\n      for (const pattern of [\"00001011101\", \"10111010000\"]) {\n        for (let from = line.indexOf(pattern); from !== -1; from = line.indexOf(pattern, from + 1)) score += 40;\n      }\n    }\n  };\n  lines(true);\n  lines(false);\n  let dark = 0;\n  for (let row = 0; row < size; row++) {\n    for (let col = 0; col < size; col++) {\n      const value = at(row, col);\n      dark += value;\n      if (row < size - 1 && col < size - 1 && value === at(row, col + 1) && value === at(row + 1, col) && value === at(row + 1, col + 1)) score += 3;\n    }\n  }\n  const total = size * size;\n  score += Math.max(0, Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1) * 10;\n  return score;\n}\n\n/** How many data codewords a version holds at a level: the free modules ÷ 8, less the check bytes. */\nconst capacityCache = new Map<string, { total: number; data: number }>();\nfunction capacity(version: number, level: QrLevel) {\n  const key = `${version}${level}`;\n  const cached = capacityCache.get(key);\n  if (cached) return cached;\n  const { fixed } = blankSymbol(version);\n  let free = 0;\n  for (const f of fixed) free += 1 - f;\n  const total = free >> 3;\n  const result = { total, data: total - EC_PER_BLOCK[level][version - 1] * BLOCKS[level][version - 1] };\n  capacityCache.set(key, result);\n  return result;\n}\n\n/** The longest text, in UTF-8 bytes, that fits at a level (version 40). */\nexport const maxBytes = (level: QrLevel) => capacity(40, level).data - 3;\n\n/**\n * Encodes text as a QR code. `minVersion` keeps the symbol at least that size, so a value that grows by a character\n * doesn't change the grid under the viewer. Returns null when the text is too long for any version.\n */\nexport function encodeQr(text: string, level: QrLevel = \"M\", minVersion = 1): QrCode | null {\n  const bytes = new TextEncoder().encode(text);\n  let version = Math.max(1, Math.min(40, Math.floor(minVersion)));\n  for (; version <= 40; version++) {\n    const countBits = version < 10 ? 8 : 16;\n    if (bytes.length < 1 << countBits && 4 + countBits + bytes.length * 8 <= capacity(version, level).data * 8) break;\n  }\n  if (version > 40) return null;\n\n  // The bit stream: byte mode, the length, the bytes, a terminator, then the alternating pad bytes.\n  const { total, data: dataLength } = capacity(version, level);\n  const bits: number[] = [];\n  const push = (value: number, length: number) => {\n    for (let i = length - 1; i >= 0; i--) bits.push((value >> i) & 1);\n  };\n  push(0b0100, 4);\n  push(bytes.length, version < 10 ? 8 : 16);\n  bytes.forEach((byte) => push(byte, 8));\n  push(0, Math.min(4, dataLength * 8 - bits.length));\n  push(0, (8 - (bits.length % 8)) % 8);\n  const data = new Uint8Array(dataLength);\n  for (let i = 0; i < bits.length; i += 8) data[i >> 3] = bits.slice(i, i + 8).reduce((byte, bit) => (byte << 1) | bit, 0);\n  for (let i = bits.length >> 3, pad = 0xec; i < dataLength; i++, pad ^= 0xec ^ 0x11) data[i] = pad;\n\n  // Split into blocks (the short ones first), add each block's check bytes, then interleave column by column.\n  const blockCount = BLOCKS[level][version - 1];\n  const ecLength = EC_PER_BLOCK[level][version - 1];\n  const longBlocks = total % blockCount;\n  const shortData = Math.floor(total / blockCount) - ecLength;\n  const blocks: Uint8Array[] = [];\n  const checks: Uint8Array[] = [];\n  for (let b = 0, at = 0; b < blockCount; b++) {\n    const length = shortData + (b >= blockCount - longBlocks ? 1 : 0);\n    const block = data.subarray(at, at + length);\n    at += length;\n    blocks.push(block);\n    checks.push(checkBytes(block, ecLength));\n  }\n  const stream: number[] = [];\n  for (let i = 0; i <= shortData; i++) blocks.forEach((block) => i < block.length && stream.push(block[i]));\n  for (let i = 0; i < ecLength; i++) checks.forEach((check) => stream.push(check[i]));\n\n  // Place the stream in two-column strips from the bottom right, snaking up and down, around the fixed patterns.\n  const { size, modules, fixed } = blankSymbol(version);\n  const isData = new Uint8Array(size * size);\n  let bit = 0;\n  let upward = true;\n  for (let right = size - 1; right >= 1; right -= 2) {\n    if (right === 6) right = 5; // the vertical timing line takes a whole column\n    for (let step = 0; step < size; step++) {\n      const row = upward ? size - 1 - step : step;\n      for (const col of [right, right - 1]) {\n        const i = row * size + col;\n        if (fixed[i]) continue;\n        isData[i] = 1;\n        const byte = stream[bit >> 3];\n        modules[i] = byte === undefined ? 0 : (byte >> (7 - (bit & 7))) & 1;\n        bit++;\n      }\n    }\n    upward = !upward;\n  }\n\n  // Try all eight masks and keep the one the penalty rules like best.\n  let best: Uint8Array = modules;\n  let bestScore = Infinity;\n  for (let mask = 0; mask < 8; mask++) {\n    const trial = modules.slice();\n    for (let row = 0; row < size; row++) {\n      for (let col = 0; col < size; col++) {\n        const i = row * size + col;\n        if (isData[i] && MASKS[mask](row, col)) trial[i] ^= 1;\n      }\n    }\n    writeFormat(trial, size, level, mask);\n    const score = penalty(trial, size);\n    if (score < bestScore) {\n      best = trial;\n      bestScore = score;\n    }\n  }\n  return { version, size, modules: best, fixed };\n}\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/live-qr. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}