qrdx 0.0.60 → 0.0.62

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.
Files changed (102) hide show
  1. package/README.md +3 -2
  2. package/dist/angular.js +7 -2
  3. package/dist/angular.js.map +1 -1
  4. package/dist/angular.mjs +7 -2
  5. package/dist/angular.mjs.map +1 -1
  6. package/dist/core.js +7 -7
  7. package/dist/core.js.map +1 -1
  8. package/dist/core.mjs +7 -7
  9. package/dist/core.mjs.map +1 -1
  10. package/dist/element.browser.mjs +6 -6
  11. package/dist/element.browser.mjs.map +1 -1
  12. package/dist/element.js +1 -1
  13. package/dist/element.js.map +1 -1
  14. package/dist/element.mjs +1 -1
  15. package/dist/element.mjs.map +1 -1
  16. package/dist/index.js +7 -7
  17. package/dist/index.js.map +1 -1
  18. package/dist/index.mjs +7 -7
  19. package/dist/index.mjs.map +1 -1
  20. package/dist/node.js +2 -2
  21. package/dist/node.js.map +1 -1
  22. package/dist/node.mjs +2 -2
  23. package/dist/node.mjs.map +1 -1
  24. package/dist/qr-code-canvas.js +1 -1
  25. package/dist/qr-code-canvas.js.map +1 -1
  26. package/dist/qr-code-canvas.mjs +1 -1
  27. package/dist/qr-code-canvas.mjs.map +1 -1
  28. package/dist/schemas.js +1 -1
  29. package/dist/schemas.js.map +1 -1
  30. package/dist/schemas.mjs +1 -1
  31. package/dist/schemas.mjs.map +1 -1
  32. package/dist/src/angular.d.ts +2 -1
  33. package/dist/src/api.d.ts +2 -3
  34. package/dist/src/api.d.ts.map +1 -1
  35. package/dist/src/element.d.ts +2 -0
  36. package/dist/src/element.d.ts.map +1 -1
  37. package/dist/src/helpers.d.ts +2 -2
  38. package/dist/src/helpers.d.ts.map +1 -1
  39. package/dist/src/logo-budget.d.ts +3 -1
  40. package/dist/src/logo-budget.d.ts.map +1 -1
  41. package/dist/src/looks.d.ts +2 -2
  42. package/dist/src/looks.d.ts.map +1 -1
  43. package/dist/src/plain.d.ts.map +1 -1
  44. package/dist/src/print.d.ts.map +1 -1
  45. package/dist/src/qr-code-canvas.d.ts +2 -8
  46. package/dist/src/qr-code-canvas.d.ts.map +1 -1
  47. package/dist/src/qr-code-props.d.ts +1 -1
  48. package/dist/src/qr-code-props.d.ts.map +1 -1
  49. package/dist/src/qr-code-svg.d.ts +2 -3
  50. package/dist/src/qr-code-svg.d.ts.map +1 -1
  51. package/dist/src/qr-code.d.ts +2 -2
  52. package/dist/src/qr-code.d.ts.map +1 -1
  53. package/dist/src/qr-frame-svg.d.ts +2 -3
  54. package/dist/src/qr-frame-svg.d.ts.map +1 -1
  55. package/dist/src/rasterize.d.ts +8 -0
  56. package/dist/src/rasterize.d.ts.map +1 -1
  57. package/dist/src/react-elements.d.ts.map +1 -1
  58. package/dist/src/scan-score.d.ts +34 -0
  59. package/dist/src/scan-score.d.ts.map +1 -1
  60. package/dist/src/symbol.d.ts +13 -0
  61. package/dist/src/symbol.d.ts.map +1 -0
  62. package/dist/src/utils/print-shared.d.ts.map +1 -1
  63. package/dist/src/utils.d.ts +1 -0
  64. package/dist/src/utils.d.ts.map +1 -1
  65. package/dist/src/vue.d.ts.map +1 -1
  66. package/dist/types/index.js +1 -1
  67. package/dist/types/index.js.map +1 -1
  68. package/dist/types/index.mjs +1 -1
  69. package/dist/types/index.mjs.map +1 -1
  70. package/dist/types/qr.d.ts +2 -0
  71. package/dist/types/qr.d.ts.map +1 -1
  72. package/dist/types/react.d.ts +21 -3
  73. package/dist/types/react.d.ts.map +1 -1
  74. package/dist/vanilla.browser.mjs +16 -16
  75. package/dist/vanilla.browser.mjs.map +1 -1
  76. package/dist/vue.js +1 -1
  77. package/dist/vue.js.map +1 -1
  78. package/dist/vue.mjs +1 -1
  79. package/dist/vue.mjs.map +1 -1
  80. package/package.json +4 -6
  81. package/src/angular.ts +2 -0
  82. package/src/api.tsx +3 -4
  83. package/src/element.ts +3 -0
  84. package/src/helpers.ts +27 -10
  85. package/src/logo-budget.ts +9 -8
  86. package/src/looks.ts +17 -14
  87. package/src/plain.tsx +5 -7
  88. package/src/print.ts +3 -6
  89. package/src/qr-code-canvas.tsx +39 -34
  90. package/src/qr-code-props.ts +4 -0
  91. package/src/qr-code-svg.tsx +3 -4
  92. package/src/qr-code.tsx +7 -5
  93. package/src/qr-frame-svg.tsx +3 -4
  94. package/src/rasterize.ts +14 -1
  95. package/src/react-elements.ts +40 -2
  96. package/src/scan-score.ts +225 -51
  97. package/src/symbol.ts +27 -0
  98. package/src/utils/print-shared.ts +5 -9
  99. package/src/utils.tsx +9 -9
  100. package/src/vue.ts +1 -0
  101. package/types/qr.ts +6 -0
  102. package/types/react.ts +22 -3
