qrcode.react
Advanced tools
Comparing version 3.1.0 to 4.0.0
@@ -31,3 +31,3 @@ var __defProp = Object.defineProperty; | ||
// src/index.tsx | ||
import React, { useRef, useEffect, useState } from "react"; | ||
import React from "react"; | ||
@@ -42,7 +42,15 @@ // src/third-party/qrcodegen/index.ts | ||
((qrcodegen2) => { | ||
const _QrCode = class { | ||
const _QrCode = class _QrCode { | ||
/*-- Constructor (low level) and fields --*/ | ||
// Creates a new QR Code with the given version number, | ||
// error correction level, data codeword bytes, and mask number. | ||
// This is a low-level API that most users should not use directly. | ||
// A mid-level API is the encodeSegments() function. | ||
constructor(version, errorCorrectionLevel, dataCodewords, msk) { | ||
this.version = version; | ||
this.errorCorrectionLevel = errorCorrectionLevel; | ||
// The modules of this QR Code (false = light, true = dark). | ||
// Immutable after constructor finishes. Accessed through getModule(). | ||
this.modules = []; | ||
// Indicates function modules that are not subjected to masking. Discarded when constructor finishes. | ||
this.isFunction = []; | ||
@@ -83,2 +91,8 @@ if (version < _QrCode.MIN_VERSION || version > _QrCode.MAX_VERSION) | ||
} | ||
/*-- Static factory functions (high level) --*/ | ||
// Returns a QR Code representing the given Unicode text string at the given error correction level. | ||
// As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer | ||
// Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible | ||
// QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the | ||
// ecl argument if it can be done without increasing the version. | ||
static encodeText(text, ecl) { | ||
@@ -88,2 +102,6 @@ const segs = qrcodegen2.QrSegment.makeSegments(text); | ||
} | ||
// Returns a QR Code representing the given binary data at the given error correction level. | ||
// This function always encodes using the binary segment mode, not any text mode. The maximum number of | ||
// bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output. | ||
// The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version. | ||
static encodeBinary(data, ecl) { | ||
@@ -93,2 +111,12 @@ const seg = qrcodegen2.QrSegment.makeBytes(data); | ||
} | ||
/*-- Static factory functions (mid level) --*/ | ||
// Returns a QR Code representing the given segments with the given encoding parameters. | ||
// The smallest possible QR Code version within the given range is automatically | ||
// chosen for the output. Iff boostEcl is true, then the ECC level of the result | ||
// may be higher than the ecl argument if it can be done without increasing the | ||
// version. The mask number is either between 0 to 7 (inclusive) to force that | ||
// mask, or -1 to automatically choose an appropriate mask (which may be slow). | ||
// This function allows the user to create a custom sequence of segments that switches | ||
// between modes (such as alphanumeric and byte) to encode text in less space. | ||
// This is a mid-level API; the high-level API is encodeText() and encodeBinary(). | ||
static encodeSegments(segs, ecl, minVersion = 1, maxVersion = 40, mask = -1, boostEcl = true) { | ||
@@ -134,8 +162,15 @@ if (!(_QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= _QrCode.MAX_VERSION) || mask < -1 || mask > 7) | ||
} | ||
/*-- Accessor methods --*/ | ||
// Returns the color of the module (pixel) at the given coordinates, which is false | ||
// for light or true for dark. The top left corner has the coordinates (x=0, y=0). | ||
// If the given coordinates are out of bounds, then false (light) is returned. | ||
getModule(x, y) { | ||
return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y][x]; | ||
} | ||
// Modified to expose modules for easy access | ||
getModules() { | ||
return this.modules; | ||
} | ||
/*-- Private helper methods for constructor: Drawing function modules --*/ | ||
// Reads this object's version field, and draws and marks all function modules. | ||
drawFunctionPatterns() { | ||
@@ -160,2 +195,4 @@ for (let i = 0; i < this.size; i++) { | ||
} | ||
// Draws two copies of the format bits (with its own error correction code) | ||
// based on the given mask and this object's error correction level field. | ||
drawFormatBits(mask) { | ||
@@ -181,2 +218,4 @@ const data = this.errorCorrectionLevel.formatBits << 3 | mask; | ||
} | ||
// Draws two copies of the version bits (with its own error correction code), | ||
// based on this object's version field, iff 7 <= version <= 40. | ||
drawVersion() { | ||
@@ -198,2 +237,4 @@ if (this.version < 7) | ||
} | ||
// Draws a 9*9 finder pattern including the border separator, | ||
// with the center module at (x, y). Modules can be out of bounds. | ||
drawFinderPattern(x, y) { | ||
@@ -210,2 +251,4 @@ for (let dy = -4; dy <= 4; dy++) { | ||
} | ||
// Draws a 5*5 alignment pattern, with the center module | ||
// at (x, y). All modules must be in bounds. | ||
drawAlignmentPattern(x, y) { | ||
@@ -217,2 +260,4 @@ for (let dy = -2; dy <= 2; dy++) { | ||
} | ||
// Sets the color of a module and marks it as a function module. | ||
// Only used by the constructor. Coordinates must be in bounds. | ||
setFunctionModule(x, y, isDark) { | ||
@@ -222,2 +267,5 @@ this.modules[y][x] = isDark; | ||
} | ||
/*-- Private helper methods for constructor: Codewords and masking --*/ | ||
// Returns a new byte string representing the given data with the appropriate error correction | ||
// codewords appended to it, based on this object's version and error correction level. | ||
addEccAndInterleave(data) { | ||
@@ -253,2 +301,4 @@ const ver = this.version; | ||
} | ||
// Draws the given sequence of 8-bit codewords (data and error correction) onto the entire | ||
// data area of this QR Code. Function modules need to be marked off before this is called. | ||
drawCodewords(data) { | ||
@@ -275,2 +325,7 @@ if (data.length != Math.floor(_QrCode.getNumRawDataModules(this.version) / 8)) | ||
} | ||
// XORs the codeword modules in this QR Code with the given mask pattern. | ||
// The function modules must be marked and the codeword bits must be drawn | ||
// before masking. Due to the arithmetic of XOR, calling applyMask() with | ||
// the same mask value a second time will undo the mask. A final well-formed | ||
// QR Code needs exactly one (not zero, two, etc.) mask applied. | ||
applyMask(mask) { | ||
@@ -315,2 +370,4 @@ if (mask < 0 || mask > 7) | ||
} | ||
// Calculates and returns the penalty score based on state of this QR Code's current modules. | ||
// This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score. | ||
getPenaltyScore() { | ||
@@ -377,2 +434,6 @@ let result = 0; | ||
} | ||
/*-- Private helper functions --*/ | ||
// Returns an ascending list of positions of alignment patterns for this version number. | ||
// Each position is in the range [0,177), and are used on both the x and y axes. | ||
// This could be implemented as lookup table of 40 variable-length lists of integers. | ||
getAlignmentPatternPositions() { | ||
@@ -390,2 +451,5 @@ if (this.version == 1) | ||
} | ||
// Returns the number of data bits that can be stored in a QR Code of the given version number, after | ||
// all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8. | ||
// The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table. | ||
static getNumRawDataModules(ver) { | ||
@@ -404,5 +468,10 @@ if (ver < _QrCode.MIN_VERSION || ver > _QrCode.MAX_VERSION) | ||
} | ||
// Returns the number of 8-bit data (i.e. not error correction) codewords contained in any | ||
// QR Code of the given version number and error correction level, with remainder bits discarded. | ||
// This stateless pure function could be implemented as a (40*4)-cell lookup table. | ||
static getNumDataCodewords(ver, ecl) { | ||
return Math.floor(_QrCode.getNumRawDataModules(ver) / 8) - _QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver] * _QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver]; | ||
} | ||
// Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be | ||
// implemented as a lookup table over all possible parameter values, instead of as an algorithm. | ||
static reedSolomonComputeDivisor(degree) { | ||
@@ -426,2 +495,3 @@ if (degree < 1 || degree > 255) | ||
} | ||
// Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials. | ||
static reedSolomonComputeRemainder(data, divisor) { | ||
@@ -436,2 +506,4 @@ let result = divisor.map((_) => 0); | ||
} | ||
// Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result | ||
// are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8. | ||
static reedSolomonMultiply(x, y) { | ||
@@ -448,2 +520,4 @@ if (x >>> 8 != 0 || y >>> 8 != 0) | ||
} | ||
// Can only be called immediately after a light run is added, and | ||
// returns either 0, 1, or 2. A helper function for getPenaltyScore(). | ||
finderPenaltyCountPatterns(runHistory) { | ||
@@ -455,2 +529,3 @@ const n = runHistory[1]; | ||
} | ||
// Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore(). | ||
finderPenaltyTerminateAndCount(currentRunColor, currentRunLength, runHistory) { | ||
@@ -465,2 +540,3 @@ if (currentRunColor) { | ||
} | ||
// Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore(). | ||
finderPenaltyAddHistory(currentRunLength, runHistory) { | ||
@@ -473,22 +549,38 @@ if (runHistory[0] == 0) | ||
}; | ||
let QrCode = _QrCode; | ||
QrCode.MIN_VERSION = 1; | ||
QrCode.MAX_VERSION = 40; | ||
QrCode.PENALTY_N1 = 3; | ||
QrCode.PENALTY_N2 = 3; | ||
QrCode.PENALTY_N3 = 40; | ||
QrCode.PENALTY_N4 = 10; | ||
QrCode.ECC_CODEWORDS_PER_BLOCK = [ | ||
/*-- Constants and tables --*/ | ||
// The minimum version number supported in the QR Code Model 2 standard. | ||
_QrCode.MIN_VERSION = 1; | ||
// The maximum version number supported in the QR Code Model 2 standard. | ||
_QrCode.MAX_VERSION = 40; | ||
// For use in getPenaltyScore(), when evaluating which mask is best. | ||
_QrCode.PENALTY_N1 = 3; | ||
_QrCode.PENALTY_N2 = 3; | ||
_QrCode.PENALTY_N3 = 40; | ||
_QrCode.PENALTY_N4 = 10; | ||
_QrCode.ECC_CODEWORDS_PER_BLOCK = [ | ||
// Version: (note that index 0 is for padding, and is set to an illegal value) | ||
//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 | ||
[-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, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], | ||
// Low | ||
[-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, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28], | ||
// Medium | ||
[-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, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], | ||
// Quartile | ||
[-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, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30] | ||
// High | ||
]; | ||
QrCode.NUM_ERROR_CORRECTION_BLOCKS = [ | ||
_QrCode.NUM_ERROR_CORRECTION_BLOCKS = [ | ||
// Version: (note that index 0 is for padding, and is set to an illegal value) | ||
//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 | ||
[-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, 19, 19, 20, 21, 22, 24, 25], | ||
// Low | ||
[-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, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49], | ||
// Medium | ||
[-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, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68], | ||
// Quartile | ||
[-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, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81] | ||
// High | ||
]; | ||
qrcodegen2.QrCode = QrCode; | ||
let QrCode = _QrCode; | ||
qrcodegen2.QrCode = _QrCode; | ||
function appendBits(val, len, bb) { | ||
@@ -507,3 +599,7 @@ if (len < 0 || len > 31 || val >>> len != 0) | ||
} | ||
const _QrSegment = class { | ||
const _QrSegment = class _QrSegment { | ||
/*-- Constructor (low level) and fields --*/ | ||
// Creates a new QR Code segment with the given attributes and data. | ||
// The character count (numChars) must agree with the mode and the bit buffer length, | ||
// but the constraint isn't checked. The given bit buffer is cloned and stored. | ||
constructor(mode, numChars, bitData) { | ||
@@ -517,2 +613,6 @@ this.mode = mode; | ||
} | ||
/*-- Static factory functions (mid level) --*/ | ||
// Returns a segment representing the given binary data encoded in | ||
// byte mode. All input byte arrays are acceptable. Any text string | ||
// can be converted to UTF-8 bytes and encoded as a byte mode segment. | ||
static makeBytes(data) { | ||
@@ -524,2 +624,3 @@ let bb = []; | ||
} | ||
// Returns a segment representing the given string of decimal digits encoded in numeric mode. | ||
static makeNumeric(digits) { | ||
@@ -531,3 +632,3 @@ if (!_QrSegment.isNumeric(digits)) | ||
const n = Math.min(digits.length - i, 3); | ||
appendBits(parseInt(digits.substr(i, n), 10), n * 3 + 1, bb); | ||
appendBits(parseInt(digits.substring(i, i + n), 10), n * 3 + 1, bb); | ||
i += n; | ||
@@ -537,2 +638,5 @@ } | ||
} | ||
// Returns a segment representing the given text string encoded in alphanumeric mode. | ||
// The characters allowed are: 0 to 9, A to Z (uppercase only), space, | ||
// dollar, percent, asterisk, plus, hyphen, period, slash, colon. | ||
static makeAlphanumeric(text) { | ||
@@ -552,2 +656,4 @@ if (!_QrSegment.isAlphanumeric(text)) | ||
} | ||
// Returns a new mutable list of zero or more segments to represent the given Unicode text string. | ||
// The result may use various segment modes and switch modes to optimize the length of the bit stream. | ||
static makeSegments(text) { | ||
@@ -563,2 +669,4 @@ if (text == "") | ||
} | ||
// Returns a segment representing an Extended Channel Interpretation | ||
// (ECI) designator with the given assignment value. | ||
static makeEci(assignVal) { | ||
@@ -580,11 +688,20 @@ let bb = []; | ||
} | ||
// Tests whether the given string can be encoded as a segment in numeric mode. | ||
// A string is encodable iff each character is in the range 0 to 9. | ||
static isNumeric(text) { | ||
return _QrSegment.NUMERIC_REGEX.test(text); | ||
} | ||
// Tests whether the given string can be encoded as a segment in alphanumeric mode. | ||
// A string is encodable iff each character is in the following set: 0 to 9, A to Z | ||
// (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon. | ||
static isAlphanumeric(text) { | ||
return _QrSegment.ALPHANUMERIC_REGEX.test(text); | ||
} | ||
/*-- Methods --*/ | ||
// Returns a new copy of the data bits of this segment. | ||
getData() { | ||
return this.bitData.slice(); | ||
} | ||
// (Package-private) Calculates and returns the number of bits needed to encode the given segments at | ||
// the given version. The result is infinity if a segment has too many characters to fit its length field. | ||
static getTotalBits(segs, version) { | ||
@@ -600,2 +717,3 @@ let result = 0; | ||
} | ||
// Returns a new array of bytes representing the given string encoded in UTF-8. | ||
static toUtf8ByteArray(str) { | ||
@@ -608,3 +726,3 @@ str = encodeURI(str); | ||
else { | ||
result.push(parseInt(str.substr(i + 1, 2), 16)); | ||
result.push(parseInt(str.substring(i + 1, i + 3), 16)); | ||
i += 2; | ||
@@ -616,7 +734,12 @@ } | ||
}; | ||
/*-- Constants --*/ | ||
// Describes precisely all strings that are encodable in numeric mode. | ||
_QrSegment.NUMERIC_REGEX = /^[0-9]*$/; | ||
// Describes precisely all strings that are encodable in alphanumeric mode. | ||
_QrSegment.ALPHANUMERIC_REGEX = /^[A-Z0-9 $%*+.\/:-]*$/; | ||
// The set of all legal characters in alphanumeric mode, | ||
// where each character value maps to the index in the string. | ||
_QrSegment.ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; | ||
let QrSegment = _QrSegment; | ||
QrSegment.NUMERIC_REGEX = /^[0-9]*$/; | ||
QrSegment.ALPHANUMERIC_REGEX = /^[A-Z0-9 $%*+.\/:-]*$/; | ||
QrSegment.ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; | ||
qrcodegen2.QrSegment = QrSegment; | ||
qrcodegen2.QrSegment = _QrSegment; | ||
})(qrcodegen || (qrcodegen = {})); | ||
@@ -626,3 +749,5 @@ ((qrcodegen2) => { | ||
((QrCode2) => { | ||
const _Ecc = class { | ||
const _Ecc = class _Ecc { | ||
// The QR Code can tolerate about 30% erroneous codewords | ||
/*-- Constructor and fields --*/ | ||
constructor(ordinal, formatBits) { | ||
@@ -633,8 +758,12 @@ this.ordinal = ordinal; | ||
}; | ||
/*-- Constants --*/ | ||
_Ecc.LOW = new _Ecc(0, 1); | ||
// The QR Code can tolerate about 7% erroneous codewords | ||
_Ecc.MEDIUM = new _Ecc(1, 0); | ||
// The QR Code can tolerate about 15% erroneous codewords | ||
_Ecc.QUARTILE = new _Ecc(2, 3); | ||
// The QR Code can tolerate about 25% erroneous codewords | ||
_Ecc.HIGH = new _Ecc(3, 2); | ||
let Ecc = _Ecc; | ||
Ecc.LOW = new _Ecc(0, 1); | ||
Ecc.MEDIUM = new _Ecc(1, 0); | ||
Ecc.QUARTILE = new _Ecc(2, 3); | ||
Ecc.HIGH = new _Ecc(3, 2); | ||
QrCode2.Ecc = Ecc; | ||
QrCode2.Ecc = _Ecc; | ||
})(QrCode = qrcodegen2.QrCode || (qrcodegen2.QrCode = {})); | ||
@@ -645,3 +774,4 @@ })(qrcodegen || (qrcodegen = {})); | ||
((QrSegment2) => { | ||
const _Mode = class { | ||
const _Mode = class _Mode { | ||
/*-- Constructor and fields --*/ | ||
constructor(modeBits, numBitsCharCount) { | ||
@@ -651,2 +781,5 @@ this.modeBits = modeBits; | ||
} | ||
/*-- Method --*/ | ||
// (Package-private) Returns the bit width of the character count field for a segment in | ||
// this mode in a QR Code at the given version number. The result is in the range [0, 16]. | ||
numCharCountBits(ver) { | ||
@@ -656,9 +789,10 @@ return this.numBitsCharCount[Math.floor((ver + 7) / 17)]; | ||
}; | ||
/*-- Constants --*/ | ||
_Mode.NUMERIC = new _Mode(1, [10, 12, 14]); | ||
_Mode.ALPHANUMERIC = new _Mode(2, [9, 11, 13]); | ||
_Mode.BYTE = new _Mode(4, [8, 16, 16]); | ||
_Mode.KANJI = new _Mode(8, [8, 10, 12]); | ||
_Mode.ECI = new _Mode(7, [0, 0, 0]); | ||
let Mode = _Mode; | ||
Mode.NUMERIC = new _Mode(1, [10, 12, 14]); | ||
Mode.ALPHANUMERIC = new _Mode(2, [9, 11, 13]); | ||
Mode.BYTE = new _Mode(4, [8, 16, 16]); | ||
Mode.KANJI = new _Mode(8, [8, 10, 12]); | ||
Mode.ECI = new _Mode(7, [0, 0, 0]); | ||
QrSegment2.Mode = Mode; | ||
QrSegment2.Mode = _Mode; | ||
})(QrSegment = qrcodegen2.QrSegment || (qrcodegen2.QrSegment = {})); | ||
@@ -685,3 +819,5 @@ })(qrcodegen || (qrcodegen = {})); | ||
var DEFAULT_INCLUDEMARGIN = false; | ||
var MARGIN_SIZE = 4; | ||
var DEFAULT_MINVERSION = 1; | ||
var SPEC_MARGIN_SIZE = 4; | ||
var DEFAULT_MARGIN_SIZE = 0; | ||
var DEFAULT_IMG_SCALE = 0.1; | ||
@@ -694,3 +830,5 @@ function generatePath(modules, margin = 0) { | ||
if (!cell && start !== null) { | ||
ops.push(`M${start + margin} ${y + margin}h${x - start}v1H${start + margin}z`); | ||
ops.push( | ||
`M${start + margin} ${y + margin}h${x - start}v1H${start + margin}z` | ||
); | ||
start = null; | ||
@@ -706,3 +844,5 @@ return; | ||
} else { | ||
ops.push(`M${start + margin},${y + margin} h${x + 1 - start}v1H${start + margin}z`); | ||
ops.push( | ||
`M${start + margin},${y + margin} h${x + 1 - start}v1H${start + margin}z` | ||
); | ||
} | ||
@@ -731,7 +871,6 @@ return; | ||
} | ||
function getImageSettings(cells, size, includeMargin, imageSettings) { | ||
function getImageSettings(cells, size, margin, imageSettings) { | ||
if (imageSettings == null) { | ||
return null; | ||
} | ||
const margin = includeMargin ? MARGIN_SIZE : 0; | ||
const numCells = cells.length + margin * 2; | ||
@@ -744,2 +883,3 @@ const defaultSize = Math.floor(size * DEFAULT_IMG_SCALE); | ||
const y = imageSettings.y == null ? cells.length / 2 - h / 2 : imageSettings.y * scale; | ||
const opacity = imageSettings.opacity == null ? 1 : imageSettings.opacity; | ||
let excavation = null; | ||
@@ -753,4 +893,53 @@ if (imageSettings.excavate) { | ||
} | ||
return { x, y, h, w, excavation }; | ||
const crossOrigin = imageSettings.crossOrigin; | ||
return { x, y, h, w, excavation, opacity, crossOrigin }; | ||
} | ||
function getMarginSize(includeMargin, marginSize) { | ||
if (marginSize != null) { | ||
return Math.max(Math.floor(marginSize), 0); | ||
} | ||
return includeMargin ? SPEC_MARGIN_SIZE : DEFAULT_MARGIN_SIZE; | ||
} | ||
function useQRCode({ | ||
value, | ||
level, | ||
minVersion, | ||
includeMargin, | ||
marginSize, | ||
imageSettings, | ||
size | ||
}) { | ||
let qrcode = React.useMemo(() => { | ||
const segments = qrcodegen_default.QrSegment.makeSegments(value); | ||
return qrcodegen_default.QrCode.encodeSegments( | ||
segments, | ||
ERROR_LEVEL_MAP[level], | ||
minVersion | ||
); | ||
}, [value, level, minVersion]); | ||
const { cells, margin, numCells, calculatedImageSettings } = React.useMemo(() => { | ||
let cells2 = qrcode.getModules(); | ||
const margin2 = getMarginSize(includeMargin, marginSize); | ||
const numCells2 = cells2.length + margin2 * 2; | ||
const calculatedImageSettings2 = getImageSettings( | ||
cells2, | ||
size, | ||
margin2, | ||
imageSettings | ||
); | ||
return { | ||
cells: cells2, | ||
margin: margin2, | ||
numCells: numCells2, | ||
calculatedImageSettings: calculatedImageSettings2 | ||
}; | ||
}, [qrcode, size, imageSettings, includeMargin, marginSize]); | ||
return { | ||
qrcode, | ||
margin, | ||
cells, | ||
numCells, | ||
calculatedImageSettings | ||
}; | ||
} | ||
var SUPPORTS_PATH2D = function() { | ||
@@ -764,152 +953,218 @@ try { | ||
}(); | ||
function QRCodeCanvas(props) { | ||
const _a = props, { | ||
value, | ||
size = DEFAULT_SIZE, | ||
level = DEFAULT_LEVEL, | ||
bgColor = DEFAULT_BGCOLOR, | ||
fgColor = DEFAULT_FGCOLOR, | ||
includeMargin = DEFAULT_INCLUDEMARGIN, | ||
style, | ||
imageSettings | ||
} = _a, otherProps = __objRest(_a, [ | ||
"value", | ||
"size", | ||
"level", | ||
"bgColor", | ||
"fgColor", | ||
"includeMargin", | ||
"style", | ||
"imageSettings" | ||
]); | ||
const imgSrc = imageSettings == null ? void 0 : imageSettings.src; | ||
const _canvas = useRef(null); | ||
const _image = useRef(null); | ||
const [isImgLoaded, setIsImageLoaded] = useState(false); | ||
useEffect(() => { | ||
if (_canvas.current != null) { | ||
const canvas = _canvas.current; | ||
const ctx = canvas.getContext("2d"); | ||
if (!ctx) { | ||
return; | ||
} | ||
let cells = qrcodegen_default.QrCode.encodeText(value, ERROR_LEVEL_MAP[level]).getModules(); | ||
const margin = includeMargin ? MARGIN_SIZE : 0; | ||
const numCells = cells.length + margin * 2; | ||
const calculatedImageSettings = getImageSettings(cells, size, includeMargin, imageSettings); | ||
const image = _image.current; | ||
const haveImageToRender = calculatedImageSettings != null && image !== null && image.complete && image.naturalHeight !== 0 && image.naturalWidth !== 0; | ||
if (haveImageToRender) { | ||
if (calculatedImageSettings.excavation != null) { | ||
cells = excavateModules(cells, calculatedImageSettings.excavation); | ||
var QRCodeCanvas = React.forwardRef( | ||
function QRCodeCanvas2(props, forwardedRef) { | ||
const _a = props, { | ||
value, | ||
size = DEFAULT_SIZE, | ||
level = DEFAULT_LEVEL, | ||
bgColor = DEFAULT_BGCOLOR, | ||
fgColor = DEFAULT_FGCOLOR, | ||
includeMargin = DEFAULT_INCLUDEMARGIN, | ||
minVersion = DEFAULT_MINVERSION, | ||
marginSize, | ||
imageSettings | ||
} = _a, extraProps = __objRest(_a, [ | ||
"value", | ||
"size", | ||
"level", | ||
"bgColor", | ||
"fgColor", | ||
"includeMargin", | ||
"minVersion", | ||
"marginSize", | ||
"imageSettings" | ||
]); | ||
const _b = extraProps, { style } = _b, otherProps = __objRest(_b, ["style"]); | ||
const imgSrc = imageSettings == null ? void 0 : imageSettings.src; | ||
const _canvas = React.useRef(null); | ||
const _image = React.useRef(null); | ||
const setCanvasRef = React.useCallback( | ||
(node) => { | ||
_canvas.current = node; | ||
if (typeof forwardedRef === "function") { | ||
forwardedRef(node); | ||
} else if (forwardedRef) { | ||
forwardedRef.current = node; | ||
} | ||
} | ||
const pixelRatio = window.devicePixelRatio || 1; | ||
canvas.height = canvas.width = size * pixelRatio; | ||
const scale = size / numCells * pixelRatio; | ||
ctx.scale(scale, scale); | ||
ctx.fillStyle = bgColor; | ||
ctx.fillRect(0, 0, numCells, numCells); | ||
ctx.fillStyle = fgColor; | ||
if (SUPPORTS_PATH2D) { | ||
ctx.fill(new Path2D(generatePath(cells, margin))); | ||
} else { | ||
cells.forEach(function(row, rdx) { | ||
row.forEach(function(cell, cdx) { | ||
if (cell) { | ||
ctx.fillRect(cdx + margin, rdx + margin, 1, 1); | ||
} | ||
}, | ||
[forwardedRef] | ||
); | ||
const [isImgLoaded, setIsImageLoaded] = React.useState(false); | ||
const { margin, cells, numCells, calculatedImageSettings } = useQRCode({ | ||
value, | ||
level, | ||
minVersion, | ||
includeMargin, | ||
marginSize, | ||
imageSettings, | ||
size | ||
}); | ||
React.useEffect(() => { | ||
if (_canvas.current != null) { | ||
const canvas = _canvas.current; | ||
const ctx = canvas.getContext("2d"); | ||
if (!ctx) { | ||
return; | ||
} | ||
let cellsToDraw = cells; | ||
const image = _image.current; | ||
const haveImageToRender = calculatedImageSettings != null && image !== null && image.complete && image.naturalHeight !== 0 && image.naturalWidth !== 0; | ||
if (haveImageToRender) { | ||
if (calculatedImageSettings.excavation != null) { | ||
cellsToDraw = excavateModules( | ||
cells, | ||
calculatedImageSettings.excavation | ||
); | ||
} | ||
} | ||
const pixelRatio = window.devicePixelRatio || 1; | ||
canvas.height = canvas.width = size * pixelRatio; | ||
const scale = size / numCells * pixelRatio; | ||
ctx.scale(scale, scale); | ||
ctx.fillStyle = bgColor; | ||
ctx.fillRect(0, 0, numCells, numCells); | ||
ctx.fillStyle = fgColor; | ||
if (SUPPORTS_PATH2D) { | ||
ctx.fill(new Path2D(generatePath(cellsToDraw, margin))); | ||
} else { | ||
cells.forEach(function(row, rdx) { | ||
row.forEach(function(cell, cdx) { | ||
if (cell) { | ||
ctx.fillRect(cdx + margin, rdx + margin, 1, 1); | ||
} | ||
}); | ||
}); | ||
}); | ||
} | ||
if (calculatedImageSettings) { | ||
ctx.globalAlpha = calculatedImageSettings.opacity; | ||
} | ||
if (haveImageToRender) { | ||
ctx.drawImage( | ||
image, | ||
calculatedImageSettings.x + margin, | ||
calculatedImageSettings.y + margin, | ||
calculatedImageSettings.w, | ||
calculatedImageSettings.h | ||
); | ||
} | ||
} | ||
if (haveImageToRender) { | ||
ctx.drawImage(image, calculatedImageSettings.x + margin, calculatedImageSettings.y + margin, calculatedImageSettings.w, calculatedImageSettings.h); | ||
} | ||
}); | ||
React.useEffect(() => { | ||
setIsImageLoaded(false); | ||
}, [imgSrc]); | ||
const canvasStyle = __spreadValues({ height: size, width: size }, style); | ||
let img = null; | ||
if (imgSrc != null) { | ||
img = /* @__PURE__ */ React.createElement( | ||
"img", | ||
{ | ||
src: imgSrc, | ||
key: imgSrc, | ||
style: { display: "none" }, | ||
onLoad: () => { | ||
setIsImageLoaded(true); | ||
}, | ||
ref: _image, | ||
crossOrigin: calculatedImageSettings == null ? void 0 : calculatedImageSettings.crossOrigin | ||
} | ||
); | ||
} | ||
}); | ||
useEffect(() => { | ||
setIsImageLoaded(false); | ||
}, [imgSrc]); | ||
const canvasStyle = __spreadValues({ height: size, width: size }, style); | ||
let img = null; | ||
if (imgSrc != null) { | ||
img = /* @__PURE__ */ React.createElement("img", { | ||
src: imgSrc, | ||
key: imgSrc, | ||
style: { display: "none" }, | ||
onLoad: () => { | ||
setIsImageLoaded(true); | ||
}, | ||
ref: _image | ||
return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement( | ||
"canvas", | ||
__spreadValues({ | ||
style: canvasStyle, | ||
height: size, | ||
width: size, | ||
ref: setCanvasRef, | ||
role: "img" | ||
}, otherProps) | ||
), img); | ||
} | ||
); | ||
QRCodeCanvas.displayName = "QRCodeCanvas"; | ||
var QRCodeSVG = React.forwardRef( | ||
function QRCodeSVG2(props, forwardedRef) { | ||
const _a = props, { | ||
value, | ||
size = DEFAULT_SIZE, | ||
level = DEFAULT_LEVEL, | ||
bgColor = DEFAULT_BGCOLOR, | ||
fgColor = DEFAULT_FGCOLOR, | ||
includeMargin = DEFAULT_INCLUDEMARGIN, | ||
minVersion = DEFAULT_MINVERSION, | ||
title, | ||
marginSize, | ||
imageSettings | ||
} = _a, otherProps = __objRest(_a, [ | ||
"value", | ||
"size", | ||
"level", | ||
"bgColor", | ||
"fgColor", | ||
"includeMargin", | ||
"minVersion", | ||
"title", | ||
"marginSize", | ||
"imageSettings" | ||
]); | ||
const { margin, cells, numCells, calculatedImageSettings } = useQRCode({ | ||
value, | ||
level, | ||
minVersion, | ||
includeMargin, | ||
marginSize, | ||
imageSettings, | ||
size | ||
}); | ||
} | ||
return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("canvas", __spreadValues({ | ||
style: canvasStyle, | ||
height: size, | ||
width: size, | ||
ref: _canvas | ||
}, otherProps)), img); | ||
} | ||
function QRCodeSVG(props) { | ||
const _a = props, { | ||
value, | ||
size = DEFAULT_SIZE, | ||
level = DEFAULT_LEVEL, | ||
bgColor = DEFAULT_BGCOLOR, | ||
fgColor = DEFAULT_FGCOLOR, | ||
includeMargin = DEFAULT_INCLUDEMARGIN, | ||
imageSettings | ||
} = _a, otherProps = __objRest(_a, [ | ||
"value", | ||
"size", | ||
"level", | ||
"bgColor", | ||
"fgColor", | ||
"includeMargin", | ||
"imageSettings" | ||
]); | ||
let cells = qrcodegen_default.QrCode.encodeText(value, ERROR_LEVEL_MAP[level]).getModules(); | ||
const margin = includeMargin ? MARGIN_SIZE : 0; | ||
const numCells = cells.length + margin * 2; | ||
const calculatedImageSettings = getImageSettings(cells, size, includeMargin, imageSettings); | ||
let image = null; | ||
if (imageSettings != null && calculatedImageSettings != null) { | ||
if (calculatedImageSettings.excavation != null) { | ||
cells = excavateModules(cells, calculatedImageSettings.excavation); | ||
let cellsToDraw = cells; | ||
let image = null; | ||
if (imageSettings != null && calculatedImageSettings != null) { | ||
if (calculatedImageSettings.excavation != null) { | ||
cellsToDraw = excavateModules( | ||
cells, | ||
calculatedImageSettings.excavation | ||
); | ||
} | ||
image = /* @__PURE__ */ React.createElement( | ||
"image", | ||
{ | ||
href: imageSettings.src, | ||
height: calculatedImageSettings.h, | ||
width: calculatedImageSettings.w, | ||
x: calculatedImageSettings.x + margin, | ||
y: calculatedImageSettings.y + margin, | ||
preserveAspectRatio: "none", | ||
opacity: calculatedImageSettings.opacity, | ||
crossOrigin: calculatedImageSettings.crossOrigin | ||
} | ||
); | ||
} | ||
image = /* @__PURE__ */ React.createElement("image", { | ||
xlinkHref: imageSettings.src, | ||
height: calculatedImageSettings.h, | ||
width: calculatedImageSettings.w, | ||
x: calculatedImageSettings.x + margin, | ||
y: calculatedImageSettings.y + margin, | ||
preserveAspectRatio: "none" | ||
}); | ||
const fgPath = generatePath(cellsToDraw, margin); | ||
return /* @__PURE__ */ React.createElement( | ||
"svg", | ||
__spreadValues({ | ||
height: size, | ||
width: size, | ||
viewBox: `0 0 ${numCells} ${numCells}`, | ||
ref: forwardedRef, | ||
role: "img" | ||
}, otherProps), | ||
!!title && /* @__PURE__ */ React.createElement("title", null, title), | ||
/* @__PURE__ */ React.createElement( | ||
"path", | ||
{ | ||
fill: bgColor, | ||
d: `M0,0 h${numCells}v${numCells}H0z`, | ||
shapeRendering: "crispEdges" | ||
} | ||
), | ||
/* @__PURE__ */ React.createElement("path", { fill: fgColor, d: fgPath, shapeRendering: "crispEdges" }), | ||
image | ||
); | ||
} | ||
const fgPath = generatePath(cells, margin); | ||
return /* @__PURE__ */ React.createElement("svg", __spreadValues({ | ||
height: size, | ||
width: size, | ||
viewBox: `0 0 ${numCells} ${numCells}` | ||
}, otherProps), /* @__PURE__ */ React.createElement("path", { | ||
fill: bgColor, | ||
d: `M0,0 h${numCells}v${numCells}H0z`, | ||
shapeRendering: "crispEdges" | ||
}), /* @__PURE__ */ React.createElement("path", { | ||
fill: fgColor, | ||
d: fgPath, | ||
shapeRendering: "crispEdges" | ||
}), image); | ||
} | ||
var QRCode = (props) => { | ||
const _a = props, { renderAs } = _a, otherProps = __objRest(_a, ["renderAs"]); | ||
if (renderAs === "svg") { | ||
return /* @__PURE__ */ React.createElement(QRCodeSVG, __spreadValues({}, otherProps)); | ||
} | ||
return /* @__PURE__ */ React.createElement(QRCodeCanvas, __spreadValues({}, otherProps)); | ||
}; | ||
); | ||
QRCodeSVG.displayName = "QRCodeSVG"; | ||
export { | ||
QRCodeCanvas, | ||
QRCodeSVG, | ||
QRCode as default | ||
QRCodeSVG | ||
}; |
@@ -1,2 +0,2 @@ | ||
import React, { CSSProperties } from 'react'; | ||
import React from 'react'; | ||
@@ -9,31 +9,110 @@ /** | ||
declare type ImageSettings = { | ||
type ErrorCorrectionLevel = 'L' | 'M' | 'Q' | 'H'; | ||
type CrossOrigin = 'anonymous' | 'use-credentials' | '' | undefined; | ||
type ImageSettings = { | ||
/** | ||
* The URI of the embedded image. | ||
*/ | ||
src: string; | ||
/** | ||
* The height, in pixels, of the image. | ||
*/ | ||
height: number; | ||
/** | ||
* The width, in pixels, of the image. | ||
*/ | ||
width: number; | ||
/** | ||
* Whether or not to "excavate" the modules around the embedded image. This | ||
* means that any modules the embedded image overlaps will use the background | ||
* color. | ||
*/ | ||
excavate: boolean; | ||
/** | ||
* The horiztonal offset of the embedded image, starting from the top left corner. | ||
* Will center if not specified. | ||
*/ | ||
x?: number; | ||
/** | ||
* The vertical offset of the embedded image, starting from the top left corner. | ||
* Will center if not specified. | ||
*/ | ||
y?: number; | ||
/** | ||
* The opacity of the embedded image in the range of 0-1. | ||
* @defaultValue 1 | ||
*/ | ||
opacity?: number; | ||
/** | ||
* The cross-origin value to use when loading the image. This is used to | ||
* ensure compatibility with CORS, particularly when extracting image data | ||
* from QRCodeCanvas. | ||
* Note: `undefined` is treated differently than the seemingly equivalent | ||
* empty string. This is intended to align with HTML behavior where omitting | ||
* the attribute behaves differently than the empty string. | ||
*/ | ||
crossOrigin?: CrossOrigin; | ||
}; | ||
declare type QRProps = { | ||
type QRProps = { | ||
/** | ||
* The value to encode into the QR Code. | ||
*/ | ||
value: string; | ||
/** | ||
* The size, in pixels, to render the QR Code. | ||
* @defaultValue 128 | ||
*/ | ||
size?: number; | ||
level?: string; | ||
/** | ||
* The Error Correction Level to use. | ||
* @see https://www.qrcode.com/en/about/error_correction.html | ||
* @defaultValue L | ||
*/ | ||
level?: ErrorCorrectionLevel; | ||
/** | ||
* The background color used to render the QR Code. | ||
* @see https://developer.mozilla.org/en-US/docs/Web/CSS/color_value | ||
* @defaultValue #FFFFFF | ||
*/ | ||
bgColor?: string; | ||
/** | ||
* The foregtound color used to render the QR Code. | ||
* @see https://developer.mozilla.org/en-US/docs/Web/CSS/color_value | ||
* @defaultValue #000000 | ||
*/ | ||
fgColor?: string; | ||
style?: CSSProperties; | ||
/** | ||
* Whether or not a margin of 4 modules should be rendered as a part of the | ||
* QR Code. | ||
* @deprecated Use `marginSize` instead. | ||
* @defaultValue false | ||
*/ | ||
includeMargin?: boolean; | ||
/** | ||
* The number of _modules_ to use for margin. The QR Code specification | ||
* requires `4`, however you can specify any number. Values will be turned to | ||
* integers with `Math.floor`. Overrides `includeMargin` when both are specified. | ||
* @defaultValue 0 | ||
*/ | ||
marginSize?: number; | ||
/** | ||
* The title to assign to the QR Code. Used for accessibility reasons. | ||
*/ | ||
title?: string; | ||
/** | ||
* The minimum version used when encoding the QR Code. Valid values are 1-40 | ||
* with higher values resulting in more complex QR Codes. The optimal | ||
* (lowest) version is determined for the `value` provided, using `minVersion` | ||
* as the lower bound. | ||
* @defaultValue 1 | ||
*/ | ||
minVersion?: number; | ||
/** | ||
* The settings for the embedded image. | ||
*/ | ||
imageSettings?: ImageSettings; | ||
}; | ||
declare type QRPropsCanvas = QRProps & React.CanvasHTMLAttributes<HTMLCanvasElement>; | ||
declare type QRPropsSVG = QRProps & React.SVGProps<SVGSVGElement>; | ||
declare function QRCodeCanvas(props: QRPropsCanvas): JSX.Element; | ||
declare function QRCodeSVG(props: QRPropsSVG): JSX.Element; | ||
declare type RootProps = (QRPropsSVG & { | ||
renderAs: 'svg'; | ||
}) | (QRPropsCanvas & { | ||
renderAs?: 'canvas'; | ||
}); | ||
declare const QRCode: (props: RootProps) => JSX.Element; | ||
declare const QRCodeCanvas: React.ForwardRefExoticComponent<QRProps & React.CanvasHTMLAttributes<HTMLCanvasElement> & React.RefAttributes<HTMLCanvasElement>>; | ||
declare const QRCodeSVG: React.ForwardRefExoticComponent<QRProps & React.SVGAttributes<SVGSVGElement> & React.RefAttributes<SVGSVGElement>>; | ||
export { QRCodeCanvas, QRCodeSVG, QRCode as default }; | ||
export { QRCodeCanvas, QRCodeSVG }; |
621
lib/index.js
@@ -0,1 +1,2 @@ | ||
"use strict"; | ||
var __create = Object.create; | ||
@@ -45,3 +46,10 @@ var __defProp = Object.defineProperty; | ||
}; | ||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod)); | ||
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( | ||
// If the importer is in node compatibility mode or this is not an ESM | ||
// file that has been converted to a CommonJS file using a Babel- | ||
// compatible transform (i.e. "__esModule" has not been set), then set | ||
// "default" to the CommonJS "module.exports" for node compatibility. | ||
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, | ||
mod | ||
)); | ||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
@@ -53,4 +61,3 @@ | ||
QRCodeCanvas: () => QRCodeCanvas, | ||
QRCodeSVG: () => QRCodeSVG, | ||
default: () => QRCode | ||
QRCodeSVG: () => QRCodeSVG | ||
}); | ||
@@ -68,7 +75,15 @@ module.exports = __toCommonJS(src_exports); | ||
((qrcodegen2) => { | ||
const _QrCode = class { | ||
const _QrCode = class _QrCode { | ||
/*-- Constructor (low level) and fields --*/ | ||
// Creates a new QR Code with the given version number, | ||
// error correction level, data codeword bytes, and mask number. | ||
// This is a low-level API that most users should not use directly. | ||
// A mid-level API is the encodeSegments() function. | ||
constructor(version, errorCorrectionLevel, dataCodewords, msk) { | ||
this.version = version; | ||
this.errorCorrectionLevel = errorCorrectionLevel; | ||
// The modules of this QR Code (false = light, true = dark). | ||
// Immutable after constructor finishes. Accessed through getModule(). | ||
this.modules = []; | ||
// Indicates function modules that are not subjected to masking. Discarded when constructor finishes. | ||
this.isFunction = []; | ||
@@ -109,2 +124,8 @@ if (version < _QrCode.MIN_VERSION || version > _QrCode.MAX_VERSION) | ||
} | ||
/*-- Static factory functions (high level) --*/ | ||
// Returns a QR Code representing the given Unicode text string at the given error correction level. | ||
// As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer | ||
// Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible | ||
// QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the | ||
// ecl argument if it can be done without increasing the version. | ||
static encodeText(text, ecl) { | ||
@@ -114,2 +135,6 @@ const segs = qrcodegen2.QrSegment.makeSegments(text); | ||
} | ||
// Returns a QR Code representing the given binary data at the given error correction level. | ||
// This function always encodes using the binary segment mode, not any text mode. The maximum number of | ||
// bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output. | ||
// The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version. | ||
static encodeBinary(data, ecl) { | ||
@@ -119,2 +144,12 @@ const seg = qrcodegen2.QrSegment.makeBytes(data); | ||
} | ||
/*-- Static factory functions (mid level) --*/ | ||
// Returns a QR Code representing the given segments with the given encoding parameters. | ||
// The smallest possible QR Code version within the given range is automatically | ||
// chosen for the output. Iff boostEcl is true, then the ECC level of the result | ||
// may be higher than the ecl argument if it can be done without increasing the | ||
// version. The mask number is either between 0 to 7 (inclusive) to force that | ||
// mask, or -1 to automatically choose an appropriate mask (which may be slow). | ||
// This function allows the user to create a custom sequence of segments that switches | ||
// between modes (such as alphanumeric and byte) to encode text in less space. | ||
// This is a mid-level API; the high-level API is encodeText() and encodeBinary(). | ||
static encodeSegments(segs, ecl, minVersion = 1, maxVersion = 40, mask = -1, boostEcl = true) { | ||
@@ -160,8 +195,15 @@ if (!(_QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= _QrCode.MAX_VERSION) || mask < -1 || mask > 7) | ||
} | ||
/*-- Accessor methods --*/ | ||
// Returns the color of the module (pixel) at the given coordinates, which is false | ||
// for light or true for dark. The top left corner has the coordinates (x=0, y=0). | ||
// If the given coordinates are out of bounds, then false (light) is returned. | ||
getModule(x, y) { | ||
return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y][x]; | ||
} | ||
// Modified to expose modules for easy access | ||
getModules() { | ||
return this.modules; | ||
} | ||
/*-- Private helper methods for constructor: Drawing function modules --*/ | ||
// Reads this object's version field, and draws and marks all function modules. | ||
drawFunctionPatterns() { | ||
@@ -186,2 +228,4 @@ for (let i = 0; i < this.size; i++) { | ||
} | ||
// Draws two copies of the format bits (with its own error correction code) | ||
// based on the given mask and this object's error correction level field. | ||
drawFormatBits(mask) { | ||
@@ -207,2 +251,4 @@ const data = this.errorCorrectionLevel.formatBits << 3 | mask; | ||
} | ||
// Draws two copies of the version bits (with its own error correction code), | ||
// based on this object's version field, iff 7 <= version <= 40. | ||
drawVersion() { | ||
@@ -224,2 +270,4 @@ if (this.version < 7) | ||
} | ||
// Draws a 9*9 finder pattern including the border separator, | ||
// with the center module at (x, y). Modules can be out of bounds. | ||
drawFinderPattern(x, y) { | ||
@@ -236,2 +284,4 @@ for (let dy = -4; dy <= 4; dy++) { | ||
} | ||
// Draws a 5*5 alignment pattern, with the center module | ||
// at (x, y). All modules must be in bounds. | ||
drawAlignmentPattern(x, y) { | ||
@@ -243,2 +293,4 @@ for (let dy = -2; dy <= 2; dy++) { | ||
} | ||
// Sets the color of a module and marks it as a function module. | ||
// Only used by the constructor. Coordinates must be in bounds. | ||
setFunctionModule(x, y, isDark) { | ||
@@ -248,2 +300,5 @@ this.modules[y][x] = isDark; | ||
} | ||
/*-- Private helper methods for constructor: Codewords and masking --*/ | ||
// Returns a new byte string representing the given data with the appropriate error correction | ||
// codewords appended to it, based on this object's version and error correction level. | ||
addEccAndInterleave(data) { | ||
@@ -279,2 +334,4 @@ const ver = this.version; | ||
} | ||
// Draws the given sequence of 8-bit codewords (data and error correction) onto the entire | ||
// data area of this QR Code. Function modules need to be marked off before this is called. | ||
drawCodewords(data) { | ||
@@ -301,2 +358,7 @@ if (data.length != Math.floor(_QrCode.getNumRawDataModules(this.version) / 8)) | ||
} | ||
// XORs the codeword modules in this QR Code with the given mask pattern. | ||
// The function modules must be marked and the codeword bits must be drawn | ||
// before masking. Due to the arithmetic of XOR, calling applyMask() with | ||
// the same mask value a second time will undo the mask. A final well-formed | ||
// QR Code needs exactly one (not zero, two, etc.) mask applied. | ||
applyMask(mask) { | ||
@@ -341,2 +403,4 @@ if (mask < 0 || mask > 7) | ||
} | ||
// Calculates and returns the penalty score based on state of this QR Code's current modules. | ||
// This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score. | ||
getPenaltyScore() { | ||
@@ -403,2 +467,6 @@ let result = 0; | ||
} | ||
/*-- Private helper functions --*/ | ||
// Returns an ascending list of positions of alignment patterns for this version number. | ||
// Each position is in the range [0,177), and are used on both the x and y axes. | ||
// This could be implemented as lookup table of 40 variable-length lists of integers. | ||
getAlignmentPatternPositions() { | ||
@@ -416,2 +484,5 @@ if (this.version == 1) | ||
} | ||
// Returns the number of data bits that can be stored in a QR Code of the given version number, after | ||
// all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8. | ||
// The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table. | ||
static getNumRawDataModules(ver) { | ||
@@ -430,5 +501,10 @@ if (ver < _QrCode.MIN_VERSION || ver > _QrCode.MAX_VERSION) | ||
} | ||
// Returns the number of 8-bit data (i.e. not error correction) codewords contained in any | ||
// QR Code of the given version number and error correction level, with remainder bits discarded. | ||
// This stateless pure function could be implemented as a (40*4)-cell lookup table. | ||
static getNumDataCodewords(ver, ecl) { | ||
return Math.floor(_QrCode.getNumRawDataModules(ver) / 8) - _QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver] * _QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver]; | ||
} | ||
// Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be | ||
// implemented as a lookup table over all possible parameter values, instead of as an algorithm. | ||
static reedSolomonComputeDivisor(degree) { | ||
@@ -452,2 +528,3 @@ if (degree < 1 || degree > 255) | ||
} | ||
// Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials. | ||
static reedSolomonComputeRemainder(data, divisor) { | ||
@@ -462,2 +539,4 @@ let result = divisor.map((_) => 0); | ||
} | ||
// Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result | ||
// are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8. | ||
static reedSolomonMultiply(x, y) { | ||
@@ -474,2 +553,4 @@ if (x >>> 8 != 0 || y >>> 8 != 0) | ||
} | ||
// Can only be called immediately after a light run is added, and | ||
// returns either 0, 1, or 2. A helper function for getPenaltyScore(). | ||
finderPenaltyCountPatterns(runHistory) { | ||
@@ -481,2 +562,3 @@ const n = runHistory[1]; | ||
} | ||
// Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore(). | ||
finderPenaltyTerminateAndCount(currentRunColor, currentRunLength, runHistory) { | ||
@@ -491,2 +573,3 @@ if (currentRunColor) { | ||
} | ||
// Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore(). | ||
finderPenaltyAddHistory(currentRunLength, runHistory) { | ||
@@ -499,22 +582,38 @@ if (runHistory[0] == 0) | ||
}; | ||
let QrCode = _QrCode; | ||
QrCode.MIN_VERSION = 1; | ||
QrCode.MAX_VERSION = 40; | ||
QrCode.PENALTY_N1 = 3; | ||
QrCode.PENALTY_N2 = 3; | ||
QrCode.PENALTY_N3 = 40; | ||
QrCode.PENALTY_N4 = 10; | ||
QrCode.ECC_CODEWORDS_PER_BLOCK = [ | ||
/*-- Constants and tables --*/ | ||
// The minimum version number supported in the QR Code Model 2 standard. | ||
_QrCode.MIN_VERSION = 1; | ||
// The maximum version number supported in the QR Code Model 2 standard. | ||
_QrCode.MAX_VERSION = 40; | ||
// For use in getPenaltyScore(), when evaluating which mask is best. | ||
_QrCode.PENALTY_N1 = 3; | ||
_QrCode.PENALTY_N2 = 3; | ||
_QrCode.PENALTY_N3 = 40; | ||
_QrCode.PENALTY_N4 = 10; | ||
_QrCode.ECC_CODEWORDS_PER_BLOCK = [ | ||
// Version: (note that index 0 is for padding, and is set to an illegal value) | ||
//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 | ||
[-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, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], | ||
// Low | ||
[-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, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28], | ||
// Medium | ||
[-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, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], | ||
// Quartile | ||
[-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, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30] | ||
// High | ||
]; | ||
QrCode.NUM_ERROR_CORRECTION_BLOCKS = [ | ||
_QrCode.NUM_ERROR_CORRECTION_BLOCKS = [ | ||
// Version: (note that index 0 is for padding, and is set to an illegal value) | ||
//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 | ||
[-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, 19, 19, 20, 21, 22, 24, 25], | ||
// Low | ||
[-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, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49], | ||
// Medium | ||
[-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, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68], | ||
// Quartile | ||
[-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, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81] | ||
// High | ||
]; | ||
qrcodegen2.QrCode = QrCode; | ||
let QrCode = _QrCode; | ||
qrcodegen2.QrCode = _QrCode; | ||
function appendBits(val, len, bb) { | ||
@@ -533,3 +632,7 @@ if (len < 0 || len > 31 || val >>> len != 0) | ||
} | ||
const _QrSegment = class { | ||
const _QrSegment = class _QrSegment { | ||
/*-- Constructor (low level) and fields --*/ | ||
// Creates a new QR Code segment with the given attributes and data. | ||
// The character count (numChars) must agree with the mode and the bit buffer length, | ||
// but the constraint isn't checked. The given bit buffer is cloned and stored. | ||
constructor(mode, numChars, bitData) { | ||
@@ -543,2 +646,6 @@ this.mode = mode; | ||
} | ||
/*-- Static factory functions (mid level) --*/ | ||
// Returns a segment representing the given binary data encoded in | ||
// byte mode. All input byte arrays are acceptable. Any text string | ||
// can be converted to UTF-8 bytes and encoded as a byte mode segment. | ||
static makeBytes(data) { | ||
@@ -550,2 +657,3 @@ let bb = []; | ||
} | ||
// Returns a segment representing the given string of decimal digits encoded in numeric mode. | ||
static makeNumeric(digits) { | ||
@@ -557,3 +665,3 @@ if (!_QrSegment.isNumeric(digits)) | ||
const n = Math.min(digits.length - i, 3); | ||
appendBits(parseInt(digits.substr(i, n), 10), n * 3 + 1, bb); | ||
appendBits(parseInt(digits.substring(i, i + n), 10), n * 3 + 1, bb); | ||
i += n; | ||
@@ -563,2 +671,5 @@ } | ||
} | ||
// Returns a segment representing the given text string encoded in alphanumeric mode. | ||
// The characters allowed are: 0 to 9, A to Z (uppercase only), space, | ||
// dollar, percent, asterisk, plus, hyphen, period, slash, colon. | ||
static makeAlphanumeric(text) { | ||
@@ -578,2 +689,4 @@ if (!_QrSegment.isAlphanumeric(text)) | ||
} | ||
// Returns a new mutable list of zero or more segments to represent the given Unicode text string. | ||
// The result may use various segment modes and switch modes to optimize the length of the bit stream. | ||
static makeSegments(text) { | ||
@@ -589,2 +702,4 @@ if (text == "") | ||
} | ||
// Returns a segment representing an Extended Channel Interpretation | ||
// (ECI) designator with the given assignment value. | ||
static makeEci(assignVal) { | ||
@@ -606,11 +721,20 @@ let bb = []; | ||
} | ||
// Tests whether the given string can be encoded as a segment in numeric mode. | ||
// A string is encodable iff each character is in the range 0 to 9. | ||
static isNumeric(text) { | ||
return _QrSegment.NUMERIC_REGEX.test(text); | ||
} | ||
// Tests whether the given string can be encoded as a segment in alphanumeric mode. | ||
// A string is encodable iff each character is in the following set: 0 to 9, A to Z | ||
// (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon. | ||
static isAlphanumeric(text) { | ||
return _QrSegment.ALPHANUMERIC_REGEX.test(text); | ||
} | ||
/*-- Methods --*/ | ||
// Returns a new copy of the data bits of this segment. | ||
getData() { | ||
return this.bitData.slice(); | ||
} | ||
// (Package-private) Calculates and returns the number of bits needed to encode the given segments at | ||
// the given version. The result is infinity if a segment has too many characters to fit its length field. | ||
static getTotalBits(segs, version) { | ||
@@ -626,2 +750,3 @@ let result = 0; | ||
} | ||
// Returns a new array of bytes representing the given string encoded in UTF-8. | ||
static toUtf8ByteArray(str) { | ||
@@ -634,3 +759,3 @@ str = encodeURI(str); | ||
else { | ||
result.push(parseInt(str.substr(i + 1, 2), 16)); | ||
result.push(parseInt(str.substring(i + 1, i + 3), 16)); | ||
i += 2; | ||
@@ -642,7 +767,12 @@ } | ||
}; | ||
/*-- Constants --*/ | ||
// Describes precisely all strings that are encodable in numeric mode. | ||
_QrSegment.NUMERIC_REGEX = /^[0-9]*$/; | ||
// Describes precisely all strings that are encodable in alphanumeric mode. | ||
_QrSegment.ALPHANUMERIC_REGEX = /^[A-Z0-9 $%*+.\/:-]*$/; | ||
// The set of all legal characters in alphanumeric mode, | ||
// where each character value maps to the index in the string. | ||
_QrSegment.ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; | ||
let QrSegment = _QrSegment; | ||
QrSegment.NUMERIC_REGEX = /^[0-9]*$/; | ||
QrSegment.ALPHANUMERIC_REGEX = /^[A-Z0-9 $%*+.\/:-]*$/; | ||
QrSegment.ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; | ||
qrcodegen2.QrSegment = QrSegment; | ||
qrcodegen2.QrSegment = _QrSegment; | ||
})(qrcodegen || (qrcodegen = {})); | ||
@@ -652,3 +782,5 @@ ((qrcodegen2) => { | ||
((QrCode2) => { | ||
const _Ecc = class { | ||
const _Ecc = class _Ecc { | ||
// The QR Code can tolerate about 30% erroneous codewords | ||
/*-- Constructor and fields --*/ | ||
constructor(ordinal, formatBits) { | ||
@@ -659,8 +791,12 @@ this.ordinal = ordinal; | ||
}; | ||
/*-- Constants --*/ | ||
_Ecc.LOW = new _Ecc(0, 1); | ||
// The QR Code can tolerate about 7% erroneous codewords | ||
_Ecc.MEDIUM = new _Ecc(1, 0); | ||
// The QR Code can tolerate about 15% erroneous codewords | ||
_Ecc.QUARTILE = new _Ecc(2, 3); | ||
// The QR Code can tolerate about 25% erroneous codewords | ||
_Ecc.HIGH = new _Ecc(3, 2); | ||
let Ecc = _Ecc; | ||
Ecc.LOW = new _Ecc(0, 1); | ||
Ecc.MEDIUM = new _Ecc(1, 0); | ||
Ecc.QUARTILE = new _Ecc(2, 3); | ||
Ecc.HIGH = new _Ecc(3, 2); | ||
QrCode2.Ecc = Ecc; | ||
QrCode2.Ecc = _Ecc; | ||
})(QrCode = qrcodegen2.QrCode || (qrcodegen2.QrCode = {})); | ||
@@ -671,3 +807,4 @@ })(qrcodegen || (qrcodegen = {})); | ||
((QrSegment2) => { | ||
const _Mode = class { | ||
const _Mode = class _Mode { | ||
/*-- Constructor and fields --*/ | ||
constructor(modeBits, numBitsCharCount) { | ||
@@ -677,2 +814,5 @@ this.modeBits = modeBits; | ||
} | ||
/*-- Method --*/ | ||
// (Package-private) Returns the bit width of the character count field for a segment in | ||
// this mode in a QR Code at the given version number. The result is in the range [0, 16]. | ||
numCharCountBits(ver) { | ||
@@ -682,9 +822,10 @@ return this.numBitsCharCount[Math.floor((ver + 7) / 17)]; | ||
}; | ||
/*-- Constants --*/ | ||
_Mode.NUMERIC = new _Mode(1, [10, 12, 14]); | ||
_Mode.ALPHANUMERIC = new _Mode(2, [9, 11, 13]); | ||
_Mode.BYTE = new _Mode(4, [8, 16, 16]); | ||
_Mode.KANJI = new _Mode(8, [8, 10, 12]); | ||
_Mode.ECI = new _Mode(7, [0, 0, 0]); | ||
let Mode = _Mode; | ||
Mode.NUMERIC = new _Mode(1, [10, 12, 14]); | ||
Mode.ALPHANUMERIC = new _Mode(2, [9, 11, 13]); | ||
Mode.BYTE = new _Mode(4, [8, 16, 16]); | ||
Mode.KANJI = new _Mode(8, [8, 10, 12]); | ||
Mode.ECI = new _Mode(7, [0, 0, 0]); | ||
QrSegment2.Mode = Mode; | ||
QrSegment2.Mode = _Mode; | ||
})(QrSegment = qrcodegen2.QrSegment || (qrcodegen2.QrSegment = {})); | ||
@@ -711,3 +852,5 @@ })(qrcodegen || (qrcodegen = {})); | ||
var DEFAULT_INCLUDEMARGIN = false; | ||
var MARGIN_SIZE = 4; | ||
var DEFAULT_MINVERSION = 1; | ||
var SPEC_MARGIN_SIZE = 4; | ||
var DEFAULT_MARGIN_SIZE = 0; | ||
var DEFAULT_IMG_SCALE = 0.1; | ||
@@ -720,3 +863,5 @@ function generatePath(modules, margin = 0) { | ||
if (!cell && start !== null) { | ||
ops.push(`M${start + margin} ${y + margin}h${x - start}v1H${start + margin}z`); | ||
ops.push( | ||
`M${start + margin} ${y + margin}h${x - start}v1H${start + margin}z` | ||
); | ||
start = null; | ||
@@ -732,3 +877,5 @@ return; | ||
} else { | ||
ops.push(`M${start + margin},${y + margin} h${x + 1 - start}v1H${start + margin}z`); | ||
ops.push( | ||
`M${start + margin},${y + margin} h${x + 1 - start}v1H${start + margin}z` | ||
); | ||
} | ||
@@ -757,7 +904,6 @@ return; | ||
} | ||
function getImageSettings(cells, size, includeMargin, imageSettings) { | ||
function getImageSettings(cells, size, margin, imageSettings) { | ||
if (imageSettings == null) { | ||
return null; | ||
} | ||
const margin = includeMargin ? MARGIN_SIZE : 0; | ||
const numCells = cells.length + margin * 2; | ||
@@ -770,2 +916,3 @@ const defaultSize = Math.floor(size * DEFAULT_IMG_SCALE); | ||
const y = imageSettings.y == null ? cells.length / 2 - h / 2 : imageSettings.y * scale; | ||
const opacity = imageSettings.opacity == null ? 1 : imageSettings.opacity; | ||
let excavation = null; | ||
@@ -779,4 +926,53 @@ if (imageSettings.excavate) { | ||
} | ||
return { x, y, h, w, excavation }; | ||
const crossOrigin = imageSettings.crossOrigin; | ||
return { x, y, h, w, excavation, opacity, crossOrigin }; | ||
} | ||
function getMarginSize(includeMargin, marginSize) { | ||
if (marginSize != null) { | ||
return Math.max(Math.floor(marginSize), 0); | ||
} | ||
return includeMargin ? SPEC_MARGIN_SIZE : DEFAULT_MARGIN_SIZE; | ||
} | ||
function useQRCode({ | ||
value, | ||
level, | ||
minVersion, | ||
includeMargin, | ||
marginSize, | ||
imageSettings, | ||
size | ||
}) { | ||
let qrcode = import_react.default.useMemo(() => { | ||
const segments = qrcodegen_default.QrSegment.makeSegments(value); | ||
return qrcodegen_default.QrCode.encodeSegments( | ||
segments, | ||
ERROR_LEVEL_MAP[level], | ||
minVersion | ||
); | ||
}, [value, level, minVersion]); | ||
const { cells, margin, numCells, calculatedImageSettings } = import_react.default.useMemo(() => { | ||
let cells2 = qrcode.getModules(); | ||
const margin2 = getMarginSize(includeMargin, marginSize); | ||
const numCells2 = cells2.length + margin2 * 2; | ||
const calculatedImageSettings2 = getImageSettings( | ||
cells2, | ||
size, | ||
margin2, | ||
imageSettings | ||
); | ||
return { | ||
cells: cells2, | ||
margin: margin2, | ||
numCells: numCells2, | ||
calculatedImageSettings: calculatedImageSettings2 | ||
}; | ||
}, [qrcode, size, imageSettings, includeMargin, marginSize]); | ||
return { | ||
qrcode, | ||
margin, | ||
cells, | ||
numCells, | ||
calculatedImageSettings | ||
}; | ||
} | ||
var SUPPORTS_PATH2D = function() { | ||
@@ -790,147 +986,214 @@ try { | ||
}(); | ||
function QRCodeCanvas(props) { | ||
const _a = props, { | ||
value, | ||
size = DEFAULT_SIZE, | ||
level = DEFAULT_LEVEL, | ||
bgColor = DEFAULT_BGCOLOR, | ||
fgColor = DEFAULT_FGCOLOR, | ||
includeMargin = DEFAULT_INCLUDEMARGIN, | ||
style, | ||
imageSettings | ||
} = _a, otherProps = __objRest(_a, [ | ||
"value", | ||
"size", | ||
"level", | ||
"bgColor", | ||
"fgColor", | ||
"includeMargin", | ||
"style", | ||
"imageSettings" | ||
]); | ||
const imgSrc = imageSettings == null ? void 0 : imageSettings.src; | ||
const _canvas = (0, import_react.useRef)(null); | ||
const _image = (0, import_react.useRef)(null); | ||
const [isImgLoaded, setIsImageLoaded] = (0, import_react.useState)(false); | ||
(0, import_react.useEffect)(() => { | ||
if (_canvas.current != null) { | ||
const canvas = _canvas.current; | ||
const ctx = canvas.getContext("2d"); | ||
if (!ctx) { | ||
return; | ||
} | ||
let cells = qrcodegen_default.QrCode.encodeText(value, ERROR_LEVEL_MAP[level]).getModules(); | ||
const margin = includeMargin ? MARGIN_SIZE : 0; | ||
const numCells = cells.length + margin * 2; | ||
const calculatedImageSettings = getImageSettings(cells, size, includeMargin, imageSettings); | ||
const image = _image.current; | ||
const haveImageToRender = calculatedImageSettings != null && image !== null && image.complete && image.naturalHeight !== 0 && image.naturalWidth !== 0; | ||
if (haveImageToRender) { | ||
if (calculatedImageSettings.excavation != null) { | ||
cells = excavateModules(cells, calculatedImageSettings.excavation); | ||
var QRCodeCanvas = import_react.default.forwardRef( | ||
function QRCodeCanvas2(props, forwardedRef) { | ||
const _a = props, { | ||
value, | ||
size = DEFAULT_SIZE, | ||
level = DEFAULT_LEVEL, | ||
bgColor = DEFAULT_BGCOLOR, | ||
fgColor = DEFAULT_FGCOLOR, | ||
includeMargin = DEFAULT_INCLUDEMARGIN, | ||
minVersion = DEFAULT_MINVERSION, | ||
marginSize, | ||
imageSettings | ||
} = _a, extraProps = __objRest(_a, [ | ||
"value", | ||
"size", | ||
"level", | ||
"bgColor", | ||
"fgColor", | ||
"includeMargin", | ||
"minVersion", | ||
"marginSize", | ||
"imageSettings" | ||
]); | ||
const _b = extraProps, { style } = _b, otherProps = __objRest(_b, ["style"]); | ||
const imgSrc = imageSettings == null ? void 0 : imageSettings.src; | ||
const _canvas = import_react.default.useRef(null); | ||
const _image = import_react.default.useRef(null); | ||
const setCanvasRef = import_react.default.useCallback( | ||
(node) => { | ||
_canvas.current = node; | ||
if (typeof forwardedRef === "function") { | ||
forwardedRef(node); | ||
} else if (forwardedRef) { | ||
forwardedRef.current = node; | ||
} | ||
} | ||
const pixelRatio = window.devicePixelRatio || 1; | ||
canvas.height = canvas.width = size * pixelRatio; | ||
const scale = size / numCells * pixelRatio; | ||
ctx.scale(scale, scale); | ||
ctx.fillStyle = bgColor; | ||
ctx.fillRect(0, 0, numCells, numCells); | ||
ctx.fillStyle = fgColor; | ||
if (SUPPORTS_PATH2D) { | ||
ctx.fill(new Path2D(generatePath(cells, margin))); | ||
} else { | ||
cells.forEach(function(row, rdx) { | ||
row.forEach(function(cell, cdx) { | ||
if (cell) { | ||
ctx.fillRect(cdx + margin, rdx + margin, 1, 1); | ||
} | ||
}, | ||
[forwardedRef] | ||
); | ||
const [isImgLoaded, setIsImageLoaded] = import_react.default.useState(false); | ||
const { margin, cells, numCells, calculatedImageSettings } = useQRCode({ | ||
value, | ||
level, | ||
minVersion, | ||
includeMargin, | ||
marginSize, | ||
imageSettings, | ||
size | ||
}); | ||
import_react.default.useEffect(() => { | ||
if (_canvas.current != null) { | ||
const canvas = _canvas.current; | ||
const ctx = canvas.getContext("2d"); | ||
if (!ctx) { | ||
return; | ||
} | ||
let cellsToDraw = cells; | ||
const image = _image.current; | ||
const haveImageToRender = calculatedImageSettings != null && image !== null && image.complete && image.naturalHeight !== 0 && image.naturalWidth !== 0; | ||
if (haveImageToRender) { | ||
if (calculatedImageSettings.excavation != null) { | ||
cellsToDraw = excavateModules( | ||
cells, | ||
calculatedImageSettings.excavation | ||
); | ||
} | ||
} | ||
const pixelRatio = window.devicePixelRatio || 1; | ||
canvas.height = canvas.width = size * pixelRatio; | ||
const scale = size / numCells * pixelRatio; | ||
ctx.scale(scale, scale); | ||
ctx.fillStyle = bgColor; | ||
ctx.fillRect(0, 0, numCells, numCells); | ||
ctx.fillStyle = fgColor; | ||
if (SUPPORTS_PATH2D) { | ||
ctx.fill(new Path2D(generatePath(cellsToDraw, margin))); | ||
} else { | ||
cells.forEach(function(row, rdx) { | ||
row.forEach(function(cell, cdx) { | ||
if (cell) { | ||
ctx.fillRect(cdx + margin, rdx + margin, 1, 1); | ||
} | ||
}); | ||
}); | ||
}); | ||
} | ||
if (calculatedImageSettings) { | ||
ctx.globalAlpha = calculatedImageSettings.opacity; | ||
} | ||
if (haveImageToRender) { | ||
ctx.drawImage( | ||
image, | ||
calculatedImageSettings.x + margin, | ||
calculatedImageSettings.y + margin, | ||
calculatedImageSettings.w, | ||
calculatedImageSettings.h | ||
); | ||
} | ||
} | ||
if (haveImageToRender) { | ||
ctx.drawImage(image, calculatedImageSettings.x + margin, calculatedImageSettings.y + margin, calculatedImageSettings.w, calculatedImageSettings.h); | ||
} | ||
}); | ||
import_react.default.useEffect(() => { | ||
setIsImageLoaded(false); | ||
}, [imgSrc]); | ||
const canvasStyle = __spreadValues({ height: size, width: size }, style); | ||
let img = null; | ||
if (imgSrc != null) { | ||
img = /* @__PURE__ */ import_react.default.createElement( | ||
"img", | ||
{ | ||
src: imgSrc, | ||
key: imgSrc, | ||
style: { display: "none" }, | ||
onLoad: () => { | ||
setIsImageLoaded(true); | ||
}, | ||
ref: _image, | ||
crossOrigin: calculatedImageSettings == null ? void 0 : calculatedImageSettings.crossOrigin | ||
} | ||
); | ||
} | ||
}); | ||
(0, import_react.useEffect)(() => { | ||
setIsImageLoaded(false); | ||
}, [imgSrc]); | ||
const canvasStyle = __spreadValues({ height: size, width: size }, style); | ||
let img = null; | ||
if (imgSrc != null) { | ||
img = /* @__PURE__ */ import_react.default.createElement("img", { | ||
src: imgSrc, | ||
key: imgSrc, | ||
style: { display: "none" }, | ||
onLoad: () => { | ||
setIsImageLoaded(true); | ||
}, | ||
ref: _image | ||
return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement( | ||
"canvas", | ||
__spreadValues({ | ||
style: canvasStyle, | ||
height: size, | ||
width: size, | ||
ref: setCanvasRef, | ||
role: "img" | ||
}, otherProps) | ||
), img); | ||
} | ||
); | ||
QRCodeCanvas.displayName = "QRCodeCanvas"; | ||
var QRCodeSVG = import_react.default.forwardRef( | ||
function QRCodeSVG2(props, forwardedRef) { | ||
const _a = props, { | ||
value, | ||
size = DEFAULT_SIZE, | ||
level = DEFAULT_LEVEL, | ||
bgColor = DEFAULT_BGCOLOR, | ||
fgColor = DEFAULT_FGCOLOR, | ||
includeMargin = DEFAULT_INCLUDEMARGIN, | ||
minVersion = DEFAULT_MINVERSION, | ||
title, | ||
marginSize, | ||
imageSettings | ||
} = _a, otherProps = __objRest(_a, [ | ||
"value", | ||
"size", | ||
"level", | ||
"bgColor", | ||
"fgColor", | ||
"includeMargin", | ||
"minVersion", | ||
"title", | ||
"marginSize", | ||
"imageSettings" | ||
]); | ||
const { margin, cells, numCells, calculatedImageSettings } = useQRCode({ | ||
value, | ||
level, | ||
minVersion, | ||
includeMargin, | ||
marginSize, | ||
imageSettings, | ||
size | ||
}); | ||
} | ||
return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("canvas", __spreadValues({ | ||
style: canvasStyle, | ||
height: size, | ||
width: size, | ||
ref: _canvas | ||
}, otherProps)), img); | ||
} | ||
function QRCodeSVG(props) { | ||
const _a = props, { | ||
value, | ||
size = DEFAULT_SIZE, | ||
level = DEFAULT_LEVEL, | ||
bgColor = DEFAULT_BGCOLOR, | ||
fgColor = DEFAULT_FGCOLOR, | ||
includeMargin = DEFAULT_INCLUDEMARGIN, | ||
imageSettings | ||
} = _a, otherProps = __objRest(_a, [ | ||
"value", | ||
"size", | ||
"level", | ||
"bgColor", | ||
"fgColor", | ||
"includeMargin", | ||
"imageSettings" | ||
]); | ||
let cells = qrcodegen_default.QrCode.encodeText(value, ERROR_LEVEL_MAP[level]).getModules(); | ||
const margin = includeMargin ? MARGIN_SIZE : 0; | ||
const numCells = cells.length + margin * 2; | ||
const calculatedImageSettings = getImageSettings(cells, size, includeMargin, imageSettings); | ||
let image = null; | ||
if (imageSettings != null && calculatedImageSettings != null) { | ||
if (calculatedImageSettings.excavation != null) { | ||
cells = excavateModules(cells, calculatedImageSettings.excavation); | ||
let cellsToDraw = cells; | ||
let image = null; | ||
if (imageSettings != null && calculatedImageSettings != null) { | ||
if (calculatedImageSettings.excavation != null) { | ||
cellsToDraw = excavateModules( | ||
cells, | ||
calculatedImageSettings.excavation | ||
); | ||
} | ||
image = /* @__PURE__ */ import_react.default.createElement( | ||
"image", | ||
{ | ||
href: imageSettings.src, | ||
height: calculatedImageSettings.h, | ||
width: calculatedImageSettings.w, | ||
x: calculatedImageSettings.x + margin, | ||
y: calculatedImageSettings.y + margin, | ||
preserveAspectRatio: "none", | ||
opacity: calculatedImageSettings.opacity, | ||
crossOrigin: calculatedImageSettings.crossOrigin | ||
} | ||
); | ||
} | ||
image = /* @__PURE__ */ import_react.default.createElement("image", { | ||
xlinkHref: imageSettings.src, | ||
height: calculatedImageSettings.h, | ||
width: calculatedImageSettings.w, | ||
x: calculatedImageSettings.x + margin, | ||
y: calculatedImageSettings.y + margin, | ||
preserveAspectRatio: "none" | ||
}); | ||
const fgPath = generatePath(cellsToDraw, margin); | ||
return /* @__PURE__ */ import_react.default.createElement( | ||
"svg", | ||
__spreadValues({ | ||
height: size, | ||
width: size, | ||
viewBox: `0 0 ${numCells} ${numCells}`, | ||
ref: forwardedRef, | ||
role: "img" | ||
}, otherProps), | ||
!!title && /* @__PURE__ */ import_react.default.createElement("title", null, title), | ||
/* @__PURE__ */ import_react.default.createElement( | ||
"path", | ||
{ | ||
fill: bgColor, | ||
d: `M0,0 h${numCells}v${numCells}H0z`, | ||
shapeRendering: "crispEdges" | ||
} | ||
), | ||
/* @__PURE__ */ import_react.default.createElement("path", { fill: fgColor, d: fgPath, shapeRendering: "crispEdges" }), | ||
image | ||
); | ||
} | ||
const fgPath = generatePath(cells, margin); | ||
return /* @__PURE__ */ import_react.default.createElement("svg", __spreadValues({ | ||
height: size, | ||
width: size, | ||
viewBox: `0 0 ${numCells} ${numCells}` | ||
}, otherProps), /* @__PURE__ */ import_react.default.createElement("path", { | ||
fill: bgColor, | ||
d: `M0,0 h${numCells}v${numCells}H0z`, | ||
shapeRendering: "crispEdges" | ||
}), /* @__PURE__ */ import_react.default.createElement("path", { | ||
fill: fgColor, | ||
d: fgPath, | ||
shapeRendering: "crispEdges" | ||
}), image); | ||
} | ||
var QRCode = (props) => { | ||
const _a = props, { renderAs } = _a, otherProps = __objRest(_a, ["renderAs"]); | ||
if (renderAs === "svg") { | ||
return /* @__PURE__ */ import_react.default.createElement(QRCodeSVG, __spreadValues({}, otherProps)); | ||
} | ||
return /* @__PURE__ */ import_react.default.createElement(QRCodeCanvas, __spreadValues({}, otherProps)); | ||
}; | ||
); | ||
QRCodeSVG.displayName = "QRCodeSVG"; |
{ | ||
"name": "qrcode.react", | ||
"version": "3.1.0", | ||
"version": "4.0.0", | ||
"description": "React component to generate QR codes", | ||
@@ -14,13 +14,7 @@ "keywords": [ | ||
"types": "./lib/index.d.ts", | ||
"scripts": { | ||
"build": "yarn run build:code && yarn run build:examples", | ||
"build:code": "tsup src/index.tsx -d lib --format esm,cjs --dts --legacy-output --target=es2017 --platform=browser", | ||
"build:examples": "tsup examples/demo.tsx -d examples --format iife --env.NODE_ENV production --minify --target=es2017 --legacy-output", | ||
"lint": "eslint .", | ||
"pretty": "prettier --write '{*,.*}.{mjs,js,json}' '**/*.{js,json}'", | ||
"prepack": "make clean && make all && yarn run typecheck", | ||
"prepublish-docs": "make clean && make all", | ||
"publish-docs": "gh-pages --dist=examples --src='{index.html,iife/demo.js}'", | ||
"test": "jest", | ||
"typecheck": "tsc --noEmit" | ||
"exports": { | ||
".": { | ||
"import": "./lib/esm/index.js", | ||
"require": "./lib/index.js" | ||
} | ||
}, | ||
@@ -36,3 +30,2 @@ "author": "Paul O’Shannessy <paul@oshannessy.com>", | ||
], | ||
"dependencies": {}, | ||
"peerDependencies": { | ||
@@ -42,34 +35,39 @@ "react": "^16.8.0 || ^17.0.0 || ^18.0.0" | ||
"devDependencies": { | ||
"@babel/core": "^7.17.5", | ||
"@babel/preset-env": "^7.16.11", | ||
"@babel/preset-react": "^7.16.7", | ||
"@babel/preset-typescript": "^7.16.7", | ||
"@types/jest": "^28.1.3", | ||
"@types/node": "^18.0.0", | ||
"@jest/globals": "^29.5.0", | ||
"@testing-library/dom": "^10.4.0", | ||
"@testing-library/jest-dom": "^6.4.8", | ||
"@testing-library/react": "^16.0.0", | ||
"@types/node": "^20.4.10", | ||
"@types/react": "^18.0.8", | ||
"@types/react-dom": "^18.0.3", | ||
"@types/react-test-renderer": "^18.0.0", | ||
"@typescript-eslint/eslint-plugin": "^5.8.1", | ||
"@typescript-eslint/parser": "^5.8.1", | ||
"babel-jest": "^28.0.3", | ||
"@typescript-eslint/eslint-plugin": "^6.3.0", | ||
"@typescript-eslint/parser": "^6.3.0", | ||
"eslint": "^8.6.0", | ||
"eslint-config-prettier": "^8.1.0", | ||
"eslint-plugin-jest": "^26.1.1", | ||
"eslint-plugin-prettier": "^4.0.0", | ||
"eslint-config-prettier": "^9.0.0", | ||
"eslint-plugin-jest": "^27.1.3", | ||
"eslint-plugin-prettier": "^5.0.0", | ||
"eslint-plugin-react": "^7.23.2", | ||
"eslint-plugin-react-hooks": "^4.5.0", | ||
"gh-pages": "^4.0.0", | ||
"jest": "^28.0.3", | ||
"prettier": "^2.2.1", | ||
"gh-pages": "^6.0.0", | ||
"jest": "^29.2.2", | ||
"jest-environment-jsdom": "^29.7.0", | ||
"prettier": "^3.0.1", | ||
"react": "^18.0.0", | ||
"react-dom": "^18.0.0", | ||
"react-test-renderer": "^18.0.0", | ||
"tsup": "5.12.6", | ||
"typescript": "^4.5.4" | ||
"ts-jest": "^29.1.0", | ||
"tsup": "^8.0.2", | ||
"typescript": "^5.0.4" | ||
}, | ||
"jest": { | ||
"transform": { | ||
"\\.[jt]sx?$": "babel-jest" | ||
} | ||
"scripts": { | ||
"build": "pnpm run build:code && pnpm run build:examples", | ||
"build:code": "tsup src/index.tsx -d lib --format esm,cjs --dts --legacy-output --target=es2017 --platform=browser", | ||
"build:examples": "tsup examples/demo.tsx -d examples --format iife --env.NODE_ENV production --minify --target=es2017 --legacy-output", | ||
"build:examples:dev": "tsup examples/demo.tsx -d examples --format iife --env.NODE_ENV development --target=es2017 --legacy-output", | ||
"lint": "eslint .", | ||
"pretty": "prettier --write '{*,.*}.{mjs,js,json}' '**/*.{js,json}'", | ||
"prepublish-docs": "make clean && make all", | ||
"publish-docs": "gh-pages --dist=examples --src='{index.html,iife/demo.js}'", | ||
"test": "jest", | ||
"typecheck": "tsc --noEmit" | ||
} | ||
} | ||
} |
296
README.md
@@ -5,2 +5,4 @@ # qrcode.react | ||
<img src="qrcode.png" height="256" width="256"> | ||
## Installation | ||
@@ -14,3 +16,3 @@ | ||
`qrcode.react` exports three components, supporting rendering as SVG or Canvas. SVG is generally recommended as it is more flexible, but Canvas may be preferable. | ||
`qrcode.react` exports two components, supporting rendering as SVG or Canvas. SVG is generally recommended as it is more flexible, but Canvas may be preferable. | ||
@@ -43,40 +45,269 @@ All examples are shown using modern JavaScript modules and syntax. CommonJS `require('qrcode.react')` is also supported. | ||
### `QRCode` - **DEPRECATED** | ||
## Available Props | ||
**Note:** Usage of this is deprecated as of v3. It is available as the `default` export for compatiblity with previous versions. The `renderAs` prop is only supported with this component. | ||
Below is a condensed type definition of the props `QRCodeSVG` and `QRCodeCanvas` accept. | ||
```js | ||
import ReactDOM from 'react-dom'; | ||
import QRCode from 'qrcode.react'; | ||
ReactDOM.render( | ||
<QRCode value="https://reactjs.org/" renderAs="canvas" />, | ||
document.getElementById('mountNode') | ||
); | ||
```ts | ||
type QRProps = { | ||
/** | ||
* The value to encode into the QR Code. | ||
*/ | ||
value: string; | ||
/** | ||
* The size, in pixels, to render the QR Code. | ||
* @defaultValue 128 | ||
*/ | ||
size?: number; | ||
/** | ||
* The Error Correction Level to use. | ||
* @see https://www.qrcode.com/en/about/error_correction.html | ||
* @defaultValue L | ||
*/ | ||
level?: 'L' | 'M' | 'Q' | 'H'; | ||
/** | ||
* The background color used to render the QR Code. | ||
* @see https://developer.mozilla.org/en-US/docs/Web/CSS/color_value | ||
* @defaultValue #FFFFFF | ||
*/ | ||
bgColor?: string; | ||
/** | ||
* The foregtound color used to render the QR Code. | ||
* @see https://developer.mozilla.org/en-US/docs/Web/CSS/color_value | ||
* @defaultValue #000000 | ||
*/ | ||
fgColor?: string; | ||
/** | ||
* Whether or not a margin of 4 modules should be rendered as a part of the | ||
* QR Code. | ||
* @deprecated Use `marginSize` instead. | ||
* @defaultValue false | ||
*/ | ||
includeMargin?: boolean; | ||
/** | ||
* The number of _modules_ to use for margin. The QR Code specification | ||
* requires `4`, however you can specify any number. Values will be turned to | ||
* integers with `Math.floor`. Overrides `includeMargin` when both are specified. | ||
* @defaultValue 0 | ||
*/ | ||
marginSize?: number; | ||
/** | ||
* The title to assign to the QR Code. Used for accessibility reasons. | ||
*/ | ||
title?: string; | ||
/** | ||
* The minimum version used when encoding the QR Code. Valid values are 1-40 | ||
* with higher values resulting in more complex QR Codes. The optimal | ||
* (lowest) version is determined for the `value` provided, using `minVersion` | ||
* as the lower bound. | ||
* @defaultValue 1 | ||
*/ | ||
minVersion?: number; | ||
/** | ||
* The settings for the embedded image. | ||
*/ | ||
imageSettings?: { | ||
/** | ||
* The URI of the embedded image. | ||
*/ | ||
src: string; | ||
/** | ||
* The height, in pixels, of the image. | ||
*/ | ||
height: number; | ||
/** | ||
* The width, in pixels, of the image. | ||
*/ | ||
width: number; | ||
/** | ||
* Whether or not to "excavate" the modules around the embedded image. This | ||
* means that any modules the embedded image overlaps will use the background | ||
* color. | ||
*/ | ||
excavate: boolean; | ||
/** | ||
* The horiztonal offset of the embedded image, starting from the top left corner. | ||
* Will center if not specified. | ||
*/ | ||
x?: number; | ||
/** | ||
* The vertical offset of the embedded image, starting from the top left corner. | ||
* Will center if not specified. | ||
*/ | ||
y?: number; | ||
/** | ||
* The opacity of the embedded image in the range of 0-1. | ||
* @defaultValue 1 | ||
*/ | ||
opacity?: number; | ||
/** | ||
* The cross-origin value to use when loading the image. This is used to | ||
* ensure compatibility with CORS, particularly when extracting image data | ||
* from QRCodeCanvas. | ||
* Note: `undefined` is treated differently than the seemingly equivalent | ||
* empty string. This is intended to align with HTML behavior where omitting | ||
* the attribute behaves differently than the empty string. | ||
*/ | ||
crossOrigin?: 'anonymous' | 'use-credentials' | '' | undefined; | ||
}; | ||
}; | ||
``` | ||
## Available Props | ||
### `value` | ||
| prop | type | default value | | ||
| --------------- | ---------------------------- | ------------- | | ||
| `value` | `string` | | ||
| `renderAs` | `string` (`'canvas' 'svg'`) | `'canvas'` | | ||
| `size` | `number` | `128` | | ||
| `bgColor` | `string` (CSS color) | `"#FFFFFF"` | | ||
| `fgColor` | `string` (CSS color) | `"#000000"` | | ||
| `level` | `string` (`'L' 'M' 'Q' 'H'`) | `'L'` | | ||
| `includeMargin` | `boolean` | `false` | | ||
| `imageSettings` | `object` (see below) | | | ||
The value to encode into the QR Code. See [Encoding Mode](#encoding-mode) for additional details. | ||
| Type | Default Value | | ||
| -------- | ------------- | | ||
| `string` | — | | ||
### `size` | ||
The size, in pixels, to render the QR Code. | ||
| Type | Default Value | | ||
| -------- | ------------- | | ||
| `number` | `128` | | ||
### `level` | ||
The Error Correction Level to use. Information is encoded in QR Codes such that they can lose part of their visible areas and still be decodable. The amount of correction depends on this value. Higher error correction will result in more complex QR Codes. | ||
- `L` = low (~7%) | ||
- `M` = medium (~15%) | ||
- `Q` = quartile (~25%) | ||
- `H` = high (~30%) | ||
See [Wikipedia](https://en.wikipedia.org/wiki/QR_code#Error_correction) or the [official QR Code documentation](https://www.qrcode.com/en/about/error_correction.html) for a more detailed explaination. | ||
| Type | Default Value | | ||
| ------------------ | ------------- | | ||
| `L \| M \| Q \| H` | `L` | | ||
### `bgColor` | ||
The background color used to render the QR Code. This is passed directly to the Canvas (`ctx.fillStyle = bgColor`) or the SVG `<path>` (`fill={bgColor}`), both which accept any [CSS color](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). | ||
| Type | Default Value | | ||
| -------- | ------------- | | ||
| `string` | `#FFFFFF` | | ||
### `fgColor` | ||
The foreground color used to render the QR Code. It follows the same constraints as `bgColor` | ||
| Type | Default Value | | ||
| -------- | ------------- | | ||
| `string` | `#000000` | | ||
### `includeMargin` | ||
> [!WARNING] | ||
> This has been deprecated in v4 and will be removed in a future version. Use `marginSize` instead. | ||
Whether or not a margin of 4 modules should be rendered as a part of the QR Code. | ||
| Type | Default Value | | ||
| --------- | ------------- | | ||
| `boolean` | `false` | | ||
### `marginSize` | ||
The number of _modules_ to use for margin. The QR Code specification requires `4`, however you can specify any number. Values will be turned to integers with `Math.floor`. Overrides `includeMargin` when both are specified. | ||
| Type | Default Value | | ||
| -------- | ------------- | | ||
| `number` | `0` | | ||
### `title` | ||
The title to assign to the QR Code. Used for accessibility reasons. | ||
| Type | Default Value | | ||
| -------- | ------------- | | ||
| `string` | — | | ||
### `minVersion` | ||
The minimum version used when encoding the QR Code. Valid values are 1-40 with higher values resulting in more complex QR Codes. The optimal (lowest) version is determined for the `value` provided, using `minVersion` as the lower bound. | ||
| Type | Default Value | | ||
| -------- | ------------- | | ||
| `number` | `1` | | ||
### `imageSettings` | ||
| field | type | default value | | ||
| ---------- | --------- | ----------------- | | ||
| `src` | `string` | | ||
| `x` | `number` | none, will center | | ||
| `y` | `number` | none, will center | | ||
| `height` | `number` | 10% of `size` | | ||
| `width` | `number` | 10% of `size` | | ||
| `excavate` | `boolean` | `false` | | ||
Used to specify the details for an embedded image, often used to embed a logo. | ||
| Type | Default Value | | ||
| --------------------------- | ------------- | | ||
| `object` (see fields below) | — | | ||
### `imageSettings.src` | ||
The URI of the embedded image. This will get passed directly to `src` of an `img` element for `QRCodeCanvas` or the `href` of an inline `image` for `QRCodeSVG`. | ||
| Type | Default Value | | ||
| -------- | ------------- | | ||
| `string` | — | | ||
### `imageSettings.height` | ||
The height, in pixels, of the embedded image. | ||
| Type | Default Value | | ||
| -------- | ------------- | | ||
| `number` | — | | ||
### `imageSettings.width` | ||
The width, in pixels, of the embedded image. | ||
| Type | Default Value | | ||
| -------- | ------------- | | ||
| `number` | — | | ||
### `imageSettings.excavate` | ||
Whether or not to "excavate" the modules around the embedded image. This means that any modules the embedded image overlaps will use the background color. Use this to ensure clean edges around your image. It is also useful when embedding images with transparency. | ||
| Type | Default Value | | ||
| --------- | ------------- | | ||
| `boolean` | — | | ||
### `imageSettings.x` | ||
The horizontal offset, in pixels, of the embedded image. Positioning follows standard DOM positioning, with top left corner being 0. | ||
When not specified, will center the image. | ||
| Type | Default Value | | ||
| -------- | ------------- | | ||
| `number` | — | | ||
### `imageSettings.y` | ||
The vertical offset, in pixels, of the embedded image. Positioning follows standard DOM positioning, with top left corner being 0. | ||
When not specified, will center the image. | ||
| Type | Default Value | | ||
| -------- | ------------- | | ||
| `number` | — | | ||
### `imageSettings.opacity` | ||
The opacity of the embedded image, in the range of 0 to 1. | ||
| Type | Default Value | | ||
| -------- | ------------- | | ||
| `number` | 1 | | ||
### `imageSettings.crossOrigin` | ||
The `cross-origin` value to use when loading the embedded image. Note that `undefined` works as typically does with React, excluding the attribute from the DOM node. This is intended to align with HTML behavior where omitting the attribute behaves differently than the empty string. | ||
| Type | Default Value | | ||
| -------- | ------------- | | ||
| `string` | — | | ||
## Custom Styles | ||
@@ -86,6 +317,5 @@ | ||
**Note:** In order to render QR Codes in `<canvas>` on high density displays, we scale the canvas element to contain an appropriate number of pixels and then use inline styles to scale back down. We will merge any additional styles, with custom `height` and `width` overriding our own values. This allows scaling to percentages _but_ if scaling beyond the `size`, you will encounter blurry images. I recommend detecting resizes with something like [react-measure](https://github.com/souporserious/react-measure) to detect and pass the appropriate size when rendering to `<canvas>`. | ||
> [!NOTE] | ||
> In order to render QR Codes in `<canvas>` on high density displays, we scale the canvas element to contain an appropriate number of pixels and then use inline styles to scale back down. We will merge any additional styles, with custom `height` and `width` overriding our own values. This allows scaling to percentages _but_ if scaling beyond the `size`, you will encounter blurry images. I recommend detecting resizes with something like [react-measure](https://github.com/souporserious/react-measure) to detect and pass the appropriate size when rendering to `<canvas>`. | ||
<img src="qrcode.png" height="256" width="256"> | ||
## Encoding Mode | ||
@@ -92,0 +322,0 @@ |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
112408
24
9
2382
326