NGU-Web/src/lib/qr.ts
Zaldimmar 2ad65cdc15 Write the site in US English
color, center, canceled, labeled, recognize and the rest, in UI
text, help text, comments, docs and names (ColorInput, QrCenter).
Migration 053 renames the two Site settings color CHECKs, whose
names are the messages the admin shows. Kept: events.status's
stored value 'cancelled' (shown as canceled), aria-labelledby,
schema.org's EventCancelled, and old migrations as they ran.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 13:24:11 -05:00

48 lines
2 KiB
TypeScript

/* ═══════════════════════════════════════════════════════════════
QR CODES
The encoding comes from the `qrcode` package: which modules are
dark, at which error-correction level. Drawing is QrCode.tsx's
job, so the on-screen code, the SVG download and the PNG download
are one picture rather than three renderers that could disagree.
Error correction is the share of the code that can be damaged and
still scan. A logo over the middle is damage, so a code carrying
the dove uses 'H' (about 30% recoverable); a plain one uses 'M',
which keeps it less dense and easier to scan from a distance.
═══════════════════════════════════════════════════════════════ */
import { create } from 'qrcode'
export type QrLevel = 'L' | 'M' | 'Q' | 'H'
export type QrMatrix = {
/** Modules per side, not counting the quiet zone. */
size: number
dark: (row: number, col: number) => boolean
}
export function qrMatrix(text: string, level: QrLevel): QrMatrix {
const { modules } = create(text, { errorCorrectionLevel: level })
return { size: modules.size, dark: (row, col) => modules.get(row, col) === 1 }
}
/* The dark modules as one SVG path, a run of horizontal neighbors
per subpath, offset by the quiet zone. One element instead of a
rect per module keeps the markup (and the SVG download) small. */
export function qrPath(matrix: QrMatrix, margin: number): string {
const parts: string[] = []
for (let row = 0; row < matrix.size; row++) {
let col = 0
while (col < matrix.size) {
if (!matrix.dark(row, col)) {
col++
continue
}
const start = col
while (col < matrix.size && matrix.dark(row, col)) col++
parts.push(`M${start + margin} ${row + margin}h${col - start}v1h-${col - start}z`)
}
}
return parts.join('')
}