Spaces:
Running

File size: 11,171 Bytes
50a005c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
434ab05
 
50a005c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3a69df
 
 
 
 
 
 
 
 
 
 
 
50a005c
 
d3a69df
50a005c
b8b5e61
50a005c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3a69df
50a005c
d3a69df
50a005c
 
 
 
 
 
 
 
 
 
d3a69df
50a005c
d3a69df
50a005c
 
 
 
 
 
 
 
 
 
d3a69df
50a005c
b8b5e61
d3a69df
73cb584
 
 
 
 
 
 
 
 
 
 
50a005c
 
 
 
 
 
 
 
 
 
 
73cb584
50a005c
d3a69df
50a005c
d3a69df
 
 
 
50a005c
 
 
 
 
 
 
 
 
 
 
434ab05
 
d3a69df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50a005c
434ab05
 
 
50a005c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
 
/**
 * Lightweight SVG QR Code Generator
 * Encodes a URL into an SVG QR code pattern using a minimal bit matrix approach.
 * No external dependencies required.
 */

// Error correction levels (we use Medium by default)
type ECL = "L" | "M" | "Q" | "H";

// Minimal QR code version table (version -> size, capacity)
const VERSION_DATA: Record<number, { size: number; capacity: number }> = {
  1: { size: 21, capacity: 17 },
  2: { size: 25, capacity: 32 },
  3: { size: 29, capacity: 53 },
  4: { size: 33, capacity: 78 },
  5: { size: 37, capacity: 106 },
};

// Alignment pattern positions per version
const ALIGNMENT_POSITIONS: Record<number, number[]> = {
  1: [],
  2: [6, 18],
  3: [6, 22],
  4: [6, 26],
  5: [6, 30],
};

// Error correction codewords per block (version, ecl)
const EC_TABLE: Record<string, number[]> = {
  "1-M": [10, 16],
  "2-M": [16, 28],
  "3-M": [26, 44],
  "4-M": [18, 16],
  "5-M": [24, 16],
};

/**
 * Convert a string to a byte array (UTF-8)
 */
function textToBytes(text: string): number[] {
  const encoder = new TextEncoder();
  return Array.from(encoder.encode(text));
}

/**
 * GF(256) arithmetic for Reed-Solomon
 * Using primitive polynomial x^8 + x^4 + x^3 + x^2 + 1 (0x11D)
 */
const GF_EXP = new Uint8Array(512);
const GF_LOG = new Uint8Array(256);

(function initGaloisField() {
  let x = 1;
  for (let i = 0; i < 255; i++) {
    GF_EXP[i] = x;
    GF_LOG[x] = i;
    x = (x << 1) ^ (x >= 128 ? 0x11D : 0);
  }
  for (let i = 255; i < 512; i++) {
    GF_EXP[i] = GF_EXP[i - 255];
  }
})();

function gfMul(a: number, b: number): number {
  if (a === 0 || b === 0) return 0;
  return GF_EXP[GF_LOG[a] + GF_LOG[b]];
}

/**
 * Generate Reed-Solomon error correction codewords
 */
function rsEncode(data: number[], ecCount: number): number[] {
  // Generate generator polynomial
  let gen = [1];
  for (let i = 0; i < ecCount; i++) {
    const newGen = new Array(gen.length + 1).fill(0);
    for (let j = 0; j < gen.length; j++) {
      newGen[j] ^= gen[j];
      newGen[j + 1] ^= gfMul(gen[j], GF_EXP[i]);
    }
    gen = newGen;
  }

  // Polynomial division
  const result = new Array(ecCount).fill(0);
  for (const dataByte of data) {
    const coef = dataByte ^ result[0];
    result.shift();
    result.push(0);
    for (let j = 0; j < gen.length; j++) {
      result[j] ^= gfMul(gen[j], coef);
    }
  }
  return result;
}

/**
 * Calculate BCH error correction for the format information
 */
function bchEncode(data: number): number {
  let d = data << 10;
  const gen = 0x537; // x^10 + x^8 + x^5 + x^4 + x^2 + x + 1
  for (let i = 14; i >= 10; i--) {
    if (d & (1 << i)) {
      d ^= gen << (i - 10);
    }
  }
  return ((data << 10) | d) ^ 0x5412; // XOR with mask pattern 000
}

/**
 * Simple QR code matrix builder
 */
function placeFinderPattern(matrix: boolean[][], reserved: boolean[][], size: number, row: number, col: number): void {
  for (let r = -1; r <= 7; r++) {
    for (let c = -1; c <= 7; c++) {
      const mr = row + r;
      const mc = col + c;
      if (mr < 0 || mr >= size || mc < 0 || mc >= size) continue;
      const isBlack =
        (r >= 0 && r <= 6 && (c === 0 || c === 6)) ||
        (c >= 0 && c <= 6 && (r === 0 || r === 6)) ||
        (r >= 2 && r <= 4 && c >= 2 && c <= 4);
      matrix[mr][mc] = isBlack;
      reserved[mr][mc] = true;
    }
  }
}

