qrcodesolid 0.0.0 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +493 -2
- package/dist/color-parse-empty.d.ts +6 -0
- package/dist/color-parse-empty.js +7 -0
- package/dist/color-parse.d.ts +8 -0
- package/dist/color-parse.js +49 -0
- package/dist/index.d.ts +372 -0
- package/dist/index.js +2640 -0
- package/dist/paint-ChCPh-rm.d.ts +29 -0
- package/dist/payload.d.ts +53 -0
- package/dist/payload.js +93 -0
- package/dist/server.d.ts +399 -0
- package/dist/server.js +2833 -0
- package/dist/source/components/GradientDef.jsx +19 -0
- package/dist/source/components/QRCode.jsx +10 -0
- package/dist/source/components/QRCodeCanvas.jsx +72 -0
- package/dist/source/components/QRCodeSVG.jsx +57 -0
- package/dist/source/core/caption.js +77 -0
- package/dist/source/core/color-names.js +34 -0
- package/dist/source/core/color-parse-empty.js +5 -0
- package/dist/source/core/color-parse.js +41 -0
- package/dist/source/core/encode.js +120 -0
- package/dist/source/core/logo.js +90 -0
- package/dist/source/core/options.js +56 -0
- package/dist/source/core/output.js +23 -0
- package/dist/source/core/paint.js +30 -0
- package/dist/source/core/path.js +46 -0
- package/dist/source/core/qrcodegen.js +875 -0
- package/dist/source/core/scene.js +141 -0
- package/dist/source/core/stages.js +24 -0
- package/dist/source/core/warnings.js +38 -0
- package/dist/source/export/index.js +105 -0
- package/dist/source/index.js +16 -0
- package/dist/source/payload/contact.js +42 -0
- package/dist/source/payload/escape.js +3 -0
- package/dist/source/payload/index.js +3 -0
- package/dist/source/payload/message.js +19 -0
- package/dist/source/payload/place.js +40 -0
- package/dist/source/primitives/createColorScheme.js +18 -0
- package/dist/source/primitives/createPixelRatio.js +25 -0
- package/dist/source/primitives/createQRCode.js +47 -0
- package/dist/source/render/canvas.js +46 -0
- package/dist/source/render/color.js +63 -0
- package/dist/source/render/image.js +123 -0
- package/dist/source/render/svg-string.js +55 -0
- package/dist/source/shapes/bars.js +50 -0
- package/dist/source/shapes/finders.js +30 -0
- package/dist/source/shapes/frames.js +62 -0
- package/dist/source/shapes/modules.js +39 -0
- package/dist/source/shapes/types.js +8 -0
- package/llms.txt +117 -0
- package/package.json +95 -6
- package/skills/qrcodesolid/SKILL.md +101 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,2640 @@
|
|
|
1
|
+
import { createComponent, effect, insert, isDev, isServer, memo, ref, setAttribute, spread, template } from "@solidjs/web";
|
|
2
|
+
import { For, Match, Show, Switch, createEffect, createMemo, createSignal, createUniqueId, omit, onSettled } from "solid-js";
|
|
3
|
+
import { parseColor } from "#color-parse";
|
|
4
|
+
// src/core/caption.ts
|
|
5
|
+
function toCaptionShape(caption) {
|
|
6
|
+
if (!caption) return void 0;
|
|
7
|
+
const { color: _color, ...shape } = caption;
|
|
8
|
+
return shape;
|
|
9
|
+
}
|
|
10
|
+
const sameCaptionShape = (a, b) => a === b || !!a && !!b && a.text === b.text && a.position === b.position && a.fontSize === b.fontSize && a.fontFamily === b.fontFamily && a.fontWeight === b.fontWeight;
|
|
11
|
+
const minFontSize = 1;
|
|
12
|
+
/** East Asian wide ranges and the main emoji blocks, by code point. */
|
|
13
|
+
const isWide = (c) => c >= 4352 && c <= 4447 || c >= 11904 && c <= 42191 || c >= 44032 && c <= 55203 || c >= 63744 && c <= 64255 || c >= 65072 && c <= 65103 || c >= 65280 && c <= 65376 || c >= 65504 && c <= 65510 || c >= 127744 && c <= 129791 || c >= 131072 && c <= 262141;
|
|
14
|
+
function estimateTextWidth(text, fontSize) {
|
|
15
|
+
let [chars, wide] = [0, 0];
|
|
16
|
+
for (const char of text) {
|
|
17
|
+
chars++;
|
|
18
|
+
if (isWide(char.codePointAt(0))) wide++;
|
|
19
|
+
}
|
|
20
|
+
return ((chars - wide) * .6 + wide) * fontSize;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Lowers `fontSize` until the text fits `width`, but not below 1 module.
|
|
24
|
+
* `overflows` is true when the text is still too wide at that size.
|
|
25
|
+
*/
|
|
26
|
+
function fitFontSize(text, fontSize, width) {
|
|
27
|
+
const fit = width / estimateTextWidth(text, 1);
|
|
28
|
+
if (fontSize <= fit) return {
|
|
29
|
+
fontSize,
|
|
30
|
+
overflows: false
|
|
31
|
+
};
|
|
32
|
+
const fitted = Math.max(fit, Math.min(fontSize, minFontSize));
|
|
33
|
+
return {
|
|
34
|
+
fontSize: fitted,
|
|
35
|
+
overflows: fitted > fit
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/** The dev warning for `subject` when its fitted text still overflows `width`, else undefined. */
|
|
39
|
+
function overflowWarning(subject, text, fitted, width, space) {
|
|
40
|
+
if (!fitted.overflows) return void 0;
|
|
41
|
+
const wide = Math.round(estimateTextWidth(text, fitted.fontSize));
|
|
42
|
+
return `The ${subject} was shrunk to fontSize ${fitted.fontSize}, the minimum, and is still about ${wide} modules wide, wider than ${space} (${width} modules); shorten it.`;
|
|
43
|
+
}
|
|
44
|
+
/** Adds a text band above or below the layout. Long text shrinks to fit the layout width. */
|
|
45
|
+
function layoutCaption({ width, height, qr }, caption) {
|
|
46
|
+
const fitted = fitFontSize(caption.text, caption.fontSize ?? 2, width);
|
|
47
|
+
const { fontSize } = fitted;
|
|
48
|
+
const warning = overflowWarning("caption", caption.text, fitted, width, "the code with its margin");
|
|
49
|
+
const band = fontSize * 1.75;
|
|
50
|
+
const top = caption.position === "top";
|
|
51
|
+
return {
|
|
52
|
+
layout: {
|
|
53
|
+
width,
|
|
54
|
+
height: height + band,
|
|
55
|
+
qr: top ? {
|
|
56
|
+
...qr,
|
|
57
|
+
y: qr.y + band
|
|
58
|
+
} : qr
|
|
59
|
+
},
|
|
60
|
+
texts: [{
|
|
61
|
+
text: caption.text,
|
|
62
|
+
x: width / 2,
|
|
63
|
+
y: (top ? 0 : height) + band / 2,
|
|
64
|
+
fontSize,
|
|
65
|
+
fontFamily: caption.fontFamily ?? "system-ui, sans-serif",
|
|
66
|
+
fontWeight: caption.fontWeight ?? "normal",
|
|
67
|
+
paint: "caption"
|
|
68
|
+
}],
|
|
69
|
+
warnings: warning ? [warning] : []
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
// src/core/qrcodegen.ts
|
|
73
|
+
/**
|
|
74
|
+
* @license QR Code generator library (TypeScript)
|
|
75
|
+
* Copyright (c) Project Nayuki.
|
|
76
|
+
* SPDX-License-Identifier: MIT
|
|
77
|
+
*
|
|
78
|
+
* Local change: the mask penalty scoring was optimised with typed arrays and fewer passes.
|
|
79
|
+
* Its scores match the original bit for bit; test/penalty.test.ts checks this.
|
|
80
|
+
*/
|
|
81
|
+
let qrcodegen;
|
|
82
|
+
(function(_qrcodegen) {
|
|
83
|
+
class QrCode {
|
|
84
|
+
version;
|
|
85
|
+
errorCorrectionLevel;
|
|
86
|
+
static encodeText(text, ecl) {
|
|
87
|
+
const segs = qrcodegen.QrSegment.makeSegments(text);
|
|
88
|
+
return QrCode.encodeSegments(segs, ecl);
|
|
89
|
+
}
|
|
90
|
+
static encodeBinary(data, ecl) {
|
|
91
|
+
const seg = qrcodegen.QrSegment.makeBytes(data);
|
|
92
|
+
return QrCode.encodeSegments([seg], ecl);
|
|
93
|
+
}
|
|
94
|
+
static encodeSegments(segs, ecl, minVersion = 1, maxVersion = 40, mask = -1, boostEcl = true) {
|
|
95
|
+
if (!(QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= QrCode.MAX_VERSION) || mask < -1 || mask > 7) throw new RangeError("Invalid value");
|
|
96
|
+
let version;
|
|
97
|
+
let dataUsedBits;
|
|
98
|
+
for (version = minVersion;; version++) {
|
|
99
|
+
const dataCapacityBits = QrCode.getNumDataCodewords(version, ecl) * 8;
|
|
100
|
+
const usedBits = QrSegment.getTotalBits(segs, version);
|
|
101
|
+
if (usedBits <= dataCapacityBits) {
|
|
102
|
+
dataUsedBits = usedBits;
|
|
103
|
+
break;
|
|
104
|
+
}
|
|
105
|
+
if (version >= maxVersion) throw new RangeError("Data too long");
|
|
106
|
+
}
|
|
107
|
+
for (const newEcl of [
|
|
108
|
+
QrCode.Ecc.MEDIUM,
|
|
109
|
+
QrCode.Ecc.QUARTILE,
|
|
110
|
+
QrCode.Ecc.HIGH
|
|
111
|
+
]) if (boostEcl && dataUsedBits <= QrCode.getNumDataCodewords(version, newEcl) * 8) ecl = newEcl;
|
|
112
|
+
let bb = [];
|
|
113
|
+
for (const seg of segs) {
|
|
114
|
+
appendBits(seg.mode.modeBits, 4, bb);
|
|
115
|
+
appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb);
|
|
116
|
+
for (const b of seg.getData()) bb.push(b);
|
|
117
|
+
}
|
|
118
|
+
assert(bb.length == dataUsedBits);
|
|
119
|
+
const dataCapacityBits = QrCode.getNumDataCodewords(version, ecl) * 8;
|
|
120
|
+
assert(bb.length <= dataCapacityBits);
|
|
121
|
+
appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb);
|
|
122
|
+
appendBits(0, (8 - bb.length % 8) % 8, bb);
|
|
123
|
+
assert(bb.length % 8 == 0);
|
|
124
|
+
for (let padByte = 236; bb.length < dataCapacityBits; padByte ^= 253) appendBits(padByte, 8, bb);
|
|
125
|
+
let dataCodewords = [];
|
|
126
|
+
while (dataCodewords.length * 8 < bb.length) dataCodewords.push(0);
|
|
127
|
+
bb.forEach((b, i) => dataCodewords[i >>> 3] |= b << 7 - (i & 7));
|
|
128
|
+
return new QrCode(version, ecl, dataCodewords, mask);
|
|
129
|
+
}
|
|
130
|
+
size;
|
|
131
|
+
mask;
|
|
132
|
+
modules = [];
|
|
133
|
+
isFunction = [];
|
|
134
|
+
constructor(version, errorCorrectionLevel, dataCodewords, msk) {
|
|
135
|
+
this.version = version;
|
|
136
|
+
this.errorCorrectionLevel = errorCorrectionLevel;
|
|
137
|
+
if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION) throw new RangeError("Version value out of range");
|
|
138
|
+
if (msk < -1 || msk > 7) throw new RangeError("Mask value out of range");
|
|
139
|
+
this.size = version * 4 + 17;
|
|
140
|
+
let row = [];
|
|
141
|
+
for (let i = 0; i < this.size; i++) row.push(false);
|
|
142
|
+
for (let i = 0; i < this.size; i++) {
|
|
143
|
+
this.modules.push(row.slice());
|
|
144
|
+
this.isFunction.push(row.slice());
|
|
145
|
+
}
|
|
146
|
+
this.drawFunctionPatterns();
|
|
147
|
+
const allCodewords = this.addEccAndInterleave(dataCodewords);
|
|
148
|
+
this.drawCodewords(allCodewords);
|
|
149
|
+
if (msk == -1) {
|
|
150
|
+
const cells = this.size * this.size;
|
|
151
|
+
const base = new Uint8Array(cells);
|
|
152
|
+
const free = new Uint8Array(cells);
|
|
153
|
+
for (let y = 0; y < this.size; y++) for (let x = 0; x < this.size; x++) {
|
|
154
|
+
base[y * this.size + x] = this.modules[y][x] ? 1 : 0;
|
|
155
|
+
free[y * this.size + x] = this.isFunction[y][x] ? 0 : 1;
|
|
156
|
+
}
|
|
157
|
+
const grid = new Uint8Array(cells);
|
|
158
|
+
let minPenalty = 1e9;
|
|
159
|
+
for (let i = 0; i < 8; i++) {
|
|
160
|
+
this.drawFormatBits(i);
|
|
161
|
+
this.fillMaskedGrid(i, base, free, grid);
|
|
162
|
+
const penalty = getPenaltyScore(grid, this.size);
|
|
163
|
+
if (penalty < minPenalty) {
|
|
164
|
+
msk = i;
|
|
165
|
+
minPenalty = penalty;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
assert(0 <= msk && msk <= 7);
|
|
170
|
+
this.mask = msk;
|
|
171
|
+
this.applyMask(msk);
|
|
172
|
+
this.drawFormatBits(msk);
|
|
173
|
+
this.isFunction = [];
|
|
174
|
+
}
|
|
175
|
+
getModule(x, y) {
|
|
176
|
+
return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y][x];
|
|
177
|
+
}
|
|
178
|
+
getModules() {
|
|
179
|
+
return this.modules;
|
|
180
|
+
}
|
|
181
|
+
drawFunctionPatterns() {
|
|
182
|
+
for (let i = 0; i < this.size; i++) {
|
|
183
|
+
this.setFunctionModule(6, i, i % 2 == 0);
|
|
184
|
+
this.setFunctionModule(i, 6, i % 2 == 0);
|
|
185
|
+
}
|
|
186
|
+
this.drawFinderPattern(3, 3);
|
|
187
|
+
this.drawFinderPattern(this.size - 4, 3);
|
|
188
|
+
this.drawFinderPattern(3, this.size - 4);
|
|
189
|
+
const alignPatPos = this.getAlignmentPatternPositions();
|
|
190
|
+
const numAlign = alignPatPos.length;
|
|
191
|
+
for (let i = 0; i < numAlign; i++) for (let j = 0; j < numAlign; j++) if (!(i == 0 && j == 0 || i == 0 && j == numAlign - 1 || i == numAlign - 1 && j == 0)) this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j]);
|
|
192
|
+
this.drawFormatBits(0);
|
|
193
|
+
this.drawVersion();
|
|
194
|
+
}
|
|
195
|
+
drawFormatBits(mask) {
|
|
196
|
+
const data = this.errorCorrectionLevel.formatBits << 3 | mask;
|
|
197
|
+
let rem = data;
|
|
198
|
+
for (let i = 0; i < 10; i++) rem = rem << 1 ^ (rem >>> 9) * 1335;
|
|
199
|
+
const bits = (data << 10 | rem) ^ 21522;
|
|
200
|
+
assert(bits >>> 15 == 0);
|
|
201
|
+
for (let i = 0; i <= 5; i++) this.setFunctionModule(8, i, getBit(bits, i));
|
|
202
|
+
this.setFunctionModule(8, 7, getBit(bits, 6));
|
|
203
|
+
this.setFunctionModule(8, 8, getBit(bits, 7));
|
|
204
|
+
this.setFunctionModule(7, 8, getBit(bits, 8));
|
|
205
|
+
for (let i = 9; i < 15; i++) this.setFunctionModule(14 - i, 8, getBit(bits, i));
|
|
206
|
+
for (let i = 0; i < 8; i++) this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i));
|
|
207
|
+
for (let i = 8; i < 15; i++) this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i));
|
|
208
|
+
this.setFunctionModule(8, this.size - 8, true);
|
|
209
|
+
}
|
|
210
|
+
drawVersion() {
|
|
211
|
+
if (this.version < 7) return;
|
|
212
|
+
let rem = this.version;
|
|
213
|
+
for (let i = 0; i < 12; i++) rem = rem << 1 ^ (rem >>> 11) * 7973;
|
|
214
|
+
const bits = this.version << 12 | rem;
|
|
215
|
+
assert(bits >>> 18 == 0);
|
|
216
|
+
for (let i = 0; i < 18; i++) {
|
|
217
|
+
const color = getBit(bits, i);
|
|
218
|
+
const a = this.size - 11 + i % 3;
|
|
219
|
+
const b = Math.floor(i / 3);
|
|
220
|
+
this.setFunctionModule(a, b, color);
|
|
221
|
+
this.setFunctionModule(b, a, color);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
drawFinderPattern(x, y) {
|
|
225
|
+
for (let dy = -4; dy <= 4; dy++) for (let dx = -4; dx <= 4; dx++) {
|
|
226
|
+
const dist = Math.max(Math.abs(dx), Math.abs(dy));
|
|
227
|
+
const xx = x + dx;
|
|
228
|
+
const yy = y + dy;
|
|
229
|
+
if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size) this.setFunctionModule(xx, yy, dist != 2 && dist != 4);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
drawAlignmentPattern(x, y) {
|
|
233
|
+
for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1);
|
|
234
|
+
}
|
|
235
|
+
setFunctionModule(x, y, isDark) {
|
|
236
|
+
this.modules[y][x] = isDark;
|
|
237
|
+
this.isFunction[y][x] = true;
|
|
238
|
+
}
|
|
239
|
+
addEccAndInterleave(data) {
|
|
240
|
+
const ver = this.version;
|
|
241
|
+
const ecl = this.errorCorrectionLevel;
|
|
242
|
+
if (data.length != QrCode.getNumDataCodewords(ver, ecl)) throw new RangeError("Invalid argument");
|
|
243
|
+
const numBlocks = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
|
|
244
|
+
const blockEccLen = QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver];
|
|
245
|
+
const rawCodewords = Math.floor(QrCode.getNumRawDataModules(ver) / 8);
|
|
246
|
+
const numShortBlocks = numBlocks - rawCodewords % numBlocks;
|
|
247
|
+
const shortBlockLen = Math.floor(rawCodewords / numBlocks);
|
|
248
|
+
let blocks = [];
|
|
249
|
+
const rsDiv = QrCode.reedSolomonComputeDivisor(blockEccLen);
|
|
250
|
+
for (let i = 0, k = 0; i < numBlocks; i++) {
|
|
251
|
+
let dat = data.slice(k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1));
|
|
252
|
+
k += dat.length;
|
|
253
|
+
const ecc = QrCode.reedSolomonComputeRemainder(dat, rsDiv);
|
|
254
|
+
if (i < numShortBlocks) dat.push(0);
|
|
255
|
+
blocks.push(dat.concat(ecc));
|
|
256
|
+
}
|
|
257
|
+
let result = [];
|
|
258
|
+
for (let i = 0; i < blocks[0].length; i++) blocks.forEach((block, j) => {
|
|
259
|
+
if (i != shortBlockLen - blockEccLen || j >= numShortBlocks) result.push(block[i]);
|
|
260
|
+
});
|
|
261
|
+
assert(result.length == rawCodewords);
|
|
262
|
+
return result;
|
|
263
|
+
}
|
|
264
|
+
drawCodewords(data) {
|
|
265
|
+
if (data.length != Math.floor(QrCode.getNumRawDataModules(this.version) / 8)) throw new RangeError("Invalid argument");
|
|
266
|
+
let i = 0;
|
|
267
|
+
for (let right = this.size - 1; right >= 1; right -= 2) {
|
|
268
|
+
if (right == 6) right = 5;
|
|
269
|
+
for (let vert = 0; vert < this.size; vert++) for (let j = 0; j < 2; j++) {
|
|
270
|
+
const x = right - j;
|
|
271
|
+
const y = (right + 1 & 2) == 0 ? this.size - 1 - vert : vert;
|
|
272
|
+
if (!this.isFunction[y][x] && i < data.length * 8) {
|
|
273
|
+
this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7));
|
|
274
|
+
i++;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
assert(i == data.length * 8);
|
|
279
|
+
}
|
|
280
|
+
applyMask(mask) {
|
|
281
|
+
if (mask < 0 || mask > 7) throw new RangeError("Mask value out of range");
|
|
282
|
+
for (let y = 0; y < this.size; y++) for (let x = 0; x < this.size; x++) if (!this.isFunction[y][x] && maskBit(mask, x, y)) this.modules[y][x] = !this.modules[y][x];
|
|
283
|
+
}
|
|
284
|
+
fillMaskedGrid(mask, base, free, grid) {
|
|
285
|
+
const size = this.size;
|
|
286
|
+
const pattern = getMaskPattern(mask);
|
|
287
|
+
for (let y = 0, p = 0; y < size; y++) {
|
|
288
|
+
const row = y % MASK_PERIOD * MASK_PERIOD;
|
|
289
|
+
for (let x = 0, column = 0; x < size; x++, p++) {
|
|
290
|
+
grid[p] = base[p] ^ pattern[row + column] & free[p];
|
|
291
|
+
if (++column == MASK_PERIOD) column = 0;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
for (let i = 0; i < size; i++) {
|
|
295
|
+
if (this.isFunction[8][i]) grid[8 * size + i] = this.modules[8][i] ? 1 : 0;
|
|
296
|
+
if (this.isFunction[i][8]) grid[i * size + 8] = this.modules[i][8] ? 1 : 0;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
getAlignmentPatternPositions() {
|
|
300
|
+
if (this.version == 1) return [];
|
|
301
|
+
else {
|
|
302
|
+
const numAlign = Math.floor(this.version / 7) + 2;
|
|
303
|
+
const step = this.version == 32 ? 26 : Math.ceil((this.version * 4 + 4) / (numAlign * 2 - 2)) * 2;
|
|
304
|
+
let result = [6];
|
|
305
|
+
for (let pos = this.size - 7; result.length < numAlign; pos -= step) result.splice(1, 0, pos);
|
|
306
|
+
return result;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
static getNumRawDataModules(ver) {
|
|
310
|
+
if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION) throw new RangeError("Version number out of range");
|
|
311
|
+
let result = (16 * ver + 128) * ver + 64;
|
|
312
|
+
if (ver >= 2) {
|
|
313
|
+
const numAlign = Math.floor(ver / 7) + 2;
|
|
314
|
+
result -= (25 * numAlign - 10) * numAlign - 55;
|
|
315
|
+
if (ver >= 7) result -= 36;
|
|
316
|
+
}
|
|
317
|
+
assert(208 <= result && result <= 29648);
|
|
318
|
+
return result;
|
|
319
|
+
}
|
|
320
|
+
static getNumDataCodewords(ver, ecl) {
|
|
321
|
+
return Math.floor(QrCode.getNumRawDataModules(ver) / 8) - QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver] * QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
|
|
322
|
+
}
|
|
323
|
+
static reedSolomonComputeDivisor(degree) {
|
|
324
|
+
if (degree < 1 || degree > 255) throw new RangeError("Degree out of range");
|
|
325
|
+
let result = [];
|
|
326
|
+
for (let i = 0; i < degree - 1; i++) result.push(0);
|
|
327
|
+
result.push(1);
|
|
328
|
+
let root = 1;
|
|
329
|
+
for (let i = 0; i < degree; i++) {
|
|
330
|
+
for (let j = 0; j < result.length; j++) {
|
|
331
|
+
result[j] = QrCode.reedSolomonMultiply(result[j], root);
|
|
332
|
+
if (j + 1 < result.length) result[j] ^= result[j + 1];
|
|
333
|
+
}
|
|
334
|
+
root = QrCode.reedSolomonMultiply(root, 2);
|
|
335
|
+
}
|
|
336
|
+
return result;
|
|
337
|
+
}
|
|
338
|
+
static reedSolomonComputeRemainder(data, divisor) {
|
|
339
|
+
let result = divisor.map((_) => 0);
|
|
340
|
+
for (const b of data) {
|
|
341
|
+
const factor = b ^ result.shift();
|
|
342
|
+
result.push(0);
|
|
343
|
+
divisor.forEach((coef, i) => result[i] ^= QrCode.reedSolomonMultiply(coef, factor));
|
|
344
|
+
}
|
|
345
|
+
return result;
|
|
346
|
+
}
|
|
347
|
+
static reedSolomonMultiply(x, y) {
|
|
348
|
+
if (x >>> 8 != 0 || y >>> 8 != 0) throw new RangeError("Byte out of range");
|
|
349
|
+
let z = 0;
|
|
350
|
+
for (let i = 7; i >= 0; i--) {
|
|
351
|
+
z = z << 1 ^ (z >>> 7) * 285;
|
|
352
|
+
z ^= (y >>> i & 1) * x;
|
|
353
|
+
}
|
|
354
|
+
assert(z >>> 8 == 0);
|
|
355
|
+
return z;
|
|
356
|
+
}
|
|
357
|
+
static MIN_VERSION = 1;
|
|
358
|
+
static MAX_VERSION = 40;
|
|
359
|
+
static ECC_CODEWORDS_PER_BLOCK = [
|
|
360
|
+
[
|
|
361
|
+
-1,
|
|
362
|
+
7,
|
|
363
|
+
10,
|
|
364
|
+
15,
|
|
365
|
+
20,
|
|
366
|
+
26,
|
|
367
|
+
18,
|
|
368
|
+
20,
|
|
369
|
+
24,
|
|
370
|
+
30,
|
|
371
|
+
18,
|
|
372
|
+
20,
|
|
373
|
+
24,
|
|
374
|
+
26,
|
|
375
|
+
30,
|
|
376
|
+
22,
|
|
377
|
+
24,
|
|
378
|
+
28,
|
|
379
|
+
30,
|
|
380
|
+
28,
|
|
381
|
+
28,
|
|
382
|
+
28,
|
|
383
|
+
28,
|
|
384
|
+
30,
|
|
385
|
+
30,
|
|
386
|
+
26,
|
|
387
|
+
28,
|
|
388
|
+
30,
|
|
389
|
+
30,
|
|
390
|
+
30,
|
|
391
|
+
30,
|
|
392
|
+
30,
|
|
393
|
+
30,
|
|
394
|
+
30,
|
|
395
|
+
30,
|
|
396
|
+
30,
|
|
397
|
+
30,
|
|
398
|
+
30,
|
|
399
|
+
30,
|
|
400
|
+
30,
|
|
401
|
+
30
|
|
402
|
+
],
|
|
403
|
+
[
|
|
404
|
+
-1,
|
|
405
|
+
10,
|
|
406
|
+
16,
|
|
407
|
+
26,
|
|
408
|
+
18,
|
|
409
|
+
24,
|
|
410
|
+
16,
|
|
411
|
+
18,
|
|
412
|
+
22,
|
|
413
|
+
22,
|
|
414
|
+
26,
|
|
415
|
+
30,
|
|
416
|
+
22,
|
|
417
|
+
22,
|
|
418
|
+
24,
|
|
419
|
+
24,
|
|
420
|
+
28,
|
|
421
|
+
28,
|
|
422
|
+
26,
|
|
423
|
+
26,
|
|
424
|
+
26,
|
|
425
|
+
26,
|
|
426
|
+
28,
|
|
427
|
+
28,
|
|
428
|
+
28,
|
|
429
|
+
28,
|
|
430
|
+
28,
|
|
431
|
+
28,
|
|
432
|
+
28,
|
|
433
|
+
28,
|
|
434
|
+
28,
|
|
435
|
+
28,
|
|
436
|
+
28,
|
|
437
|
+
28,
|
|
438
|
+
28,
|
|
439
|
+
28,
|
|
440
|
+
28,
|
|
441
|
+
28,
|
|
442
|
+
28,
|
|
443
|
+
28,
|
|
444
|
+
28
|
|
445
|
+
],
|
|
446
|
+
[
|
|
447
|
+
-1,
|
|
448
|
+
13,
|
|
449
|
+
22,
|
|
450
|
+
18,
|
|
451
|
+
26,
|
|
452
|
+
18,
|
|
453
|
+
24,
|
|
454
|
+
18,
|
|
455
|
+
22,
|
|
456
|
+
20,
|
|
457
|
+
24,
|
|
458
|
+
28,
|
|
459
|
+
26,
|
|
460
|
+
24,
|
|
461
|
+
20,
|
|
462
|
+
30,
|
|
463
|
+
24,
|
|
464
|
+
28,
|
|
465
|
+
28,
|
|
466
|
+
26,
|
|
467
|
+
30,
|
|
468
|
+
28,
|
|
469
|
+
30,
|
|
470
|
+
30,
|
|
471
|
+
30,
|
|
472
|
+
30,
|
|
473
|
+
28,
|
|
474
|
+
30,
|
|
475
|
+
30,
|
|
476
|
+
30,
|
|
477
|
+
30,
|
|
478
|
+
30,
|
|
479
|
+
30,
|
|
480
|
+
30,
|
|
481
|
+
30,
|
|
482
|
+
30,
|
|
483
|
+
30,
|
|
484
|
+
30,
|
|
485
|
+
30,
|
|
486
|
+
30,
|
|
487
|
+
30
|
|
488
|
+
],
|
|
489
|
+
[
|
|
490
|
+
-1,
|
|
491
|
+
17,
|
|
492
|
+
28,
|
|
493
|
+
22,
|
|
494
|
+
16,
|
|
495
|
+
22,
|
|
496
|
+
28,
|
|
497
|
+
26,
|
|
498
|
+
26,
|
|
499
|
+
24,
|
|
500
|
+
28,
|
|
501
|
+
24,
|
|
502
|
+
28,
|
|
503
|
+
22,
|
|
504
|
+
24,
|
|
505
|
+
24,
|
|
506
|
+
30,
|
|
507
|
+
28,
|
|
508
|
+
28,
|
|
509
|
+
26,
|
|
510
|
+
28,
|
|
511
|
+
30,
|
|
512
|
+
24,
|
|
513
|
+
30,
|
|
514
|
+
30,
|
|
515
|
+
30,
|
|
516
|
+
30,
|
|
517
|
+
30,
|
|
518
|
+
30,
|
|
519
|
+
30,
|
|
520
|
+
30,
|
|
521
|
+
30,
|
|
522
|
+
30,
|
|
523
|
+
30,
|
|
524
|
+
30,
|
|
525
|
+
30,
|
|
526
|
+
30,
|
|
527
|
+
30,
|
|
528
|
+
30,
|
|
529
|
+
30,
|
|
530
|
+
30
|
|
531
|
+
]
|
|
532
|
+
];
|
|
533
|
+
static NUM_ERROR_CORRECTION_BLOCKS = [
|
|
534
|
+
[
|
|
535
|
+
-1,
|
|
536
|
+
1,
|
|
537
|
+
1,
|
|
538
|
+
1,
|
|
539
|
+
1,
|
|
540
|
+
1,
|
|
541
|
+
2,
|
|
542
|
+
2,
|
|
543
|
+
2,
|
|
544
|
+
2,
|
|
545
|
+
4,
|
|
546
|
+
4,
|
|
547
|
+
4,
|
|
548
|
+
4,
|
|
549
|
+
4,
|
|
550
|
+
6,
|
|
551
|
+
6,
|
|
552
|
+
6,
|
|
553
|
+
6,
|
|
554
|
+
7,
|
|
555
|
+
8,
|
|
556
|
+
8,
|
|
557
|
+
9,
|
|
558
|
+
9,
|
|
559
|
+
10,
|
|
560
|
+
12,
|
|
561
|
+
12,
|
|
562
|
+
12,
|
|
563
|
+
13,
|
|
564
|
+
14,
|
|
565
|
+
15,
|
|
566
|
+
16,
|
|
567
|
+
17,
|
|
568
|
+
18,
|
|
569
|
+
19,
|
|
570
|
+
19,
|
|
571
|
+
20,
|
|
572
|
+
21,
|
|
573
|
+
22,
|
|
574
|
+
24,
|
|
575
|
+
25
|
|
576
|
+
],
|
|
577
|
+
[
|
|
578
|
+
-1,
|
|
579
|
+
1,
|
|
580
|
+
1,
|
|
581
|
+
1,
|
|
582
|
+
2,
|
|
583
|
+
2,
|
|
584
|
+
4,
|
|
585
|
+
4,
|
|
586
|
+
4,
|
|
587
|
+
5,
|
|
588
|
+
5,
|
|
589
|
+
5,
|
|
590
|
+
8,
|
|
591
|
+
9,
|
|
592
|
+
9,
|
|
593
|
+
10,
|
|
594
|
+
10,
|
|
595
|
+
11,
|
|
596
|
+
13,
|
|
597
|
+
14,
|
|
598
|
+
16,
|
|
599
|
+
17,
|
|
600
|
+
17,
|
|
601
|
+
18,
|
|
602
|
+
20,
|
|
603
|
+
21,
|
|
604
|
+
23,
|
|
605
|
+
25,
|
|
606
|
+
26,
|
|
607
|
+
28,
|
|
608
|
+
29,
|
|
609
|
+
31,
|
|
610
|
+
33,
|
|
611
|
+
35,
|
|
612
|
+
37,
|
|
613
|
+
38,
|
|
614
|
+
40,
|
|
615
|
+
43,
|
|
616
|
+
45,
|
|
617
|
+
47,
|
|
618
|
+
49
|
|
619
|
+
],
|
|
620
|
+
[
|
|
621
|
+
-1,
|
|
622
|
+
1,
|
|
623
|
+
1,
|
|
624
|
+
2,
|
|
625
|
+
2,
|
|
626
|
+
4,
|
|
627
|
+
4,
|
|
628
|
+
6,
|
|
629
|
+
6,
|
|
630
|
+
8,
|
|
631
|
+
8,
|
|
632
|
+
8,
|
|
633
|
+
10,
|
|
634
|
+
12,
|
|
635
|
+
16,
|
|
636
|
+
12,
|
|
637
|
+
17,
|
|
638
|
+
16,
|
|
639
|
+
18,
|
|
640
|
+
21,
|
|
641
|
+
20,
|
|
642
|
+
23,
|
|
643
|
+
23,
|
|
644
|
+
25,
|
|
645
|
+
27,
|
|
646
|
+
29,
|
|
647
|
+
34,
|
|
648
|
+
34,
|
|
649
|
+
35,
|
|
650
|
+
38,
|
|
651
|
+
40,
|
|
652
|
+
43,
|
|
653
|
+
45,
|
|
654
|
+
48,
|
|
655
|
+
51,
|
|
656
|
+
53,
|
|
657
|
+
56,
|
|
658
|
+
59,
|
|
659
|
+
62,
|
|
660
|
+
65,
|
|
661
|
+
68
|
|
662
|
+
],
|
|
663
|
+
[
|
|
664
|
+
-1,
|
|
665
|
+
1,
|
|
666
|
+
1,
|
|
667
|
+
2,
|
|
668
|
+
4,
|
|
669
|
+
4,
|
|
670
|
+
4,
|
|
671
|
+
5,
|
|
672
|
+
6,
|
|
673
|
+
8,
|
|
674
|
+
8,
|
|
675
|
+
11,
|
|
676
|
+
11,
|
|
677
|
+
16,
|
|
678
|
+
16,
|
|
679
|
+
18,
|
|
680
|
+
16,
|
|
681
|
+
19,
|
|
682
|
+
21,
|
|
683
|
+
25,
|
|
684
|
+
25,
|
|
685
|
+
25,
|
|
686
|
+
34,
|
|
687
|
+
30,
|
|
688
|
+
32,
|
|
689
|
+
35,
|
|
690
|
+
37,
|
|
691
|
+
40,
|
|
692
|
+
42,
|
|
693
|
+
45,
|
|
694
|
+
48,
|
|
695
|
+
51,
|
|
696
|
+
54,
|
|
697
|
+
57,
|
|
698
|
+
60,
|
|
699
|
+
63,
|
|
700
|
+
66,
|
|
701
|
+
70,
|
|
702
|
+
74,
|
|
703
|
+
77,
|
|
704
|
+
81
|
|
705
|
+
]
|
|
706
|
+
];
|
|
707
|
+
}
|
|
708
|
+
_qrcodegen.QrCode = QrCode;
|
|
709
|
+
function appendBits(val, len, bb) {
|
|
710
|
+
if (len < 0 || len > 31 || val >>> len != 0) throw new RangeError("Value out of range");
|
|
711
|
+
for (let i = len - 1; i >= 0; i--) bb.push(val >>> i & 1);
|
|
712
|
+
}
|
|
713
|
+
function getBit(x, i) {
|
|
714
|
+
return (x >>> i & 1) != 0;
|
|
715
|
+
}
|
|
716
|
+
function maskBit(mask, x, y) {
|
|
717
|
+
switch (mask) {
|
|
718
|
+
case 0: return (x + y) % 2 == 0;
|
|
719
|
+
case 1: return y % 2 == 0;
|
|
720
|
+
case 2: return x % 3 == 0;
|
|
721
|
+
case 3: return (x + y) % 3 == 0;
|
|
722
|
+
case 4: return (Math.floor(x / 3) + Math.floor(y / 2)) % 2 == 0;
|
|
723
|
+
case 5: return x * y % 2 + x * y % 3 == 0;
|
|
724
|
+
case 6: return (x * y % 2 + x * y % 3) % 2 == 0;
|
|
725
|
+
case 7: return ((x + y) % 2 + x * y % 3) % 2 == 0;
|
|
726
|
+
default: throw new Error("Unreachable");
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
const MASK_PERIOD = 12;
|
|
730
|
+
const maskPatterns = [];
|
|
731
|
+
function getMaskPattern(mask) {
|
|
732
|
+
if (!maskPatterns[mask]) {
|
|
733
|
+
const tile = /* @__PURE__ */ new Uint8Array(144);
|
|
734
|
+
for (let y = 0; y < MASK_PERIOD; y++) for (let x = 0; x < MASK_PERIOD; x++) tile[y * MASK_PERIOD + x] = maskBit(mask, x, y) ? 1 : 0;
|
|
735
|
+
maskPatterns[mask] = tile;
|
|
736
|
+
}
|
|
737
|
+
return maskPatterns[mask];
|
|
738
|
+
}
|
|
739
|
+
const PENALTY_N1 = 3;
|
|
740
|
+
const PENALTY_N2 = 3;
|
|
741
|
+
const PENALTY_N3 = 40;
|
|
742
|
+
const PENALTY_N4 = 10;
|
|
743
|
+
const BLOCK_PENALTY = new Uint8Array([
|
|
744
|
+
PENALTY_N2,
|
|
745
|
+
0,
|
|
746
|
+
0,
|
|
747
|
+
0,
|
|
748
|
+
PENALTY_N2
|
|
749
|
+
]);
|
|
750
|
+
function getPenaltyScore(grid, size) {
|
|
751
|
+
let result = 0;
|
|
752
|
+
const runStarts = new Int32Array(size + 1);
|
|
753
|
+
for (let i = 0; i < size; i++) {
|
|
754
|
+
result += getLinePenalty(grid, i * size, 1, size, runStarts);
|
|
755
|
+
result += getLinePenalty(grid, i, size, size, runStarts);
|
|
756
|
+
}
|
|
757
|
+
let dark = 0;
|
|
758
|
+
for (let y = 0; y < size - 1; y++) {
|
|
759
|
+
let p = y * size;
|
|
760
|
+
let left = grid[p] + grid[p + size];
|
|
761
|
+
dark += grid[p];
|
|
762
|
+
for (let x = 1; x < size; x++) {
|
|
763
|
+
p++;
|
|
764
|
+
const right = grid[p] + grid[p + size];
|
|
765
|
+
result += BLOCK_PENALTY[left + right];
|
|
766
|
+
dark += grid[p];
|
|
767
|
+
left = right;
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
for (let p = (size - 1) * size; p < size * size; p++) dark += grid[p];
|
|
771
|
+
const total = size * size;
|
|
772
|
+
const k = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1;
|
|
773
|
+
assert(0 <= k && k <= 9);
|
|
774
|
+
result += k * PENALTY_N4;
|
|
775
|
+
assert(0 <= result && result <= 2568888);
|
|
776
|
+
return result;
|
|
777
|
+
}
|
|
778
|
+
_qrcodegen.getPenaltyScore = getPenaltyScore;
|
|
779
|
+
function getLinePenalty(grid, start, step, size, runStarts) {
|
|
780
|
+
const firstColor = grid[start];
|
|
781
|
+
let runs = 1;
|
|
782
|
+
let previous = firstColor;
|
|
783
|
+
runStarts[0] = 0;
|
|
784
|
+
for (let i = 1, p = start + step; i < size; i++, p += step) {
|
|
785
|
+
const color = grid[p];
|
|
786
|
+
runStarts[runs] = i;
|
|
787
|
+
runs += color ^ previous;
|
|
788
|
+
previous = color;
|
|
789
|
+
}
|
|
790
|
+
runStarts[runs] = size;
|
|
791
|
+
let result = 0;
|
|
792
|
+
let h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, h5 = 0, h6 = 0;
|
|
793
|
+
let color = firstColor;
|
|
794
|
+
if (color == 1) {
|
|
795
|
+
h0 = size;
|
|
796
|
+
result += countFinderPatterns(h0, h1, h2, h3, h4, h5, h6) * PENALTY_N3;
|
|
797
|
+
}
|
|
798
|
+
for (let r = 0; r < runs; r++, color ^= 1) {
|
|
799
|
+
let length = runStarts[r + 1] - runStarts[r];
|
|
800
|
+
if (length >= 5) result += PENALTY_N1 + length - 5;
|
|
801
|
+
if (r == runs - 1 && color == 0) length += size;
|
|
802
|
+
h6 = h5;
|
|
803
|
+
h5 = h4;
|
|
804
|
+
h4 = h3;
|
|
805
|
+
h3 = h2;
|
|
806
|
+
h2 = h1;
|
|
807
|
+
h1 = h0;
|
|
808
|
+
h0 = h1 == 0 ? length + size : length;
|
|
809
|
+
if (color == 0) result += countFinderPatterns(h0, h1, h2, h3, h4, h5, h6) * PENALTY_N3;
|
|
810
|
+
}
|
|
811
|
+
if (color == 0) {
|
|
812
|
+
h6 = h5;
|
|
813
|
+
h5 = h4;
|
|
814
|
+
h4 = h3;
|
|
815
|
+
h3 = h2;
|
|
816
|
+
h2 = h1;
|
|
817
|
+
h1 = h0;
|
|
818
|
+
h0 = size;
|
|
819
|
+
result += countFinderPatterns(h0, h1, h2, h3, h4, h5, h6) * PENALTY_N3;
|
|
820
|
+
}
|
|
821
|
+
return result;
|
|
822
|
+
}
|
|
823
|
+
function countFinderPatterns(h0, h1, h2, h3, h4, h5, h6) {
|
|
824
|
+
const n = h1;
|
|
825
|
+
const core = n > 0 && h2 == n && h3 == n * 3 && h4 == n && h5 == n;
|
|
826
|
+
return (core && h0 >= n * 4 && h6 >= n ? 1 : 0) + (core && h6 >= n * 4 && h0 >= n ? 1 : 0);
|
|
827
|
+
}
|
|
828
|
+
function assert(cond) {
|
|
829
|
+
if (!cond) throw new Error("Assertion error");
|
|
830
|
+
}
|
|
831
|
+
class QrSegment {
|
|
832
|
+
mode;
|
|
833
|
+
numChars;
|
|
834
|
+
bitData;
|
|
835
|
+
static makeBytes(data) {
|
|
836
|
+
let bb = [];
|
|
837
|
+
for (const b of data) appendBits(b, 8, bb);
|
|
838
|
+
return new QrSegment(QrSegment.Mode.BYTE, data.length, bb);
|
|
839
|
+
}
|
|
840
|
+
static makeNumeric(digits) {
|
|
841
|
+
if (!QrSegment.isNumeric(digits)) throw new RangeError("String contains non-numeric characters");
|
|
842
|
+
let bb = [];
|
|
843
|
+
for (let i = 0; i < digits.length;) {
|
|
844
|
+
const n = Math.min(digits.length - i, 3);
|
|
845
|
+
appendBits(parseInt(digits.substring(i, i + n), 10), n * 3 + 1, bb);
|
|
846
|
+
i += n;
|
|
847
|
+
}
|
|
848
|
+
return new QrSegment(QrSegment.Mode.NUMERIC, digits.length, bb);
|
|
849
|
+
}
|
|
850
|
+
static makeAlphanumeric(text) {
|
|
851
|
+
if (!QrSegment.isAlphanumeric(text)) throw new RangeError("String contains unencodable characters in alphanumeric mode");
|
|
852
|
+
let bb = [];
|
|
853
|
+
let i = 0;
|
|
854
|
+
for (; i + 2 <= text.length; i += 2) {
|
|
855
|
+
let temp = QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45;
|
|
856
|
+
temp += QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1));
|
|
857
|
+
appendBits(temp, 11, bb);
|
|
858
|
+
}
|
|
859
|
+
if (i < text.length) appendBits(QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb);
|
|
860
|
+
return new QrSegment(QrSegment.Mode.ALPHANUMERIC, text.length, bb);
|
|
861
|
+
}
|
|
862
|
+
static makeSegments(text) {
|
|
863
|
+
if (text == "") return [];
|
|
864
|
+
else if (QrSegment.isNumeric(text)) return [QrSegment.makeNumeric(text)];
|
|
865
|
+
else if (QrSegment.isAlphanumeric(text)) return [QrSegment.makeAlphanumeric(text)];
|
|
866
|
+
else return [QrSegment.makeBytes(QrSegment.toUtf8ByteArray(text))];
|
|
867
|
+
}
|
|
868
|
+
static makeEci(assignVal) {
|
|
869
|
+
let bb = [];
|
|
870
|
+
if (assignVal < 0) throw new RangeError("ECI assignment value out of range");
|
|
871
|
+
else if (assignVal < 128) appendBits(assignVal, 8, bb);
|
|
872
|
+
else if (assignVal < 16384) {
|
|
873
|
+
appendBits(2, 2, bb);
|
|
874
|
+
appendBits(assignVal, 14, bb);
|
|
875
|
+
} else if (assignVal < 1e6) {
|
|
876
|
+
appendBits(6, 3, bb);
|
|
877
|
+
appendBits(assignVal, 21, bb);
|
|
878
|
+
} else throw new RangeError("ECI assignment value out of range");
|
|
879
|
+
return new QrSegment(QrSegment.Mode.ECI, 0, bb);
|
|
880
|
+
}
|
|
881
|
+
static isNumeric(text) {
|
|
882
|
+
return QrSegment.NUMERIC_REGEX.test(text);
|
|
883
|
+
}
|
|
884
|
+
static isAlphanumeric(text) {
|
|
885
|
+
return QrSegment.ALPHANUMERIC_REGEX.test(text);
|
|
886
|
+
}
|
|
887
|
+
constructor(mode, numChars, bitData) {
|
|
888
|
+
this.mode = mode;
|
|
889
|
+
this.numChars = numChars;
|
|
890
|
+
this.bitData = bitData;
|
|
891
|
+
if (numChars < 0) throw new RangeError("Invalid argument");
|
|
892
|
+
this.bitData = bitData.slice();
|
|
893
|
+
}
|
|
894
|
+
getData() {
|
|
895
|
+
return this.bitData.slice();
|
|
896
|
+
}
|
|
897
|
+
static getTotalBits(segs, version) {
|
|
898
|
+
let result = 0;
|
|
899
|
+
for (const seg of segs) {
|
|
900
|
+
const ccbits = seg.mode.numCharCountBits(version);
|
|
901
|
+
if (seg.numChars >= 1 << ccbits) return 1e400;
|
|
902
|
+
result += 4 + ccbits + seg.bitData.length;
|
|
903
|
+
}
|
|
904
|
+
return result;
|
|
905
|
+
}
|
|
906
|
+
static toUtf8ByteArray(str) {
|
|
907
|
+
str = encodeURI(str);
|
|
908
|
+
let result = [];
|
|
909
|
+
for (let i = 0; i < str.length; i++) if (str.charAt(i) != "%") result.push(str.charCodeAt(i));
|
|
910
|
+
else {
|
|
911
|
+
result.push(parseInt(str.substring(i + 1, i + 3), 16));
|
|
912
|
+
i += 2;
|
|
913
|
+
}
|
|
914
|
+
return result;
|
|
915
|
+
}
|
|
916
|
+
static NUMERIC_REGEX = /^[0-9]*$/;
|
|
917
|
+
static ALPHANUMERIC_REGEX = /^[A-Z0-9 $%*+.\/:-]*$/;
|
|
918
|
+
static ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
|
|
919
|
+
}
|
|
920
|
+
_qrcodegen.QrSegment = QrSegment;
|
|
921
|
+
})(qrcodegen || (qrcodegen = {}));
|
|
922
|
+
(function(_qrcodegen2) {
|
|
923
|
+
let QrCode;
|
|
924
|
+
(function(_QrCode) {
|
|
925
|
+
class Ecc {
|
|
926
|
+
ordinal;
|
|
927
|
+
formatBits;
|
|
928
|
+
static LOW = new Ecc(0, 1);
|
|
929
|
+
static MEDIUM = new Ecc(1, 0);
|
|
930
|
+
static QUARTILE = new Ecc(2, 3);
|
|
931
|
+
static HIGH = new Ecc(3, 2);
|
|
932
|
+
constructor(ordinal, formatBits) {
|
|
933
|
+
this.ordinal = ordinal;
|
|
934
|
+
this.formatBits = formatBits;
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
_QrCode.Ecc = Ecc;
|
|
938
|
+
})(QrCode || (QrCode = _qrcodegen2.QrCode || (_qrcodegen2.QrCode = {})));
|
|
939
|
+
})(qrcodegen || (qrcodegen = {}));
|
|
940
|
+
(function(_qrcodegen3) {
|
|
941
|
+
let QrSegment;
|
|
942
|
+
(function(_QrSegment) {
|
|
943
|
+
class Mode {
|
|
944
|
+
modeBits;
|
|
945
|
+
numBitsCharCount;
|
|
946
|
+
static NUMERIC = new Mode(1, [
|
|
947
|
+
10,
|
|
948
|
+
12,
|
|
949
|
+
14
|
|
950
|
+
]);
|
|
951
|
+
static ALPHANUMERIC = new Mode(2, [
|
|
952
|
+
9,
|
|
953
|
+
11,
|
|
954
|
+
13
|
|
955
|
+
]);
|
|
956
|
+
static BYTE = new Mode(4, [
|
|
957
|
+
8,
|
|
958
|
+
16,
|
|
959
|
+
16
|
|
960
|
+
]);
|
|
961
|
+
static KANJI = new Mode(8, [
|
|
962
|
+
8,
|
|
963
|
+
10,
|
|
964
|
+
12
|
|
965
|
+
]);
|
|
966
|
+
static ECI = new Mode(7, [
|
|
967
|
+
0,
|
|
968
|
+
0,
|
|
969
|
+
0
|
|
970
|
+
]);
|
|
971
|
+
constructor(modeBits, numBitsCharCount) {
|
|
972
|
+
this.modeBits = modeBits;
|
|
973
|
+
this.numBitsCharCount = numBitsCharCount;
|
|
974
|
+
}
|
|
975
|
+
numCharCountBits(ver) {
|
|
976
|
+
return this.numBitsCharCount[Math.floor((ver + 7) / 17)];
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
_QrSegment.Mode = Mode;
|
|
980
|
+
})(QrSegment || (QrSegment = _qrcodegen3.QrSegment || (_qrcodegen3.QrSegment = {})));
|
|
981
|
+
})(qrcodegen || (qrcodegen = {}));
|
|
982
|
+
// src/core/encode.ts
|
|
983
|
+
const { QrCode, QrSegment } = qrcodegen;
|
|
984
|
+
const Region = {
|
|
985
|
+
Data: 0,
|
|
986
|
+
Finder: 1,
|
|
987
|
+
Alignment: 2,
|
|
988
|
+
Timing: 3,
|
|
989
|
+
Format: 4
|
|
990
|
+
};
|
|
991
|
+
var QRCapacityError = class extends Error {
|
|
992
|
+
version;
|
|
993
|
+
level;
|
|
994
|
+
dataLength;
|
|
995
|
+
constructor(version, level, dataLength) {
|
|
996
|
+
super(`Data too long for QR version ${version} at level ${level}`);
|
|
997
|
+
this.version = version;
|
|
998
|
+
this.level = level;
|
|
999
|
+
this.dataLength = dataLength;
|
|
1000
|
+
this.name = "QRCapacityError";
|
|
1001
|
+
}
|
|
1002
|
+
};
|
|
1003
|
+
const eccByLevel = {
|
|
1004
|
+
L: QrCode.Ecc.LOW,
|
|
1005
|
+
M: QrCode.Ecc.MEDIUM,
|
|
1006
|
+
Q: QrCode.Ecc.QUARTILE,
|
|
1007
|
+
H: QrCode.Ecc.HIGH
|
|
1008
|
+
};
|
|
1009
|
+
const levelByOrdinal = [
|
|
1010
|
+
"L",
|
|
1011
|
+
"M",
|
|
1012
|
+
"Q",
|
|
1013
|
+
"H"
|
|
1014
|
+
];
|
|
1015
|
+
function isDark(m, x, y) {
|
|
1016
|
+
return x >= 0 && y >= 0 && x < m.size && y < m.size && m.dark[y * m.size + x] === 1;
|
|
1017
|
+
}
|
|
1018
|
+
function makeSegments(value) {
|
|
1019
|
+
if (typeof value === "string") return QrSegment.makeSegments(value);
|
|
1020
|
+
return value.flatMap((v) => QrSegment.makeSegments(v));
|
|
1021
|
+
}
|
|
1022
|
+
function markRegions(qr) {
|
|
1023
|
+
const { size, version } = qr;
|
|
1024
|
+
const region = new Uint8Array(size * size);
|
|
1025
|
+
const inFinder = (x, y) => x < 8 && y < 8 || x >= size - 8 && y < 8 || x < 8 && y >= size - 8;
|
|
1026
|
+
for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) {
|
|
1027
|
+
let r = Region.Data;
|
|
1028
|
+
if (inFinder(x, y)) r = Region.Finder;
|
|
1029
|
+
else if (y === 8 && x !== 6 && (x <= 8 || x >= size - 8) || x === 8 && y !== 6 && (y <= 8 || y >= size - 8)) r = Region.Format;
|
|
1030
|
+
else if (version >= 7 && (x < 6 && y >= size - 11 && y < size - 8 || y < 6 && x >= size - 11 && x < size - 8)) r = Region.Format;
|
|
1031
|
+
else if (x === 6 || y === 6) r = Region.Timing;
|
|
1032
|
+
region[y * size + x] = r;
|
|
1033
|
+
}
|
|
1034
|
+
const pos = qr.getAlignmentPatternPositions();
|
|
1035
|
+
const last = pos.length - 1;
|
|
1036
|
+
pos.forEach((cy, i) => pos.forEach((cx, j) => {
|
|
1037
|
+
if (i === 0 && (j === 0 || j === last) || i === last && j === 0) return;
|
|
1038
|
+
for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) region[(cy + dy) * size + cx + dx] = Region.Alignment;
|
|
1039
|
+
}));
|
|
1040
|
+
return region;
|
|
1041
|
+
}
|
|
1042
|
+
const cacheSize = 16;
|
|
1043
|
+
/** Recent matrices by input, oldest first: a Map keeps insertion order. */
|
|
1044
|
+
const cache = /* @__PURE__ */ new Map();
|
|
1045
|
+
/**
|
|
1046
|
+
* Encodes `value` into a module matrix, without Solid.
|
|
1047
|
+
* Repeat calls with the same input return the cached object; see `QRMatrix`.
|
|
1048
|
+
* `level` defaults to `'L'` here. The components default to `'M'`, or `'Q'` with a logo.
|
|
1049
|
+
* @throws {QRCapacityError} when the data does not fit `maxVersion`.
|
|
1050
|
+
* @throws {RangeError} when `minVersion` exceeds `maxVersion`, or a version or mask is out of range.
|
|
1051
|
+
*/
|
|
1052
|
+
function encode(value, options = {}) {
|
|
1053
|
+
const { level = "L", minVersion = 1, maxVersion = 40, mask = -1, boostLevel = true } = options;
|
|
1054
|
+
const key = JSON.stringify([
|
|
1055
|
+
value,
|
|
1056
|
+
level,
|
|
1057
|
+
minVersion,
|
|
1058
|
+
maxVersion,
|
|
1059
|
+
mask,
|
|
1060
|
+
boostLevel
|
|
1061
|
+
]);
|
|
1062
|
+
const hit = cache.get(key);
|
|
1063
|
+
if (hit) {
|
|
1064
|
+
cache.delete(key);
|
|
1065
|
+
cache.set(key, hit);
|
|
1066
|
+
return hit;
|
|
1067
|
+
}
|
|
1068
|
+
const matrix = encodeUncached(value, level, minVersion, maxVersion, mask, boostLevel);
|
|
1069
|
+
cache.set(key, matrix);
|
|
1070
|
+
if (cache.size > cacheSize) cache.delete(cache.keys().next().value);
|
|
1071
|
+
return matrix;
|
|
1072
|
+
}
|
|
1073
|
+
function encodeUncached(value, level, minVersion, maxVersion, mask, boostLevel) {
|
|
1074
|
+
if (minVersion > maxVersion) throw new RangeError(`minVersion (${minVersion}) must not exceed maxVersion (${maxVersion})`);
|
|
1075
|
+
const segments = makeSegments(value);
|
|
1076
|
+
let qr;
|
|
1077
|
+
try {
|
|
1078
|
+
qr = QrCode.encodeSegments(segments, eccByLevel[level], minVersion, maxVersion, mask, boostLevel);
|
|
1079
|
+
} catch (e) {
|
|
1080
|
+
if (e instanceof RangeError && e.message === "Data too long") throw new QRCapacityError(maxVersion, level, segments.reduce((n, s) => n + s.numChars, 0));
|
|
1081
|
+
throw e;
|
|
1082
|
+
}
|
|
1083
|
+
const { size } = qr;
|
|
1084
|
+
const dark = new Uint8Array(size * size);
|
|
1085
|
+
qr.getModules().forEach((row, y) => row.forEach((on, x) => dark[y * size + x] = on ? 1 : 0));
|
|
1086
|
+
return Object.freeze({
|
|
1087
|
+
size,
|
|
1088
|
+
version: qr.version,
|
|
1089
|
+
level: levelByOrdinal[qr.errorCorrectionLevel.ordinal],
|
|
1090
|
+
mask: qr.mask,
|
|
1091
|
+
dark,
|
|
1092
|
+
region: markRegions(qr),
|
|
1093
|
+
finders: Object.freeze([
|
|
1094
|
+
Object.freeze([0, 0]),
|
|
1095
|
+
Object.freeze([size - 7, 0]),
|
|
1096
|
+
Object.freeze([0, size - 7])
|
|
1097
|
+
])
|
|
1098
|
+
});
|
|
1099
|
+
}
|
|
1100
|
+
// src/shapes/types.ts
|
|
1101
|
+
function defineModuleShape(draw) {
|
|
1102
|
+
return {
|
|
1103
|
+
kind: "module",
|
|
1104
|
+
draw
|
|
1105
|
+
};
|
|
1106
|
+
}
|
|
1107
|
+
function defineLayerShape(draw) {
|
|
1108
|
+
return {
|
|
1109
|
+
kind: "layer",
|
|
1110
|
+
draw
|
|
1111
|
+
};
|
|
1112
|
+
}
|
|
1113
|
+
/** Formats a path coordinate without float noise: 3 decimals, trailing zeros trimmed. */
|
|
1114
|
+
const coord = (v) => String(Math.round(v * 1e3) / 1e3 + 0);
|
|
1115
|
+
// src/shapes/modules.ts
|
|
1116
|
+
/** Square modules, merged into one subpath per horizontal run. */
|
|
1117
|
+
const square = defineLayerShape(({ matrix: m, include, offset }) => {
|
|
1118
|
+
let d = "";
|
|
1119
|
+
for (let y = 0; y < m.size; y++) {
|
|
1120
|
+
let x = 0;
|
|
1121
|
+
while (x < m.size) {
|
|
1122
|
+
if (!(include(x, y) && isDark(m, x, y))) {
|
|
1123
|
+
x++;
|
|
1124
|
+
continue;
|
|
1125
|
+
}
|
|
1126
|
+
const start = x;
|
|
1127
|
+
while (x < m.size && include(x, y) && isDark(m, x, y)) x++;
|
|
1128
|
+
const len = x - start;
|
|
1129
|
+
d += `M${coord(start + offset.x)} ${coord(y + offset.y)}h${len}v1h-${len}z`;
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
return d;
|
|
1133
|
+
});
|
|
1134
|
+
const cell = (x, y) => `M${coord(x)} ${coord(y)}h1v1h-1z`;
|
|
1135
|
+
const dots = defineModuleShape(({ x, y, alignment }) => {
|
|
1136
|
+
if (alignment) return cell(x, y);
|
|
1137
|
+
const r = .4;
|
|
1138
|
+
return `M${coord(x + .5 - r)} ${coord(y + .5)}a${r} ${r} 0 1 0 ${coord(2 * r)} 0a${r} ${r} 0 1 0 -${coord(2 * r)} 0z`;
|
|
1139
|
+
});
|
|
1140
|
+
const diamond = defineModuleShape(({ x, y, alignment }) => alignment ? cell(x, y) : `M${coord(x + .5)} ${coord(y)}L${coord(x + 1)} ${coord(y + .5)}L${coord(x + .5)} ${coord(y + 1)}L${coord(x)} ${coord(y + .5)}z`);
|
|
1141
|
+
/** A corner is round only when both orthogonal neighbours on that side are not drawn. */
|
|
1142
|
+
const rounded = defineModuleShape(({ x, y, neighbors: { n, e, s, w } }) => {
|
|
1143
|
+
const [tl, tr, br, bl] = [
|
|
1144
|
+
!n && !w,
|
|
1145
|
+
!n && !e,
|
|
1146
|
+
!s && !e,
|
|
1147
|
+
!s && !w
|
|
1148
|
+
].map((round) => round ? .5 : 0);
|
|
1149
|
+
const arc = (to, r) => r ? `A.5 .5 0 0 1 ${coord(to[0])} ${coord(to[1])}` : "";
|
|
1150
|
+
return `M${coord(x + tl)} ${coord(y)}H${coord(x + 1 - tr)}${arc([x + 1, y + tr], tr)}V${coord(y + 1 - br)}${arc([x + 1 - br, y + 1], br)}H${coord(x + bl)}${arc([x, y + 1 - bl], bl)}V${coord(y + tl)}${arc([x + tl, y], tl)}z`;
|
|
1151
|
+
});
|
|
1152
|
+
/** The option props, which the components keep off the DOM element. */
|
|
1153
|
+
const optionKeys = Object.keys({
|
|
1154
|
+
value: true,
|
|
1155
|
+
size: true,
|
|
1156
|
+
level: true,
|
|
1157
|
+
margin: true,
|
|
1158
|
+
fg: true,
|
|
1159
|
+
bg: true,
|
|
1160
|
+
modules: true,
|
|
1161
|
+
finder: true,
|
|
1162
|
+
image: true,
|
|
1163
|
+
caption: true,
|
|
1164
|
+
frame: true,
|
|
1165
|
+
title: true,
|
|
1166
|
+
id: true,
|
|
1167
|
+
encoding: true
|
|
1168
|
+
});
|
|
1169
|
+
const defaults = {
|
|
1170
|
+
size: 128,
|
|
1171
|
+
margin: 4,
|
|
1172
|
+
fg: "var(--qr-fg, #000)",
|
|
1173
|
+
bg: "var(--qr-bg, #fff)"
|
|
1174
|
+
};
|
|
1175
|
+
/** The finder shape without its colours. */
|
|
1176
|
+
const toFinderShape = (finder = {}) => ({
|
|
1177
|
+
outer: finder.outer,
|
|
1178
|
+
inner: finder.inner
|
|
1179
|
+
});
|
|
1180
|
+
/**
|
|
1181
|
+
* The paint-free part of the design, with defaults applied. Reads no colour field.
|
|
1182
|
+
* Pass `finder` and `caption` to keep it from reading the options that also hold colours.
|
|
1183
|
+
*/
|
|
1184
|
+
function toGeometryDesign(options, finder = toFinderShape(options.finder), caption = toCaptionShape(options.caption)) {
|
|
1185
|
+
return {
|
|
1186
|
+
margin: options.margin ?? defaults.margin,
|
|
1187
|
+
modules: options.modules ?? square,
|
|
1188
|
+
finder,
|
|
1189
|
+
image: options.image,
|
|
1190
|
+
caption,
|
|
1191
|
+
frame: options.frame
|
|
1192
|
+
};
|
|
1193
|
+
}
|
|
1194
|
+
/** The paints, with defaults applied. */
|
|
1195
|
+
function toPaints(options) {
|
|
1196
|
+
return {
|
|
1197
|
+
fg: options.fg ?? defaults.fg,
|
|
1198
|
+
bg: options.bg ?? defaults.bg,
|
|
1199
|
+
finder: options.finder?.color,
|
|
1200
|
+
finderInner: options.finder?.innerColor,
|
|
1201
|
+
caption: options.caption?.color
|
|
1202
|
+
};
|
|
1203
|
+
}
|
|
1204
|
+
// src/core/output.ts
|
|
1205
|
+
/** The size of a drawing in CSS pixels. `size` is the width; the height keeps the scene ratio. */
|
|
1206
|
+
const outputSize = (scene, size = defaults.size) => ({
|
|
1207
|
+
width: size,
|
|
1208
|
+
height: size * scene.height / scene.width
|
|
1209
|
+
});
|
|
1210
|
+
/** A JSX attribute may hold `false` to remove it, so only a non-empty string counts. */
|
|
1211
|
+
const text = (value) => typeof value === "string" && value ? value : void 0;
|
|
1212
|
+
/**
|
|
1213
|
+
* The `aria-label` for a drawing, or undefined when another attribute names it.
|
|
1214
|
+
* An SVG names itself through its `<title>`; a canvas has no such element,
|
|
1215
|
+
* so with `titleIsLabel` the title becomes its label.
|
|
1216
|
+
*/
|
|
1217
|
+
function ariaLabel(props, titleIsLabel) {
|
|
1218
|
+
const [title, label, labelledby] = [
|
|
1219
|
+
text(props.title),
|
|
1220
|
+
text(props["aria-label"]),
|
|
1221
|
+
text(props["aria-labelledby"])
|
|
1222
|
+
];
|
|
1223
|
+
if (titleIsLabel) return title ?? label ?? (labelledby ? void 0 : "QR code");
|
|
1224
|
+
return title || label || labelledby ? void 0 : "QR code";
|
|
1225
|
+
}
|
|
1226
|
+
// src/primitives/createColorScheme.ts
|
|
1227
|
+
/** Tracks `prefers-color-scheme`. 'light' on the server and where `matchMedia` is missing. */
|
|
1228
|
+
function createColorScheme() {
|
|
1229
|
+
if (isServer) return () => "light";
|
|
1230
|
+
const [scheme, setScheme] = createSignal("light");
|
|
1231
|
+
onSettled(() => {
|
|
1232
|
+
if (typeof matchMedia !== "function") return;
|
|
1233
|
+
const query = matchMedia("(prefers-color-scheme: dark)");
|
|
1234
|
+
const onChange = () => setScheme(query.matches ? "dark" : "light");
|
|
1235
|
+
onChange();
|
|
1236
|
+
query.addEventListener("change", onChange);
|
|
1237
|
+
return () => query.removeEventListener("change", onChange);
|
|
1238
|
+
});
|
|
1239
|
+
return scheme;
|
|
1240
|
+
}
|
|
1241
|
+
// src/primitives/createPixelRatio.ts
|
|
1242
|
+
/** Tracks `devicePixelRatio`, which changes on zoom or a move to another screen. 1 on the server. */
|
|
1243
|
+
function createPixelRatio() {
|
|
1244
|
+
if (isServer) return () => 1;
|
|
1245
|
+
const [ratio, setRatio] = createSignal(window.devicePixelRatio || 1);
|
|
1246
|
+
onSettled(() => {
|
|
1247
|
+
if (typeof matchMedia !== "function") return;
|
|
1248
|
+
let query;
|
|
1249
|
+
const arm = () => {
|
|
1250
|
+
query = matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);
|
|
1251
|
+
query.addEventListener("change", onChange, { once: true });
|
|
1252
|
+
};
|
|
1253
|
+
const onChange = () => {
|
|
1254
|
+
setRatio(window.devicePixelRatio || 1);
|
|
1255
|
+
arm();
|
|
1256
|
+
};
|
|
1257
|
+
arm();
|
|
1258
|
+
return () => query.removeEventListener("change", onChange);
|
|
1259
|
+
});
|
|
1260
|
+
return ratio;
|
|
1261
|
+
}
|
|
1262
|
+
// src/core/logo.ts
|
|
1263
|
+
/**
|
|
1264
|
+
* The largest share of all modules (size squared) that the excavated box may cover, per level,
|
|
1265
|
+
* as `[versions 1-6, versions 7+]`. The box is the image plus padding, rounded outward.
|
|
1266
|
+
* About 75% of the smallest box share that jsQR and ZXing both decoded on versions 2-15,
|
|
1267
|
+
* with two values and the square and dots shapes. L is not recommended with a logo: its budget
|
|
1268
|
+
* fits a tiny logo at best, so most L logos are reduced or dropped.
|
|
1269
|
+
*/
|
|
1270
|
+
const maxLogoArea = {
|
|
1271
|
+
L: [.022, .022],
|
|
1272
|
+
M: [.03, .07],
|
|
1273
|
+
Q: [.072, .088],
|
|
1274
|
+
H: [.116, .07]
|
|
1275
|
+
};
|
|
1276
|
+
/** A logo narrower than this many modules is dropped, not drawn over modules. */
|
|
1277
|
+
const minLogoWidth = 2;
|
|
1278
|
+
function place(n, image, size) {
|
|
1279
|
+
const aspect = image.aspect ?? 1;
|
|
1280
|
+
const padding = image.excavate === false ? 0 : image.padding ?? 1;
|
|
1281
|
+
const width = size * n;
|
|
1282
|
+
const height = width / aspect;
|
|
1283
|
+
const [x, y] = [(n - width) / 2, (n - height) / 2];
|
|
1284
|
+
return {
|
|
1285
|
+
x,
|
|
1286
|
+
y,
|
|
1287
|
+
width,
|
|
1288
|
+
height,
|
|
1289
|
+
cells: {
|
|
1290
|
+
x0: Math.floor(x - padding),
|
|
1291
|
+
y0: Math.floor(y - padding),
|
|
1292
|
+
x1: Math.ceil(x + width + padding),
|
|
1293
|
+
y1: Math.ceil(y + height + padding)
|
|
1294
|
+
}
|
|
1295
|
+
};
|
|
1296
|
+
}
|
|
1297
|
+
/**
|
|
1298
|
+
* True when the box stays in budget and covers only data cells. From version 7 an alignment
|
|
1299
|
+
* pattern sits at the centre, so there the box may also cover alignment cells.
|
|
1300
|
+
*/
|
|
1301
|
+
function fits(m, c, budget) {
|
|
1302
|
+
if (c.x0 < 0 || c.y0 < 0 || c.x1 > m.size || c.y1 > m.size) return false;
|
|
1303
|
+
if ((c.x1 - c.x0) * (c.y1 - c.y0) > budget * m.size * m.size) return false;
|
|
1304
|
+
const allowed = (r) => r === Region.Data || m.version >= 7 && r === Region.Alignment;
|
|
1305
|
+
for (let y = c.y0; y < c.y1; y++) for (let x = c.x0; x < c.x1; x++) if (!allowed(m.region[y * m.size + x])) return false;
|
|
1306
|
+
return true;
|
|
1307
|
+
}
|
|
1308
|
+
/**
|
|
1309
|
+
* The largest logo width fraction, up to `image.size`, whose box fits the level budget and
|
|
1310
|
+
* covers only data cells. Returns 0 when no logo fits.
|
|
1311
|
+
*/
|
|
1312
|
+
function clampImageSize(matrix, image) {
|
|
1313
|
+
const budget = maxLogoArea[matrix.level][matrix.version >= 7 ? 1 : 0];
|
|
1314
|
+
const ok = (size) => fits(matrix, place(matrix.size, image, size).cells, budget);
|
|
1315
|
+
const size = image.size ?? .2;
|
|
1316
|
+
if (ok(size)) return size;
|
|
1317
|
+
let [lo, hi] = [0, size];
|
|
1318
|
+
for (let i = 0; i < 24; i++) {
|
|
1319
|
+
const mid = (lo + hi) / 2;
|
|
1320
|
+
if (ok(mid)) lo = mid;
|
|
1321
|
+
else hi = mid;
|
|
1322
|
+
}
|
|
1323
|
+
return lo * matrix.size < minLogoWidth ? 0 : lo;
|
|
1324
|
+
}
|
|
1325
|
+
/**
|
|
1326
|
+
* Centres the logo on the code, in scene units with the code box at the origin, or returns
|
|
1327
|
+
* undefined when it cannot fit. `cells` is empty when `excavate` is false.
|
|
1328
|
+
*/
|
|
1329
|
+
function logoBox(matrix, margin, image) {
|
|
1330
|
+
const size = clampImageSize(matrix, image);
|
|
1331
|
+
if (!size) return void 0;
|
|
1332
|
+
const { x, y, width, height, cells } = place(matrix.size, image, size);
|
|
1333
|
+
const box = {
|
|
1334
|
+
href: image.src,
|
|
1335
|
+
x: x + margin,
|
|
1336
|
+
y: y + margin,
|
|
1337
|
+
width,
|
|
1338
|
+
height,
|
|
1339
|
+
radius: Math.min(.5, image.radius ?? 0) * Math.min(width, height),
|
|
1340
|
+
opacity: image.opacity ?? 1,
|
|
1341
|
+
cells: image.excavate === false ? {
|
|
1342
|
+
x0: 0,
|
|
1343
|
+
y0: 0,
|
|
1344
|
+
x1: 0,
|
|
1345
|
+
y1: 0
|
|
1346
|
+
} : cells
|
|
1347
|
+
};
|
|
1348
|
+
if (image.crossOrigin !== void 0) box.crossOrigin = image.crossOrigin;
|
|
1349
|
+
return box;
|
|
1350
|
+
}
|
|
1351
|
+
// src/core/path.ts
|
|
1352
|
+
/** The axis each argument of an absolute command moves along: x, y, or none (-). */
|
|
1353
|
+
const axes = {
|
|
1354
|
+
M: "xy",
|
|
1355
|
+
L: "xy",
|
|
1356
|
+
T: "xy",
|
|
1357
|
+
H: "x",
|
|
1358
|
+
V: "y",
|
|
1359
|
+
C: "xyxyxy",
|
|
1360
|
+
S: "xyxy",
|
|
1361
|
+
Q: "xyxy",
|
|
1362
|
+
A: "-----xy",
|
|
1363
|
+
Z: ""
|
|
1364
|
+
};
|
|
1365
|
+
const numberPattern = /^[\s,]*([-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)/i;
|
|
1366
|
+
const flagPattern = /^[\s,]*([01])/;
|
|
1367
|
+
/**
|
|
1368
|
+
* Moves SVG path data by (dx, dy). Relative commands keep their values; absolute commands and
|
|
1369
|
+
* the first pair of a leading `m` move.
|
|
1370
|
+
*/
|
|
1371
|
+
function translatePath(d, dx, dy) {
|
|
1372
|
+
if (!dx && !dy) return d;
|
|
1373
|
+
let first = true;
|
|
1374
|
+
return d.replace(/([a-df-z])([^a-df-z]*)/gi, (_, command, args) => {
|
|
1375
|
+
const leadingMove = first && command === "m";
|
|
1376
|
+
first = false;
|
|
1377
|
+
const upper = command.toUpperCase();
|
|
1378
|
+
if (command !== upper && !leadingMove) return command + args;
|
|
1379
|
+
const pattern = leadingMove ? "xy" : axes[upper];
|
|
1380
|
+
const values = [];
|
|
1381
|
+
for (let i = 0;; i++) {
|
|
1382
|
+
const axis = pattern[i % pattern.length];
|
|
1383
|
+
const match = (upper === "A" && (i % 7 === 3 || i % 7 === 4) ? flagPattern : numberPattern).exec(args);
|
|
1384
|
+
if (!match || !axis || leadingMove && i >= 2) break;
|
|
1385
|
+
args = args.slice(match[0].length);
|
|
1386
|
+
const value = Number(match[1]);
|
|
1387
|
+
values.push(axis === "x" ? coord(value + dx) : axis === "y" ? coord(value + dy) : match[1]);
|
|
1388
|
+
}
|
|
1389
|
+
return command + values.join(" ") + args;
|
|
1390
|
+
});
|
|
1391
|
+
}
|
|
1392
|
+
// src/core/paint.ts
|
|
1393
|
+
/** Rounds to 4 decimals; `+ 0` turns -0 into 0. */
|
|
1394
|
+
const round = (v) => Math.round(v * 1e4) / 1e4 + 0;
|
|
1395
|
+
const clamp = (v) => Math.min(1, Math.max(0, v));
|
|
1396
|
+
function placeStops(stops) {
|
|
1397
|
+
if (stops.length < 2) throw new RangeError(`A gradient needs at least 2 stops, got ${stops.length}.`);
|
|
1398
|
+
const last = stops.length - 1;
|
|
1399
|
+
return stops.map((s, i) => typeof s === "string" ? [round(i / last), s] : [clamp(s[0]), s[1]]);
|
|
1400
|
+
}
|
|
1401
|
+
/** Maps a paint to user-space gradient coordinates over `box`. */
|
|
1402
|
+
function placePaint(paint, box) {
|
|
1403
|
+
if (typeof paint === "string") return paint;
|
|
1404
|
+
const half = box.size / 2;
|
|
1405
|
+
const [cx, cy] = [box.x + half, box.y + half];
|
|
1406
|
+
const stops = placeStops(paint.stops);
|
|
1407
|
+
if (paint.type === "radial") return {
|
|
1408
|
+
type: "radial",
|
|
1409
|
+
cx,
|
|
1410
|
+
cy,
|
|
1411
|
+
r: half,
|
|
1412
|
+
stops
|
|
1413
|
+
};
|
|
1414
|
+
const angle = (paint.rotate ?? 0) * Math.PI / 180;
|
|
1415
|
+
const [dx, dy] = [Math.cos(angle) * half, Math.sin(angle) * half];
|
|
1416
|
+
return {
|
|
1417
|
+
type: "linear",
|
|
1418
|
+
x1: round(cx - dx),
|
|
1419
|
+
y1: round(cy - dy),
|
|
1420
|
+
x2: round(cx + dx),
|
|
1421
|
+
y2: round(cy + dy),
|
|
1422
|
+
stops
|
|
1423
|
+
};
|
|
1424
|
+
}
|
|
1425
|
+
// src/shapes/finders.ts
|
|
1426
|
+
const rect = (x, y, w, h, radius) => {
|
|
1427
|
+
const r = Math.max(0, Math.min(radius, w / 2, h / 2));
|
|
1428
|
+
if (r === 0) return `M${coord(x)} ${coord(y)}h${coord(w)}v${coord(h)}h-${coord(w)}z`;
|
|
1429
|
+
const [rc, sw, sh] = [
|
|
1430
|
+
coord(r),
|
|
1431
|
+
coord(w - 2 * r),
|
|
1432
|
+
coord(h - 2 * r)
|
|
1433
|
+
];
|
|
1434
|
+
const arc = (dx, dy) => `a${rc} ${rc} 0 0 1 ${dx} ${dy}`;
|
|
1435
|
+
return `M${coord(x + r)} ${coord(y)}h${sw}${arc(rc, rc)}v${sh}${arc(`-${rc}`, rc)}h-${sw}${arc(`-${rc}`, `-${rc}`)}v-${sh}${arc(rc, `-${rc}`)}z`;
|
|
1436
|
+
};
|
|
1437
|
+
const circle = (cx, cy, r) => `M${coord(cx - r)} ${coord(cy)}a${r} ${r} 0 1 0 ${coord(2 * r)} 0a${r} ${r} 0 1 0 -${coord(2 * r)} 0z`;
|
|
1438
|
+
/** Outer presets are two subpaths (contour + hole); the layer fills with `evenodd`. */
|
|
1439
|
+
const finderOuter = {
|
|
1440
|
+
square: (x, y) => rect(x, y, 7, 7, 0) + rect(x + 1, y + 1, 5, 5, 0),
|
|
1441
|
+
rounded: (x, y) => rect(x, y, 7, 7, 2) + rect(x + 1, y + 1, 5, 5, 1),
|
|
1442
|
+
circle: (x, y) => circle(x + 3.5, y + 3.5, 3.5) + circle(x + 3.5, y + 3.5, 2.5)
|
|
1443
|
+
};
|
|
1444
|
+
const finderInner = {
|
|
1445
|
+
square: (x, y) => rect(x + 2, y + 2, 3, 3, 0),
|
|
1446
|
+
rounded: (x, y) => rect(x + 2, y + 2, 3, 3, .8),
|
|
1447
|
+
dot: (x, y) => circle(x + 3.5, y + 3.5, 1.6),
|
|
1448
|
+
diamond: (x, y) => `M${coord(x + 3.5)} ${coord(y + 1.5)}L${coord(x + 5.5)} ${coord(y + 3.5)}L${coord(x + 3.5)} ${coord(y + 5.5)}L${coord(x + 1.5)} ${coord(y + 3.5)}z`
|
|
1449
|
+
};
|
|
1450
|
+
function getFinder(style) {
|
|
1451
|
+
const { outer = "square", inner = "square" } = style;
|
|
1452
|
+
return {
|
|
1453
|
+
outer: typeof outer === "function" ? outer : finderOuter[outer],
|
|
1454
|
+
inner: typeof inner === "function" ? inner : finderInner[inner]
|
|
1455
|
+
};
|
|
1456
|
+
}
|
|
1457
|
+
// src/core/scene.ts
|
|
1458
|
+
const toShape = (input) => typeof input === "function" ? {
|
|
1459
|
+
kind: "module",
|
|
1460
|
+
draw: input
|
|
1461
|
+
} : input;
|
|
1462
|
+
function drawModules(m, shape, offset, cut) {
|
|
1463
|
+
const excavated = (x, y) => !!cut && x >= cut.x0 && x < cut.x1 && y >= cut.y0 && y < cut.y1;
|
|
1464
|
+
const include = (x, y) => x >= 0 && y >= 0 && x < m.size && y < m.size && m.region[y * m.size + x] !== Region.Finder && !excavated(x, y);
|
|
1465
|
+
if (shape.kind === "layer") return shape.draw({
|
|
1466
|
+
matrix: m,
|
|
1467
|
+
include,
|
|
1468
|
+
offset
|
|
1469
|
+
});
|
|
1470
|
+
const on = (x, y) => include(x, y) && isDark(m, x, y);
|
|
1471
|
+
let d = "";
|
|
1472
|
+
for (let y = 0; y < m.size; y++) for (let x = 0; x < m.size; x++) {
|
|
1473
|
+
if (!on(x, y)) continue;
|
|
1474
|
+
const neighbors = {
|
|
1475
|
+
n: on(x, y - 1),
|
|
1476
|
+
e: on(x + 1, y),
|
|
1477
|
+
s: on(x, y + 1),
|
|
1478
|
+
w: on(x - 1, y)
|
|
1479
|
+
};
|
|
1480
|
+
const alignment = m.region[y * m.size + x] === Region.Alignment;
|
|
1481
|
+
const context = {
|
|
1482
|
+
x: x + offset.x,
|
|
1483
|
+
y: y + offset.y,
|
|
1484
|
+
neighbors,
|
|
1485
|
+
alignment
|
|
1486
|
+
};
|
|
1487
|
+
d += shape.draw(context);
|
|
1488
|
+
}
|
|
1489
|
+
return d;
|
|
1490
|
+
}
|
|
1491
|
+
/**
|
|
1492
|
+
* Applies the frames from the inside out. Each frame's paths and texts move with the code
|
|
1493
|
+
* when an outer frame moves it. Outer frames draw first, so inner ones paint over them.
|
|
1494
|
+
*/
|
|
1495
|
+
function applyFrames(content, frame) {
|
|
1496
|
+
const results = (typeof frame === "function" ? [frame] : frame ?? []).reduce((done, plugin) => [...done, plugin(done.at(-1)?.layout ?? content)], []);
|
|
1497
|
+
const layout = results.at(-1)?.layout ?? content;
|
|
1498
|
+
const ids = /* @__PURE__ */ new Set();
|
|
1499
|
+
const paths = [];
|
|
1500
|
+
const texts = [];
|
|
1501
|
+
const warnings = results.flatMap((result) => result.warnings ?? []);
|
|
1502
|
+
for (const result of [...results].reverse()) {
|
|
1503
|
+
const [dx, dy] = [layout.qr.x - result.layout.qr.x, layout.qr.y - result.layout.qr.y];
|
|
1504
|
+
for (const path of result.paths) {
|
|
1505
|
+
let id = path.id;
|
|
1506
|
+
for (let n = 2; ids.has(id); n++) id = `${path.id}-${n}`;
|
|
1507
|
+
ids.add(id);
|
|
1508
|
+
paths.push({
|
|
1509
|
+
...path,
|
|
1510
|
+
id,
|
|
1511
|
+
d: translatePath(path.d, dx, dy)
|
|
1512
|
+
});
|
|
1513
|
+
}
|
|
1514
|
+
texts.unshift(...result.texts.map((t) => ({
|
|
1515
|
+
...t,
|
|
1516
|
+
x: t.x + dx,
|
|
1517
|
+
y: t.y + dy
|
|
1518
|
+
})));
|
|
1519
|
+
}
|
|
1520
|
+
return {
|
|
1521
|
+
layout,
|
|
1522
|
+
paths,
|
|
1523
|
+
texts,
|
|
1524
|
+
warnings
|
|
1525
|
+
};
|
|
1526
|
+
}
|
|
1527
|
+
/**
|
|
1528
|
+
* Builds paint-free path data. Colour changes only need `paintScene`.
|
|
1529
|
+
* The layout composes code, then caption, then frames: the frames wrap the caption.
|
|
1530
|
+
* Layer order: frame layers, then `bg` over the code and caption, then modules and finders.
|
|
1531
|
+
* Texts follow every layer: the caption, then frame texts.
|
|
1532
|
+
*/
|
|
1533
|
+
function buildGeometry(matrix, design) {
|
|
1534
|
+
const size = matrix.size + 2 * design.margin;
|
|
1535
|
+
const base = {
|
|
1536
|
+
width: size,
|
|
1537
|
+
height: size,
|
|
1538
|
+
qr: {
|
|
1539
|
+
x: 0,
|
|
1540
|
+
y: 0,
|
|
1541
|
+
size
|
|
1542
|
+
}
|
|
1543
|
+
};
|
|
1544
|
+
const captioned = design.caption ? layoutCaption(base, design.caption) : {
|
|
1545
|
+
layout: base,
|
|
1546
|
+
texts: [],
|
|
1547
|
+
warnings: []
|
|
1548
|
+
};
|
|
1549
|
+
const content = captioned.layout;
|
|
1550
|
+
const framed = applyFrames(content, design.frame);
|
|
1551
|
+
const layout = framed.layout;
|
|
1552
|
+
const [dx, dy] = [layout.qr.x - content.qr.x, layout.qr.y - content.qr.y];
|
|
1553
|
+
const offset = {
|
|
1554
|
+
x: layout.qr.x + design.margin,
|
|
1555
|
+
y: layout.qr.y + design.margin
|
|
1556
|
+
};
|
|
1557
|
+
const finder = getFinder(design.finder);
|
|
1558
|
+
const corners = matrix.finders.map(([x, y]) => [x + offset.x, y + offset.y]);
|
|
1559
|
+
const logo = design.image && logoBox(matrix, design.margin, design.image);
|
|
1560
|
+
const [w, h] = [coord(content.width), coord(content.height)];
|
|
1561
|
+
const geometry = {
|
|
1562
|
+
...layout,
|
|
1563
|
+
paths: [
|
|
1564
|
+
...framed.paths,
|
|
1565
|
+
{
|
|
1566
|
+
id: "bg",
|
|
1567
|
+
d: `M${coord(dx)} ${coord(dy)}h${w}v${h}h-${w}z`,
|
|
1568
|
+
paint: "bg"
|
|
1569
|
+
},
|
|
1570
|
+
{
|
|
1571
|
+
id: "modules",
|
|
1572
|
+
d: drawModules(matrix, toShape(design.modules), offset, logo?.cells),
|
|
1573
|
+
paint: "fg"
|
|
1574
|
+
},
|
|
1575
|
+
{
|
|
1576
|
+
id: "finder-outer",
|
|
1577
|
+
d: corners.map(([x, y]) => finder.outer(x, y)).join(""),
|
|
1578
|
+
fillRule: "evenodd",
|
|
1579
|
+
paint: "finder"
|
|
1580
|
+
},
|
|
1581
|
+
{
|
|
1582
|
+
id: "finder-inner",
|
|
1583
|
+
d: corners.map(([x, y]) => finder.inner(x, y)).join(""),
|
|
1584
|
+
paint: "finderInner"
|
|
1585
|
+
}
|
|
1586
|
+
],
|
|
1587
|
+
texts: [...captioned.texts.map((t) => ({
|
|
1588
|
+
...t,
|
|
1589
|
+
x: t.x + dx,
|
|
1590
|
+
y: t.y + dy
|
|
1591
|
+
})), ...framed.texts]
|
|
1592
|
+
};
|
|
1593
|
+
const warnings = [...captioned.warnings, ...framed.warnings ?? []];
|
|
1594
|
+
if (warnings.length) geometry.warnings = warnings;
|
|
1595
|
+
if (logo) {
|
|
1596
|
+
const { cells: _cells, x, y, ...rest } = logo;
|
|
1597
|
+
geometry.image = {
|
|
1598
|
+
...rest,
|
|
1599
|
+
x: x + layout.qr.x,
|
|
1600
|
+
y: y + layout.qr.y
|
|
1601
|
+
};
|
|
1602
|
+
}
|
|
1603
|
+
return geometry;
|
|
1604
|
+
}
|
|
1605
|
+
function pickPaint(key, paints) {
|
|
1606
|
+
switch (key) {
|
|
1607
|
+
case "fg":
|
|
1608
|
+
case "bg": return paints[key];
|
|
1609
|
+
case "finder": return paints.finder ?? paints.fg;
|
|
1610
|
+
case "finderInner": return paints.finderInner ?? paints.finder ?? paints.fg;
|
|
1611
|
+
case "caption": return paints.caption ?? paints.fg;
|
|
1612
|
+
default: return key;
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
/** Places every paint over the qr box. Path strings are reused, not copied. */
|
|
1616
|
+
function paintScene(geometry, paints) {
|
|
1617
|
+
const place = (key) => placePaint(pickPaint(key, paints), geometry.qr);
|
|
1618
|
+
const layers = [];
|
|
1619
|
+
for (const { id, d, fillRule, paint } of geometry.paths) {
|
|
1620
|
+
const fill = place(paint);
|
|
1621
|
+
if (fill === "transparent" || !d) continue;
|
|
1622
|
+
layers.push(fillRule ? {
|
|
1623
|
+
id,
|
|
1624
|
+
d,
|
|
1625
|
+
fill,
|
|
1626
|
+
fillRule
|
|
1627
|
+
} : {
|
|
1628
|
+
id,
|
|
1629
|
+
d,
|
|
1630
|
+
fill
|
|
1631
|
+
});
|
|
1632
|
+
}
|
|
1633
|
+
const texts = geometry.texts.map(({ paint, ...text }) => ({
|
|
1634
|
+
...text,
|
|
1635
|
+
fill: place(paint)
|
|
1636
|
+
}));
|
|
1637
|
+
const { width, height, image } = geometry;
|
|
1638
|
+
return image ? {
|
|
1639
|
+
width,
|
|
1640
|
+
height,
|
|
1641
|
+
layers,
|
|
1642
|
+
image,
|
|
1643
|
+
texts
|
|
1644
|
+
} : {
|
|
1645
|
+
width,
|
|
1646
|
+
height,
|
|
1647
|
+
layers,
|
|
1648
|
+
texts
|
|
1649
|
+
};
|
|
1650
|
+
}
|
|
1651
|
+
// src/core/stages.ts
|
|
1652
|
+
/** An image covers modules, so it defaults to the stronger 'Q' level. */
|
|
1653
|
+
function applyLevelDefault(level, hasImage) {
|
|
1654
|
+
return level ?? (hasImage ? "Q" : "M");
|
|
1655
|
+
}
|
|
1656
|
+
/**
|
|
1657
|
+
* The encode options for a code, with scan-safety defaults applied.
|
|
1658
|
+
* With an image, `level` defaults to Q and `minVersion` to 2, capped by `maxVersion`.
|
|
1659
|
+
*/
|
|
1660
|
+
function applyEncodingDefaults(options, hasImage) {
|
|
1661
|
+
const lift = Math.min(2, options.encoding?.maxVersion ?? 40);
|
|
1662
|
+
const minVersion = options.encoding?.minVersion ?? (hasImage ? lift : void 0);
|
|
1663
|
+
return {
|
|
1664
|
+
...options.encoding,
|
|
1665
|
+
minVersion,
|
|
1666
|
+
level: applyLevelDefault(options.level, hasImage)
|
|
1667
|
+
};
|
|
1668
|
+
}
|
|
1669
|
+
/** The matrix stage. `hasImage` is a parameter so a new image src does not re-encode. */
|
|
1670
|
+
const toMatrix = (options, hasImage = !!options.image) => encode(options.value, applyEncodingDefaults(options, hasImage));
|
|
1671
|
+
/**
|
|
1672
|
+
* The geometry stage. Pass `finder` and `caption` to keep it from reading the options
|
|
1673
|
+
* that also hold colours.
|
|
1674
|
+
*/
|
|
1675
|
+
const toGeometry = (matrix, options, finder, caption) => buildGeometry(matrix, toGeometryDesign(options, finder, caption));
|
|
1676
|
+
// src/core/warnings.ts
|
|
1677
|
+
/** WCAG 2 relative luminance. */
|
|
1678
|
+
function luminance(rgb) {
|
|
1679
|
+
const [r, g, b] = rgb.map((v) => {
|
|
1680
|
+
const c = v / 255;
|
|
1681
|
+
return c <= .03928 ? c / 12.92 : ((c + .055) / 1.055) ** 2.4;
|
|
1682
|
+
});
|
|
1683
|
+
return .2126 * r + .7152 * g + .0722 * b;
|
|
1684
|
+
}
|
|
1685
|
+
/** WCAG non-text contrast; a rough scan-safety floor. */
|
|
1686
|
+
const minContrast = 3;
|
|
1687
|
+
/** Lists scan risks in the options. The caller logs them in dev builds. */
|
|
1688
|
+
function devWarnings(o) {
|
|
1689
|
+
const warnings = [];
|
|
1690
|
+
const [fg, bg] = [parseColor(o.fg), parseColor(o.bg)];
|
|
1691
|
+
if (fg && bg) {
|
|
1692
|
+
const [fgLight, bgLight] = [luminance(fg), luminance(bg)];
|
|
1693
|
+
const [hi, lo] = [Math.max(fgLight, bgLight), Math.min(fgLight, bgLight)];
|
|
1694
|
+
const ratio = (hi + .05) / (lo + .05);
|
|
1695
|
+
if (ratio < minContrast) warnings.push(`Low contrast ${ratio.toFixed(2)}:1 between fg and bg; aim for ${minContrast}:1.`);
|
|
1696
|
+
else if (fgLight > bgLight) warnings.push("fg is lighter than bg: light-on-dark codes are not read by every scanner.");
|
|
1697
|
+
}
|
|
1698
|
+
if (o.margin < 2) warnings.push(`A margin of ${o.margin} leaves too small a quiet zone; use at least 2.`);
|
|
1699
|
+
if (o.image) {
|
|
1700
|
+
const size = o.image.size ?? .2;
|
|
1701
|
+
const clamped = clampImageSize(o.matrix, o.image);
|
|
1702
|
+
const at = `at level ${o.matrix.level}, version ${o.matrix.version}`;
|
|
1703
|
+
if (!clamped) warnings.push(`The logo does not fit ${at}; it was dropped to keep the code scannable.`);
|
|
1704
|
+
else if (clamped < size) warnings.push(`The logo was reduced to ${clamped.toFixed(3)} to keep the code scannable ${at}.`);
|
|
1705
|
+
}
|
|
1706
|
+
return warnings;
|
|
1707
|
+
}
|
|
1708
|
+
// src/primitives/createQRCode.ts
|
|
1709
|
+
/**
|
|
1710
|
+
* Derives the matrix, geometry and scene from options, which may be a reactive props object.
|
|
1711
|
+
* A colour change repaints the scene only; it does not encode or rebuild paths.
|
|
1712
|
+
*/
|
|
1713
|
+
function createQRCode(options) {
|
|
1714
|
+
const hasImage = createMemo(() => !!options.image);
|
|
1715
|
+
const matrix = createMemo(() => toMatrix(options, hasImage()), { name: "qr.matrix" });
|
|
1716
|
+
const finderShape = createMemo(() => toFinderShape(options.finder), {
|
|
1717
|
+
name: "qr.finderShape",
|
|
1718
|
+
equals: (a, b) => a.outer === b.outer && a.inner === b.inner
|
|
1719
|
+
});
|
|
1720
|
+
const captionShape = createMemo(() => toCaptionShape(options.caption), {
|
|
1721
|
+
name: "qr.captionShape",
|
|
1722
|
+
equals: sameCaptionShape
|
|
1723
|
+
});
|
|
1724
|
+
const geometry = createMemo(() => toGeometry(matrix(), options, finderShape(), captionShape()), { name: "qr.geometry" });
|
|
1725
|
+
const scene = createMemo(() => paintScene(geometry(), toPaints(options)), { name: "qr.scene" });
|
|
1726
|
+
if (isDev) createEffect(() => devWarnings({
|
|
1727
|
+
fg: options.fg ?? defaults.fg,
|
|
1728
|
+
bg: options.bg ?? defaults.bg,
|
|
1729
|
+
margin: options.margin ?? defaults.margin,
|
|
1730
|
+
image: options.image,
|
|
1731
|
+
matrix: matrix()
|
|
1732
|
+
}).concat(geometry().warnings ?? []).map((w) => `[qrcodesolid] ${w}`).join("\n"), (text) => {
|
|
1733
|
+
if (text) console.warn(text);
|
|
1734
|
+
});
|
|
1735
|
+
return {
|
|
1736
|
+
matrix,
|
|
1737
|
+
geometry,
|
|
1738
|
+
scene
|
|
1739
|
+
};
|
|
1740
|
+
}
|
|
1741
|
+
// src/render/canvas.ts
|
|
1742
|
+
function fillStyle(ctx, paint, resolve) {
|
|
1743
|
+
if (typeof paint === "string") return resolve(paint);
|
|
1744
|
+
const gradient = paint.type === "linear" ? ctx.createLinearGradient(paint.x1, paint.y1, paint.x2, paint.y2) : ctx.createRadialGradient(paint.cx, paint.cy, 0, paint.cx, paint.cy, paint.r);
|
|
1745
|
+
for (const [offset, color] of paint.stops) gradient.addColorStop(offset, resolve(color));
|
|
1746
|
+
return gradient;
|
|
1747
|
+
}
|
|
1748
|
+
function sourceSize(source) {
|
|
1749
|
+
const s = source;
|
|
1750
|
+
const width = s.naturalWidth || s.videoWidth || s.displayWidth || s.width;
|
|
1751
|
+
const height = s.naturalHeight || s.videoHeight || s.displayHeight || s.height;
|
|
1752
|
+
return typeof width === "number" && typeof height === "number" ? [width, height] : [0, 0];
|
|
1753
|
+
}
|
|
1754
|
+
/** Draws the image centred in its box at its own aspect ratio, like `xMidYMid meet`. */
|
|
1755
|
+
function drawImage(ctx, source, box) {
|
|
1756
|
+
const [w, h] = sourceSize(source);
|
|
1757
|
+
const k = w && h ? Math.min(box.width / w, box.height / h) : 0;
|
|
1758
|
+
const [dw, dh] = k ? [w * k, h * k] : [box.width, box.height];
|
|
1759
|
+
ctx.save();
|
|
1760
|
+
ctx.beginPath();
|
|
1761
|
+
ctx.roundRect(box.x, box.y, box.width, box.height, box.radius);
|
|
1762
|
+
ctx.clip();
|
|
1763
|
+
ctx.globalAlpha = box.opacity;
|
|
1764
|
+
ctx.drawImage(source, box.x + (box.width - dw) / 2, box.y + (box.height - dh) / 2, dw, dh);
|
|
1765
|
+
ctx.restore();
|
|
1766
|
+
}
|
|
1767
|
+
/** Paints a scene onto a 2D context. The caller sizes and clears the canvas. */
|
|
1768
|
+
function drawScene(ctx, scene, options) {
|
|
1769
|
+
ctx.setTransform(options.scale, 0, 0, options.scale, 0, 0);
|
|
1770
|
+
for (const layer of scene.layers) {
|
|
1771
|
+
ctx.fillStyle = fillStyle(ctx, layer.fill, options.resolveColor);
|
|
1772
|
+
ctx.fill(new Path2D(layer.d), layer.fillRule ?? "nonzero");
|
|
1773
|
+
}
|
|
1774
|
+
if (scene.image && options.image) drawImage(ctx, options.image, scene.image);
|
|
1775
|
+
ctx.textAlign = "center";
|
|
1776
|
+
ctx.textBaseline = "middle";
|
|
1777
|
+
for (const text of scene.texts) {
|
|
1778
|
+
ctx.font = `${text.fontWeight} ${text.fontSize}px ${text.fontFamily}`;
|
|
1779
|
+
ctx.fillStyle = fillStyle(ctx, text.fill, options.resolveColor);
|
|
1780
|
+
ctx.fillText(text.text, text.x, text.y);
|
|
1781
|
+
}
|
|
1782
|
+
}
|
|
1783
|
+
// src/render/color.ts
|
|
1784
|
+
/**
|
|
1785
|
+
* Follows nested `var(--x, fallback)` to the innermost fallback.
|
|
1786
|
+
* A var with no fallback becomes black: canvas rejects a bare var() without a word.
|
|
1787
|
+
*/
|
|
1788
|
+
function parseVarFallback(value) {
|
|
1789
|
+
let v = value.trim();
|
|
1790
|
+
while (v.startsWith("var(")) {
|
|
1791
|
+
const comma = v.indexOf(",");
|
|
1792
|
+
if (comma < 0) return "#000";
|
|
1793
|
+
v = v.slice(comma + 1, v.lastIndexOf(")")).trim();
|
|
1794
|
+
}
|
|
1795
|
+
return v;
|
|
1796
|
+
}
|
|
1797
|
+
/**
|
|
1798
|
+
* Turns a CSS colour into one canvas accepts. With `el`, custom properties and
|
|
1799
|
+
* `currentColor` resolve against `el` through a hidden probe child.
|
|
1800
|
+
*/
|
|
1801
|
+
function resolveColor(value, el) {
|
|
1802
|
+
if (el?.isConnected) {
|
|
1803
|
+
const probe = document.createElement("span");
|
|
1804
|
+
probe.style.color = value;
|
|
1805
|
+
if (probe.style.color) {
|
|
1806
|
+
probe.style.display = "none";
|
|
1807
|
+
el.appendChild(probe);
|
|
1808
|
+
const color = getComputedStyle(probe).color;
|
|
1809
|
+
probe.remove();
|
|
1810
|
+
if (color) return color;
|
|
1811
|
+
}
|
|
1812
|
+
}
|
|
1813
|
+
const color = parseVarFallback(value);
|
|
1814
|
+
return color === "currentColor" ? "#000" : color;
|
|
1815
|
+
}
|
|
1816
|
+
/**
|
|
1817
|
+
* A `resolveColor` for one element that remembers each answer.
|
|
1818
|
+
* Layers share colours, and each probe lookup adds an element to the page.
|
|
1819
|
+
*/
|
|
1820
|
+
function colorResolver(el) {
|
|
1821
|
+
const answers = /* @__PURE__ */ new Map();
|
|
1822
|
+
return (value) => {
|
|
1823
|
+
if (!answers.has(value)) answers.set(value, resolveColor(value, el));
|
|
1824
|
+
return answers.get(value);
|
|
1825
|
+
};
|
|
1826
|
+
}
|
|
1827
|
+
function resolvePaintColors(paint, resolve) {
|
|
1828
|
+
if (typeof paint === "string") return resolve(paint);
|
|
1829
|
+
return {
|
|
1830
|
+
...paint,
|
|
1831
|
+
stops: paint.stops.map(([offset, c]) => [offset, resolve(c)])
|
|
1832
|
+
};
|
|
1833
|
+
}
|
|
1834
|
+
/**
|
|
1835
|
+
* Replaces var() and currentColor in every paint, for output that has no page CSS.
|
|
1836
|
+
* With `el`, they resolve against it, as on a canvas drawn there. A detached `el` is ignored.
|
|
1837
|
+
*/
|
|
1838
|
+
function resolveSceneColors(scene, el) {
|
|
1839
|
+
const resolve = colorResolver(el);
|
|
1840
|
+
return {
|
|
1841
|
+
...scene,
|
|
1842
|
+
layers: scene.layers.map((l) => ({
|
|
1843
|
+
...l,
|
|
1844
|
+
fill: resolvePaintColors(l.fill, resolve)
|
|
1845
|
+
})),
|
|
1846
|
+
texts: scene.texts.map((t) => ({
|
|
1847
|
+
...t,
|
|
1848
|
+
fill: resolvePaintColors(t.fill, resolve)
|
|
1849
|
+
}))
|
|
1850
|
+
};
|
|
1851
|
+
}
|
|
1852
|
+
// src/render/image.ts
|
|
1853
|
+
const browserIO = {
|
|
1854
|
+
fetch: (input, init) => fetch(input, init),
|
|
1855
|
+
makeImage: () => typeof Image === "undefined" ? void 0 : new Image(),
|
|
1856
|
+
decodeBlob: (blob) => createImageBitmap(blob)
|
|
1857
|
+
};
|
|
1858
|
+
const timeoutDefault = 1e4;
|
|
1859
|
+
const maxBytesDefault = 2097152;
|
|
1860
|
+
/**
|
|
1861
|
+
* Fetches the image with the CORS mode an `<img crossorigin>` would use.
|
|
1862
|
+
* Rejects on a timeout, a cancel, an HTTP error, a body over `maxBytes`, or a non-image body.
|
|
1863
|
+
*/
|
|
1864
|
+
async function fetchImage(image, limits = {}, io = browserIO) {
|
|
1865
|
+
const { timeout = timeoutDefault, maxBytes = maxBytesDefault, signal } = limits;
|
|
1866
|
+
const credentials = image.crossOrigin === "use-credentials" ? "include" : "same-origin";
|
|
1867
|
+
const controller = new AbortController();
|
|
1868
|
+
const timer = setTimeout(() => controller.abort(/* @__PURE__ */ new Error(`Timed out after ${timeout} ms`)), timeout);
|
|
1869
|
+
const cancel = () => controller.abort(signal?.reason);
|
|
1870
|
+
signal?.addEventListener("abort", cancel, { once: true });
|
|
1871
|
+
const tooLarge = (bytes) => /* @__PURE__ */ new Error(`Image is ${bytes} bytes, over the ${maxBytes} byte limit`);
|
|
1872
|
+
try {
|
|
1873
|
+
signal?.throwIfAborted();
|
|
1874
|
+
const response = await io.fetch(image.src, {
|
|
1875
|
+
mode: "cors",
|
|
1876
|
+
credentials,
|
|
1877
|
+
signal: controller.signal
|
|
1878
|
+
});
|
|
1879
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
1880
|
+
const length = Number(response.headers.get("content-length"));
|
|
1881
|
+
if (length > maxBytes) {
|
|
1882
|
+
controller.abort();
|
|
1883
|
+
throw tooLarge(length);
|
|
1884
|
+
}
|
|
1885
|
+
const blob = await readBody(response, maxBytes, (bytes) => {
|
|
1886
|
+
controller.abort();
|
|
1887
|
+
return tooLarge(bytes);
|
|
1888
|
+
});
|
|
1889
|
+
if (!blob.type.startsWith("image/")) throw new Error(`Not an image: ${blob.type || "no type"}`);
|
|
1890
|
+
return blob;
|
|
1891
|
+
} finally {
|
|
1892
|
+
clearTimeout(timer);
|
|
1893
|
+
signal?.removeEventListener("abort", cancel);
|
|
1894
|
+
}
|
|
1895
|
+
}
|
|
1896
|
+
/** Reads the body, and stops once it passes `maxBytes`, so a huge logo is never held whole. */
|
|
1897
|
+
async function readBody(response, maxBytes, tooLarge) {
|
|
1898
|
+
if (!response.body) {
|
|
1899
|
+
const blob = await response.blob();
|
|
1900
|
+
if (blob.size > maxBytes) throw tooLarge(blob.size);
|
|
1901
|
+
return blob;
|
|
1902
|
+
}
|
|
1903
|
+
const reader = response.body.getReader();
|
|
1904
|
+
const chunks = [];
|
|
1905
|
+
let bytes = 0;
|
|
1906
|
+
for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
|
|
1907
|
+
bytes += chunk.value.byteLength;
|
|
1908
|
+
if (bytes > maxBytes) {
|
|
1909
|
+
reader.cancel().catch(() => {});
|
|
1910
|
+
throw tooLarge(bytes);
|
|
1911
|
+
}
|
|
1912
|
+
chunks.push(chunk.value);
|
|
1913
|
+
}
|
|
1914
|
+
return new Blob(chunks, { type: response.headers.get("content-type") ?? "" });
|
|
1915
|
+
}
|
|
1916
|
+
/** Loads the image, or returns undefined when it fails: the code draws without it. */
|
|
1917
|
+
async function loadImage(image, limits = {}, io = browserIO) {
|
|
1918
|
+
const { timeout = timeoutDefault, signal, warn = true } = limits;
|
|
1919
|
+
try {
|
|
1920
|
+
signal?.throwIfAborted();
|
|
1921
|
+
const img = io.makeImage();
|
|
1922
|
+
if (!img) return await io.decodeBlob(await fetchImage(image, limits, io));
|
|
1923
|
+
if (image.crossOrigin !== void 0) img.crossOrigin = image.crossOrigin;
|
|
1924
|
+
img.src = image.src;
|
|
1925
|
+
let timer;
|
|
1926
|
+
let stop = () => {};
|
|
1927
|
+
const cancelled = new Promise((_resolve, reject) => {
|
|
1928
|
+
timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`Timed out after ${timeout} ms`)), timeout);
|
|
1929
|
+
const onAbort = () => reject(signal?.reason);
|
|
1930
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1931
|
+
stop = () => signal?.removeEventListener("abort", onAbort);
|
|
1932
|
+
});
|
|
1933
|
+
cancelled.catch(() => {});
|
|
1934
|
+
try {
|
|
1935
|
+
await Promise.race([img.decode(), cancelled]);
|
|
1936
|
+
} catch (err) {
|
|
1937
|
+
img.src = "";
|
|
1938
|
+
throw err;
|
|
1939
|
+
} finally {
|
|
1940
|
+
clearTimeout(timer);
|
|
1941
|
+
stop();
|
|
1942
|
+
}
|
|
1943
|
+
return img;
|
|
1944
|
+
} catch (err) {
|
|
1945
|
+
if (warn && !signal?.aborted) console.warn(`[qrcodesolid] Failed to load image: ${image.src}`, err);
|
|
1946
|
+
return;
|
|
1947
|
+
}
|
|
1948
|
+
}
|
|
1949
|
+
async function blobToDataURL(blob) {
|
|
1950
|
+
if (typeof FileReader !== "undefined") return new Promise((resolve, reject) => {
|
|
1951
|
+
const reader = new FileReader();
|
|
1952
|
+
reader.onload = () => resolve(reader.result);
|
|
1953
|
+
reader.onerror = () => reject(reader.error);
|
|
1954
|
+
reader.readAsDataURL(blob);
|
|
1955
|
+
});
|
|
1956
|
+
const bytes = new Uint8Array(await blob.arrayBuffer());
|
|
1957
|
+
let binary = "";
|
|
1958
|
+
for (let i = 0; i < bytes.length; i += 32768) binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
|
|
1959
|
+
return `data:${blob.type || "application/octet-stream"};base64,${btoa(binary)}`;
|
|
1960
|
+
}
|
|
1961
|
+
// src/components/QRCodeCanvas.tsx
|
|
1962
|
+
var _tmpl$$2 = /* @__PURE__ */ template(`<canvas>`);
|
|
1963
|
+
/**
|
|
1964
|
+
* Renders a QR code to a canvas sized for the device pixel ratio.
|
|
1965
|
+
* It redraws when `prefers-color-scheme` changes, since CSS colours may depend on it.
|
|
1966
|
+
*/
|
|
1967
|
+
function QRCodeCanvas(props) {
|
|
1968
|
+
const rest = omit(props, ...optionKeys, "onReady", "repaint", "imageTimeout");
|
|
1969
|
+
const { scene } = createQRCode(props);
|
|
1970
|
+
const ratio = createPixelRatio();
|
|
1971
|
+
const scheme = createColorScheme();
|
|
1972
|
+
const src = createMemo(() => props.image?.src, { name: "qr.imageSrc" });
|
|
1973
|
+
const crossOrigin = createMemo(() => props.image?.crossOrigin, { name: "qr.crossOrigin" });
|
|
1974
|
+
const imageTimeout = createMemo(() => props.imageTimeout, { name: "qr.imageTimeout" });
|
|
1975
|
+
const [loaded, setLoaded] = createSignal();
|
|
1976
|
+
let canvas;
|
|
1977
|
+
createEffect(() => [
|
|
1978
|
+
src(),
|
|
1979
|
+
crossOrigin(),
|
|
1980
|
+
imageTimeout()
|
|
1981
|
+
], ([src, crossOrigin, timeout]) => {
|
|
1982
|
+
if (!src) return;
|
|
1983
|
+
const controller = new AbortController();
|
|
1984
|
+
loadImage({
|
|
1985
|
+
src,
|
|
1986
|
+
crossOrigin
|
|
1987
|
+
}, {
|
|
1988
|
+
timeout,
|
|
1989
|
+
signal: controller.signal,
|
|
1990
|
+
warn: isDev
|
|
1991
|
+
}).then((image) => {
|
|
1992
|
+
if (!controller.signal.aborted) setLoaded({
|
|
1993
|
+
src,
|
|
1994
|
+
image: image ?? "error"
|
|
1995
|
+
});
|
|
1996
|
+
});
|
|
1997
|
+
return () => controller.abort();
|
|
1998
|
+
});
|
|
1999
|
+
createEffect(() => {
|
|
2000
|
+
const result = loaded();
|
|
2001
|
+
return {
|
|
2002
|
+
scene: scene(),
|
|
2003
|
+
ratio: ratio(),
|
|
2004
|
+
scheme: scheme(),
|
|
2005
|
+
repaint: props.repaint,
|
|
2006
|
+
size: props.size,
|
|
2007
|
+
image: result && result.src === src() ? result.image : void 0,
|
|
2008
|
+
settled: !src() || result?.src === src(),
|
|
2009
|
+
onReady: props.onReady
|
|
2010
|
+
};
|
|
2011
|
+
}, {
|
|
2012
|
+
error: (err) => {
|
|
2013
|
+
throw err;
|
|
2014
|
+
},
|
|
2015
|
+
effect: ({ scene, ratio, size, image, settled, onReady }) => {
|
|
2016
|
+
const output = outputSize(scene, size);
|
|
2017
|
+
canvas.width = Math.round(output.width * ratio);
|
|
2018
|
+
canvas.height = Math.round(output.height * ratio);
|
|
2019
|
+
canvas.style.width = `${output.width}px`;
|
|
2020
|
+
canvas.style.height = `${output.height}px`;
|
|
2021
|
+
const ctx = canvas.getContext("2d");
|
|
2022
|
+
if (!ctx) throw new Error("[qrcodesolid] No 2D canvas context.");
|
|
2023
|
+
drawScene(ctx, scene, {
|
|
2024
|
+
scale: canvas.width / scene.width,
|
|
2025
|
+
image: image === "error" ? void 0 : image,
|
|
2026
|
+
resolveColor: colorResolver(canvas)
|
|
2027
|
+
});
|
|
2028
|
+
if (settled) onReady?.(canvas);
|
|
2029
|
+
}
|
|
2030
|
+
});
|
|
2031
|
+
var _el$ = _tmpl$$2();
|
|
2032
|
+
spread(_el$, [
|
|
2033
|
+
{
|
|
2034
|
+
role: "img",
|
|
2035
|
+
get id() {
|
|
2036
|
+
return props.id;
|
|
2037
|
+
}
|
|
2038
|
+
},
|
|
2039
|
+
rest,
|
|
2040
|
+
{ get "aria-label"() {
|
|
2041
|
+
return ariaLabel(props, true);
|
|
2042
|
+
} }
|
|
2043
|
+
], false);
|
|
2044
|
+
var _ref$ = canvas;
|
|
2045
|
+
typeof _ref$ === "function" || Array.isArray(_ref$) ? ref(() => {
|
|
2046
|
+
return _ref$;
|
|
2047
|
+
}, _el$) : canvas = _el$;
|
|
2048
|
+
return _el$;
|
|
2049
|
+
}
|
|
2050
|
+
// src/render/svg-string.ts
|
|
2051
|
+
const entities = {
|
|
2052
|
+
"&": "&",
|
|
2053
|
+
"<": "<",
|
|
2054
|
+
">": ">",
|
|
2055
|
+
"\"": """,
|
|
2056
|
+
"'": "'"
|
|
2057
|
+
};
|
|
2058
|
+
const escape = (s) => s.replace(/[&<>"']/g, (c) => entities[c]);
|
|
2059
|
+
/** Square-only scenes contain no curves or diagonals, so crisp edges cannot hurt them. */
|
|
2060
|
+
const isRectilinear = (d) => /^[MHVhvZz\d .-]*$/.test(d);
|
|
2061
|
+
function gradient(id, paint) {
|
|
2062
|
+
const stops = paint.stops.map(([offset, color]) => `<stop offset="${offset}" stop-color="${escape(color)}"/>`).join("");
|
|
2063
|
+
const attrs = paint.type === "linear" ? `x1="${paint.x1}" y1="${paint.y1}" x2="${paint.x2}" y2="${paint.y2}"` : `cx="${paint.cx}" cy="${paint.cy}" r="${paint.r}"`;
|
|
2064
|
+
const tag = paint.type === "linear" ? "linearGradient" : "radialGradient";
|
|
2065
|
+
return `<${tag} id="${escape(id)}" gradientUnits="userSpaceOnUse" ${attrs}>${stops}</${tag}>`;
|
|
2066
|
+
}
|
|
2067
|
+
/** Serialises a scene to a standalone SVG document string. */
|
|
2068
|
+
function sceneToSVGString(scene, options) {
|
|
2069
|
+
const { width, height, image } = scene;
|
|
2070
|
+
const defs = [];
|
|
2071
|
+
const fill = (id, paint) => {
|
|
2072
|
+
if (typeof paint === "string") return escape(paint);
|
|
2073
|
+
const ref = `${options.idPrefix}-${id}`;
|
|
2074
|
+
defs.push(gradient(ref, paint));
|
|
2075
|
+
return `url(#${escape(ref)})`;
|
|
2076
|
+
};
|
|
2077
|
+
const body = scene.layers.map((layer) => {
|
|
2078
|
+
const rule = layer.fillRule ? ` fill-rule="${layer.fillRule}"` : "";
|
|
2079
|
+
return `<path d="${escape(layer.d)}" fill="${fill(layer.id, layer.fill)}"${rule}/>`;
|
|
2080
|
+
});
|
|
2081
|
+
if (image) {
|
|
2082
|
+
const clip = `${options.idPrefix}-image-clip`;
|
|
2083
|
+
const box = `x="${coord(image.x)}" y="${coord(image.y)}" width="${coord(image.width)}" height="${coord(image.height)}"`;
|
|
2084
|
+
const r = coord(image.radius);
|
|
2085
|
+
defs.push(`<clipPath id="${escape(clip)}"><rect ${box} rx="${r}" ry="${r}"/></clipPath>`);
|
|
2086
|
+
const crossOrigin = image.crossOrigin === void 0 ? "" : ` crossorigin="${image.crossOrigin}"`;
|
|
2087
|
+
body.push(`<image href="${escape(image.href)}" ${box} opacity="${image.opacity}" preserveAspectRatio="xMidYMid meet" clip-path="url(#${escape(clip)})"${crossOrigin}/>`);
|
|
2088
|
+
}
|
|
2089
|
+
scene.texts.forEach((t, i) => {
|
|
2090
|
+
const font = `font-size="${coord(t.fontSize)}" font-family="${escape(t.fontFamily)}" font-weight="${escape(String(t.fontWeight))}"`;
|
|
2091
|
+
body.push(`<text x="${coord(t.x)}" y="${coord(t.y)}" ${font} fill="${fill(`text-${i}`, t.fill)}" text-anchor="middle" dominant-baseline="central">${escape(t.text)}</text>`);
|
|
2092
|
+
});
|
|
2093
|
+
const crisp = scene.layers.every((l) => isRectilinear(l.d)) ? " shape-rendering=\"crispEdges\"" : "";
|
|
2094
|
+
const title = options.title ? `<title>${escape(options.title)}</title>` : "";
|
|
2095
|
+
return `${`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${coord(width)} ${coord(height)}" width="${coord(options.size)}" height="${coord(options.size * height / width)}"${crisp}>`}${title}${defs.length ? `<defs>${defs.join("")}</defs>` : ""}${body.join("")}</svg>`;
|
|
2096
|
+
}
|
|
2097
|
+
// src/components/GradientDef.tsx
|
|
2098
|
+
var _tmpl$$1 = /* @__PURE__ */ template(`<svg><stop></svg>`, 2);
|
|
2099
|
+
var _tmpl$2$1 = /* @__PURE__ */ template(`<svg><linearGradient gradientUnits=userSpaceOnUse></svg>`, 2);
|
|
2100
|
+
var _tmpl$3$1 = /* @__PURE__ */ template(`<svg><radialGradient gradientUnits=userSpaceOnUse></svg>`, 2);
|
|
2101
|
+
/** One `<defs>` gradient in user-space units, as `sceneToSVGString` writes it. */
|
|
2102
|
+
function GradientDef(props) {
|
|
2103
|
+
const stops = () => createComponent(For, {
|
|
2104
|
+
get each() {
|
|
2105
|
+
return props.paint.stops;
|
|
2106
|
+
},
|
|
2107
|
+
keyed: false,
|
|
2108
|
+
children: (stop) => (() => {
|
|
2109
|
+
var _el$ = _tmpl$$1();
|
|
2110
|
+
effect(() => {
|
|
2111
|
+
return {
|
|
2112
|
+
e: stop()[0],
|
|
2113
|
+
t: stop()[1]
|
|
2114
|
+
};
|
|
2115
|
+
}, ({ e, t }, _p$) => {
|
|
2116
|
+
e !== _p$?.e && setAttribute(_el$, "offset", e);
|
|
2117
|
+
t !== _p$?.t && setAttribute(_el$, "stop-color", t);
|
|
2118
|
+
});
|
|
2119
|
+
return _el$;
|
|
2120
|
+
})()
|
|
2121
|
+
});
|
|
2122
|
+
return createComponent(Switch, { get children() {
|
|
2123
|
+
return [createComponent(Match, {
|
|
2124
|
+
get when() {
|
|
2125
|
+
return memo(() => {
|
|
2126
|
+
return props.paint.type === "linear";
|
|
2127
|
+
})() && props.paint;
|
|
2128
|
+
},
|
|
2129
|
+
children: (p) => (() => {
|
|
2130
|
+
var _el$2 = _tmpl$2$1();
|
|
2131
|
+
insert(_el$2, stops);
|
|
2132
|
+
effect(() => {
|
|
2133
|
+
return {
|
|
2134
|
+
e: props.id,
|
|
2135
|
+
t: p().x1,
|
|
2136
|
+
a: p().y1,
|
|
2137
|
+
o: p().x2,
|
|
2138
|
+
i: p().y2
|
|
2139
|
+
};
|
|
2140
|
+
}, ({ e, t, a, o, i }, _p$) => {
|
|
2141
|
+
e !== _p$?.e && setAttribute(_el$2, "id", e);
|
|
2142
|
+
t !== _p$?.t && setAttribute(_el$2, "x1", t);
|
|
2143
|
+
a !== _p$?.a && setAttribute(_el$2, "y1", a);
|
|
2144
|
+
o !== _p$?.o && setAttribute(_el$2, "x2", o);
|
|
2145
|
+
i !== _p$?.i && setAttribute(_el$2, "y2", i);
|
|
2146
|
+
});
|
|
2147
|
+
return _el$2;
|
|
2148
|
+
})()
|
|
2149
|
+
}), createComponent(Match, {
|
|
2150
|
+
get when() {
|
|
2151
|
+
return memo(() => {
|
|
2152
|
+
return props.paint.type === "radial";
|
|
2153
|
+
})() && props.paint;
|
|
2154
|
+
},
|
|
2155
|
+
children: (p) => (() => {
|
|
2156
|
+
var _el$3 = _tmpl$3$1();
|
|
2157
|
+
insert(_el$3, stops);
|
|
2158
|
+
effect(() => {
|
|
2159
|
+
return {
|
|
2160
|
+
e: props.id,
|
|
2161
|
+
t: p().cx,
|
|
2162
|
+
a: p().cy,
|
|
2163
|
+
o: p().r
|
|
2164
|
+
};
|
|
2165
|
+
}, ({ e, t, a, o }, _p$) => {
|
|
2166
|
+
e !== _p$?.e && setAttribute(_el$3, "id", e);
|
|
2167
|
+
t !== _p$?.t && setAttribute(_el$3, "cx", t);
|
|
2168
|
+
a !== _p$?.a && setAttribute(_el$3, "cy", a);
|
|
2169
|
+
o !== _p$?.o && setAttribute(_el$3, "r", o);
|
|
2170
|
+
});
|
|
2171
|
+
return _el$3;
|
|
2172
|
+
})()
|
|
2173
|
+
})];
|
|
2174
|
+
} });
|
|
2175
|
+
}
|
|
2176
|
+
// src/components/QRCodeSVG.tsx
|
|
2177
|
+
var _tmpl$ = /* @__PURE__ */ template(`<svg><!><!><!><!><!>`);
|
|
2178
|
+
var _tmpl$2 = /* @__PURE__ */ template(`<title>`);
|
|
2179
|
+
var _tmpl$3 = /* @__PURE__ */ template(`<svg><defs><!><!><!></svg>`, 2);
|
|
2180
|
+
var _tmpl$4 = /* @__PURE__ */ template(`<svg><clipPath><rect></svg>`, 2);
|
|
2181
|
+
var _tmpl$5 = /* @__PURE__ */ template(`<svg><path></svg>`, 2);
|
|
2182
|
+
var _tmpl$6 = /* @__PURE__ */ template(`<svg><image></svg>`, 2);
|
|
2183
|
+
var _tmpl$7 = /* @__PURE__ */ template(`<svg><text text-anchor=middle dominant-baseline=central></svg>`, 2);
|
|
2184
|
+
/** Renders a QR code as inline SVG. The markup matches `sceneToSVGString`. */
|
|
2185
|
+
function QRCodeSVG(props) {
|
|
2186
|
+
const rest = omit(props, ...optionKeys);
|
|
2187
|
+
const { scene } = createQRCode(props);
|
|
2188
|
+
const uniqueId = createUniqueId();
|
|
2189
|
+
const prefix = () => props.id ?? `qr-${uniqueId}`;
|
|
2190
|
+
const output = () => outputSize(scene(), props.size);
|
|
2191
|
+
const fill = (id, paint) => typeof paint === "string" ? paint : `url(#${prefix()}-${id})`;
|
|
2192
|
+
const gradientsOf = (painted) => painted.filter((p) => typeof p[1] !== "string");
|
|
2193
|
+
const layerGradients = createMemo(() => gradientsOf(scene().layers.map((l) => [l.id, l.fill])));
|
|
2194
|
+
const textGradients = createMemo(() => gradientsOf(scene().texts.map((t, i) => [`text-${i}`, t.fill])));
|
|
2195
|
+
const gradientDefs = (gradients) => createComponent(For, {
|
|
2196
|
+
each: gradients,
|
|
2197
|
+
keyed: false,
|
|
2198
|
+
children: (g) => createComponent(GradientDef, {
|
|
2199
|
+
get id() {
|
|
2200
|
+
return `${prefix()}-${g()[0]}`;
|
|
2201
|
+
},
|
|
2202
|
+
get paint() {
|
|
2203
|
+
return g()[1];
|
|
2204
|
+
}
|
|
2205
|
+
})
|
|
2206
|
+
});
|
|
2207
|
+
const image = () => scene().image;
|
|
2208
|
+
const clipId = () => `${prefix()}-image-clip`;
|
|
2209
|
+
var _el$ = _tmpl$();
|
|
2210
|
+
var _el$2 = _el$.firstChild;
|
|
2211
|
+
var _el$3 = _el$2.nextSibling;
|
|
2212
|
+
var _el$4 = _el$3.nextSibling;
|
|
2213
|
+
var _el$5 = _el$4.nextSibling;
|
|
2214
|
+
var _el$6 = _el$5.nextSibling;
|
|
2215
|
+
spread(_el$, [{
|
|
2216
|
+
xmlns: "http://www.w3.org/2000/svg",
|
|
2217
|
+
get id() {
|
|
2218
|
+
return props.id;
|
|
2219
|
+
},
|
|
2220
|
+
role: "img",
|
|
2221
|
+
get "aria-labelledby"() {
|
|
2222
|
+
return props.title ? `${prefix()}-title` : void 0;
|
|
2223
|
+
},
|
|
2224
|
+
get "aria-label"() {
|
|
2225
|
+
return ariaLabel(props, false);
|
|
2226
|
+
},
|
|
2227
|
+
get viewBox() {
|
|
2228
|
+
return `0 0 ${coord(scene().width)} ${coord(scene().height)}`;
|
|
2229
|
+
},
|
|
2230
|
+
get width() {
|
|
2231
|
+
return coord(output().width);
|
|
2232
|
+
},
|
|
2233
|
+
get height() {
|
|
2234
|
+
return coord(output().height);
|
|
2235
|
+
},
|
|
2236
|
+
get "shape-rendering"() {
|
|
2237
|
+
return scene().layers.every((l) => isRectilinear(l.d)) ? "crispEdges" : void 0;
|
|
2238
|
+
}
|
|
2239
|
+
}, rest], true);
|
|
2240
|
+
insert(_el$, createComponent(Show, {
|
|
2241
|
+
get when() {
|
|
2242
|
+
return props.title;
|
|
2243
|
+
},
|
|
2244
|
+
children: (title) => (() => {
|
|
2245
|
+
var _el$7 = _tmpl$2();
|
|
2246
|
+
insert(_el$7, title);
|
|
2247
|
+
effect(() => `${prefix()}-title`, (_v$) => {
|
|
2248
|
+
setAttribute(_el$7, "id", _v$);
|
|
2249
|
+
});
|
|
2250
|
+
return _el$7;
|
|
2251
|
+
})()
|
|
2252
|
+
}), _el$2);
|
|
2253
|
+
insert(_el$, (() => {
|
|
2254
|
+
var _c$ = memo(() => {
|
|
2255
|
+
return !!(layerGradients().length > 0 || textGradients().length > 0 || image());
|
|
2256
|
+
});
|
|
2257
|
+
return () => {
|
|
2258
|
+
return _c$() ? (() => {
|
|
2259
|
+
var _el$8 = _tmpl$3();
|
|
2260
|
+
var _el$9 = _el$8.firstChild;
|
|
2261
|
+
var _el$10 = _el$9.nextSibling;
|
|
2262
|
+
var _el$11 = _el$10.nextSibling;
|
|
2263
|
+
insert(_el$8, () => {
|
|
2264
|
+
return gradientDefs(layerGradients());
|
|
2265
|
+
}, _el$9);
|
|
2266
|
+
insert(_el$8, createComponent(Show, {
|
|
2267
|
+
get when() {
|
|
2268
|
+
return image();
|
|
2269
|
+
},
|
|
2270
|
+
children: (img) => (() => {
|
|
2271
|
+
var _el$12 = _tmpl$4();
|
|
2272
|
+
var _el$13 = _el$12.firstChild;
|
|
2273
|
+
effect(() => {
|
|
2274
|
+
return {
|
|
2275
|
+
e: clipId(),
|
|
2276
|
+
t: coord(img().x),
|
|
2277
|
+
a: coord(img().y),
|
|
2278
|
+
o: coord(img().width),
|
|
2279
|
+
i: coord(img().height),
|
|
2280
|
+
n: coord(img().radius),
|
|
2281
|
+
s: coord(img().radius)
|
|
2282
|
+
};
|
|
2283
|
+
}, ({ e, t, a, o, i, n, s }, _p$) => {
|
|
2284
|
+
e !== _p$?.e && setAttribute(_el$12, "id", e);
|
|
2285
|
+
t !== _p$?.t && setAttribute(_el$13, "x", t);
|
|
2286
|
+
a !== _p$?.a && setAttribute(_el$13, "y", a);
|
|
2287
|
+
o !== _p$?.o && setAttribute(_el$13, "width", o);
|
|
2288
|
+
i !== _p$?.i && setAttribute(_el$13, "height", i);
|
|
2289
|
+
n !== _p$?.n && setAttribute(_el$13, "rx", n);
|
|
2290
|
+
s !== _p$?.s && setAttribute(_el$13, "ry", s);
|
|
2291
|
+
});
|
|
2292
|
+
return _el$12;
|
|
2293
|
+
})()
|
|
2294
|
+
}), _el$10);
|
|
2295
|
+
insert(_el$8, () => {
|
|
2296
|
+
return gradientDefs(textGradients());
|
|
2297
|
+
}, _el$11);
|
|
2298
|
+
return _el$8;
|
|
2299
|
+
})() : void 0;
|
|
2300
|
+
};
|
|
2301
|
+
})(), _el$3);
|
|
2302
|
+
insert(_el$, createComponent(For, {
|
|
2303
|
+
get each() {
|
|
2304
|
+
return scene().layers;
|
|
2305
|
+
},
|
|
2306
|
+
keyed: false,
|
|
2307
|
+
children: (layer) => (() => {
|
|
2308
|
+
var _el$14 = _tmpl$5();
|
|
2309
|
+
effect(() => {
|
|
2310
|
+
return {
|
|
2311
|
+
e: layer().d,
|
|
2312
|
+
t: fill(layer().id, layer().fill),
|
|
2313
|
+
a: layer().fillRule
|
|
2314
|
+
};
|
|
2315
|
+
}, ({ e, t, a }, _p$) => {
|
|
2316
|
+
e !== _p$?.e && setAttribute(_el$14, "d", e);
|
|
2317
|
+
t !== _p$?.t && setAttribute(_el$14, "fill", t);
|
|
2318
|
+
a !== _p$?.a && setAttribute(_el$14, "fill-rule", a);
|
|
2319
|
+
});
|
|
2320
|
+
return _el$14;
|
|
2321
|
+
})()
|
|
2322
|
+
}), _el$4);
|
|
2323
|
+
insert(_el$, createComponent(Show, {
|
|
2324
|
+
get when() {
|
|
2325
|
+
return image();
|
|
2326
|
+
},
|
|
2327
|
+
children: (img) => (() => {
|
|
2328
|
+
var _el$15 = _tmpl$6();
|
|
2329
|
+
spread(_el$15, [{
|
|
2330
|
+
get href() {
|
|
2331
|
+
return img().href;
|
|
2332
|
+
},
|
|
2333
|
+
get x() {
|
|
2334
|
+
return coord(img().x);
|
|
2335
|
+
},
|
|
2336
|
+
get y() {
|
|
2337
|
+
return coord(img().y);
|
|
2338
|
+
},
|
|
2339
|
+
get width() {
|
|
2340
|
+
return coord(img().width);
|
|
2341
|
+
},
|
|
2342
|
+
get height() {
|
|
2343
|
+
return coord(img().height);
|
|
2344
|
+
},
|
|
2345
|
+
get opacity() {
|
|
2346
|
+
return img().opacity;
|
|
2347
|
+
},
|
|
2348
|
+
preserveAspectRatio: "xMidYMid meet",
|
|
2349
|
+
get "clip-path"() {
|
|
2350
|
+
return `url(#${clipId()})`;
|
|
2351
|
+
},
|
|
2352
|
+
onError: () => {
|
|
2353
|
+
if (isDev) console.warn(`[qrcodesolid] Failed to load image: ${img().href}`);
|
|
2354
|
+
}
|
|
2355
|
+
}, () => {
|
|
2356
|
+
return { crossorigin: img().crossOrigin };
|
|
2357
|
+
}], false);
|
|
2358
|
+
return _el$15;
|
|
2359
|
+
})()
|
|
2360
|
+
}), _el$5);
|
|
2361
|
+
insert(_el$, createComponent(For, {
|
|
2362
|
+
get each() {
|
|
2363
|
+
return scene().texts;
|
|
2364
|
+
},
|
|
2365
|
+
keyed: false,
|
|
2366
|
+
children: (text, i) => (() => {
|
|
2367
|
+
var _el$16 = _tmpl$7();
|
|
2368
|
+
insert(_el$16, () => {
|
|
2369
|
+
return text().text;
|
|
2370
|
+
});
|
|
2371
|
+
effect(() => {
|
|
2372
|
+
return {
|
|
2373
|
+
e: coord(text().x),
|
|
2374
|
+
t: coord(text().y),
|
|
2375
|
+
a: coord(text().fontSize),
|
|
2376
|
+
o: text().fontFamily,
|
|
2377
|
+
i: text().fontWeight,
|
|
2378
|
+
n: fill(`text-${i}`, text().fill)
|
|
2379
|
+
};
|
|
2380
|
+
}, ({ e, t, a, o, i, n }, _p$) => {
|
|
2381
|
+
e !== _p$?.e && setAttribute(_el$16, "x", e);
|
|
2382
|
+
t !== _p$?.t && setAttribute(_el$16, "y", t);
|
|
2383
|
+
a !== _p$?.a && setAttribute(_el$16, "font-size", a);
|
|
2384
|
+
o !== _p$?.o && setAttribute(_el$16, "font-family", o);
|
|
2385
|
+
i !== _p$?.i && setAttribute(_el$16, "font-weight", i);
|
|
2386
|
+
n !== _p$?.n && setAttribute(_el$16, "fill", n);
|
|
2387
|
+
});
|
|
2388
|
+
return _el$16;
|
|
2389
|
+
})()
|
|
2390
|
+
}), _el$6);
|
|
2391
|
+
return _el$;
|
|
2392
|
+
}
|
|
2393
|
+
// src/components/QRCode.tsx
|
|
2394
|
+
/** Renders a QR code with the renderer that `renderAs` names. Default 'svg'. */
|
|
2395
|
+
function QRCode(props) {
|
|
2396
|
+
const rest = omit(props, "renderAs");
|
|
2397
|
+
return memo(() => {
|
|
2398
|
+
return memo(() => {
|
|
2399
|
+
return props.renderAs === "canvas";
|
|
2400
|
+
})() ? createComponent(QRCodeCanvas, rest) : createComponent(QRCodeSVG, rest);
|
|
2401
|
+
});
|
|
2402
|
+
}
|
|
2403
|
+
// src/export/index.ts
|
|
2404
|
+
const limitsOf = (o) => ({
|
|
2405
|
+
timeout: o.imageTimeout,
|
|
2406
|
+
maxBytes: o.imageMaxBytes
|
|
2407
|
+
});
|
|
2408
|
+
/** The scene `createQRCode` derives, computed once without Solid. */
|
|
2409
|
+
function toScene(options) {
|
|
2410
|
+
return paintScene(toGeometry(toMatrix(options), options), toPaints(options));
|
|
2411
|
+
}
|
|
2412
|
+
/**
|
|
2413
|
+
* A standalone SVG document. Ids start with `options.id`, else `qr`.
|
|
2414
|
+
* `resolveColors` replaces var() and currentColor, for files that have no page CSS.
|
|
2415
|
+
* `element` then resolves them against a mounted element; a detached one is ignored.
|
|
2416
|
+
*/
|
|
2417
|
+
function toSVGString(options) {
|
|
2418
|
+
const scene = toScene(options);
|
|
2419
|
+
return serialise(options.resolveColors ? resolveSceneColors(scene, options.element) : scene, options);
|
|
2420
|
+
}
|
|
2421
|
+
const serialise = (scene, options) => sceneToSVGString(scene, {
|
|
2422
|
+
size: options.size ?? defaults.size,
|
|
2423
|
+
idPrefix: options.id ?? "qr",
|
|
2424
|
+
title: options.title
|
|
2425
|
+
});
|
|
2426
|
+
/** Inlines the logo as a data URL: a standalone SVG cannot load blob, relative or nested URLs. */
|
|
2427
|
+
async function embedImage(scene, options) {
|
|
2428
|
+
const { image } = options;
|
|
2429
|
+
if (!scene.image || !image || image.src.startsWith("data:")) return scene;
|
|
2430
|
+
try {
|
|
2431
|
+
const href = await blobToDataURL(await fetchImage(image, limitsOf(options)));
|
|
2432
|
+
return {
|
|
2433
|
+
...scene,
|
|
2434
|
+
image: {
|
|
2435
|
+
...scene.image,
|
|
2436
|
+
href
|
|
2437
|
+
}
|
|
2438
|
+
};
|
|
2439
|
+
} catch (err) {
|
|
2440
|
+
console.warn(`[qrcodesolid] Failed to embed image: ${image.src}. The SVG keeps the external URL.`, err);
|
|
2441
|
+
return scene;
|
|
2442
|
+
}
|
|
2443
|
+
}
|
|
2444
|
+
function makeCanvas(width, height) {
|
|
2445
|
+
if (typeof OffscreenCanvas !== "undefined") return new OffscreenCanvas(width, height);
|
|
2446
|
+
return Object.assign(document.createElement("canvas"), {
|
|
2447
|
+
width,
|
|
2448
|
+
height
|
|
2449
|
+
});
|
|
2450
|
+
}
|
|
2451
|
+
/** Draws the code onto `canvas`, or onto a new canvas, preferring OffscreenCanvas. */
|
|
2452
|
+
async function toCanvas(options, canvas) {
|
|
2453
|
+
const scene = toScene(options);
|
|
2454
|
+
const image = scene.image && options.image ? await loadImage(options.image, limitsOf(options)) : void 0;
|
|
2455
|
+
const width = Math.round((options.size ?? defaults.size) * (options.scale ?? 1));
|
|
2456
|
+
const height = Math.round(outputSize(scene, width).height);
|
|
2457
|
+
const target = canvas ?? makeCanvas(width, height);
|
|
2458
|
+
Object.assign(target, {
|
|
2459
|
+
width,
|
|
2460
|
+
height
|
|
2461
|
+
});
|
|
2462
|
+
const ctx = target.getContext("2d");
|
|
2463
|
+
if (!ctx) throw new Error("[qrcodesolid] No 2D canvas context.");
|
|
2464
|
+
drawScene(ctx, scene, {
|
|
2465
|
+
scale: width / scene.width,
|
|
2466
|
+
image,
|
|
2467
|
+
resolveColor: colorResolver(options.element)
|
|
2468
|
+
});
|
|
2469
|
+
return target;
|
|
2470
|
+
}
|
|
2471
|
+
/** A PNG of the code. Rejects with a SecurityError when a cross-origin image taints it. */
|
|
2472
|
+
async function toPNGBlob(options) {
|
|
2473
|
+
const canvas = await toCanvas(options);
|
|
2474
|
+
if (!("toBlob" in canvas)) return canvas.convertToBlob({ type: "image/png" });
|
|
2475
|
+
return new Promise((resolve, reject) => canvas.toBlob((blob) => blob ? resolve(blob) : reject(/* @__PURE__ */ new Error("[qrcodesolid] PNG encoding failed.")), "image/png"));
|
|
2476
|
+
}
|
|
2477
|
+
/** A standalone SVG file: colours resolved and the logo embedded. */
|
|
2478
|
+
async function toSVGFile(options) {
|
|
2479
|
+
return serialise(resolveSceneColors(await embedImage(toScene(options), options), options.element), options);
|
|
2480
|
+
}
|
|
2481
|
+
/**
|
|
2482
|
+
* A data URL of the code as PNG or SVG. SVG colours are resolved: a data URL has no page CSS.
|
|
2483
|
+
* The SVG embeds the logo as a data URL, or keeps its URL when the fetch fails.
|
|
2484
|
+
*/
|
|
2485
|
+
async function toDataURL(options, type = "image/png") {
|
|
2486
|
+
if (type === "image/svg+xml") return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(await toSVGFile(options))}`;
|
|
2487
|
+
return blobToDataURL(await toPNGBlob(options));
|
|
2488
|
+
}
|
|
2489
|
+
/** Saves the code as a file. A `.svg` filename saves SVG with the logo embedded, any other saves PNG. */
|
|
2490
|
+
async function download(options, filename = "qrcode.png") {
|
|
2491
|
+
const blob = filename.toLowerCase().endsWith(".svg") ? new Blob([await toSVGFile(options)], { type: "image/svg+xml" }) : await toPNGBlob(options);
|
|
2492
|
+
const url = URL.createObjectURL(blob);
|
|
2493
|
+
const a = Object.assign(document.createElement("a"), {
|
|
2494
|
+
href: url,
|
|
2495
|
+
download: filename
|
|
2496
|
+
});
|
|
2497
|
+
a.style.display = "none";
|
|
2498
|
+
document.body.append(a);
|
|
2499
|
+
a.click();
|
|
2500
|
+
a.remove();
|
|
2501
|
+
setTimeout(() => URL.revokeObjectURL(url), 0);
|
|
2502
|
+
}
|
|
2503
|
+
async function copyToClipboard(options) {
|
|
2504
|
+
await navigator.clipboard.write([new ClipboardItem({ "image/png": toPNGBlob(options) })]);
|
|
2505
|
+
}
|
|
2506
|
+
// src/shapes/bars.ts
|
|
2507
|
+
const inset = .1;
|
|
2508
|
+
const radius = .4;
|
|
2509
|
+
/** Pill for one run of `length` cells. `cross` is the cell column (or row), `start` the run origin. */
|
|
2510
|
+
const pill = (vertical, cross, start, length) => {
|
|
2511
|
+
const c0 = cross + inset;
|
|
2512
|
+
const c1 = cross + 1 - inset;
|
|
2513
|
+
const s0 = start + radius;
|
|
2514
|
+
const s1 = start + length - radius;
|
|
2515
|
+
const p = (c, s) => vertical ? `${coord(c)} ${coord(s)}` : `${coord(s)} ${coord(c)}`;
|
|
2516
|
+
const arc = `A${radius} ${radius} 0 0 ${vertical ? 1 : 0}`;
|
|
2517
|
+
return `M${p(c0, s0)}${arc} ${p(c1, s0)}L${p(c1, s1)}${arc} ${p(c0, s1)}z`;
|
|
2518
|
+
};
|
|
2519
|
+
function bars(vertical) {
|
|
2520
|
+
return defineLayerShape(({ matrix: m, include, offset }) => {
|
|
2521
|
+
const on = (a, b) => {
|
|
2522
|
+
const [x, y] = vertical ? [a, b] : [b, a];
|
|
2523
|
+
return include(x, y) && isDark(m, x, y);
|
|
2524
|
+
};
|
|
2525
|
+
const solid = (a, b) => {
|
|
2526
|
+
const [x, y] = vertical ? [a, b] : [b, a];
|
|
2527
|
+
return m.region[y * m.size + x] === Region.Alignment;
|
|
2528
|
+
};
|
|
2529
|
+
let d = "";
|
|
2530
|
+
for (let a = 0; a < m.size; a++) {
|
|
2531
|
+
let b = 0;
|
|
2532
|
+
while (b < m.size) {
|
|
2533
|
+
if (!on(a, b)) {
|
|
2534
|
+
b++;
|
|
2535
|
+
continue;
|
|
2536
|
+
}
|
|
2537
|
+
const start = b;
|
|
2538
|
+
if (solid(a, b)) {
|
|
2539
|
+
b++;
|
|
2540
|
+
const [x, y] = vertical ? [a, start] : [start, a];
|
|
2541
|
+
d += `M${coord(x + offset.x)} ${coord(y + offset.y)}h1v1h-1z`;
|
|
2542
|
+
continue;
|
|
2543
|
+
}
|
|
2544
|
+
while (b < m.size && on(a, b) && !solid(a, b)) b++;
|
|
2545
|
+
const cross = (vertical ? offset.x : offset.y) + a;
|
|
2546
|
+
d += pill(vertical, cross, (vertical ? offset.y : offset.x) + start, b - start);
|
|
2547
|
+
}
|
|
2548
|
+
}
|
|
2549
|
+
return d;
|
|
2550
|
+
});
|
|
2551
|
+
}
|
|
2552
|
+
const verticalBars = bars(true);
|
|
2553
|
+
const horizontalBars = bars(false);
|
|
2554
|
+
// src/shapes/frames.ts
|
|
2555
|
+
const fontFamily = "system-ui, sans-serif";
|
|
2556
|
+
/** Moves the code by `pad` and grows the layout by `pad` on every side. */
|
|
2557
|
+
const grow = ({ width, height, qr }, pad) => ({
|
|
2558
|
+
width: width + 2 * pad,
|
|
2559
|
+
height: height + 2 * pad,
|
|
2560
|
+
qr: {
|
|
2561
|
+
...qr,
|
|
2562
|
+
x: qr.x + pad,
|
|
2563
|
+
y: qr.y + pad
|
|
2564
|
+
}
|
|
2565
|
+
});
|
|
2566
|
+
/** A ring of `width` modules around the code. Default colour is fg. */
|
|
2567
|
+
function border(o = {}) {
|
|
2568
|
+
const { width: w = 1, radius = 0, color = "fg" } = o;
|
|
2569
|
+
return (inner) => {
|
|
2570
|
+
const layout = grow(inner, w);
|
|
2571
|
+
return {
|
|
2572
|
+
layout,
|
|
2573
|
+
paths: [{
|
|
2574
|
+
id: "frame-border",
|
|
2575
|
+
d: rect(0, 0, layout.width, layout.height, radius) + rect(w, w, inner.width, inner.height, Math.max(radius - w, 0)),
|
|
2576
|
+
fillRule: "evenodd",
|
|
2577
|
+
paint: color
|
|
2578
|
+
}],
|
|
2579
|
+
texts: []
|
|
2580
|
+
};
|
|
2581
|
+
};
|
|
2582
|
+
}
|
|
2583
|
+
/** A rounded panel `padding` modules wider than the code on every side. */
|
|
2584
|
+
function card(o = {}) {
|
|
2585
|
+
const { padding = 2, radius = 2, color = "#fff" } = o;
|
|
2586
|
+
return (inner) => {
|
|
2587
|
+
const layout = grow(inner, padding);
|
|
2588
|
+
return {
|
|
2589
|
+
layout,
|
|
2590
|
+
paths: [{
|
|
2591
|
+
id: "frame-card",
|
|
2592
|
+
d: rect(0, 0, layout.width, layout.height, radius),
|
|
2593
|
+
paint: color
|
|
2594
|
+
}],
|
|
2595
|
+
texts: []
|
|
2596
|
+
};
|
|
2597
|
+
};
|
|
2598
|
+
}
|
|
2599
|
+
/**
|
|
2600
|
+
* A band with a label above or below the code, outside its quiet zone.
|
|
2601
|
+
* Long text shrinks to fit the width, down to 1 module, and the band shrinks with it.
|
|
2602
|
+
*/
|
|
2603
|
+
function banner(o) {
|
|
2604
|
+
const { text, position = "bottom", color = "#000", textColor = "#fff" } = o;
|
|
2605
|
+
return ({ width, height, qr }) => {
|
|
2606
|
+
const fitted = fitFontSize(text, o.fontSize ?? 2, width);
|
|
2607
|
+
const { fontSize } = fitted;
|
|
2608
|
+
const warning = overflowWarning("banner text", text, fitted, width, "the banner");
|
|
2609
|
+
const band = fontSize * 2;
|
|
2610
|
+
const top = position === "top";
|
|
2611
|
+
const y = top ? 0 : height;
|
|
2612
|
+
const label = {
|
|
2613
|
+
text,
|
|
2614
|
+
x: width / 2,
|
|
2615
|
+
y: y + band / 2,
|
|
2616
|
+
fontSize,
|
|
2617
|
+
fontFamily,
|
|
2618
|
+
fontWeight: "bold",
|
|
2619
|
+
paint: textColor
|
|
2620
|
+
};
|
|
2621
|
+
return {
|
|
2622
|
+
layout: {
|
|
2623
|
+
width,
|
|
2624
|
+
height: height + band,
|
|
2625
|
+
qr: top ? {
|
|
2626
|
+
...qr,
|
|
2627
|
+
y: qr.y + band
|
|
2628
|
+
} : qr
|
|
2629
|
+
},
|
|
2630
|
+
paths: [{
|
|
2631
|
+
id: "frame-banner",
|
|
2632
|
+
d: rect(0, y, width, band, 0),
|
|
2633
|
+
paint: color
|
|
2634
|
+
}],
|
|
2635
|
+
texts: [label],
|
|
2636
|
+
warnings: warning ? [warning] : []
|
|
2637
|
+
};
|
|
2638
|
+
};
|
|
2639
|
+
}
|
|
2640
|
+
export { QRCapacityError, QRCode, QRCodeCanvas, QRCodeSVG, Region, banner, border, card, copyToClipboard, createColorScheme, createPixelRatio, createQRCode, defineLayerShape, defineModuleShape, diamond, dots, download, drawScene, encode, finderInner, finderOuter, getFinder, horizontalBars, isDark, resolveSceneColors, rounded, sceneToSVGString, square, toCanvas, toDataURL, toPNGBlob, toSVGString, toScene, verticalBars };
|