@@ -1,5 +1,4 @@
1
- import type { JSX } from "react";
2
- import type { QRPropsSVG } from "../types/react";
1
+ import type { QRPropsSVG, ReactQRElement } from "../types/react";
3
2
  import { withElementFactory } from "./jsx/runtime";
4
3
  import { REACT_ELEMENTS } from "./react-elements";
5
4
  import { createQRCodeTree } from "./utils";
@@ -10,8 +9,8 @@ import { createQRCodeTree } from "./utils";
10
9
  * markup is exactly `toSVGString`'s. No hooks: it renders in React Server
11
10
  * Components too.
12
11
  */
13
- export function QRCodeSVG(props: QRPropsSVG): JSX.Element {
12
+ export function QRCodeSVG(props: QRPropsSVG): ReactQRElement {
14
13
  return withElementFactory(REACT_ELEMENTS, () =>
15
14
  createQRCodeTree(props)
16
- ) as unknown as JSX.Element;
15
+ ) as unknown as ReactQRElement;
17
16
  }
package/src/qr-code.tsx CHANGED
@@ -1,7 +1,9 @@
1
1
  // memo/useMemo are available in React Server Components, so QRCode can render
2
- // on the server; only QRCodeCanvas needs a client boundary.
3
- import { memo, useMemo } from "react";
4
- import type { QRCodePropsSVG } from "../types/react";
2
+ // on the server; only QRCodeCanvas needs a client boundary. createElement
3
+ // rather than JSX: compiled JSX would import react/jsx-runtime, which React
4
+ // has had only since 16.14.
5
+ import { createElement, memo, useMemo } from "react";
6
+ import type { QRCodePropsSVG, ReactQRElement } from "../types/react";
5
7
  import {
6
8
  getQRCodeData,
7
9
  getQRCodeSVGProps,
@@ -14,14 +16,14 @@ import { QRCodeSVG } from "./qr-code-svg";
14
16
  * `scale`). Any other prop (`className`, `aria-label`, `role`, `data-*`…)
15
17
  * goes on the `<svg>`, as with `QRCodeSVG`.
16
18
  */
17
- export const QRCode = memo((props: QRCodePropsSVG) => {
19
+ export const QRCode = memo((props: QRCodePropsSVG): ReactQRElement => {
18
20
  const qrData = useMemo(
19
21
  () => getQRCodeData(props),
20
22
  // biome-ignore lint/correctness/useExhaustiveDependencies: the layout reads exactly these props (QR_CODE_DATA_KEYS, the list getQRCodeData lays out from)
21
23
  QR_CODE_DATA_KEYS.map((key) => props[key])
22
24
  );
23
25
 
24
- return <QRCodeSVG {...getQRCodeSVGProps(props, qrData)} />;
26
+ return createElement(QRCodeSVG, getQRCodeSVGProps(props, qrData));
25
27
  });
26
28
 
27
29
  QRCode.displayName = "QRCode";
@@ -1,5 +1,4 @@
1
- import type { JSX } from "react";
2
- import type { QRFrameSVGProps } from "../types/react";
1
+ import type { QRFrameSVGProps, ReactQRElement } from "../types/react";
3
2
  import { createFrameTree } from "./frame";
4
3
  import { type QRNode, withElementFactory } from "./jsx/runtime";
5
4
  import { REACT_ELEMENTS } from "./react-elements";
@@ -16,11 +15,11 @@ export function QRFrameSVG({
16
15
  bgColor,
17
16
  slot,
18
17
  ...svgProps
19
- }: QRFrameSVGProps): JSX.Element {
18
+ }: QRFrameSVGProps): ReactQRElement {
20
19
  // Drawn with React's elements, the tree's nodes are React elements: the
21
20
  // slot is placed with React's cloneElement.
22
21
  const node = slot as unknown as QRNode | undefined;
23
22
  return withElementFactory(REACT_ELEMENTS, () =>
24
23
  createFrameTree({ frame, size, bgColor, slot: node, svgProps })
25
- ) as unknown as JSX.Element;
24
+ ) as unknown as ReactQRElement;
26
25
  }
