仰望星辰工作室

miaopanel

miaopanel/ web/src/qr.ts 2.2 KB · 68 行 原始文件
1// QR encoding helpers shared by the login page.
2//
3// The heavy lifting lives in qrcode-generator (MIT, Kazuhiko Arase); this
4// module only turns its module grid into a compact SVG path and keeps the
5// rendering math testable outside of Vue.
6import qrcode from 'qrcode-generator'
7
8export type QrLevel = 'L' | 'M' | 'Q' | 'H'
9
10export interface QrMatrix {
11 /** Number of modules per side, excluding the quiet zone. */
12 count: number
13 /** Row major grid, `true` means a dark module. */
14 modules: boolean[][]
15}
16
17/** Encodes text, returning null when the payload cannot be encoded. */
18export function qrMatrix(text: string, level: QrLevel = 'M'): QrMatrix | null {
19 if (!text) return null
20 try {
21 const qr = qrcode(0, level)
22 qr.addData(text)
23 qr.make()
24 const count = qr.getModuleCount()
25 const modules: boolean[][] = []
26 for (let row = 0; row < count; row++) {
27 const line: boolean[] = []
28 for (let col = 0; col < count; col++) line.push(qr.isDark(row, col))
29 modules.push(line)
30 }
31 return { count, modules }
32 } catch {
33 return null
34 }
35}
36
37/**
38 * Builds one SVG path for the whole symbol. Horizontal runs are merged so the
39 * DOM stays small, and every rectangle lands on whole module coordinates.
40 */
41export function qrPath(matrix: QrMatrix, margin = 3): { size: number; path: string } {
42 const parts: string[] = []
43 for (let row = 0; row < matrix.count; row++) {
44 let col = 0
45 while (col < matrix.count) {
46 if (!matrix.modules[row][col]) {
47 col++
48 continue
49 }
50 let run = 1
51 while (col + run < matrix.count && matrix.modules[row][col + run]) run++
52 const x = col + margin
53 const y = row + margin
54 parts.push(`M${x} ${y}h${run}v1h-${run}z`)
55 col += run
56 }
57 }
58 return { size: matrix.count + margin * 2, path: parts.join('') }
59}
60
61/**
62 * Integer pixel size per module. Rendering each module on a whole number of
63 * device independent pixels is what keeps the symbol crisp on every zoom level;
64 * the callers size the frame from the result, so the symbol is never clipped.
65 */
66export function qrCellSize(size: number, count: number): number {
67 return Math.max(2, Math.round(size / Math.max(1, count)))
68}