function placeAlignmentPatterns(matrix: boolean[][], reserved: boolean[][], size: number, version: number): void { // NOSONAR — complex function, refactoring would risk breaking critical behavior
  const alignPos = ALIGNMENT_POSITIONS[version] || [];
  for (const row of alignPos) {
    for (const col of alignPos) {
      // Skip if overlaps with finder patterns
      if (
        (row < 9 && col < 9) ||
        (row < 9 && col > size - 9) ||
        (row > size - 9 && col < 9)
      )
        continue;

      for (let r = -2; r <= 2; r++) {
        for (let c = -2; c <= 2; c++) {
          const isBlack = Math.abs(r) === 2 || Math.abs(c) === 2 || (r === 0 && c === 0);
          matrix[row + r][col + c] = isBlack;
          reserved[row + r][col + c] = true;
        }
      }
    }
  }
}

function placeTimingPatterns(matrix: boolean[][], reserved: boolean[][], size: number): void {
  for (let i = 8; i < size - 8; i++) {
    if (!reserved[6][i]) {
      matrix[6][i] = i % 2 === 0;
      reserved[6][i] = true;
    }
    if (!reserved[i][6]) {
      matrix[i][6] = i % 2 === 0;
      reserved[i][6] = true;
    }
  }
}

function reserveFormatAreas(reserved: boolean[][], matrix: boolean[][], size: number): void {
  for (let i = 0; i < 8; i++) {
    reserved[8][i] = true;
    reserved[8][size - 1 - i] = true;
    reserved[i][8] = true;
    reserved[size - 1 - i][8] = true;
  }
  reserved[8][8] = true;
  // Dark module
  matrix[size - 8][8] = true;
  reserved[size - 8][8] = true;
}

function placeDataBits(matrix: boolean[][], reserved: boolean[][], size: number, dataBits: number[]): void { // NOSONAR — complex function, refactoring would risk breaking critical behavior
  let bitIndex = 0;
  // Walk columns in pairs (col, col-1) from right to left. When we reach
  // col 6 (vertical timing pattern) we substitute col 5 and continue from
  // col 3 — implemented as a `while` loop so the iterator variable is not
  // a for-loop counter (SonarCloud S2310 forbids assigning the for-loop
  // counter inside the body).
  let col = size - 1;
  while (col >= 0) {
    if (col === 6) {
      col = 5; // Skip vertical timing pattern column
      continue;
    }
    for (let row = 0; row < size; row++) {
      for (let c = 0; c < 2; c++) {
        const mc = col - c;
        if (mc < 0 || reserved[row][mc]) continue;
        if (bitIndex < dataBits.length) {
          matrix[row][mc] = dataBits[bitIndex] === 1;
        }
        // Remaining bits are 0 (false) by default
        bitIndex++;
      }
    }
    col -= 2;
  }
}

function placeFormatInfo(matrix: boolean[][], size: number, ecl: ECL): void {
  const eclBitsH = ecl === "H" ? 3 : 2;
  const eclBitsL = ecl === "L" ? 1 : eclBitsH;
  const eclBits = ecl === "M" ? 0 : eclBitsL;
  const formatInfo = bchEncode(eclBits);
  const formatBits = Array.from({ length: 15 }, (_, i) => !!(formatInfo & (1 << (14 - i))));

  // Around top-left finder
  for (let i = 0; i < 6; i++) matrix[8][i] = formatBits[i];
  matrix[8][7] = formatBits[6];
  matrix[8][8] = formatBits[7];
  matrix[7][8] = formatBits[8];
  for (let i = 0; i < 6; i++) matrix[5 - i][8] = formatBits[9 + i];

  // Around top-right and bottom-left finders
  for (let i = 0; i < 7; i++) { matrix[size - 1 - i][8] = formatBits[i]; }
  for (let i = 0; i < 8; i++) { matrix[8][size - 8 + i] = formatBits[7 + i]; }
}