package/src/rasterize.ts CHANGED
@@ -203,10 +203,23 @@ export async function rasterizeSvgToPng(
203
203
  }
204
204
  // fitTo "original" (the default) renders at the SVG's own width and
205
205
  // height, so the PNG is exactly as large as the SVG markup says.
206
- const rendered = new Resvg(svg).render();
206
+ const rendered = new Resvg(svg, {
207
+ font: { loadSystemFonts: svgNeedsFonts(svg) },
208
+ }).render();
207
209
  return new Uint8Array(rendered.asPng());
208
210
  }
209
211
 
212
+ /**
213
+ * Whether drawing `svg` can need a font: it has text (a frame's label) or
214
+ * embeds an SVG image (a logo, which may have text of its own). resvg reads
215
+ * every system font each time it's created when asked to (about 50 ms on a
216
+ * Mac, the most of a plain code's render), and nothing else in a code needs
217
+ * them.
218
+ */
219
+ export function svgNeedsFonts(svg: string): boolean {
220
+ return svg.includes("<text") || svg.includes("image/svg+xml");
221
+ }
222
+
210
223
  const describeError = (error: unknown) =>
211
224
  error instanceof Error ? error.message : String(error);
212
225
 
@@ -1,13 +1,51 @@
1
1
  // React's element functions, plugged into the renderer (jsx/runtime.ts) when
2
2
  // a React component draws the code, so it builds React elements directly.
3
+ // Only `createElement`, never react/jsx-runtime, which React has had only
4
+ // since 16.14: the React entry works from React 16.8.
3
5
  import { cloneElement, createElement, Fragment } from "react";
4
- import { jsx, jsxs } from "react/jsx-runtime";
5
6
  import type { ElementFactory } from "./jsx/runtime";
6
7
 
8
+ const createReactElement: ElementFactory["createElement"] = createElement;
9
+
10
+ /** The props without their children, with the key in them if there is one. */
11
+ function configOf(props: object | null, key: unknown) {
12
+ const { children: _children, ...config } = (props ?? {}) as {
13
+ children?: unknown;
14
+ };
15
+ return key === undefined ? config : { ...config, key };
16
+ }
17
+
18
+ /**
19
+ * The automatic runtime's `jsx(type, props, key)` through `createElement`.
20
+ * The children go in as `createElement`'s argument, not inside the props:
21
+ * every React checks the keys of children passed that way exactly as `jsx`
22
+ * checks its `props.children`.
23
+ */
24
+ const jsx: ElementFactory["jsx"] = (type, props, key) =>
25
+ props && "children" in props
26
+ ? createReactElement(
27
+ type,
28
+ configOf(props, key),
29
+ (props as { children: unknown }).children
30
+ )
31
+ : createReactElement(type, configOf(props, key));
32
+
33
+ /**
34
+ * `jsxs`, for children written out in the source (a static array): each
35
+ * child is an argument of its own, as compiled classic JSX passes them, so
36
+ * no React asks them for keys, as with `jsxs`.
37
+ */
38
+ const jsxs: ElementFactory["jsxs"] = (type, props, key) => {
39
+ const children = (props as { children?: unknown } | null)?.children;
40
+ return Array.isArray(children)
41
+ ? createReactElement(type, configOf(props, key), ...children)
42
+ : jsx(type, props, key);
43
+ };
44
+
7
45
  export const REACT_ELEMENTS: ElementFactory = {
8
46
  jsx,
9
47
  jsxs,
10
- createElement,
48
+ createElement: createReactElement,
11
49
  cloneElement: cloneElement as ElementFactory["cloneElement"],
12
50
  Fragment,
13
51
  };
package/src/scan-score.ts CHANGED
@@ -4,13 +4,11 @@ import type { ColorConfig, QRProps } from "../types";
4
4
  import { normalizeColorConfig } from "../types/color-helpers";
5
5
  import { EYE_POSITIONS } from "../types/constants";
