ng-zorro-antd-qr-code.mjs 60 KB

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