function buildMatrix(
  size: number,
  dataBits: number[],
  version: number,
  ecl: ECL
): boolean[][] {
  // Initialize matrix
  const matrix: boolean[][] = Array.from({ length: size }, () => new Array(size).fill(false));
  const reserved: boolean[][] = Array.from({ length: size }, () => new Array(size).fill(false));

  // Place finder patterns (7x7 squares at three corners)
  placeFinderPattern(matrix, reserved, size, 0, 0);
  placeFinderPattern(matrix, reserved, size, 0, size - 7);
  placeFinderPattern(matrix, reserved, size, size - 7, 0);

  // Place alignment patterns
  placeAlignmentPatterns(matrix, reserved, size, version);

  // Place timing patterns
  placeTimingPatterns(matrix, reserved, size);

  // Reserve format information areas + dark module
  reserveFormatAreas(reserved, matrix, size);

  // Place data bits in zigzag pattern
  placeDataBits(matrix, reserved, size, dataBits);

  // Place format information
  placeFormatInfo(matrix, size, ecl);

  // Apply mask pattern 0 (no masking for simplicity)
  return matrix;
}

/**
 * Convert data bytes and EC bytes into a bit array
 */
function bytesToBits(data: number[], ecBytes: number[]): number[] {
  const bits: number[] = [];
  for (const byte of data) {
    for (let i = 7; i >= 0; i--) {
      bits.push((byte >> i) & 1);
    }
  }
  for (const byte of ecBytes) {
    for (let i = 7; i >= 0; i--) {
      bits.push((byte >> i) & 1);
    }
  }
  return bits;
}

/**
 * Pad data to required length
 */
function padData(data: number[], totalCodewords: number): number[] {
  const padded = [...data];
  // Add terminator
  padded.push(0xEC);
  // Pad with 0x11 and 0xEC alternating
  let padByte = 0x11;
  while (padded.length < totalCodewords) {
    padded.push(padByte);
    padByte = padByte === 0x11 ? 0xEC : 0x11;
  }
  return padded.slice(0, totalCodewords);
}

/**
 * Encode data into QR code data bits (byte mode)
 */
function encodeData(text: string): number[] {
  const bytes = textToBytes(text);

  // Byte mode indicator (0100) + character count (8 bits for version 1-9) + data
  const modeBits = [0, 1, 0, 0];
  const countBits = Array.from({ length: 8 }, (_, i) => (bytes.length >> (7 - i)) & 1);
  const dataBits = [...modeBits, ...countBits];
  for (const byte of bytes) {
    for (let i = 7; i >= 0; i--) {
      dataBits.push((byte >> i) & 1);
    }
  }

  return dataBits;
}

/**
 * Generate an SVG QR code for a given URL
 * @param url - The URL to encode
 * @param size - The SVG size in pixels (default: 90)
 * @returns SVG string
 */
export function generateQRCodeSVG(url: string, size: number = 90): string {
  // Determine version needed
  const bytes = textToBytes(url);
  let version = 1;
  for (const [v, info] of Object.entries(VERSION_DATA)) {
    if (bytes.length <= info.capacity) {
      version = Number(v);
      break;
    }
  }

  const ecl: ECL = "M";
  const { size: matrixSize } = VERSION_DATA[version];
  const ecKey = `${version}-${ecl}`;
  const ecInfo = EC_TABLE[ecKey] || [10, 16];
  const ecCodewordsPerBlock = ecInfo[0];
  const totalCodewords = ecInfo[1];
  const dataCodewords = totalCodewords - ecCodewordsPerBlock;

   // Encode data
   const dataBits = encodeData(url);
  const dataBytes: number[] = [];
  for (let i = 0; i + 7 < dataBits.length; i += 8) {
    let byte = 0;
    for (let j = 0; j < 8; j++) {
      byte = (byte << 1) | dataBits[i + j];
    }
    dataBytes.push(byte);
  }

  // Pad data
  const paddedData = padData(dataBytes, dataCodewords);

  // Generate error correction
  const ecBytes = rsEncode(paddedData, ecCodewordsPerBlock);

  // Combine and convert to bits
  const allBits = bytesToBits(paddedData, ecBytes);

  // Build matrix
  const matrix = buildMatrix(matrixSize, allBits, version, ecl);

   // Generate SVG
   const cellSize = size / matrixSize;
   const quietZone = 2;
   const totalSize = size + quietZone * 2 * cellSize;

   let rects = "";
  for (let row = 0; row < matrixSize; row++) {
    for (let col = 0; col < matrixSize; col++) {
      if (matrix[row][col]) {
        const x = (col + quietZone) * cellSize;
        const y = (row + quietZone) * cellSize;
        rects += `<rect x="${x.toFixed(2)}" y="${y.toFixed(2)}" width="${(cellSize + 0.5).toFixed(2)}" height="${(cellSize + 0.5).toFixed(2)}" fill="#0f172a"/>`;
      }
    }
  }

  return `<svg viewBox="0 0 ${totalSize.toFixed(2)} ${totalSize.toFixed(2)}" xmlns="http://www.w3.org/2000/svg" style="width:100%;height:100%;">${rects}</svg>`;
}