6
6
  import type { QRArtPixels } from "./art";
7
- import qrcodegen from "./codegen";
8
7
  import {
9
8
  DEFAULT_BGCOLOR,
10
9
  DEFAULT_FGCOLOR,
11
10
  DEFAULT_MARGIN,
12
11
  DEFAULT_SIZE,
13
- ERROR_LEVEL_MAP,
14
12
  } from "./constants";
15
13
  import { handleImageLoad } from "./detection";
16
14
  import { withQRSize } from "./download";
@@ -24,6 +22,7 @@ import {
24
22
  weakestEyePattern,
25
23
  } from "./looks";
26
24
  import { circleQuietZone, getLayoutMargin, isShapedCode } from "./qr-shape";
25
+ import { encodeSymbol } from "./symbol";
27
26
  import { getTemplateCodeShare } from "./template-placement";
28
27
  import { getImageSettings, getLuminance, resolveErrorLevel } from "./utils";
29
28
  import { parseColor, type RGBAColor } from "./utils/parse-color";
@@ -110,21 +109,75 @@ function matches(result: JsQRResult | null, value: string): boolean {
110
109
 
111
110
  /**
112
111
  * Camera-like degradation, in place: contrast loss plus a blur of about a
113
- * quarter module (two box-blur passes approximate a Gaussian).
112
+ * quarter module (two box-blur passes approximate a Gaussian). Each channel
113
+ * is rounded to a byte after every step, as drawing would.
114
114
  */
115
115
  function simulateCamera(image: ImageData, modulePx: number, contrast = 0.7) {
116
116
  const { data, width, height } = image;
117
- for (let i = 0; i < data.length; i += 4) {
118
- for (let c = 0; c < 3; c++) {
119
- data[i + c] = 128 + ((data[i + c] as number) - 128) * contrast;
117
+ const count = width * height;
118
+ const radius = Math.max(1, Math.round(modulePx * 0.25));
119
+ // Grey artwork (black on white, anti-aliased to greys) has one channel's
120
+ // worth of values: blur it once and copy it out, a third of the work. The
121
+ // bytes are exactly those blurring red, green and blue gives.
122
+ const grey = greyChannel(data, count);
123
+ if (grey) {
124
+ for (let p = 0; p < count; p++) {
125
+ grey[p] = 128 + ((grey[p] as number) - 128) * contrast;
126
+ }
127
+ boxBlur(grey, width, height, radius);
128
+ for (let p = 0, i = 0; p < count; p++, i += 4) {
129
+ const value = grey[p] as number;
130
+ data[i] = value;
131
+ data[i + 1] = value;
132
+ data[i + 2] = value;
133
+ }
134
+ return;
135
+ }
136
+ // Colours: each channel on its own plane (the same arithmetic, read and
137
+ // written in order rather than every fourth byte).
138
+ const plane = new Uint8ClampedArray(count);
139
+ for (let c = 0; c < 3; c++) {
140
+ for (let p = 0, i = c; p < count; p++, i += 4) {
141
+ plane[p] = 128 + ((data[i] as number) - 128) * contrast;
142
+ }
143
+ boxBlur(plane, width, height, radius);
144
+ for (let p = 0, i = c; p < count; p++, i += 4) {
145
+ data[i] = plane[p] as number;
120
146
  }
121
147
  }
122
- const radius = Math.max(1, Math.round(modulePx * 0.25));
148
+ }
149
+
150
+ /** The red channel when every pixel is grey (red = green = blue), else null. */
151
+ function greyChannel(
152
+ data: Uint8ClampedArray,
153
+ count: number
154
+ ): Uint8ClampedArray | null {
155
+ const grey = new Uint8ClampedArray(count);
156
+ for (let p = 0, i = 0; p < count; p++, i += 4) {
157
+ const red = data[i] as number;
158
+ if (red !== data[i + 1] || red !== data[i + 2]) {
159
+ return null;
160
+ }
161
+ grey[p] = red;
162
+ }
163
+ return grey;
164
+ }
165
+
166
+ /**
167
+ * Two passes of a box blur `2 * radius + 1` wide, across then down, on one
168
+ * channel in place, rounding to a byte after each. Sliding window with
169
+ * clamped edges: pixel (line, position) is `line * lineStep + position *
170
+ * step`, and the sum is a plain local (this runs up to nine times a score,
171
+ * on every pixel).
172
+ */
173
+ function boxBlur(
174
+ channel: Uint8ClampedArray,
175
+ width: number,
176
+ height: number,
177
+ radius: number
178
+ ) {
123
179
  const span = 2 * radius + 1;
124
- const buffer = new Float32Array(width * height * 3);
125
- // Sliding window with clamped edges. Pixel (line, position) is
126
- // `line * lineStep + position * step`; the sums are plain locals (this
127
- // runs nine times a score, on every pixel).
180
+ const buffer = new Float32Array(width * height);
128
181
  const blur = (horizontal: boolean) => {
129
182
  const lines = horizontal ? height : width;
130
183
  const length = horizontal ? width : height;
@@ -132,33 +185,24 @@ function simulateCamera(image: ImageData, modulePx: number, contrast = 0.7) {
132
185
  const step = horizontal ? 1 : width;
133
186
  for (let line = 0; line < lines; line++) {
134
187
  const start = line * lineStep;
135
- let red = 0;
136
- let green = 0;
137
- let blue = 0;
188
+ let sum = 0;
138
189
  for (let k = -radius; k <= radius; k++) {
139
- const p = (start + Math.min(Math.max(k, 0), length - 1) * step) * 4;
140
- red += data[p] as number;
141
- green += data[p + 1] as number;
142
- blue += data[p + 2] as number;
190
+ sum += channel[
191
+ start + Math.min(Math.max(k, 0), length - 1) * step
192
+ ] as number;
143
193
  }
144
194
  for (let position = 0; position < length; position++) {
145
- const target = (start + position * step) * 3;
146
- buffer[target] = red / span;
147
- buffer[target + 1] = green / span;
148
- buffer[target + 2] = blue / span;
149
- const out = (start + Math.max(position - radius, 0) * step) * 4;
150
- const into =
151
- (start + Math.min(position + radius + 1, length - 1) * step) * 4;
152
- red = red - (data[out] as number) + (data[into] as number);
153
- green = green - (data[out + 1] as number) + (data[into + 1] as number);
154
- blue = blue - (data[out + 2] as number) + (data[into + 2] as number);
195
+ buffer[start + position * step] = sum / span;
196
+ sum =
197
+ sum -
198
+ (channel[start + Math.max(position - radius, 0) * step] as number) +
199
+ (channel[
200
+ start + Math.min(position + radius + 1, length - 1) * step
201
+ ] as number);
155
202
  }
156
203
  }
157
- for (let i = 0, o = 0; i < width * height * 3; i += 3, o += 4) {
158
- data[o] = buffer[i] as number;
159
- data[o + 1] = buffer[i + 1] as number;
160
- data[o + 2] = buffer[i + 2] as number;
161
- }
204
+ // Rounds and clamps each value to a byte, as assigning one does
205
+ channel.set(buffer);
162
206
  };
163
207
  for (let pass = 0; pass < 2; pass++) {
164
208
  blur(true);
@@ -182,10 +226,16 @@ function createCanvas(width: number, height: number) {
182
226
  // A phone tries many frames at slightly different distances.
183
227
  const ATTEMPT_SCALES = [0.9, 1, 1.1];
184
228
 
229
+ /** Code widths (px) `decodeAtSize` draws for `size`, in the order it tries them. */
230
+ function attemptWidths(size: number): number[] {
231
+ return ATTEMPT_SCALES.map((scale) => size * scale);
232
+ }
233
+
185
234
  /**
186
235
  * Decodes the code at `size` px wide a few times at slightly different
187
236
  * scales through the camera simulation. `draw` returns the pixels with the
188
- * code `codeWidth` px wide.
237
+ * code `codeWidth` px wide. Two hits are a pass whatever the rest would
238
+ * read, so it stops there.
189
239
  */
190
240
  function decodeAtSize(
191
241
  jsQR: Decoder,
@@ -195,12 +245,14 @@ function decodeAtSize(
195
245
  expected: (result: JsQRResult | null) => boolean
196
246
  ): DecodeState {
197
247
  let hits = 0;
198
- for (const scale of ATTEMPT_SCALES) {
199
- const codeWidth = size * scale;
248
+ for (const codeWidth of attemptWidths(size)) {
200
249
  const image = draw(codeWidth);
201
250
  simulateCamera(image, codeWidth / moduleCount);
202
251
  if (expected(jsQR(image.data, image.width, image.height))) {
203
252
  hits++;
253
+ if (hits >= 2) {
254
+ break;
255
+ }
204
256
  }
205
257
  }
206
258
  if (hits >= 2) {
@@ -649,9 +701,10 @@ function contrastChecks(
649
701
  }
650
702
 
651
703
  function moduleCount(props: QRProps) {
652
- return qrcodegen.QrCode.encodeText(
704
+ return encodeSymbol(
653
705
  props.value,
654
- ERROR_LEVEL_MAP[resolveErrorLevel(props)]
706
+ resolveErrorLevel(props),
707
+ props.exactLevel
655
708
  ).getModules();
656
709
  }
657
710
 
@@ -724,6 +777,7 @@ function logoCheck(props: QRProps): {
724
777
  margin: props.margin ?? DEFAULT_MARGIN,
725
778
  level,
726
779
  shape: props.shape,
780
+ exactLevel: props.exactLevel,
727
781
  },
728
782
  imageSettings
729
783
  );
@@ -1053,6 +1107,97 @@ export async function getScanScore(
1053
1107
  options: ScanScoreOptions = {}
1054
1108
  ): Promise<ScanScoreResult> {
1055
1109
  assertBrowser();
1110
+ const { draw, sizes, imageTones } = await prepareScan(props, options);
1111
+ return await scoreArtwork(props, draw, sizes, options.signal, imageTones);
1112
+ }
1113
+
1114
+ /**
1115
+ * One frame `getScanScore` decodes: the artwork on white with the code
1116
+ * `codeWidth` px wide, before the camera model.
1117
+ */
1118
+ export interface ScanFrame {
1119
+ codeWidth: number;
1120
+ width: number;
1121
+ height: number;
1122
+ /** RGBA bytes, `width × height × 4` */
1123
+ data: Uint8ClampedArray;
1124
+ }
1125
+
1126
+ export interface ScanFrames {
1127
+ /** The test sizes, smallest first */
1128
+ sizes: number[];
1129
+ /** Every frame the score may decode, smallest code first */
1130
+ frames: ScanFrame[];
1131
+ /** Tones of the images the design paints with, for the contrast checks */
1132
+ imageTones: ImageToneMap;
1133
+ }
1134
+
1135
+ /**
1136
+ * The frames `getScanScore` decodes, drawn on the page's canvas (browser
1137
+ * only), for `getScanScoreFromFrames` to score somewhere else, such as a Web
1138
+ * Worker: drawing is quick native work, and the camera model and decoding
1139
+ * are what keep the page busy. It can be posted as it is (transfer each
1140
+ * frame's `data.buffer` to skip the copy).
1141
+ */
1142
+ export async function drawScanFrames(
1143
+ props: QRProps,
1144
+ options: ScanScoreOptions = {}
1145
+ ): Promise<ScanFrames> {
1146
+ assertBrowser();
1147
+ const { draw, sizes, imageTones } = await prepareScan(props, options);
1148
+ const frames = sizes.flatMap((size) =>
1149
+ attemptWidths(size).map((codeWidth) => {
1150
+ const { data, width, height } = draw(codeWidth);
1151
+ return { codeWidth, width, height, data };
1152
+ })
1153
+ );
1154
+ return { sizes, frames, imageTones };
1155
+ }
1156
+
1157
+ /**
1158
+ * `getScanScore`'s result from the frames `drawScanFrames` drew for the same
1159
+ * props. Needs no DOM, so it runs in a Web Worker. The frames aren't changed
1160
+ * (each is copied before the camera model blurs it), so they can be scored
1161
+ * again.
1162
+ */
1163
+ export async function getScanScoreFromFrames(
1164
+ props: QRProps,
1165
+ scan: ScanFrames,
1166
+ options: Pick<ScanScoreOptions, "signal"> = {}
1167
+ ): Promise<ScanScoreResult> {
1168
+ const byWidth = new Map(scan.frames.map((frame) => [frame.codeWidth, frame]));
1169
+ const draw = (codeWidth: number) => {
1170
+ const frame = byWidth.get(codeWidth);
1171
+ if (!frame || frame.data.length < frame.width * frame.height * 4) {
1172
+ throw new Error(
1173
+ `No scan frame with the code ${codeWidth} px wide: draw the frames with drawScanFrames for these props and sizes`
1174
+ );
1175
+ }
1176
+ return {
1177
+ data: new Uint8ClampedArray(frame.data),
1178
+ width: frame.width,
1179
+ height: frame.height,
1180
+ colorSpace: "srgb",
1181
+ } as ImageData;
1182
+ };
1183
+ return await scoreArtwork(
1184
+ props,
1185
+ draw,
1186
+ scan.sizes,
1187
+ options.signal,
1188
+ scan.imageTones
1189
+ );
1190
+ }
1191
+
1192
+ /**
1193
+ * What `getScanScore` does on the page before decoding: logos and image
1194
+ * fills inlined, the images' tones read and the artwork loaded, with a
1195
+ * `draw` that puts it on white at any code width.
1196
+ */
1197
+ async function prepareScan(
1198
+ props: QRProps,
1199
+ options: ScanScoreOptions
1200
+ ): Promise<{ draw: DrawArtwork; sizes: number[]; imageTones: ImageToneMap }> {
1056
1201
  const { signal } = options;
1057
1202
  const sizes = testSizes(options);
1058
1203
 
@@ -1096,7 +1241,7 @@ export async function getScanScore(
1096
1241
  canvas.remove();
1097
1242
  return image;
1098
1243
  };
1099
- return await scoreArtwork(props, drawArtwork, sizes, signal, imageTones);
1244
+ return { draw: drawArtwork, sizes, imageTones };
1100
1245
  }
1101
1246
 
1102
1247
  /**
@@ -1134,9 +1279,10 @@ export async function getScanScoreFromPixels(
1134
1279
  const sourceCodeWidth =
1135
1280
  (width * size * getTemplateCodeShare(props)) / artwork.width;
1136
1281
  const source = { data: onWhite(pixels), width, height };
1282
+ const grey = isGrey(source.data);
1137
1283
 
1138
1284
  const drawArtwork = (codeWidth: number) => {
1139
- const art = resizePixels(source, codeWidth / sourceCodeWidth);
1285
+ const art = resizePixels(source, codeWidth / sourceCodeWidth, grey);
1140
1286
  const pad = Math.max(8, Math.round(codeWidth * 0.12));
1141
1287
  return padWhite(art, pad);
1142
1288
  };
@@ -1569,10 +1715,26 @@ export interface PixelScanResult {
1569
1715
  /** Code widths (px) `scanQRPixels` checks through the camera model. */
1570
1716
  export const PIXEL_SCAN_SIZES = [320] as const;
1571
1717
 
1572
- /** Area-average resize of RGBA pixels by `scale` (at most 1). */
1718
+ /** True when every pixel is grey (red = green = blue). */
1719
+ function isGrey(data: Uint8ClampedArray): boolean {
1720
+ for (let i = 0; i < data.length; i += 4) {
1721
+ if (data[i] !== data[i + 1] || data[i] !== data[i + 2]) {
1722
+ return false;
1723
+ }
1724
+ }
1725
+ return true;
1726
+ }
1727
+
1728
+ /**
1729
+ * Area-average resize of RGBA pixels by `scale` (at most 1), for decoding:
1730
+ * the result is opaque (alpha isn't averaged; jsQR doesn't read it). With
1731
+ * `grey` (every source pixel grey, see `isGrey`) only red is averaged and
1732
+ * copied to green and blue, which is what averaging each gives.
1733
+ */
1573
1734
  function resizePixels(
1574
1735
  source: { data: Uint8ClampedArray; width: number; height: number },
1575
- scale: number
1736
+ scale: number,
1737
+ grey = false
1576
1738
  ): ImageData {
1577
1739
  const factor = Math.min(1, scale);
1578
1740
  const width = Math.max(1, Math.round(source.width * factor));
@@ -1580,6 +1742,7 @@ function resizePixels(
1580
1742
  const out = new Uint8ClampedArray(width * height * 4);
1581
1743
  const stepX = source.width / width;
1582
1744
  const stepY = source.height / height;
1745
+ const { data } = source;
1583
1746
  for (let y = 0; y < height; y++) {
1584
1747
  const y0 = Math.floor(y * stepY);
1585
1748
  const y1 = Math.max(
@@ -1592,26 +1755,36 @@ function resizePixels(
1592
1755
  x0 + 1,
1593
1756
  Math.min(source.width, Math.floor((x + 1) * stepX))
1594
1757
  );
1758
+ const count = (y1 - y0) * (x1 - x0);
1759
+ const o = (y * width + x) * 4;
1595
1760
  // Plain locals, not an array: this runs on every output pixel
1596
1761
  let red = 0;
1762
+ if (grey) {
1763
+ for (let sy = y0; sy < y1; sy++) {
1764
+ for (let sx = x0; sx < x1; sx++) {
1765
+ red += data[(sy * source.width + sx) * 4] as number;
1766
+ }
1767
+ }
1768
+ out[o] = red / count;
1769
+ out[o + 1] = out[o] as number;
1770
+ out[o + 2] = out[o] as number;
1771
+ out[o + 3] = 255;
1772
+ continue;
1773
+ }
1597
1774
  let green = 0;
1598
1775
  let blue = 0;
1599
- let alpha = 0;
1600
1776
  for (let sy = y0; sy < y1; sy++) {
1601
1777
  for (let sx = x0; sx < x1; sx++) {
1602
1778
  const i = (sy * source.width + sx) * 4;
1603
- red += source.data[i] as number;
1604
- green += source.data[i + 1] as number;
1605
- blue += source.data[i + 2] as number;
1606
- alpha += source.data[i + 3] as number;
1779
+ red += data[i] as number;
1780
+ green += data[i + 1] as number;
1781
+ blue += data[i + 2] as number;
1607
1782
  }
1608
1783
  }
1609
- const count = (y1 - y0) * (x1 - x0);
1610
- const o = (y * width + x) * 4;
1611
1784
  out[o] = red / count;
1612
1785
  out[o + 1] = green / count;
1613
1786
  out[o + 2] = blue / count;
1614
- out[o + 3] = alpha / count;
1787
+ out[o + 3] = 255;
1615
1788
  }
1616
1789
  }
1617
1790
  return { data: out, width, height, colorSpace: "srgb" } as ImageData;
@@ -1670,10 +1843,11 @@ export async function scanQRPixels(
1670
1843
  distance(location.topLeftCorner, location.bottomLeftCorner) +
1671
1844
  distance(location.topRightCorner, location.bottomRightCorner)) /
1672
1845
  4;
1846
+ const grey = isGrey(source.data);
1673
1847
  for (const size of options.sizes ?? PIXEL_SCAN_SIZES) {
1674
1848
  const state = decodeAtSize(
1675
1849
  jsQR,
1676
- (target) => resizePixels(source, target / codeWidth),
1850
+ (target) => resizePixels(source, target / codeWidth, grey),
1677
1851
  size,
1678
1852
  dimension,
1679
1853
  (result) => matches(result, expected)
package/src/symbol.ts ADDED
@@ -0,0 +1,27 @@
1
+ import type { ErrorLevel } from "../types";
2
+ import qrcodegen from "./codegen";
3
+ import { ERROR_LEVEL_MAP } from "./constants";
4
+
5
+ /**
6
+ * The QR symbol for `value` at `level`, in the smallest version that holds
7
+ * it. Every renderer, the logo budget, the scan score and the print layout
8
+ * encode through here, so they all draw and judge the same symbol.
9
+ *
10
+ * The encoder raises the level to Q or H when the data still fits that
11
+ * version (more error correction for free); `exactLevel` keeps `level`, as
12
+ * a Swiss QR-bill needs (M). Without it this is QrCode.encodeText.
13
+ */
14
+ export function encodeSymbol(
15
+ value: string,
16
+ level: ErrorLevel,
17
+ exactLevel?: boolean
18
+ ): qrcodegen.QrCode {
19
+ return qrcodegen.QrCode.encodeSegments(
20
+ qrcodegen.QrSegment.makeSegments(value),
21
+ ERROR_LEVEL_MAP[level],
22
+ qrcodegen.QrCode.MIN_VERSION,
23
+ qrcodegen.QrCode.MAX_VERSION,
24
+ -1,
25
+ !exactLevel
26
+ );
27
+ }
@@ -1,17 +1,12 @@
1
1
  import type { QRProps } from "../../types";
2
2
  import { isGradient } from "../../types/color-helpers";
3
- import qrcodegen from "../codegen";
4
- import {
5
- DEFAULT_BGCOLOR,
6
- DEFAULT_MARGIN,
7
- DEFAULT_SIZE,
8
- ERROR_LEVEL_MAP,
9
- } from "../constants";
3
+ import { DEFAULT_BGCOLOR, DEFAULT_MARGIN, DEFAULT_SIZE } from "../constants";
10
4
  import { withQRSize } from "../download";
11
5
  import { getQRAsSVGDataUri } from "../export";
12
6
  import { getFrameLayout, isFrameActive } from "../frame";
13
7
  import { clampBgRadius } from "../looks";
14
8
  import { getLayoutMargin } from "../qr-shape";
9
+ import { encodeSymbol } from "../symbol";
15
10
  import { resolveErrorLevel } from "../utils";
16
11
  import { getSolidColor } from "./color";
17
12
  import { flattenOver } from "./paint";
@@ -43,9 +38,10 @@ export function getPrintBleedColor(props: QRProps): string | null {
43
38
  }
44
39
  // Outside rounded corners the backdrop shows, so the bleed continues it
45
40
  if (props.backdrop && props.bgRadius) {
46
- const modules = qrcodegen.QrCode.encodeText(
41
+ const modules = encodeSymbol(
47
42
  props.value,
48
- ERROR_LEVEL_MAP[resolveErrorLevel(props)]
43
+ resolveErrorLevel(props),
44
+ props.exactLevel
49
45
  ).size;
50
46
  const margin = getLayoutMargin(
51
47
  modules,