ngwr 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1118 @@
1
+ import * as i2 from '@angular/common';
2
+ import { isPlatformBrowser, CommonModule } from '@angular/common';
3
+ import * as i0 from '@angular/core';
4
+ import { PLATFORM_ID, Component, ChangeDetectionStrategy, ViewEncapsulation, Inject, HostBinding, ViewChild, Input, NgModule } from '@angular/core';
5
+ import { WrAbstractBase } from 'ngwr/core/abstract';
6
+ import * as i1 from 'ngwr/icon';
7
+ import { WrIconModule } from 'ngwr/icon';
8
+
9
+ /*
10
+ * QR Code generator library (TypeScript)
11
+ *
12
+ * Copyright (c) Project Nayuki. (MIT License)
13
+ * https://www.nayuki.io/page/qr-code-generator-library
14
+ *
15
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of
16
+ * this software and associated documentation files (the "Software"), to deal in
17
+ * the Software without restriction, including without limitation the rights to
18
+ * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
19
+ * the Software, and to permit persons to whom the Software is furnished to do so,
20
+ * subject to the following conditions:
21
+ * - The above copyright notice and this permission notice shall be included in
22
+ * all copies or substantial portions of the Software.
23
+ * - The Software is provided "as is", without warranty of any kind, express or
24
+ * implied, including but not limited to the warranties of merchantability,
25
+ * fitness for a particular purpose and noninfringement. In no event shall the
26
+ * authors or copyright holders be liable for any claim, damages or other
27
+ * liability, whether in an action of contract, tort or otherwise, arising from,
28
+ * out of or in connection with the Software or the use or other dealings in the
29
+ * Software.
30
+ */
31
+ 'use strict';
32
+ var qrcodegen;
33
+ (function (qrcodegen) {
34
+ /*---- QR Code symbol class ----*/
35
+ /*
36
+ * A QR Code symbol, which is a type of two-dimension barcode.
37
+ * Invented by Denso Wave and described in the ISO/IEC 18004 standard.
38
+ * Instances of this class represent an immutable square grid of dark and light cells.
39
+ * The class provides static factory functions to create a QR Code from text or binary data.
40
+ * The class covers the QR Code Model 2 specification, supporting all versions (sizes)
41
+ * from 1 to 40, all 4 error correction levels, and 4 character encoding modes.
42
+ *
43
+ * Ways to create a QR Code object:
44
+ * - High level: Take the payload data and call QrCode.encodeText() or QrCode.encodeBinary().
45
+ * - Mid level: Custom-make the list of segments and call QrCode.encodeSegments().
46
+ * - Low level: Custom-make the array of data codeword bytes (including
47
+ * segment headers and final padding, excluding error correction codewords),
48
+ * supply the appropriate version number, and call the QrCode() constructor.
49
+ * (Note that all ways require supplying the desired error correction level.)
50
+ */
51
+ class QrCode {
52
+ /*-- Static factory functions (high level) --*/
53
+ // Returns a QR Code representing the given Unicode text string at the given error correction level.
54
+ // As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer
55
+ // Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible
56
+ // QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the
57
+ // ecl argument if it can be done without increasing the version.
58
+ static encodeText(text, ecl) {
59
+ const segs = qrcodegen.QrSegment.makeSegments(text);
60
+ return QrCode.encodeSegments(segs, ecl);
61
+ }
62
+ // Returns a QR Code representing the given binary data at the given error correction level.
63
+ // This function always encodes using the binary segment mode, not any text mode. The maximum number of
64
+ // bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.
65
+ // The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.
66
+ static encodeBinary(data, ecl) {
67
+ const seg = qrcodegen.QrSegment.makeBytes(data);
68
+ return QrCode.encodeSegments([seg], ecl);
69
+ }
70
+ /*-- Static factory functions (mid level) --*/
71
+ // Returns a QR Code representing the given segments with the given encoding parameters.
72
+ // The smallest possible QR Code version within the given range is automatically
73
+ // chosen for the output. Iff boostEcl is true, then the ECC level of the result
74
+ // may be higher than the ecl argument if it can be done without increasing the
75
+ // version. The mask number is either between 0 to 7 (inclusive) to force that
76
+ // mask, or -1 to automatically choose an appropriate mask (which may be slow).
77
+ // This function allows the user to create a custom sequence of segments that switches
78
+ // between modes (such as alphanumeric and byte) to encode text in less space.
79
+ // This is a mid-level API; the high-level API is encodeText() and encodeBinary().
80
+ static encodeSegments(segs, ecl, minVersion = 1, maxVersion = 40, mask = -1, boostEcl = true) {
81
+ if (!(QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= QrCode.MAX_VERSION) ||
82
+ mask < -1 ||
83
+ mask > 7)
84
+ throw new RangeError('Invalid value');
85
+ // Find the minimal version number to use
86
+ let version;
87
+ let dataUsedBits;
88
+ for (version = minVersion;; version++) {
89
+ const dataCapacityBits = QrCode.getNumDataCodewords(version, ecl) * 8; // Number of data bits available
90
+ const usedBits = QrSegment.getTotalBits(segs, version);
91
+ if (usedBits <= dataCapacityBits) {
92
+ dataUsedBits = usedBits;
93
+ break; // This version number is found to be suitable
94
+ }
95
+ if (version >= maxVersion)
96
+ // All versions in the range could not fit the given data
97
+ throw new RangeError('Data too long');
98
+ }
99
+ // Increase the error correction level while the data still fits in the current version number
100
+ for (const newEcl of [QrCode.Ecc.MEDIUM, QrCode.Ecc.QUARTILE, QrCode.Ecc.HIGH]) {
101
+ // From low to high
102
+ if (boostEcl && dataUsedBits <= QrCode.getNumDataCodewords(version, newEcl) * 8)
103
+ ecl = newEcl;
104
+ }
105
+ // Concatenate all segments to create the data bit string
106
+ let bb = [];
107
+ for (const seg of segs) {
108
+ appendBits(seg.mode.modeBits, 4, bb);
109
+ appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb);
110
+ for (const b of seg.getData())
111
+ bb.push(b);
112
+ }
113
+ assert(bb.length == dataUsedBits);
114
+ // Add terminator and pad up to a byte if applicable
115
+ const dataCapacityBits = QrCode.getNumDataCodewords(version, ecl) * 8;
116
+ assert(bb.length <= dataCapacityBits);
117
+ appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb);
118
+ appendBits(0, (8 - (bb.length % 8)) % 8, bb);
119
+ assert(bb.length % 8 == 0);
120
+ // Pad with alternating bytes until data capacity is reached
121
+ for (let padByte = 0xec; bb.length < dataCapacityBits; padByte ^= 0xec ^ 0x11)
122
+ appendBits(padByte, 8, bb);
123
+ // Pack bits into bytes in big endian
124
+ let dataCodewords = [];
125
+ while (dataCodewords.length * 8 < bb.length)
126
+ dataCodewords.push(0);
127
+ bb.forEach((b, i) => (dataCodewords[i >>> 3] |= b << (7 - (i & 7))));
128
+ // Create the QR Code object
129
+ return new QrCode(version, ecl, dataCodewords, mask);
130
+ }
131
+ /*-- Constructor (low level) and fields --*/
132
+ // Creates a new QR Code with the given version number,
133
+ // error correction level, data codeword bytes, and mask number.
134
+ // This is a low-level API that most users should not use directly.
135
+ // A mid-level API is the encodeSegments() function.
136
+ constructor(
137
+ // The version number of this QR Code, which is between 1 and 40 (inclusive).
138
+ // This determines the size of this barcode.
139
+ version,
140
+ // The error correction level used in this QR Code.
141
+ errorCorrectionLevel, dataCodewords, msk) {
142
+ this.version = version;
143
+ this.errorCorrectionLevel = errorCorrectionLevel;
144
+ // The modules of this QR Code (false = light, true = dark).
145
+ // Immutable after constructor finishes. Accessed through getModule().
146
+ this.modules = [];
147
+ // Indicates function modules that are not subjected to masking. Discarded when constructor finishes.
148
+ this.isFunction = [];
149
+ // Check scalar arguments
150
+ if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION)
151
+ throw new RangeError('Version value out of range');
152
+ if (msk < -1 || msk > 7)
153
+ throw new RangeError('Mask value out of range');
154
+ this.size = version * 4 + 17;
155
+ // Initialize both grids to be size*size arrays of Boolean false
156
+ let row = [];
157
+ for (let i = 0; i < this.size; i++)
158
+ row.push(false);
159
+ for (let i = 0; i < this.size; i++) {
160
+ this.modules.push(row.slice()); // Initially all light
161
+ this.isFunction.push(row.slice());
162
+ }
163
+ // Compute ECC, draw modules
164
+ this.drawFunctionPatterns();
165
+ const allCodewords = this.addEccAndInterleave(dataCodewords);
166
+ this.drawCodewords(allCodewords);
167
+ // Do masking
168
+ if (msk == -1) {
169
+ // Automatically choose best mask
170
+ let minPenalty = 1000000000;
171
+ for (let i = 0; i < 8; i++) {
172
+ this.applyMask(i);
173
+ this.drawFormatBits(i);
174
+ const penalty = this.getPenaltyScore();
175
+ if (penalty < minPenalty) {
176
+ msk = i;
177
+ minPenalty = penalty;
178
+ }
179
+ this.applyMask(i); // Undoes the mask due to XOR
180
+ }
181
+ }
182
+ assert(msk >= 0 && msk <= 7);
183
+ this.mask = msk;
184
+ this.applyMask(msk); // Apply the final choice of mask
185
+ this.drawFormatBits(msk); // Overwrite old format bits
186
+ this.isFunction = [];
187
+ }
188
+ /*-- Accessor methods --*/
189
+ // Returns the color of the module (pixel) at the given coordinates, which is false
190
+ // for light or true for dark. The top left corner has the coordinates (x=0, y=0).
191
+ // If the given coordinates are out of bounds, then false (light) is returned.
192
+ getModule(x, y) {
193
+ return x >= 0 && x < this.size && y >= 0 && y < this.size && this.modules[y][x];
194
+ }
195
+ /*-- Private helper methods for constructor: Drawing function modules --*/
196
+ // Reads this object's version field, and draws and marks all function modules.
197
+ drawFunctionPatterns() {
198
+ // Draw horizontal and vertical timing patterns
199
+ for (let i = 0; i < this.size; i++) {
200
+ this.setFunctionModule(6, i, i % 2 == 0);
201
+ this.setFunctionModule(i, 6, i % 2 == 0);
202
+ }
203
+ // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
204
+ this.drawFinderPattern(3, 3);
205
+ this.drawFinderPattern(this.size - 4, 3);
206
+ this.drawFinderPattern(3, this.size - 4);
207
+ // Draw numerous alignment patterns
208
+ const alignPatPos = this.getAlignmentPatternPositions();
209
+ const numAlign = alignPatPos.length;
210
+ for (let i = 0; i < numAlign; i++) {
211
+ for (let j = 0; j < numAlign; j++) {
212
+ // Don't draw on the three finder corners
213
+ if (!((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0)))
214
+ this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j]);
215
+ }
216
+ }
217
+ // Draw configuration data
218
+ this.drawFormatBits(0); // Dummy mask value; overwritten later in the constructor
219
+ this.drawVersion();
220
+ }
221
+ // Draws two copies of the format bits (with its own error correction code)
222
+ // based on the given mask and this object's error correction level field.
223
+ drawFormatBits(mask) {
224
+ // Calculate error correction code and pack bits
225
+ const data = (this.errorCorrectionLevel.formatBits << 3) | mask; // errCorrLvl is uint2, mask is uint3
226
+ let rem = data;
227
+ for (let i = 0; i < 10; i++)
228
+ rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
229
+ const bits = ((data << 10) | rem) ^ 0x5412; // uint15
230
+ assert(bits >>> 15 == 0);
231
+ // Draw first copy
232
+ for (let i = 0; i <= 5; i++)
233
+ this.setFunctionModule(8, i, getBit(bits, i));
234
+ this.setFunctionModule(8, 7, getBit(bits, 6));
235
+ this.setFunctionModule(8, 8, getBit(bits, 7));
236
+ this.setFunctionModule(7, 8, getBit(bits, 8));
237
+ for (let i = 9; i < 15; i++)
238
+ this.setFunctionModule(14 - i, 8, getBit(bits, i));
239
+ // Draw second copy
240
+ for (let i = 0; i < 8; i++)
241
+ this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i));
242
+ for (let i = 8; i < 15; i++)
243
+ this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i));
244
+ this.setFunctionModule(8, this.size - 8, true); // Always dark
245
+ }
246
+ // Draws two copies of the version bits (with its own error correction code),
247
+ // based on this object's version field, iff 7 <= version <= 40.
248
+ drawVersion() {
249
+ if (this.version < 7)
250
+ return;
251
+ // Calculate error correction code and pack bits
252
+ let rem = this.version; // version is uint6, in the range [7, 40]
253
+ for (let i = 0; i < 12; i++)
254
+ rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25);
255
+ const bits = (this.version << 12) | rem; // uint18
256
+ assert(bits >>> 18 == 0);
257
+ // Draw two copies
258
+ for (let i = 0; i < 18; i++) {
259
+ const color = getBit(bits, i);
260
+ const a = this.size - 11 + (i % 3);
261
+ const b = Math.floor(i / 3);
262
+ this.setFunctionModule(a, b, color);
263
+ this.setFunctionModule(b, a, color);
264
+ }
265
+ }
266
+ // Draws a 9*9 finder pattern including the border separator,
267
+ // with the center module at (x, y). Modules can be out of bounds.
268
+ drawFinderPattern(x, y) {
269
+ for (let dy = -4; dy <= 4; dy++) {
270
+ for (let dx = -4; dx <= 4; dx++) {
271
+ const dist = Math.max(Math.abs(dx), Math.abs(dy)); // Chebyshev/infinity norm
272
+ const xx = x + dx;
273
+ const yy = y + dy;
274
+ if (xx >= 0 && xx < this.size && yy >= 0 && yy < this.size)
275
+ this.setFunctionModule(xx, yy, dist != 2 && dist != 4);
276
+ }
277
+ }
278
+ }
279
+ // Draws a 5*5 alignment pattern, with the center module
280
+ // at (x, y). All modules must be in bounds.
281
+ drawAlignmentPattern(x, y) {
282
+ for (let dy = -2; dy <= 2; dy++) {
283
+ for (let dx = -2; dx <= 2; dx++)
284
+ this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1);
285
+ }
286
+ }
287
+ // Sets the color of a module and marks it as a function module.
288
+ // Only used by the constructor. Coordinates must be in bounds.
289
+ setFunctionModule(x, y, isDark) {
290
+ this.modules[y][x] = isDark;
291
+ this.isFunction[y][x] = true;
292
+ }
293
+ /*-- Private helper methods for constructor: Codewords and masking --*/
294
+ // Returns a new byte string representing the given data with the appropriate error correction
295
+ // codewords appended to it, based on this object's version and error correction level.
296
+ addEccAndInterleave(data) {
297
+ const ver = this.version;
298
+ const ecl = this.errorCorrectionLevel;
299
+ if (data.length != QrCode.getNumDataCodewords(ver, ecl))
300
+ throw new RangeError('Invalid argument');
301
+ // Calculate parameter numbers
302
+ const numBlocks = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
303
+ const blockEccLen = QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver];
304
+ const rawCodewords = Math.floor(QrCode.getNumRawDataModules(ver) / 8);
305
+ const numShortBlocks = numBlocks - (rawCodewords % numBlocks);
306
+ const shortBlockLen = Math.floor(rawCodewords / numBlocks);
307
+ // Split data into blocks and append ECC to each block
308
+ let blocks = [];
309
+ const rsDiv = QrCode.reedSolomonComputeDivisor(blockEccLen);
310
+ for (let i = 0, k = 0; i < numBlocks; i++) {
311
+ let dat = data.slice(k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1));
312
+ k += dat.length;
313
+ const ecc = QrCode.reedSolomonComputeRemainder(dat, rsDiv);
314
+ if (i < numShortBlocks)
315
+ dat.push(0);
316
+ blocks.push(dat.concat(ecc));
317
+ }
318
+ // Interleave (not concatenate) the bytes from every block into a single sequence
319
+ let result = [];
320
+ for (let i = 0; i < blocks[0].length; i++) {
321
+ blocks.forEach((block, j) => {
322
+ // Skip the padding byte in short blocks
323
+ if (i != shortBlockLen - blockEccLen || j >= numShortBlocks)
324
+ result.push(block[i]);
325
+ });
326
+ }
327
+ assert(result.length == rawCodewords);
328
+ return result;
329
+ }
330
+ // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire
331
+ // data area of this QR Code. Function modules need to be marked off before this is called.
332
+ drawCodewords(data) {
333
+ if (data.length != Math.floor(QrCode.getNumRawDataModules(this.version) / 8))
334
+ throw new RangeError('Invalid argument');
335
+ let i = 0; // Bit index into the data
336
+ // Do the funny zigzag scan
337
+ for (let right = this.size - 1; right >= 1; right -= 2) {
338
+ // Index of right column in each column pair
339
+ if (right == 6)
340
+ right = 5;
341
+ for (let vert = 0; vert < this.size; vert++) {
342
+ // Vertical counter
343
+ for (let j = 0; j < 2; j++) {
344
+ const x = right - j; // Actual x coordinate
345
+ const upward = ((right + 1) & 2) == 0;
346
+ const y = upward ? this.size - 1 - vert : vert; // Actual y coordinate
347
+ if (!this.isFunction[y][x] && i < data.length * 8) {
348
+ this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7));
349
+ i++;
350
+ }
351
+ // If this QR Code has any remainder bits (0 to 7), they were assigned as
352
+ // 0/false/light by the constructor and are left unchanged by this method
353
+ }
354
+ }
355
+ }
356
+ assert(i == data.length * 8);
357
+ }
358
+ // XORs the codeword modules in this QR Code with the given mask pattern.
359
+ // The function modules must be marked and the codeword bits must be drawn
360
+ // before masking. Due to the arithmetic of XOR, calling applyMask() with
361
+ // the same mask value a second time will undo the mask. A final well-formed
362
+ // QR Code needs exactly one (not zero, two, etc.) mask applied.
363
+ applyMask(mask) {
364
+ if (mask < 0 || mask > 7)
365
+ throw new RangeError('Mask value out of range');
366
+ for (let y = 0; y < this.size; y++) {
367
+ for (let x = 0; x < this.size; x++) {
368
+ let invert;
369
+ switch (mask) {
370
+ case 0:
371
+ invert = (x + y) % 2 == 0;
372
+ break;
373
+ case 1:
374
+ invert = y % 2 == 0;
375
+ break;
376
+ case 2:
377
+ invert = x % 3 == 0;
378
+ break;
379
+ case 3:
380
+ invert = (x + y) % 3 == 0;
381
+ break;
382
+ case 4:
383
+ invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 == 0;
384
+ break;
385
+ case 5:
386
+ invert = ((x * y) % 2) + ((x * y) % 3) == 0;
387
+ break;
388
+ case 6:
389
+ invert = (((x * y) % 2) + ((x * y) % 3)) % 2 == 0;
390
+ break;
391
+ case 7:
392
+ invert = (((x + y) % 2) + ((x * y) % 3)) % 2 == 0;
393
+ break;
394
+ default:
395
+ throw new Error('Unreachable');
396
+ }
397
+ if (!this.isFunction[y][x] && invert)
398
+ this.modules[y][x] = !this.modules[y][x];
399
+ }
400
+ }
401
+ }
402
+ // Calculates and returns the penalty score based on state of this QR Code's current modules.
403
+ // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
404
+ getPenaltyScore() {
405
+ let result = 0;
406
+ // Adjacent modules in row having same color, and finder-like patterns
407
+ for (let y = 0; y < this.size; y++) {
408
+ let runColor = false;
409
+ let runX = 0;
410
+ let runHistory = [0, 0, 0, 0, 0, 0, 0];
411
+ for (let x = 0; x < this.size; x++) {
412
+ if (this.modules[y][x] == runColor) {
413
+ runX++;
414
+ if (runX == 5)
415
+ result += QrCode.PENALTY_N1;
416
+ else if (runX > 5)
417
+ result++;
418
+ }
419
+ else {
420
+ this.finderPenaltyAddHistory(runX, runHistory);
421
+ if (!runColor)
422
+ result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;
423
+ runColor = this.modules[y][x];
424
+ runX = 1;
425
+ }
426
+ }
427
+ result += this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * QrCode.PENALTY_N3;
428
+ }
429
+ // Adjacent modules in column having same color, and finder-like patterns
430
+ for (let x = 0; x < this.size; x++) {
431
+ let runColor = false;
432
+ let runY = 0;
433
+ let runHistory = [0, 0, 0, 0, 0, 0, 0];
434
+ for (let y = 0; y < this.size; y++) {
435
+ if (this.modules[y][x] == runColor) {
436
+ runY++;
437
+ if (runY == 5)
438
+ result += QrCode.PENALTY_N1;
439
+ else if (runY > 5)
440
+ result++;
441
+ }
442
+ else {
443
+ this.finderPenaltyAddHistory(runY, runHistory);
444
+ if (!runColor)
445
+ result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;
446
+ runColor = this.modules[y][x];
447
+ runY = 1;
448
+ }
449
+ }
450
+ result += this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * QrCode.PENALTY_N3;
451
+ }
452
+ // 2*2 blocks of modules having same color
453
+ for (let y = 0; y < this.size - 1; y++) {
454
+ for (let x = 0; x < this.size - 1; x++) {
455
+ const color = this.modules[y][x];
456
+ if (color == this.modules[y][x + 1] && color == this.modules[y + 1][x] && color == this.modules[y + 1][x + 1])
457
+ result += QrCode.PENALTY_N2;
458
+ }
459
+ }
460
+ // Balance of dark and light modules
461
+ let dark = 0;
462
+ for (const row of this.modules)
463
+ dark = row.reduce((sum, color) => sum + (color ? 1 : 0), dark);
464
+ const total = this.size * this.size; // Note that size is odd, so dark/total != 1/2
465
+ // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)%
466
+ const k = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1;
467
+ assert(k >= 0 && k <= 9);
468
+ result += k * QrCode.PENALTY_N4;
469
+ assert(result >= 0 && result <= 2568888); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4
470
+ return result;
471
+ }
472
+ /*-- Private helper functions --*/
473
+ // Returns an ascending list of positions of alignment patterns for this version number.
474
+ // Each position is in the range [0,177), and are used on both the x and y axes.
475
+ // This could be implemented as lookup table of 40 variable-length lists of integers.
476
+ getAlignmentPatternPositions() {
477
+ if (this.version == 1)
478
+ return [];
479
+ else {
480
+ const numAlign = Math.floor(this.version / 7) + 2;
481
+ const step = this.version == 32 ? 26 : Math.ceil((this.version * 4 + 4) / (numAlign * 2 - 2)) * 2;
482
+ let result = [6];
483
+ for (let pos = this.size - 7; result.length < numAlign; pos -= step)
484
+ result.splice(1, 0, pos);
485
+ return result;
486
+ }
487
+ }
488
+ // Returns the number of data bits that can be stored in a QR Code of the given version number, after
489
+ // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
490
+ // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.
491
+ static getNumRawDataModules(ver) {
492
+ if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION)
493
+ throw new RangeError('Version number out of range');
494
+ let result = (16 * ver + 128) * ver + 64;
495
+ if (ver >= 2) {
496
+ const numAlign = Math.floor(ver / 7) + 2;
497
+ result -= (25 * numAlign - 10) * numAlign - 55;
498
+ if (ver >= 7)
499
+ result -= 36;
500
+ }
501
+ assert(result >= 208 && result <= 29648);
502
+ return result;
503
+ }
504
+ // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any
505
+ // QR Code of the given version number and error correction level, with remainder bits discarded.
506
+ // This stateless pure function could be implemented as a (40*4)-cell lookup table.
507
+ static getNumDataCodewords(ver, ecl) {
508
+ return (Math.floor(QrCode.getNumRawDataModules(ver) / 8) -
509
+ QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver] * QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver]);
510
+ }
511
+ // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be
512
+ // implemented as a lookup table over all possible parameter values, instead of as an algorithm.
513
+ static reedSolomonComputeDivisor(degree) {
514
+ if (degree < 1 || degree > 255)
515
+ throw new RangeError('Degree out of range');
516
+ // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.
517
+ // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93].
518
+ let result = [];
519
+ for (let i = 0; i < degree - 1; i++)
520
+ result.push(0);
521
+ result.push(1); // Start off with the monomial x^0
522
+ // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
523
+ // and drop the highest monomial term which is always 1x^degree.
524
+ // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
525
+ let root = 1;
526
+ for (let i = 0; i < degree; i++) {
527
+ // Multiply the current product by (x - r^i)
528
+ for (let j = 0; j < result.length; j++) {
529
+ result[j] = QrCode.reedSolomonMultiply(result[j], root);
530
+ if (j + 1 < result.length)
531
+ result[j] ^= result[j + 1];
532
+ }
533
+ root = QrCode.reedSolomonMultiply(root, 0x02);
534
+ }
535
+ return result;
536
+ }
537
+ // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials.
538
+ static reedSolomonComputeRemainder(data, divisor) {
539
+ let result = divisor.map(_ => 0);
540
+ for (const b of data) {
541
+ // Polynomial division
542
+ const factor = b ^ result.shift();
543
+ result.push(0);
544
+ divisor.forEach((coef, i) => (result[i] ^= QrCode.reedSolomonMultiply(coef, factor)));
545
+ }
546
+ return result;
547
+ }
548
+ // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result
549
+ // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8.
550
+ static reedSolomonMultiply(x, y) {
551
+ if (x >>> 8 != 0 || y >>> 8 != 0)
552
+ throw new RangeError('Byte out of range');
553
+ // Russian peasant multiplication
554
+ let z = 0;
555
+ for (let i = 7; i >= 0; i--) {
556
+ z = (z << 1) ^ ((z >>> 7) * 0x11d);
557
+ z ^= ((y >>> i) & 1) * x;
558
+ }
559
+ assert(z >>> 8 == 0);
560
+ return z;
561
+ }
562
+ // Can only be called immediately after a light run is added, and
563
+ // returns either 0, 1, or 2. A helper function for getPenaltyScore().
564
+ finderPenaltyCountPatterns(runHistory) {
565
+ const n = runHistory[1];
566
+ assert(n <= this.size * 3);
567
+ const core = n > 0 && runHistory[2] == n && runHistory[3] == n * 3 && runHistory[4] == n && runHistory[5] == n;
568
+ return ((core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0) +
569
+ (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0));
570
+ }
571
+ // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore().
572
+ finderPenaltyTerminateAndCount(currentRunColor, currentRunLength, runHistory) {
573
+ if (currentRunColor) {
574
+ // Terminate dark run
575
+ this.finderPenaltyAddHistory(currentRunLength, runHistory);
576
+ currentRunLength = 0;
577
+ }
578
+ currentRunLength += this.size; // Add light border to final run
579
+ this.finderPenaltyAddHistory(currentRunLength, runHistory);
580
+ return this.finderPenaltyCountPatterns(runHistory);
581
+ }
582
+ // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore().
583
+ finderPenaltyAddHistory(currentRunLength, runHistory) {
584
+ if (runHistory[0] == 0)
585
+ currentRunLength += this.size; // Add light border to initial run
586
+ runHistory.pop();
587
+ runHistory.unshift(currentRunLength);
588
+ }
589
+ /*-- Constants and tables --*/
590
+ // The minimum version number supported in the QR Code Model 2 standard.
591
+ static { this.MIN_VERSION = 1; }
592
+ // The maximum version number supported in the QR Code Model 2 standard.
593
+ static { this.MAX_VERSION = 40; }
594
+ // For use in getPenaltyScore(), when evaluating which mask is best.
595
+ static { this.PENALTY_N1 = 3; }
596
+ static { this.PENALTY_N2 = 3; }
597
+ static { this.PENALTY_N3 = 40; }
598
+ static { this.PENALTY_N4 = 10; }
599
+ static { this.ECC_CODEWORDS_PER_BLOCK = [
600
+ // Version: (note that index 0 is for padding, and is set to an illegal value)
601
+ //0, 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 Error correction level
602
+ [
603
+ -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,
604
+ 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
605
+ ],
606
+ [
607
+ -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,
608
+ 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
609
+ ],
610
+ [
611
+ -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,
612
+ 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
613
+ ],
614
+ [
615
+ -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,
616
+ 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
617
+ ], // High
618
+ ]; }
619
+ static { this.NUM_ERROR_CORRECTION_BLOCKS = [
620
+ // Version: (note that index 0 is for padding, and is set to an illegal value)
621
+ //0, 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 Error correction level
622
+ [
623
+ -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,
624
+ 19, 19, 20, 21, 22, 24, 25,
625
+ ],
626
+ [
627
+ -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,
628
+ 31, 33, 35, 37, 38, 40, 43, 45, 47, 49,
629
+ ],
630
+ [
631
+ -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,
632
+ 43, 45, 48, 51, 53, 56, 59, 62, 65, 68,
633
+ ],
634
+ [
635
+ -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,
636
+ 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81,
637
+ ], // High
638
+ ]; }
639
+ }
640
+ qrcodegen.QrCode = QrCode;
641
+ // Appends the given number of low-order bits of the given value
642
+ // to the given buffer. Requires 0 <= len <= 31 and 0 <= val < 2^len.
643
+ function appendBits(val, len, bb) {
644
+ if (len < 0 || len > 31 || val >>> len != 0)
645
+ throw new RangeError('Value out of range');
646
+ for (let i = len - 1; i >= 0; i-- // Append bit by bit
647
+ )
648
+ bb.push((val >>> i) & 1);
649
+ }
650
+ // Returns true iff the i'th bit of x is set to 1.
651
+ function getBit(x, i) {
652
+ return ((x >>> i) & 1) != 0;
653
+ }
654
+ // Throws an exception if the given condition is false.
655
+ function assert(cond) {
656
+ if (!cond)
657
+ throw new Error('Assertion error');
658
+ }
659
+ /*---- Data segment class ----*/
660
+ /*
661
+ * A segment of character/binary/control data in a QR Code symbol.
662
+ * Instances of this class are immutable.
663
+ * The mid-level way to create a segment is to take the payload data
664
+ * and call a static factory function such as QrSegment.makeNumeric().
665
+ * The low-level way to create a segment is to custom-make the bit buffer
666
+ * and call the QrSegment() constructor with appropriate values.
667
+ * This segment class imposes no length restrictions, but QR Codes have restrictions.
668
+ * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.
669
+ * Any segment longer than this is meaningless for the purpose of generating QR Codes.
670
+ */
671
+ class QrSegment {
672
+ /*-- Static factory functions (mid level) --*/
673
+ // Returns a segment representing the given binary data encoded in
674
+ // byte mode. All input byte arrays are acceptable. Any text string
675
+ // can be converted to UTF-8 bytes and encoded as a byte mode segment.
676
+ static makeBytes(data) {
677
+ let bb = [];
678
+ for (const b of data)
679
+ appendBits(b, 8, bb);
680
+ return new QrSegment(QrSegment.Mode.BYTE, data.length, bb);
681
+ }
682
+ // Returns a segment representing the given string of decimal digits encoded in numeric mode.
683
+ static makeNumeric(digits) {
684
+ if (!QrSegment.isNumeric(digits))
685
+ throw new RangeError('String contains non-numeric characters');
686
+ let bb = [];
687
+ for (let i = 0; i < digits.length;) {
688
+ // Consume up to 3 digits per iteration
689
+ const n = Math.min(digits.length - i, 3);
690
+ appendBits(parseInt(digits.substring(i, i + n), 10), n * 3 + 1, bb);
691
+ i += n;
692
+ }
693
+ return new QrSegment(QrSegment.Mode.NUMERIC, digits.length, bb);
694
+ }
695
+ // Returns a segment representing the given text string encoded in alphanumeric mode.
696
+ // The characters allowed are: 0 to 9, A to Z (uppercase only), space,
697
+ // dollar, percent, asterisk, plus, hyphen, period, slash, colon.
698
+ static makeAlphanumeric(text) {
699
+ if (!QrSegment.isAlphanumeric(text))
700
+ throw new RangeError('String contains unencodable characters in alphanumeric mode');
701
+ let bb = [];
702
+ let i;
703
+ for (i = 0; i + 2 <= text.length; i += 2) {
704
+ // Process groups of 2
705
+ let temp = QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45;
706
+ temp += QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1));
707
+ appendBits(temp, 11, bb);
708
+ }
709
+ if (i < text.length)
710
+ // 1 character remaining
711
+ appendBits(QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb);
712
+ return new QrSegment(QrSegment.Mode.ALPHANUMERIC, text.length, bb);
713
+ }
714
+ // Returns a new mutable list of zero or more segments to represent the given Unicode text string.
715
+ // The result may use various segment modes and switch modes to optimize the length of the bit stream.
716
+ static makeSegments(text) {
717
+ // Select the most efficient segment encoding automatically
718
+ if (text == '')
719
+ return [];
720
+ else if (QrSegment.isNumeric(text))
721
+ return [QrSegment.makeNumeric(text)];
722
+ else if (QrSegment.isAlphanumeric(text))
723
+ return [QrSegment.makeAlphanumeric(text)];
724
+ else
725
+ return [QrSegment.makeBytes(QrSegment.toUtf8ByteArray(text))];
726
+ }
727
+ // Returns a segment representing an Extended Channel Interpretation
728
+ // (ECI) designator with the given assignment value.
729
+ static makeEci(assignVal) {
730
+ let bb = [];
731
+ if (assignVal < 0)
732
+ throw new RangeError('ECI assignment value out of range');
733
+ else if (assignVal < 1 << 7)
734
+ appendBits(assignVal, 8, bb);
735
+ else if (assignVal < 1 << 14) {
736
+ appendBits(0b10, 2, bb);
737
+ appendBits(assignVal, 14, bb);
738
+ }
739
+ else if (assignVal < 1000000) {
740
+ appendBits(0b110, 3, bb);
741
+ appendBits(assignVal, 21, bb);
742
+ }
743
+ else
744
+ throw new RangeError('ECI assignment value out of range');
745
+ return new QrSegment(QrSegment.Mode.ECI, 0, bb);
746
+ }
747
+ // Tests whether the given string can be encoded as a segment in numeric mode.
748
+ // A string is encodable iff each character is in the range 0 to 9.
749
+ static isNumeric(text) {
750
+ return QrSegment.NUMERIC_REGEX.test(text);
751
+ }
752
+ // Tests whether the given string can be encoded as a segment in alphanumeric mode.
753
+ // A string is encodable iff each character is in the following set: 0 to 9, A to Z
754
+ // (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.
755
+ static isAlphanumeric(text) {
756
+ return QrSegment.ALPHANUMERIC_REGEX.test(text);
757
+ }
758
+ /*-- Constructor (low level) and fields --*/
759
+ // Creates a new QR Code segment with the given attributes and data.
760
+ // The character count (numChars) must agree with the mode and the bit buffer length,
761
+ // but the constraint isn't checked. The given bit buffer is cloned and stored.
762
+ constructor(
763
+ // The mode indicator of this segment.
764
+ mode,
765
+ // The length of this segment's unencoded data. Measured in characters for
766
+ // numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.
767
+ // Always zero or positive. Not the same as the data's bit length.
768
+ numChars,
769
+ // The data bits of this segment. Accessed through getData().
770
+ bitData) {
771
+ this.mode = mode;
772
+ this.numChars = numChars;
773
+ this.bitData = bitData;
774
+ if (numChars < 0)
775
+ throw new RangeError('Invalid argument');
776
+ this.bitData = bitData.slice(); // Make defensive copy
777
+ }
778
+ /*-- Methods --*/
779
+ // Returns a new copy of the data bits of this segment.
780
+ getData() {
781
+ return this.bitData.slice(); // Make defensive copy
782
+ }
783
+ // (Package-private) Calculates and returns the number of bits needed to encode the given segments at
784
+ // the given version. The result is infinity if a segment has too many characters to fit its length field.
785
+ static getTotalBits(segs, version) {
786
+ let result = 0;
787
+ for (const seg of segs) {
788
+ const ccbits = seg.mode.numCharCountBits(version);
789
+ if (seg.numChars >= 1 << ccbits)
790
+ return Infinity; // The segment's length doesn't fit the field's bit width
791
+ result += 4 + ccbits + seg.bitData.length;
792
+ }
793
+ return result;
794
+ }
795
+ // Returns a new array of bytes representing the given string encoded in UTF-8.
796
+ static toUtf8ByteArray(str) {
797
+ str = encodeURI(str);
798
+ let result = [];
799
+ for (let i = 0; i < str.length; i++) {
800
+ if (str.charAt(i) != '%')
801
+ result.push(str.charCodeAt(i));
802
+ else {
803
+ result.push(parseInt(str.substring(i + 1, i + 3), 16));
804
+ i += 2;
805
+ }
806
+ }
807
+ return result;
808
+ }
809
+ /*-- Constants --*/
810
+ // Describes precisely all strings that are encodable in numeric mode.
811
+ static { this.NUMERIC_REGEX = /^[0-9]*$/; }
812
+ // Describes precisely all strings that are encodable in alphanumeric mode.
813
+ static { this.ALPHANUMERIC_REGEX = /^[A-Z0-9 $%*+.\/:-]*$/; }
814
+ // The set of all legal characters in alphanumeric mode,
815
+ // where each character value maps to the index in the string.
816
+ static { this.ALPHANUMERIC_CHARSET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:'; }
817
+ }
818
+ qrcodegen.QrSegment = QrSegment;
819
+ })(qrcodegen || (qrcodegen = {}));
820
+ /*---- Public helper enumeration ----*/
821
+ (function (qrcodegen) {
822
+ var QrCode;
823
+ (function (QrCode) {
824
+ /*
825
+ * The error correction level in a QR Code symbol. Immutable.
826
+ */
827
+ class Ecc {
828
+ /*-- Constants --*/
829
+ static { this.LOW = new Ecc(0, 1); } // The QR Code can tolerate about 7% erroneous codewords
830
+ static { this.MEDIUM = new Ecc(1, 0); } // The QR Code can tolerate about 15% erroneous codewords
831
+ static { this.QUARTILE = new Ecc(2, 3); } // The QR Code can tolerate about 25% erroneous codewords
832
+ static { this.HIGH = new Ecc(3, 2); } // The QR Code can tolerate about 30% erroneous codewords
833
+ /*-- Constructor and fields --*/
834
+ constructor(
835
+ // In the range 0 to 3 (unsigned 2-bit integer).
836
+ ordinal,
837
+ // (Package-private) In the range 0 to 3 (unsigned 2-bit integer).
838
+ formatBits) {
839
+ this.ordinal = ordinal;
840
+ this.formatBits = formatBits;
841
+ }
842
+ }
843
+ QrCode.Ecc = Ecc;
844
+ })(QrCode = qrcodegen.QrCode || (qrcodegen.QrCode = {}));
845
+ })(qrcodegen || (qrcodegen = {}));
846
+ /*---- Public helper enumeration ----*/
847
+ (function (qrcodegen) {
848
+ var QrSegment;
849
+ (function (QrSegment) {
850
+ /*
851
+ * Describes how a segment's data bits are interpreted. Immutable.
852
+ */
853
+ class Mode {
854
+ /*-- Constants --*/
855
+ static { this.NUMERIC = new Mode(0x1, [10, 12, 14]); }
856
+ static { this.ALPHANUMERIC = new Mode(0x2, [9, 11, 13]); }
857
+ static { this.BYTE = new Mode(0x4, [8, 16, 16]); }
858
+ static { this.KANJI = new Mode(0x8, [8, 10, 12]); }
859
+ static { this.ECI = new Mode(0x7, [0, 0, 0]); }
860
+ /*-- Constructor and fields --*/
861
+ constructor(
862
+ // The mode indicator bits, which is a uint4 value (range 0 to 15).
863
+ modeBits,
864
+ // Number of character count bits for three different version ranges.
865
+ numBitsCharCount) {
866
+ this.modeBits = modeBits;
867
+ this.numBitsCharCount = numBitsCharCount;
868
+ }
869
+ /*-- Method --*/
870
+ // (Package-private) Returns the bit width of the character count field for a segment in
871
+ // this mode in a QR Code at the given version number. The result is in the range [0, 16].
872
+ numCharCountBits(ver) {
873
+ return this.numBitsCharCount[Math.floor((ver + 7) / 17)];
874
+ }
875
+ }
876
+ QrSegment.Mode = Mode;
877
+ })(QrSegment = qrcodegen.QrSegment || (qrcodegen.QrSegment = {}));
878
+ })(qrcodegen || (qrcodegen = {}));
879
+ var qrcodegen$1 = qrcodegen;
880
+
881
+ const ERROR_LEVEL_MAP = {
882
+ L: qrcodegen$1.QrCode.Ecc.LOW,
883
+ M: qrcodegen$1.QrCode.Ecc.MEDIUM,
884
+ Q: qrcodegen$1.QrCode.Ecc.QUARTILE,
885
+ H: qrcodegen$1.QrCode.Ecc.HIGH,
886
+ };
887
+ const DEFAULT_SIZE = 160;
888
+ const DEFAULT_SCALE = 10;
889
+ const DEFAULT_PADDING = 10;
890
+ const DEFAULT_COLOR = '#000000';
891
+ const DEFAULT_BACKGROUND_COLOR = '#FFFFFF';
892
+ const DEFAULT_ICONSIZE = 40;
893
+ const DEFAULT_LEVEL = 'M';
894
+ const plotQRCodeData = (value, level = DEFAULT_LEVEL) => {
895
+ if (!value) {
896
+ return null;
897
+ }
898
+ return qrcodegen$1.QrCode.encodeText(value, ERROR_LEVEL_MAP[level]);
899
+ };
900
+ function drawCanvas(canvas, value, size = DEFAULT_SIZE, scale = DEFAULT_SCALE, padding = DEFAULT_PADDING, color = DEFAULT_COLOR, backgroundColor = DEFAULT_BACKGROUND_COLOR, iconSize = DEFAULT_ICONSIZE, icon) {
901
+ const ctx = canvas.getContext('2d');
902
+ const formattedPadding = formatPadding(padding);
903
+ canvas.style.width = `${size}px`;
904
+ canvas.style.height = `${size}px`;
905
+ if (!value) {
906
+ ctx.fillStyle = 'rgba(0, 0, 0, 0)';
907
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
908
+ return;
909
+ }
910
+ canvas.width = value.size * scale + formattedPadding[1] + formattedPadding[3];
911
+ canvas.height = value.size * scale + formattedPadding[0] + formattedPadding[2];
912
+ if (!icon) {
913
+ drawCanvasBackground(ctx, canvas.width, canvas.height, scale, backgroundColor);
914
+ drawCanvasColor(ctx, value, scale, formattedPadding, backgroundColor, color);
915
+ }
916
+ else {
917
+ const iconImg = new Image();
918
+ iconImg.src = icon;
919
+ iconImg.crossOrigin = 'anonymous';
920
+ iconImg.width = iconSize * (canvas.width / size);
921
+ iconImg.height = iconSize * (canvas.width / size);
922
+ iconImg.onload = () => {
923
+ drawCanvasBackground(ctx, canvas.width, canvas.height, scale, backgroundColor);
924
+ drawCanvasColor(ctx, value, scale, formattedPadding, backgroundColor, color);
925
+ const iconCoordinate = canvas.width / 2 - (iconSize * (canvas.width / size)) / 2;
926
+ ctx.fillStyle = backgroundColor;
927
+ ctx.fillRect(iconCoordinate, iconCoordinate, iconSize * (canvas.width / size), iconSize * (canvas.width / size));
928
+ ctx.drawImage(iconImg, iconCoordinate + 10, iconCoordinate + 10, iconSize * (canvas.width / size) - 20, iconSize * (canvas.width / size) - 20);
929
+ };
930
+ iconImg.onerror = () => {
931
+ drawCanvasBackground(ctx, canvas.width, canvas.height, scale, backgroundColor);
932
+ drawCanvasColor(ctx, value, scale, formattedPadding, backgroundColor, color);
933
+ };
934
+ }
935
+ }
936
+ function drawCanvasColor(ctx, value, scale, padding, backgroundColor, color) {
937
+ for (let y = 0; y < value.size; y++) {
938
+ for (let x = 0; x < value.size; x++) {
939
+ ctx.fillStyle = value.getModule(x, y) ? color : backgroundColor;
940
+ ctx.fillRect(padding[3] + x * scale, padding[0] + y * scale, scale, scale);
941
+ }
942
+ }
943
+ }
944
+ function drawCanvasBackground(ctx, width, height, scale, backgroundColor) {
945
+ for (let y = 0; y < height; y++) {
946
+ for (let x = 0; x < width; x++) {
947
+ ctx.fillStyle = backgroundColor;
948
+ ctx.fillRect(x * scale, y * scale, scale, scale);
949
+ }
950
+ }
951
+ }
952
+ function formatPadding(padding) {
953
+ if (Array.isArray(padding)) {
954
+ // Build an array of 4 elements and repeat values from padding as necessary to set the value of the array
955
+ return Array(4)
956
+ .fill(0)
957
+ .map((_, index) => padding[index % padding.length]);
958
+ }
959
+ else {
960
+ return [padding, padding, padding, padding];
961
+ }
962
+ }
963
+
964
+ class WrQRCode extends WrAbstractBase {
965
+ get value() {
966
+ return this._value;
967
+ }
968
+ set value(value) {
969
+ this._value = value;
970
+ this.cdr.markForCheck();
971
+ }
972
+ get level() {
973
+ return this._level;
974
+ }
975
+ set level(level) {
976
+ this._level = level;
977
+ this.cdr.markForCheck();
978
+ }
979
+ get padding() {
980
+ return this._padding;
981
+ }
982
+ set padding(padding) {
983
+ this._padding = padding;
984
+ this.cdr.markForCheck();
985
+ }
986
+ get color() {
987
+ return this._color;
988
+ }
989
+ set color(color) {
990
+ this._color = color;
991
+ this.cdr.markForCheck();
992
+ }
993
+ get bgColor() {
994
+ return this._bgColor;
995
+ }
996
+ set bgColor(color) {
997
+ this._bgColor = color;
998
+ this.cdr.markForCheck();
999
+ }
1000
+ get size() {
1001
+ return this._size;
1002
+ }
1003
+ set size(size) {
1004
+ this._size = size;
1005
+ this.cdr.markForCheck();
1006
+ }
1007
+ get icon() {
1008
+ return this._icon;
1009
+ }
1010
+ set icon(icon) {
1011
+ this._icon = icon;
1012
+ this.cdr.markForCheck();
1013
+ }
1014
+ get iconSize() {
1015
+ return this._iconSize;
1016
+ }
1017
+ set iconSize(size) {
1018
+ this._iconSize = size;
1019
+ this.cdr.markForCheck();
1020
+ }
1021
+ constructor(pid, cdr, el, wrIconService) {
1022
+ super();
1023
+ this.pid = pid;
1024
+ this.cdr = cdr;
1025
+ this.el = el;
1026
+ this.wrIconService = wrIconService;
1027
+ this.class = 'wr-qrcode';
1028
+ this._value = '';
1029
+ this._level = 'M';
1030
+ this._padding = 10;
1031
+ this._color = '#000000';
1032
+ this._bgColor = '#ffffff';
1033
+ this._size = 150;
1034
+ this._icon = '';
1035
+ this._iconSize = 42;
1036
+ this.isBrowser = true;
1037
+ this.isBrowser = isPlatformBrowser(this.pid);
1038
+ }
1039
+ ngOnInit() {
1040
+ this.setElBg();
1041
+ }
1042
+ ngAfterViewInit() {
1043
+ this.drawCanvas();
1044
+ }
1045
+ ngOnChanges(changes) {
1046
+ const { value, level, padding, color, bgColor, size, icon, iconSize } = changes;
1047
+ if ((value || level || padding || color || bgColor || size || icon || iconSize) && this.canvas) {
1048
+ this.drawCanvas();
1049
+ }
1050
+ if (bgColor) {
1051
+ this.setElBg();
1052
+ }
1053
+ }
1054
+ setElBg() {
1055
+ this.el.nativeElement.style.backgroundColor = this.bgColor;
1056
+ }
1057
+ drawCanvas() {
1058
+ if (this.canvas) {
1059
+ let icon = this.wrIconService.registry.get(this.icon) || this.icon;
1060
+ if (this.wrIconService.registry.has(this.icon)) {
1061
+ icon = `data:image/svg+xml;base64,${btoa(icon)}`;
1062
+ }
1063
+ drawCanvas(this.canvas.nativeElement, plotQRCodeData(this.value, this.level), this.size, 10, this.padding, this.color, this.bgColor, this.iconSize, icon);
1064
+ }
1065
+ }
1066
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.1.3", ngImport: i0, type: WrQRCode, deps: [{ token: PLATFORM_ID }, { token: i0.ChangeDetectorRef }, { token: i0.ElementRef }, { token: i1.WrIconService }], target: i0.ɵɵFactoryTarget.Component }); }
1067
+ static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.1.3", type: WrQRCode, selector: "wr-qrcode", inputs: { value: "value", level: "level", padding: "padding", color: "color", bgColor: "bgColor", size: "size", icon: "icon", iconSize: "iconSize" }, host: { properties: { "class": "this.class" } }, viewQueries: [{ propertyName: "canvas", first: true, predicate: ["canvas"], descendants: true }], exportAs: ["wrQrCode"], usesInheritance: true, usesOnChanges: true, ngImport: i0, template: "<ng-container *ngIf=\"isBrowser\">\n <canvas #canvas></canvas>\n</ng-container>\n", dependencies: [{ kind: "directive", type: i2.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); }
1068
+ }
1069
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.1.3", ngImport: i0, type: WrQRCode, decorators: [{
1070
+ type: Component,
1071
+ args: [{ selector: 'wr-qrcode', exportAs: 'wrQrCode', changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, template: "<ng-container *ngIf=\"isBrowser\">\n <canvas #canvas></canvas>\n</ng-container>\n" }]
1072
+ }], ctorParameters: function () { return [{ type: Object, decorators: [{
1073
+ type: Inject,
1074
+ args: [PLATFORM_ID]
1075
+ }] }, { type: i0.ChangeDetectorRef }, { type: i0.ElementRef }, { type: i1.WrIconService }]; }, propDecorators: { class: [{
1076
+ type: HostBinding,
1077
+ args: ['class']
1078
+ }], canvas: [{
1079
+ type: ViewChild,
1080
+ args: ['canvas', { static: false }]
1081
+ }], value: [{
1082
+ type: Input
1083
+ }], level: [{
1084
+ type: Input
1085
+ }], padding: [{
1086
+ type: Input
1087
+ }], color: [{
1088
+ type: Input
1089
+ }], bgColor: [{
1090
+ type: Input
1091
+ }], size: [{
1092
+ type: Input
1093
+ }], icon: [{
1094
+ type: Input
1095
+ }], iconSize: [{
1096
+ type: Input
1097
+ }] } });
1098
+
1099
+ class WrQRCodeModule {
1100
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.1.3", ngImport: i0, type: WrQRCodeModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
1101
+ static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "16.1.3", ngImport: i0, type: WrQRCodeModule, declarations: [WrQRCode], imports: [CommonModule, WrIconModule], exports: [WrQRCode] }); }
1102
+ static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "16.1.3", ngImport: i0, type: WrQRCodeModule, imports: [CommonModule, WrIconModule] }); }
1103
+ }
1104
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.1.3", ngImport: i0, type: WrQRCodeModule, decorators: [{
1105
+ type: NgModule,
1106
+ args: [{
1107
+ imports: [CommonModule, WrIconModule],
1108
+ declarations: [WrQRCode],
1109
+ exports: [WrQRCode],
1110
+ }]
1111
+ }] });
1112
+
1113
+ /**
1114
+ * Generated bundle index. Do not edit.
1115
+ */
1116
+
1117
+ export { WrQRCode, WrQRCodeModule };
1118
+ //# sourceMappingURL=ngwr-qrcode.mjs.map