{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "qr-code",
  "type": "registry:ui",
  "title": "Qr Code",
  "description": "A QR code for a link or a short text, drawn as one SVG path from the pure encoder in `qr-model.ts`. No dependency, no canvas, no image request: it renders on the server and stays sharp at any size, from a phone card to a projector.",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "games",
    "game"
  ],
  "dependencies": [],
  "registryDependencies": [
    "https://ds.interlace.tools/r/interlace-base.json",
    "https://ds.interlace.tools/r/cn.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/games/qr-code.tsx",
      "target": "components/ui/games/qr-code.tsx",
      "type": "registry:ui",
      "content": "import * as React from 'react';\n\n// @interlace/qr-code v1.0.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/qr-code\n// What changed since: https://ds.interlace.tools/c/qr-code#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — QrCode\n *\n * A QR code for a link or a short text, drawn as one SVG path from the pure\n * encoder in `qr-model.ts`. No dependency, no canvas, no image request: it\n * renders on the server and stays sharp at any size, from a phone card to a\n * projector.\n *\n * ## Anatomy\n *\n *   QrCode                         (div — data-slot=\"qr-code\", data-scheme, data-state)\n *     └─ svg role=\"img\"            (data-slot=\"qr-code-svg\", named by `label`)\n *         ├─ rect                  (quiet zone, the background token)\n *         └─ path                  (dark modules, the foreground token)\n *\n * ## Contrast\n *\n * Phone cameras read dark modules on a light ground most reliably, so the\n * code keeps the light scheme on a dark page (`scheme=\"light\"`, the default)\n * through `data-scheme`, and the brand's own light background and\n * foreground tokens draw it. `scheme=\"inherit\"` follows the page instead.\n * The four-module quiet zone is part of the code; leave `margin` at 4 unless\n * the code sits on a plain light surface already.\n *\n * ## Server first\n *\n * No hooks: the matrix is computed while rendering.\n *\n * ## Too long\n *\n * A QR code holds at most 2,953 bytes (version 40, level L), fewer at higher\n * error correction. A longer `value` does not throw: the box keeps its size\n * and label, carries `data-state=\"too-long\"`, and draws no code. Keep links\n * short; a join link is well under 100 bytes.\n *\n * ## MIN_VIEWPORT — 320\n *\n * | Rule | Concept                   | Where in this file                         |\n * | ---- | ------------------------- | ------------------------------------------ |\n * | R4   | Extends native el         | `React.ComponentProps<'div'>`              |\n * | R6   | data-slot per part        | qr-code / -svg                              |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`          |\n * | R8   | Enums, not booleans       | `size`, `scheme`, `errorCorrection`        |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const       |\n * | R19  | Tokens only               | background, foreground                     |\n * | R26  | A11y                      | role=\"img\" named by `label`                 |\n */\n\nimport { cn } from '@/lib/utils';\nimport { encodeQr, qrPath, type QrErrorCorrection } from '@/components/ui/games/qr-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\nconst SIZE = {\n  sm: 'w-24',\n  default: 'w-40',\n  lg: 'w-56',\n  /** Fills its container: for a big screen, size the parent. */\n  fill: 'w-full',\n} as const;\n\ntype QrCodeProps = Omit<React.ComponentProps<'div'>, 'children'> & {\n  /** What the code holds, usually a join link. Too long to encode renders an empty box (see \"Too long\"). */\n  value: string;\n  /** Names the code for assistive tech, e.g. \"QR code to join the room\". */\n  label: string;\n  /** @default 'default' */\n  size?: keyof typeof SIZE;\n  /** @default 'M' */\n  errorCorrection?: QrErrorCorrection;\n  /** Quiet zone, in modules. @default 4 */\n  margin?: number;\n  /** Keep the light scheme on a dark page, so every camera reads it. @default 'light' */\n  scheme?: 'light' | 'inherit';\n};\n\nfunction QrCode({\n  value,\n  label,\n  size = 'default',\n  errorCorrection = 'M',\n  margin = 4,\n  scheme = 'light',\n  className,\n  ...props\n}: QrCodeProps) {\n  let matrix: ReturnType<typeof encodeQr> | null = null;\n  try {\n    matrix = encodeQr(value, { errorCorrection });\n  } catch {\n    matrix = null;\n  }\n  const m = Math.max(0, Math.round(margin));\n  const side = (matrix?.size ?? 21) + m * 2;\n  return (\n    <div\n      data-slot=\"qr-code\"\n      data-state={matrix ? undefined : 'too-long'}\n      data-scheme={scheme === 'light' ? 'light' : undefined}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('bg-background text-foreground inline-block max-w-full shrink-0 rounded-lg', SIZE[size], className)}\n      {...props}\n    >\n      <svg\n        data-slot=\"qr-code-svg\"\n        role=\"img\"\n        aria-label={label}\n        viewBox={`0 0 ${side} ${side}`}\n        shapeRendering=\"crispEdges\"\n        className=\"block h-auto w-full\"\n      >\n        <rect width={side} height={side} className=\"fill-background\" />\n        {matrix && <path d={qrPath(matrix, m)} className=\"fill-current\" />}\n      </svg>\n    </div>\n  );\n}\nQrCode.displayName = 'QrCode';\n\nexport { QrCode };\nexport type { QrCodeProps };\n"
    },
    {
      "path": "registry/interlace-ui/games/qr-model.ts",
      "target": "components/ui/games/qr-model.ts",
      "type": "registry:ui",
      "content": "export type QrErrorCorrection = 'L' | 'M' | 'Q' | 'H';\n\nexport interface QrMatrix {\n  /** Modules per side, without the quiet zone. */\n  size: number;\n  /** 1 to 40. */\n  version: number;\n  errorCorrection: QrErrorCorrection;\n  /** The mask the encoder chose, 0 to 7. */\n  mask: number;\n  /** `modules[y][x]` is true for a dark module. */\n  modules: boolean[][];\n}\n\nexport interface EncodeQrOptions {\n  /** How much damage the code survives: L 7%, M 15%, Q 25%, H 30%. @default 'M' */\n  errorCorrection?: QrErrorCorrection;\n  /** The smallest version to use. @default 1 */\n  minVersion?: number;\n}\n\n// Indexed by level, then version (index 0 unused). From the standard's table 9.\nconst LEVEL_INDEX: Record<QrErrorCorrection, number> = {\n  L: 0,\n  M: 1,\n  Q: 2,\n  H: 3,\n};\nconst FORMAT_BITS: Record<QrErrorCorrection, number> = {\n  L: 1,\n  M: 0,\n  Q: 3,\n  H: 2,\n};\n\nconst ECC_PER_BLOCK: readonly (readonly number[])[] = [\n  [\n    -1, 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,\n    30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,\n  ],\n  [\n    -1, 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,\n    28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,\n  ],\n  [\n    -1, 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,\n    30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,\n  ],\n  [\n    -1, 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,\n    30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,\n  ],\n];\n\nconst BLOCKS: readonly (readonly number[])[] = [\n  [\n    -1, 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,\n    19, 20, 21, 22, 24, 25,\n  ],\n  [\n    -1, 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,\n    33, 35, 37, 38, 40, 43, 45, 47, 49,\n  ],\n  [\n    -1, 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,\n    45, 48, 51, 53, 56, 59, 62, 65, 68,\n  ],\n  [\n    -1, 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,\n    51, 54, 57, 60, 63, 66, 70, 74, 77, 81,\n  ],\n];\n\n/** Bits available for data and error correction in a version. */\nfunction rawModules(version: number): number {\n  let n = (16 * version + 128) * version + 64;\n  if (version >= 2) {\n    const align = Math.floor(version / 7) + 2;\n    n -= (25 * align - 10) * align - 55;\n    if (version >= 7) n -= 36;\n  }\n  return n;\n}\n\nfunction dataCodewords(version: number, level: QrErrorCorrection): number {\n  const l = LEVEL_INDEX[level];\n  return Math.floor(rawModules(version) / 8) - ECC_PER_BLOCK[l]![version]! * BLOCKS[l]![version]!;\n}\n\n/** Byte-mode capacity in bytes, for a version and level. */\nexport function qrCapacity(version: number, level: QrErrorCorrection = 'M'): number {\n  const countBits = version <= 9 ? 8 : 16;\n  return Math.floor((dataCodewords(version, level) * 8 - 4 - countBits) / 8);\n}\n\n// --- Reed-Solomon over GF(2^8), polynomial 0x11D ------------------------------\n\nfunction gfMul(x: number, y: number): number {\n  let z = 0;\n  for (let i = 7; i >= 0; i--) {\n    z = (z << 1) ^ ((z >>> 7) * 0x11d);\n    z ^= ((y >>> i) & 1) * x;\n  }\n  return z & 0xff;\n}\n\nfunction rsDivisor(degree: number): number[] {\n  const result: number[] = Array.from({ length: degree }, () => 0);\n  result[degree - 1] = 1;\n  let root = 1;\n  for (let i = 0; i < degree; i++) {\n    for (let j = 0; j < degree; j++) {\n      result[j] = gfMul(result[j]!, root);\n      if (j + 1 < degree) result[j] = result[j]! ^ result[j + 1]!;\n    }\n    root = gfMul(root, 0x02);\n  }\n  return result;\n}\n\nfunction rsRemainder(data: readonly number[], divisor: readonly number[]): number[] {\n  const result: number[] = Array.from({ length: divisor.length }, () => 0);\n  for (const b of data) {\n    const factor = b ^ result.shift()!;\n    result.push(0);\n    divisor.forEach((d, i) => {\n      result[i] = result[i]! ^ gfMul(d, factor);\n    });\n  }\n  return result;\n}\n\n// --- Data ---------------------------------------------------------------------\n\nfunction dataWithEcc(bytes: readonly number[], version: number, level: QrErrorCorrection): number[] {\n  const bits: number[] = [];\n  const put = (value: number, length: number) => {\n    for (let i = length - 1; i >= 0; i--) bits.push((value >>> i) & 1);\n  };\n  put(0b0100, 4); // byte mode\n  put(bytes.length, version <= 9 ? 8 : 16);\n  for (const b of bytes) put(b, 8);\n\n  const capacityBits = dataCodewords(version, level) * 8;\n  put(0, Math.min(4, capacityBits - bits.length));\n  put(0, (8 - (bits.length % 8)) % 8);\n  for (let pad = 0xec; bits.length < capacityBits; pad ^= 0xec ^ 0x11) put(pad, 8);\n\n  const data: number[] = [];\n  for (let i = 0; i < bits.length; i += 8) {\n    let byte = 0;\n    for (let j = 0; j < 8; j++) byte = (byte << 1) | bits[i + j]!;\n    data.push(byte);\n  }\n\n  const l = LEVEL_INDEX[level];\n  const blockCount = BLOCKS[l]![version]!;\n  const eccLength = ECC_PER_BLOCK[l]![version]!;\n  const raw = Math.floor(rawModules(version) / 8);\n  const shortBlocks = blockCount - (raw % blockCount);\n  const shortLength = Math.floor(raw / blockCount);\n  const divisor = rsDivisor(eccLength);\n\n  const blocks: number[][] = [];\n  for (let i = 0, k = 0; i < blockCount; i++) {\n    const length = shortLength - eccLength + (i < shortBlocks ? 0 : 1);\n    const block = data.slice(k, k + length);\n    k += length;\n    const ecc = rsRemainder(block, divisor);\n    if (i < shortBlocks) block.push(0); // placeholder, skipped when interleaving\n    blocks.push(block.concat(ecc));\n  }\n\n  const out: number[] = [];\n  for (let i = 0; i < blocks[0]!.length; i++) {\n    blocks.forEach((block, j) => {\n      if (i !== shortLength - eccLength || j >= shortBlocks) out.push(block[i]!);\n    });\n  }\n  return out;\n}\n\n// --- Matrix -------------------------------------------------------------------\n\nfunction alignmentPositions(version: number): number[] {\n  if (version === 1) return [];\n  const count = Math.floor(version / 7) + 2;\n  const step = version === 32 ? 26 : Math.ceil((version * 4 + 4) / (count * 2 - 2)) * 2;\n  const result = [6];\n  for (let pos = version * 4 + 10; result.length < count; pos -= step) result.splice(1, 0, pos);\n  return result;\n}\n\nconst MASKS: readonly ((x: number, y: number) => boolean)[] = [\n  (x, y) => (x + y) % 2 === 0,\n  (_x, y) => y % 2 === 0,\n  (x) => x % 3 === 0,\n  (x, y) => (x + y) % 3 === 0,\n  (x, y) => (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0,\n  (x, y) => ((x * y) % 2) + ((x * y) % 3) === 0,\n  (x, y) => (((x * y) % 2) + ((x * y) % 3)) % 2 === 0,\n  (x, y) => (((x + y) % 2) + ((x * y) % 3)) % 2 === 0,\n];\n\nclass Grid {\n  readonly modules: boolean[][];\n  readonly fixed: boolean[][];\n  constructor(readonly size: number) {\n    this.modules = Array.from({ length: size }, () => Array.from({ length: size }, () => false));\n    this.fixed = Array.from({ length: size }, () => Array.from({ length: size }, () => false));\n  }\n  set(x: number, y: number, dark: boolean) {\n    this.modules[y]![x] = dark;\n    this.fixed[y]![x] = true;\n  }\n}\n\nfunction drawFunctionPatterns(g: Grid, version: number) {\n  const { size } = g;\n  for (let i = 0; i < size; i++) {\n    g.set(6, i, i % 2 === 0);\n    g.set(i, 6, i % 2 === 0);\n  }\n  const finder = (cx: number, cy: number) => {\n    for (let dy = -4; dy <= 4; dy++) {\n      for (let dx = -4; dx <= 4; dx++) {\n        const x = cx + dx;\n        const y = cy + dy;\n        if (x < 0 || y < 0 || x >= size || y >= size) continue;\n        const d = Math.max(Math.abs(dx), Math.abs(dy));\n        g.set(x, y, d !== 2 && d !== 4);\n      }\n    }\n  };\n  finder(3, 3);\n  finder(size - 4, 3);\n  finder(3, size - 4);\n\n  const align = alignmentPositions(version);\n  const n = align.length;\n  for (let i = 0; i < n; i++) {\n    for (let j = 0; j < n; j++) {\n      if ((i === 0 && j === 0) || (i === 0 && j === n - 1) || (i === n - 1 && j === 0)) continue;\n      for (let dy = -2; dy <= 2; dy++) {\n        for (let dx = -2; dx <= 2; dx++) {\n          g.set(align[i]! + dx, align[j]! + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);\n        }\n      }\n    }\n  }\n\n  if (version >= 7) {\n    let rem = version;\n    for (let i = 0; i < 12; i++) rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25);\n    const bits = (version << 12) | rem;\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      g.set(a, b, dark);\n      g.set(b, a, dark);\n    }\n  }\n}\n\nfunction drawFormat(g: Grid, level: QrErrorCorrection, mask: number) {\n  const data = (FORMAT_BITS[level] << 3) | mask;\n  let rem = data;\n  for (let i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537);\n  const bits = ((data << 10) | rem) ^ 0x5412;\n  const bit = (i: number) => ((bits >>> i) & 1) === 1;\n  const { size } = g;\n\n  for (let i = 0; i <= 5; i++) g.set(8, i, bit(i));\n  g.set(8, 7, bit(6));\n  g.set(8, 8, bit(7));\n  g.set(7, 8, bit(8));\n  for (let i = 9; i < 15; i++) g.set(14 - i, 8, bit(i));\n\n  for (let i = 0; i < 8; i++) g.set(size - 1 - i, 8, bit(i));\n  for (let i = 8; i < 15; i++) g.set(8, size - 15 + i, bit(i));\n  g.set(8, size - 8, true);\n}\n\nfunction drawData(g: Grid, codewords: readonly number[]) {\n  const { size } = g;\n  let i = 0;\n  for (let right = size - 1; right >= 1; right -= 2) {\n    if (right === 6) right = 5;\n    for (let vert = 0; vert < size; vert++) {\n      for (let j = 0; j < 2; j++) {\n        const x = right - j;\n        const upward = ((right + 1) & 2) === 0;\n        const y = upward ? size - 1 - vert : vert;\n        if (g.fixed[y]![x] || i >= codewords.length * 8) continue;\n        g.modules[y]![x] = ((codewords[i >>> 3]! >>> (7 - (i & 7))) & 1) === 1;\n        i++;\n      }\n    }\n  }\n}\n\nfunction applyMask(g: Grid, mask: number) {\n  const fn = MASKS[mask]!;\n  for (let y = 0; y < g.size; y++) {\n    for (let x = 0; x < g.size; x++) {\n      if (!g.fixed[y]![x] && fn(x, y)) g.modules[y]![x] = !g.modules[y]![x];\n    }\n  }\n}\n\nconst FINDER_LIKE = [\n  [true, false, true, true, true, false, true, false, false, false, false],\n  [false, false, false, false, true, false, true, true, true, false, true],\n] as const;\n\n/** The standard's four penalty rules; the mask with the lowest score wins. */\nfunction penalty(modules: readonly (readonly boolean[])[]): number {\n  const size = modules.length;\n  let score = 0;\n  const line = (get: (i: number) => boolean) => {\n    let run = 1;\n    for (let i = 1; i <= size; i++) {\n      if (i < size && get(i) === get(i - 1)) run++;\n      else {\n        if (run >= 5) score += 3 + (run - 5);\n        run = 1;\n      }\n    }\n    for (let i = 0; i + 11 <= size; i++) {\n      for (const pattern of FINDER_LIKE) {\n        if (pattern.every((dark, k) => get(i + k) === dark)) score += 40;\n      }\n    }\n  };\n  for (let y = 0; y < size; y++) line((x) => modules[y]![x]!);\n  for (let x = 0; x < size; x++) line((y) => modules[y]![x]!);\n\n  for (let y = 0; y < size - 1; y++) {\n    for (let x = 0; x < size - 1; x++) {\n      const c = modules[y]![x];\n      if (c === modules[y]![x + 1] && c === modules[y + 1]![x] && c === modules[y + 1]![x + 1]) score += 3;\n    }\n  }\n\n  let dark = 0;\n  for (const row of modules) for (const m of row) if (m) dark++;\n  const total = size * size;\n  score += (Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1) * 10;\n  return score;\n}\n\n/**\n * Encode text as a QR code. Throws a RangeError when the text does not fit\n * a version-40 code at the chosen level.\n */\nexport function encodeQr(text: string, options: EncodeQrOptions = {}): QrMatrix {\n  const errorCorrection = options.errorCorrection ?? 'M';\n  const bytes = Array.from(new TextEncoder().encode(text));\n  let version = Math.max(1, Math.min(40, Math.floor(options.minVersion ?? 1)));\n  while (version <= 40 && qrCapacity(version, errorCorrection) < bytes.length) version++;\n  if (version > 40) throw new RangeError(`Text is too long for a QR code (${bytes.length} bytes).`);\n\n  const codewords = dataWithEcc(bytes, version, errorCorrection);\n  const size = version * 4 + 17;\n\n  let best: { mask: number; modules: boolean[][]; score: number } | null = null;\n  for (let mask = 0; mask < 8; mask++) {\n    const g = new Grid(size);\n    drawFunctionPatterns(g, version);\n    drawFormat(g, errorCorrection, mask); // reserves the format areas before data\n    drawData(g, codewords);\n    applyMask(g, mask);\n    const score = penalty(g.modules);\n    if (!best || score < best.score) best = { mask, modules: g.modules, score };\n  }\n\n  return {\n    size,\n    version,\n    errorCorrection,\n    mask: best!.mask,\n    modules: best!.modules,\n  };\n}\n\n/**\n * One SVG path for the dark modules, as horizontal runs, offset by a quiet\n * zone of `margin` modules. Draw it in a `0 0 size+2m size+2m` viewBox.\n */\nexport function qrPath(matrix: Pick<QrMatrix, 'size' | 'modules'>, margin = 4): string {\n  const parts: string[] = [];\n  matrix.modules.forEach((row, y) => {\n    let x = 0;\n    while (x < matrix.size) {\n      if (!row[x]) {\n        x++;\n        continue;\n      }\n      const start = x;\n      while (x < matrix.size && row[x]) x++;\n      parts.push(`M${start + margin} ${y + margin}h${x - start}v1h${start - x}z`);\n    }\n  });\n  return parts.join('');\n}\n\n/**\n * @interlace/ui — games/qr-model\n *\n * A QR code encoder with no dependencies, so a join link turns into a code\n * on the server, in a worker or in the browser, and the same text always\n * gives the same matrix. It follows ISO/IEC 18004: byte mode (UTF-8),\n * versions 1 to 40, the four error-correction levels, and the mask with the\n * lowest penalty score.\n *\n * `encodeQr` returns the matrix; `qrPath` turns it into one SVG path, so a\n * renderer draws it with a single element.\n */\n"
    }
  ],
  "meta": {
    "tier": "game",
    "client": false,
    "minViewport": 320,
    "loading": false,
    "version": "1.0.0",
    "since": "2.0.0"
  },
  "docs": "## @interlace/qr-code\n\nInstalled to `components/ui/games/qr-code.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/games/qr-code';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/qr-code\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
