# QR code

> A scannable QR code drawn as one server-rendered SVG path, with error correction levels and a readable value.

- Kind: ui · Category: Data display · Interactivity: none
- Install: `npx shadcn@latest add @haze/qr-code`
- File: `src/components/haze/ui/qr-code.astro`
- npm dependencies: none
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/ui/qr-code

## Use when
- A phone should open a link, invoice or pairing URL by scanning the screen
- The code must render without client JavaScript or an image service
- The encoded text must also stay readable for people who cannot scan

## Avoid when
- The payload is longer than a few hundred characters. Link to a short URL instead.
- Users need to copy a link on the same device. Use a plain link or copy-button.

## Alternatives
- [copy-button](https://hazeui.com/ui/copy-button.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| value | `string` | "https://pay.northwind.example/inv/2048" | no | Text to encode as UTF-8 bytes. The smallest version from 1 to 40 that fits is chosen. Over capacity (2953 bytes at L, 1273 at H) throws a build error. |
| level | `"L" \| "M" \| "Q" \| "H"` | "M" | no | Error correction: about 7, 15, 25 or 30 percent of the codewords can be damaged. Higher levels make denser codes. |
| size | `number` | 160 | no | Width and height in px, including the quiet zone. The SVG shrinks to fit narrow containers. |
| label | `string` |  | no | Accessible name. Defaults to "QR code" while the value is printed below, and to "QR code for <value>" when showValue is false. |
| caption | `string` |  | no | Instruction shown under the code, such as what scanning does. |
| showValue | `boolean` | true | no | Show the encoded text under the code so it can be read and copied. |
| class | `string` |  | no | Additional classes on the figure. |

## Accessibility
- The SVG has role img and a label. A QR code is not readable by screen readers, so the encoded value is printed as selectable text by default.
- Modules are always dark on a light panel, in both themes, because many scanners fail on inverted codes. The panel includes the 4-module quiet zone.
- Keep the code at least 120 px wide for phone cameras; raise the level only when the code may be partly covered or worn.

## Agent prompts

### Install and use

Install the Haze UI component "QR code" with `npx shadcn@latest add @haze/qr-code`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import QrCode from "@/components/haze/ui/qr-code.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/qr-code.md

### Customize with real content

Adapt the Haze qr-code ui for our product. Replace the demo values of these props with our real content: value, level, size, label, caption, showValue, class. Keep the layout, the heading level rules and these accessibility details: The SVG has role img and a label. A QR code is not readable by screen readers, so the encoded value is printed as selectable text by default. Modules are always dark on a light panel, in both themes, because many scanners fail on inverted codes. The panel includes the 4-module quiet zone. Keep the code at least 120 px wide for phone cameras; raise the level only when the code may be partly covered or worn. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using qr-code, check it fits: use it when a phone should open a link, invoice or pairing url by scanning the screen; the code must render without client javascript or an image service; the encoded text must also stay readable for people who cannot scan. Avoid it when the payload is longer than a few hundred characters. link to a short url instead.; users need to copy a link on the same device. use a plain link or copy-button.. Alternatives: @haze/copy-button.

## Example requests that should lead here
- Show a QR code for an invoice payment link with the caption Scan to pay and the URL printed below it.

## Source

```astro
---
import { cn } from "../../../lib/haze/utils";

interface Props {
  value?: string;
  level?: "L" | "M" | "Q" | "H";
  size?: number;
  label?: string;
  caption?: string;
  showValue?: boolean;
  class?: string;
}

const {
  value: rawValue = "https://pay.northwind.example/inv/2048",
  level = "M",
  size = 160,
  label,
  caption,
  showValue = true,
  class: className,
} = Astro.props;
// Encode exactly the text shown; a null or number prop would otherwise be coerced to "null" or "42" silently.
if (typeof rawValue !== "string") throw new Error(`QR code: value must be a string, got ${typeof rawValue}.`);
const value = rawValue;

// QR Code encoder, ISO/IEC 18004: byte mode, versions 1-40, levels L/M/Q/H, all 8 masks with penalty scoring.
// Error-correction codewords per block and block counts, indexed [level][version - 1], level order L, M, Q, H.
const EC_PER_BLOCK = [
  [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],
  [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],
  [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],
  [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],
];
const BLOCK_COUNT = [
  [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],
  [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],
  [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],
  [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],
];
const LEVEL_INDEX: Record<string, number> = { L: 0, M: 1, Q: 2, H: 3 };
const LEVEL_BITS = [1, 0, 3, 2];

type Grid = boolean[][];
const makeGrid = (n: number): Grid => Array.from({ length: n }, () => new Array<boolean>(n).fill(false));

// GF(256) with the field polynomial x^8 + x^4 + x^3 + x^2 + 1.
const EXP = new Array<number>(512).fill(0);
const LOG = new Array<number>(256).fill(0);
for (let i = 0, x = 1; i < 255; i++) {
  EXP[i] = x;
  LOG[x] = i;
  x <<= 1;
  if (x & 0x100) x ^= 0x11d;
}
for (let i = 255; i < 512; i++) EXP[i] = EXP[i - 255];
const mul = (a: number, b: number) => (a && b ? EXP[LOG[a] + LOG[b]] : 0);

// Generator polynomial (x - a^0)(x - a^1)...(x - a^(degree-1)), highest power first.
const generator = (degree: number) => {
  let g = [1];
  for (let i = 0; i < degree; i++) {
    const next = new Array<number>(g.length + 1).fill(0);
    g.forEach((c, k) => {
      next[k] ^= c;
      next[k + 1] ^= mul(c, EXP[i]);
    });
    g = next;
  }
  return g;
};
const remainder = (data: number[], degree: number) => {
  const g = generator(degree);
  const rem = new Array<number>(degree).fill(0);
  for (const byte of data) {
    const factor = byte ^ (rem.shift() as number);
    rem.push(0);
    for (let k = 0; k < degree; k++) rem[k] ^= mul(g[k + 1], factor);
  }
  return rem;
};

// BCH check bits: remainder of (data << degree) divided by the generator, which has the given degree.
const bch = (data: number, poly: number, degree: number) => {
  let rem = data << degree;
  for (let i = 31 - Math.clz32(rem); i >= degree; i--) if ((rem >>> i) & 1) rem ^= poly << (i - degree);
  return rem;
};

const alignmentCenters = (version: number) => {
  if (version === 1) return [];
  const count = Math.floor(version / 7) + 2;
  const last = 4 * version + 10;
  const step = version === 32 ? 26 : Math.ceil((last - 6) / (count - 1) / 2) * 2;
  const centers = [6];
  for (let p = last - (count - 2) * step; p <= last; p += step) centers.push(p);
  return centers;
};

// [x, y, bit index] of the two copies of the 15-bit format word and the two copies of the 18-bit version word.
const formatCells = (n: number) => {
  const cells: number[][] = [];
  for (let i = 0; i < 6; i++) cells.push([8, i, i]);
  cells.push([8, 7, 6], [8, 8, 7], [7, 8, 8]);
  for (let i = 9; i < 15; i++) cells.push([14 - i, 8, i]);
  for (let i = 0; i < 8; i++) cells.push([n - 1 - i, 8, i]);
  for (let i = 8; i < 15; i++) cells.push([8, n - 15 + i, i]);
  return cells;
};
const versionCells = (n: number) => {
  const cells: number[][] = [];
  for (let i = 0; i < 18; i++) {
    const a = n - 11 + (i % 3);
    const b = Math.floor(i / 3);
    cells.push([a, b, i], [b, a, i]);
  }
  return cells;
};

// Function patterns of one version: the fixed dark modules, and a mask of every cell that does not carry data.
const functionPatterns = (version: number) => {
  const n = 4 * version + 17;
  const dark = makeGrid(n);
  const fn = makeGrid(n);
  const put = (x: number, y: number, d: boolean) => {
    dark[y][x] = d;
    fn[y][x] = true;
  };
  for (let i = 0; i < n; i++) {
    put(6, i, i % 2 === 0);
    put(i, 6, i % 2 === 0);
  }
  for (const [cx, cy] of [[3, 3], [n - 4, 3], [3, n - 4]]) {
    for (let dy = -4; dy <= 4; dy++) {
      for (let dx = -4; dx <= 4; dx++) {
        const x = cx + dx;
        const y = cy + dy;
        const ring = Math.max(Math.abs(dx), Math.abs(dy));
        if (x >= 0 && y >= 0 && x < n && y < n) put(x, y, ring !== 2 && ring !== 4);
      }
    }
  }
  const centers = alignmentCenters(version);
  const lastCenter = centers.length - 1;
  centers.forEach((cy, i) => centers.forEach((cx, j) => {
    if ((i === 0 && j === 0) || (i === 0 && j === lastCenter) || (i === lastCenter && j === 0)) return;
    for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) put(cx + dx, cy + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);
  }));
  for (const [x, y] of formatCells(n)) put(x, y, false);
  if (version >= 7) for (const [x, y] of versionCells(n)) put(x, y, false);
  put(8, n - 8, true);
  return { n, dark, fn };
};

const patternCache = new Map<number, ReturnType<typeof functionPatterns>>();
const patternsFor = (version: number) => {
  if (!patternCache.has(version)) patternCache.set(version, functionPatterns(version));
  return patternCache.get(version)!;
};
const rawCodewords = (version: number) => {
  const { fn } = patternsFor(version);
  return Math.floor(fn.reduce((sum, row) => sum + row.filter((isFunction) => !isFunction).length, 0) / 8);
};
const dataCodewords = (version: number, lvl: number) =>
  rawCodewords(version) - EC_PER_BLOCK[lvl][version - 1] * BLOCK_COUNT[lvl][version - 1];

const maskTest = [
  (i: number, j: number) => (i + j) % 2 === 0,
  (i: number) => i % 2 === 0,
  (_i: number, j: number) => j % 3 === 0,
  (i: number, j: number) => (i + j) % 3 === 0,
  (i: number, j: number) => (Math.floor(i / 2) + Math.floor(j / 3)) % 2 === 0,
  (i: number, j: number) => ((i * j) % 2) + ((i * j) % 3) === 0,
  (i: number, j: number) => (((i * j) % 2) + ((i * j) % 3)) % 2 === 0,
  (i: number, j: number) => (((i + j) % 2) + ((i * j) % 3)) % 2 === 0,
];

// The four penalty rules: runs of five or more, 2x2 blocks, finder-like patterns, dark/light balance.
const penalty = (m: Grid) => {
  const n = m.length;
  let score = 0;
  for (let pass = 0; pass < 2; pass++) {
    const cell = (a: number, b: number) => (pass === 0 ? m[a][b] : m[b][a]);
    for (let a = 0; a < n; a++) {
      let run = 1;
      for (let b = 1; b <= n; b++) {
        if (b < n && cell(a, b) === cell(a, b - 1)) run++;
        else {
          if (run >= 5) score += run - 2;
          run = 1;
        }
      }
      for (let b = 0; b + 11 <= n; b++) {
        const window = Array.from({ length: 11 }, (_, k) => (cell(a, b + k) ? 1 : 0)).join("");
        if (window === "10111010000" || window === "00001011101") score += 40;
      }
    }
  }
  let dark = 0;
  for (let y = 0; y < n; y++) {
    for (let x = 0; x < n; x++) {
      if (m[y][x]) dark++;
      if (x + 1 < n && y + 1 < n && m[y][x] === m[y][x + 1] && m[y][x] === m[y + 1][x] && m[y][x] === m[y + 1][x + 1]) score += 3;
    }
  }
  return score + 10 * Math.floor(Math.abs((dark * 100) / (n * n) - 50) / 5);
};

const encode = (text: string, levelName: string) => {
  const lvl = LEVEL_INDEX[levelName];
  if (lvl === undefined) throw new Error(`QR code: level must be L, M, Q or H, got "${levelName}".`);
  const bytes = Array.from(new TextEncoder().encode(text));
  let version = 0;
  for (let v = 1; v <= 40 && !version; v++) {
    if (4 + (v < 10 ? 8 : 16) + 8 * bytes.length <= 8 * dataCodewords(v, lvl)) version = v;
  }
  if (!version) {
    const max = dataCodewords(40, lvl) - 3;
    throw new Error(`QR code: the value is ${bytes.length} bytes, over the ${max}-byte limit of version 40 at level ${levelName}. Shorten it or use a lower level.`);
  }

  // Bit stream: mode 0100, character count, bytes, terminator, byte padding, pad codewords 0xEC and 0x11.
  const bits: number[] = [];
  const push = (v: number, count: number) => { for (let i = count - 1; i >= 0; i--) bits.push((v >>> i) & 1); };
  push(0b0100, 4);
  push(bytes.length, version < 10 ? 8 : 16);
  bytes.forEach((b) => push(b, 8));
  const capacity = 8 * dataCodewords(version, lvl);
  push(0, Math.min(4, capacity - bits.length));
  push(0, (8 - (bits.length % 8)) % 8);
  for (let pad = 0xec; bits.length < capacity; pad ^= 0xec ^ 0x11) push(pad, 8);
  const data: number[] = [];
  for (let i = 0; i < bits.length; i += 8) data.push(parseInt(bits.slice(i, i + 8).join(""), 2));

  // Split into blocks (the shorter ones first), add Reed-Solomon codewords, interleave.
  const blocks = BLOCK_COUNT[lvl][version - 1];
  const ecLen = EC_PER_BLOCK[lvl][version - 1];
  const total = rawCodewords(version);
  const shortBlocks = blocks - (total % blocks);
  const shortData = Math.floor(total / blocks) - ecLen;
  const dataBlocks: number[][] = [];
  let from = 0;
  for (let b = 0; b < blocks; b++) {
    const len = shortData + (b < shortBlocks ? 0 : 1);
    dataBlocks.push(data.slice(from, from + len));
    from += len;
  }
  const ecBlocks = dataBlocks.map((block) => remainder(block, ecLen));
  const stream: number[] = [];
  for (let i = 0; i <= shortData; i++) dataBlocks.forEach((block) => { if (i < block.length) stream.push(block[i]); });
  for (let i = 0; i < ecLen; i++) ecBlocks.forEach((block) => stream.push(block[i]));
  const streamBits = stream.flatMap((byte) => Array.from({ length: 8 }, (_, k) => ((byte >>> (7 - k)) & 1) === 1));

  // Place the bits in the two-column zigzag (right to left, skipping the timing column), then try all eight masks.
  const { n, dark, fn } = patternsFor(version);
  const placed = dark.map((row) => row.slice());
  let index = 0;
  let upward = true;
  for (let right = n - 1; right >= 1; right -= 2) {
    if (right === 6) right = 5;
    for (let step = 0; step < n; step++) {
      const y = upward ? n - 1 - step : step;
      for (const x of [right, right - 1]) if (!fn[y][x]) placed[y][x] = streamBits[index++] ?? false;
    }
    upward = !upward;
  }
  let best: Grid = placed;
  let bestScore = Infinity;
  for (let mask = 0; mask < 8; mask++) {
    const m = placed.map((row) => row.slice());
    for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) if (!fn[y][x] && maskTest[mask](y, x)) m[y][x] = !m[y][x];
    const format = (LEVEL_BITS[lvl] << 3) | mask;
    const formatWord = ((format << 10) | bch(format, 0x537, 10)) ^ 0x5412;
    for (const [x, y, i] of formatCells(n)) m[y][x] = ((formatWord >>> i) & 1) === 1;
    if (version >= 7) {
      const versionWord = (version << 12) | bch(version, 0x1f25, 12);
      for (const [x, y, i] of versionCells(n)) m[y][x] = ((versionWord >>> i) & 1) === 1;
    }
    const score = penalty(m);
    if (score < bestScore) {
      bestScore = score;
      best = m;
    }
  }
  return { modules: best, version };
};

const { modules, version } = encode(value, level);
const quiet = 4;
const span = modules.length + quiet * 2;
const runs: string[] = [];
modules.forEach((row, y) => {
  for (let x = 0; x < row.length; x++) {
    if (!row[x]) continue;
    let end = x;
    while (end + 1 < row.length && row[end + 1]) end++;
    runs.push(`M${x + quiet} ${y + quiet}h${end - x + 1}v1h-${end - x + 1}z`);
    x = end;
  }
});
const path = runs.join("");
// When the value is printed below, the name stays short so a screen reader does not read the value twice.
const accessibleName = label ?? (showValue || !value ? "QR code" : `QR code for ${value}`);
---

<figure class={cn("grid w-fit max-w-full justify-items-center gap-3 text-center", className)} data-qr-version={version}>
  {/* data-theme="light" pins the panel and modules to the light token set, so the code is dark on light in every theme and inside nested theme scopes. Scanners often fail on inverted codes. */}
  <svg data-theme="light" role="img" aria-label={accessibleName} viewBox={`0 0 ${span} ${span}`} width={size} height={size} shape-rendering="crispEdges"
    class="h-auto max-w-full rounded-lg bg-background inset-ring inset-ring-border">
    <path d={path} class="fill-foreground" />
  </svg>
  {(caption || showValue) && (
    <figcaption class="grid max-w-full gap-1">
      {caption && <span class="wrap-anywhere text-[0.8125rem]/5 font-medium">{caption}</span>}
      {showValue && <span class="wrap-anywhere text-xs/4 text-muted-foreground select-all">{value}</span>}
    </figcaption>
  )}
</figure>
```
