qrdx 0.0.60 → 0.0.61

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 (46) hide show
  1. package/README.md +1 -1
  2. package/dist/core.js +7 -7
  3. package/dist/core.js.map +1 -1
  4. package/dist/core.mjs +7 -7
  5. package/dist/core.mjs.map +1 -1
  6. package/dist/index.js +7 -7
  7. package/dist/index.js.map +1 -1
  8. package/dist/index.mjs +7 -7
  9. package/dist/index.mjs.map +1 -1
  10. package/dist/node.js +2 -2
  11. package/dist/node.js.map +1 -1
  12. package/dist/node.mjs +2 -2
  13. package/dist/node.mjs.map +1 -1
  14. package/dist/qr-code-canvas.js +1 -1
  15. package/dist/qr-code-canvas.js.map +1 -1
  16. package/dist/qr-code-canvas.mjs +1 -1
  17. package/dist/qr-code-canvas.mjs.map +1 -1
  18. package/dist/src/api.d.ts +2 -3
  19. package/dist/src/api.d.ts.map +1 -1
  20. package/dist/src/qr-code-canvas.d.ts +2 -8
  21. package/dist/src/qr-code-canvas.d.ts.map +1 -1
  22. package/dist/src/qr-code-svg.d.ts +2 -3
  23. package/dist/src/qr-code-svg.d.ts.map +1 -1
  24. package/dist/src/qr-code.d.ts +2 -2
  25. package/dist/src/qr-code.d.ts.map +1 -1
  26. package/dist/src/qr-frame-svg.d.ts +2 -3
  27. package/dist/src/qr-frame-svg.d.ts.map +1 -1
  28. package/dist/src/rasterize.d.ts +8 -0
  29. package/dist/src/rasterize.d.ts.map +1 -1
  30. package/dist/src/react-elements.d.ts.map +1 -1
  31. package/dist/src/scan-score.d.ts +34 -0
  32. package/dist/src/scan-score.d.ts.map +1 -1
  33. package/dist/types/react.d.ts +21 -3
  34. package/dist/types/react.d.ts.map +1 -1
  35. package/dist/vanilla.browser.mjs +12 -12
  36. package/dist/vanilla.browser.mjs.map +1 -1
  37. package/package.json +4 -6
  38. package/src/api.tsx +3 -4
  39. package/src/qr-code-canvas.tsx +34 -27
  40. package/src/qr-code-svg.tsx +3 -4
  41. package/src/qr-code.tsx +7 -5
  42. package/src/qr-frame-svg.tsx +3 -4
  43. package/src/rasterize.ts +14 -1
  44. package/src/react-elements.ts +40 -2
  45. package/src/scan-score.ts +220 -47
  46. package/types/react.ts +22 -3
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "qrdx",
3
- "version": "0.0.60",
3
+ "version": "0.0.61",
4
4
  "description": "Customizable QR code generator for React and plain JavaScript: SVG and canvas rendering, dot and eye patterns, gradients, logos, frames, Logo QR and Image QR art, PNG/JPG/WebP/SVG/PDF/EPS export, a scan score and QR scanning.",
5
5
  "keywords": [
6
6
  "qr-code",
@@ -199,6 +199,7 @@
199
199
  "test": "vitest run",
200
200
  "readme": "node scripts/readme-catalogue.mjs",
201
201
  "check:package": "node scripts/check-package.mjs",
202
+ "check:react": "node scripts/react-compat.mjs",
202
203
  "prepublishOnly": "node -e \"if(!(process.env.npm_config_user_agent||'').startsWith('bun/')){console.error('Publish through the Publish workflow, or with bun publish, which replaces workspace ranges with real versions.');process.exit(1)}\" && bun run build && bun run test && node scripts/readme-catalogue.mjs --check"
203
204
  },
204
205
  "dependencies": {
@@ -218,6 +219,7 @@
218
219
  "next": "16.4.5",
219
220
  "publint": "0.3.25",
220
221
  "react": "^19.3.1",
222
+ "react-dom": "^19.3.1",
221
223
  "sharp": "0.35.5",
222
224
  "tsup": "^9.0.0",
223
225
  "typescript": "6.0.3",
@@ -238,8 +240,7 @@
238
240
  "peerDependencies": {
239
241
  "@resvg/resvg-js": "^2.6.2",
240
242
  "jspdf": "^2.5.0 || ^3.0.0 || ^4.0.0",
241
- "react": ">=18.0.0",
242
- "react-dom": ">=18.0.0",
243
+ "react": ">=16.8.0",
243
244
  "sharp": ">=0.34.0",
244
245
  "vue": ">=3.3.0",
245
246
  "preact": ">=10.0.0",
@@ -256,9 +257,6 @@
256
257
  "react": {
257
258
  "optional": true
258
259
  },
259
- "react-dom": {
260
- "optional": true
261
- },
262
260
  "sharp": {
263
261
  "optional": true
264
262
  },
package/src/api.tsx CHANGED
@@ -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 { drawPlainQRCode, preparePlainQRCode } from "./plain";
5
4
  import { REACT_ELEMENTS } from "./react-elements";
@@ -9,9 +8,9 @@ import { REACT_ELEMENTS } from "./react-elements";
9
8
  * background rect, plus the logo and frame (`getQRAsSVGNode` is the same
10
9
  * without React). A logo that isn't a data URL is fetched as base64 first.
11
10
  */
12
- export async function getQRAsSVG(props: QRPropsSVG): Promise<JSX.Element> {
11
+ export async function getQRAsSVG(props: QRPropsSVG): Promise<ReactQRElement> {
13
12
  const plain = await preparePlainQRCode(props);
14
13
  return withElementFactory(REACT_ELEMENTS, () =>
15
14
  drawPlainQRCode(plain)
16
- ) as unknown as JSX.Element;
15
+ ) as unknown as ReactQRElement;
17
16
  }
@@ -10,8 +10,17 @@
10
10
  * Copyright (c) Paul O'Shannessy
11
11
  * SPDX-License-Identifier: ISC
12
12
  */
13
- import { type JSX, useEffect, useRef, useState } from "react";
14
- import type { QRPropsCanvas } from "../types/react";
13
+ // createElement rather than JSX: compiled JSX would import
14
+ // react/jsx-runtime, which React has had only since 16.14.
15
+ import {
16
+ createElement,
17
+ Fragment,
18
+ type ReactElement,
19
+ useEffect,
20
+ useRef,
21
+ useState,
22
+ } from "react";
23
+ import type { QRPropsCanvas, ReactQRElement } from "../types/react";
15
24
  import qrcodegen from "./codegen";
16
25
  import {
17
26
  DEFAULT_BGCOLOR,
@@ -35,7 +44,7 @@ import {
35
44
  } from "./utils";
36
45
  import { getSolidColor } from "./utils/color";
37
46
 
38
- export function QRCodeCanvas(props: QRPropsCanvas) {
47
+ export function QRCodeCanvas(props: QRPropsCanvas): ReactQRElement {
39
48
  const {
40
49
  value,
41
50
  size = DEFAULT_SIZE,
@@ -233,31 +242,29 @@ export function QRCodeCanvas(props: QRPropsCanvas) {
233
242
  });
234
243
 
235
244
  const canvasStyle = { height: outputHeight, width: outputWidth, ...style };
236
- let img: JSX.Element | null = null;
245
+ let img: ReactElement | null = null;
237
246
  if (imgSrc != null) {
238
- img = (
239
- <img
240
- alt="QR code"
241
- key={imgSrc}
242
- onLoad={() => {
243
- setIsImageLoaded(true);
244
- }}
245
- ref={_image}
246
- src={imgSrc}
247
- style={{ display: "none" }}
248
- />
249
- );
247
+ img = createElement("img", {
248
+ alt: "QR code",
249
+ key: imgSrc,
250
+ onLoad: () => {
251
+ setIsImageLoaded(true);
252
+ },
253
+ ref: _image,
254
+ src: imgSrc,
255
+ style: { display: "none" },
256
+ });
250
257
  }
251
- return (
252
- <>
253
- <canvas
254
- height={outputHeight}
255
- ref={_canvas}
256
- style={canvasStyle}
257
- width={outputWidth}
258
- {...otherProps}
259
- />
260
- {img}
261
- </>
258
+ return createElement(
259
+ Fragment,
260
+ null,
261
+ createElement("canvas", {
262
+ height: outputHeight,
263
+ ref: _canvas,
264
+ style: canvasStyle,
265
+ width: outputWidth,
266
+ ...otherProps,
267
+ }),
268
+ img
262
269
  );
263
270
  }
@@ -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
@@ -110,21 +110,75 @@ function matches(result: JsQRResult | null, value: string): boolean {
110
110
 
111
111
  /**
112
112
  * Camera-like degradation, in place: contrast loss plus a blur of about a
113
- * quarter module (two box-blur passes approximate a Gaussian).
113
+ * quarter module (two box-blur passes approximate a Gaussian). Each channel
114
+ * is rounded to a byte after every step, as drawing would.
114
115
  */
115
116
  function simulateCamera(image: ImageData, modulePx: number, contrast = 0.7) {
116
117
  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;
118
+ const count = width * height;
119
+ const radius = Math.max(1, Math.round(modulePx * 0.25));
120
+ // Grey artwork (black on white, anti-aliased to greys) has one channel's
121
+ // worth of values: blur it once and copy it out, a third of the work. The
122
+ // bytes are exactly those blurring red, green and blue gives.
123
+ const grey = greyChannel(data, count);
124
+ if (grey) {
125
+ for (let p = 0; p < count; p++) {
126
+ grey[p] = 128 + ((grey[p] as number) - 128) * contrast;
127
+ }
128
+ boxBlur(grey, width, height, radius);
129
+ for (let p = 0, i = 0; p < count; p++, i += 4) {
130
+ const value = grey[p] as number;
131
+ data[i] = value;
132
+ data[i + 1] = value;
133
+ data[i + 2] = value;
134
+ }
135
+ return;
136
+ }
137
+ // Colours: each channel on its own plane (the same arithmetic, read and
138
+ // written in order rather than every fourth byte).
139
+ const plane = new Uint8ClampedArray(count);
140
+ for (let c = 0; c < 3; c++) {
141
+ for (let p = 0, i = c; p < count; p++, i += 4) {
142
+ plane[p] = 128 + ((data[i] as number) - 128) * contrast;
143
+ }
144
+ boxBlur(plane, width, height, radius);
145
+ for (let p = 0, i = c; p < count; p++, i += 4) {
146
+ data[i] = plane[p] as number;
120
147
  }
121
148
  }
122
- const radius = Math.max(1, Math.round(modulePx * 0.25));
149
+ }
150
+
151
+ /** The red channel when every pixel is grey (red = green = blue), else null. */
152
+ function greyChannel(
153
+ data: Uint8ClampedArray,
154
+ count: number
155
+ ): Uint8ClampedArray | null {
156
+ const grey = new Uint8ClampedArray(count);
157
+ for (let p = 0, i = 0; p < count; p++, i += 4) {
158
+ const red = data[i] as number;
159
+ if (red !== data[i + 1] || red !== data[i + 2]) {
160
+ return null;
161
+ }
162
+ grey[p] = red;
163
+ }
164
+ return grey;
165
+ }
166
+
167
+ /**
168
+ * Two passes of a box blur `2 * radius + 1` wide, across then down, on one
169
+ * channel in place, rounding to a byte after each. Sliding window with
170
+ * clamped edges: pixel (line, position) is `line * lineStep + position *
171
+ * step`, and the sum is a plain local (this runs up to nine times a score,
172
+ * on every pixel).
173
+ */
174
+ function boxBlur(
175
+ channel: Uint8ClampedArray,
176
+ width: number,
177
+ height: number,
178
+ radius: number
179
+ ) {
123
180
  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).
181
+ const buffer = new Float32Array(width * height);
128
182
  const blur = (horizontal: boolean) => {
129
183
  const lines = horizontal ? height : width;
130
184
  const length = horizontal ? width : height;
@@ -132,33 +186,24 @@ function simulateCamera(image: ImageData, modulePx: number, contrast = 0.7) {
132
186
  const step = horizontal ? 1 : width;
133
187
  for (let line = 0; line < lines; line++) {
134
188
  const start = line * lineStep;
135
- let red = 0;
136
- let green = 0;
137
- let blue = 0;
189
+ let sum = 0;
138
190
  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;
191
+ sum += channel[
192
+ start + Math.min(Math.max(k, 0), length - 1) * step
193
+ ] as number;
143
194
  }
144
195
  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);
196
+ buffer[start + position * step] = sum / span;
197
+ sum =
198
+ sum -
199
+ (channel[start + Math.max(position - radius, 0) * step] as number) +
200
+ (channel[
201
+ start + Math.min(position + radius + 1, length - 1) * step
202
+ ] as number);
155
203
  }
156
204
  }
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
- }
205
+ // Rounds and clamps each value to a byte, as assigning one does
206
+ channel.set(buffer);
162
207
  };
163
208
  for (let pass = 0; pass < 2; pass++) {
164
209
  blur(true);
@@ -182,10 +227,16 @@ function createCanvas(width: number, height: number) {
182
227
  // A phone tries many frames at slightly different distances.
183
228
  const ATTEMPT_SCALES = [0.9, 1, 1.1];
184
229
 
230
+ /** Code widths (px) `decodeAtSize` draws for `size`, in the order it tries them. */
231
+ function attemptWidths(size: number): number[] {
232
+ return ATTEMPT_SCALES.map((scale) => size * scale);
233
+ }
234
+
185
235
  /**
186
236
  * Decodes the code at `size` px wide a few times at slightly different
187
237
  * scales through the camera simulation. `draw` returns the pixels with the
188
- * code `codeWidth` px wide.
238
+ * code `codeWidth` px wide. Two hits are a pass whatever the rest would
239
+ * read, so it stops there.
189
240
  */
190
241
  function decodeAtSize(
191
242
  jsQR: Decoder,
@@ -195,12 +246,14 @@ function decodeAtSize(
195
246
  expected: (result: JsQRResult | null) => boolean
196
247
  ): DecodeState {
197
248
  let hits = 0;
198
- for (const scale of ATTEMPT_SCALES) {
199
- const codeWidth = size * scale;
249
+ for (const codeWidth of attemptWidths(size)) {
200
250
  const image = draw(codeWidth);
201
251
  simulateCamera(image, codeWidth / moduleCount);
202
252
  if (expected(jsQR(image.data, image.width, image.height))) {
203
253
  hits++;
254
+ if (hits >= 2) {
255
+ break;
256
+ }
204
257
  }
205
258
  }
206
259
  if (hits >= 2) {
@@ -1053,6 +1106,97 @@ export async function getScanScore(
1053
1106
  options: ScanScoreOptions = {}
1054
1107
  ): Promise<ScanScoreResult> {
1055
1108
  assertBrowser();
1109
+ const { draw, sizes, imageTones } = await prepareScan(props, options);
1110
+ return await scoreArtwork(props, draw, sizes, options.signal, imageTones);
1111
+ }
1112
+
1113
+ /**
1114
+ * One frame `getScanScore` decodes: the artwork on white with the code
1115
+ * `codeWidth` px wide, before the camera model.
1116
+ */
1117
+ export interface ScanFrame {
1118
+ codeWidth: number;
1119
+ width: number;
1120
+ height: number;
1121
+ /** RGBA bytes, `width × height × 4` */
1122
+ data: Uint8ClampedArray;
1123
+ }
1124
+
1125
+ export interface ScanFrames {
1126
+ /** The test sizes, smallest first */
1127
+ sizes: number[];
1128
+ /** Every frame the score may decode, smallest code first */
1129
+ frames: ScanFrame[];
1130
+ /** Tones of the images the design paints with, for the contrast checks */
1131
+ imageTones: ImageToneMap;
1132
+ }
1133
+
1134
+ /**
1135
+ * The frames `getScanScore` decodes, drawn on the page's canvas (browser
1136
+ * only), for `getScanScoreFromFrames` to score somewhere else, such as a Web
1137
+ * Worker: drawing is quick native work, and the camera model and decoding
1138
+ * are what keep the page busy. It can be posted as it is (transfer each
1139
+ * frame's `data.buffer` to skip the copy).
1140
+ */
1141
+ export async function drawScanFrames(
1142
+ props: QRProps,
1143
+ options: ScanScoreOptions = {}
1144
+ ): Promise<ScanFrames> {
1145
+ assertBrowser();
1146
+ const { draw, sizes, imageTones } = await prepareScan(props, options);
1147
+ const frames = sizes.flatMap((size) =>
1148
+ attemptWidths(size).map((codeWidth) => {
1149
+ const { data, width, height } = draw(codeWidth);
1150
+ return { codeWidth, width, height, data };
1151
+ })
1152
+ );
1153
+ return { sizes, frames, imageTones };
1154
+ }
1155
+
1156
+ /**
1157
+ * `getScanScore`'s result from the frames `drawScanFrames` drew for the same
1158
+ * props. Needs no DOM, so it runs in a Web Worker. The frames aren't changed
1159
+ * (each is copied before the camera model blurs it), so they can be scored
1160
+ * again.
1161
+ */
1162
+ export async function getScanScoreFromFrames(
1163
+ props: QRProps,
1164
+ scan: ScanFrames,
1165
+ options: Pick<ScanScoreOptions, "signal"> = {}
1166
+ ): Promise<ScanScoreResult> {
1167
+ const byWidth = new Map(scan.frames.map((frame) => [frame.codeWidth, frame]));
1168
+ const draw = (codeWidth: number) => {
1169
+ const frame = byWidth.get(codeWidth);
1170
+ if (!frame || frame.data.length < frame.width * frame.height * 4) {
1171
+ throw new Error(
1172
+ `No scan frame with the code ${codeWidth} px wide: draw the frames with drawScanFrames for these props and sizes`
1173
+ );
1174
+ }
1175
+ return {
1176
+ data: new Uint8ClampedArray(frame.data),
1177
+ width: frame.width,
1178
+ height: frame.height,
1179
+ colorSpace: "srgb",
1180
+ } as ImageData;
1181
+ };
1182
+ return await scoreArtwork(
1183
+ props,
1184
+ draw,
1185
+ scan.sizes,
1186
+ options.signal,
1187
+ scan.imageTones
1188
+ );
1189
+ }
1190
+
1191
+ /**
1192
+ * What `getScanScore` does on the page before decoding: logos and image
1193
+ * fills inlined, the images' tones read and the artwork loaded, with a
1194
+ * `draw` that puts it on white at any code width.
1195
+ */
1196
+ async function prepareScan(
1197
+ props: QRProps,
1198
+ options: ScanScoreOptions
1199
+ ): Promise<{ draw: DrawArtwork; sizes: number[]; imageTones: ImageToneMap }> {
1056
1200
  const { signal } = options;
1057
1201
  const sizes = testSizes(options);
1058
1202
 
@@ -1096,7 +1240,7 @@ export async function getScanScore(
1096
1240
  canvas.remove();
1097
1241
  return image;
1098
1242
  };
1099
- return await scoreArtwork(props, drawArtwork, sizes, signal, imageTones);
1243
+ return { draw: drawArtwork, sizes, imageTones };
1100
1244
  }
1101
1245
 
1102
1246
  /**
@@ -1134,9 +1278,10 @@ export async function getScanScoreFromPixels(
1134
1278
  const sourceCodeWidth =
1135
1279
  (width * size * getTemplateCodeShare(props)) / artwork.width;
1136
1280
  const source = { data: onWhite(pixels), width, height };
1281
+ const grey = isGrey(source.data);
1137
1282
 
1138
1283
  const drawArtwork = (codeWidth: number) => {
1139
- const art = resizePixels(source, codeWidth / sourceCodeWidth);
1284
+ const art = resizePixels(source, codeWidth / sourceCodeWidth, grey);
1140
1285
  const pad = Math.max(8, Math.round(codeWidth * 0.12));
1141
1286
  return padWhite(art, pad);
1142
1287
  };
@@ -1569,10 +1714,26 @@ export interface PixelScanResult {
1569
1714
  /** Code widths (px) `scanQRPixels` checks through the camera model. */
1570
1715
  export const PIXEL_SCAN_SIZES = [320] as const;
1571
1716
 
1572
- /** Area-average resize of RGBA pixels by `scale` (at most 1). */
1717
+ /** True when every pixel is grey (red = green = blue). */
1718
+ function isGrey(data: Uint8ClampedArray): boolean {
1719
+ for (let i = 0; i < data.length; i += 4) {
1720
+ if (data[i] !== data[i + 1] || data[i] !== data[i + 2]) {
1721
+ return false;
1722
+ }
1723
+ }
1724
+ return true;
1725
+ }
1726
+
1727
+ /**
1728
+ * Area-average resize of RGBA pixels by `scale` (at most 1), for decoding:
1729
+ * the result is opaque (alpha isn't averaged; jsQR doesn't read it). With
1730
+ * `grey` (every source pixel grey, see `isGrey`) only red is averaged and
1731
+ * copied to green and blue, which is what averaging each gives.
1732
+ */
1573
1733
  function resizePixels(
1574
1734
  source: { data: Uint8ClampedArray; width: number; height: number },
1575
- scale: number
1735
+ scale: number,
1736
+ grey = false
1576
1737
  ): ImageData {
1577
1738
  const factor = Math.min(1, scale);
1578
1739
  const width = Math.max(1, Math.round(source.width * factor));
@@ -1580,6 +1741,7 @@ function resizePixels(
1580
1741
  const out = new Uint8ClampedArray(width * height * 4);
1581
1742
  const stepX = source.width / width;
1582
1743
  const stepY = source.height / height;
1744
+ const { data } = source;
1583
1745
  for (let y = 0; y < height; y++) {
1584
1746
  const y0 = Math.floor(y * stepY);
1585
1747
  const y1 = Math.max(
@@ -1592,26 +1754,36 @@ function resizePixels(
1592
1754
  x0 + 1,
1593
1755
  Math.min(source.width, Math.floor((x + 1) * stepX))
1594
1756
  );
1757
+ const count = (y1 - y0) * (x1 - x0);
1758
+ const o = (y * width + x) * 4;
1595
1759
  // Plain locals, not an array: this runs on every output pixel
1596
1760
  let red = 0;
1761
+ if (grey) {
1762
+ for (let sy = y0; sy < y1; sy++) {
1763
+ for (let sx = x0; sx < x1; sx++) {
1764
+ red += data[(sy * source.width + sx) * 4] as number;
1765
+ }
1766
+ }
1767
+ out[o] = red / count;
1768
+ out[o + 1] = out[o] as number;
1769
+ out[o + 2] = out[o] as number;
1770
+ out[o + 3] = 255;
1771
+ continue;
1772
+ }
1597
1773
  let green = 0;
1598
1774
  let blue = 0;
1599
- let alpha = 0;
1600
1775
  for (let sy = y0; sy < y1; sy++) {
1601
1776
  for (let sx = x0; sx < x1; sx++) {
1602
1777
  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;
1778
+ red += data[i] as number;
1779
+ green += data[i + 1] as number;
1780
+ blue += data[i + 2] as number;
1607
1781
  }
1608
1782
  }
1609
- const count = (y1 - y0) * (x1 - x0);
1610
- const o = (y * width + x) * 4;
1611
1783
  out[o] = red / count;
1612
1784
  out[o + 1] = green / count;
1613
1785
  out[o + 2] = blue / count;
1614
- out[o + 3] = alpha / count;
1786
+ out[o + 3] = 255;
1615
1787
  }
1616
1788
  }
1617
1789
  return { data: out, width, height, colorSpace: "srgb" } as ImageData;
@@ -1670,10 +1842,11 @@ export async function scanQRPixels(
1670
1842
  distance(location.topLeftCorner, location.bottomLeftCorner) +
1671
1843
  distance(location.topRightCorner, location.bottomRightCorner)) /
1672
1844
  4;
1845
+ const grey = isGrey(source.data);
1673
1846
  for (const size of options.sizes ?? PIXEL_SCAN_SIZES) {
1674
1847
  const state = decodeAtSize(
1675
1848
  jsQR,
1676
- (target) => resizePixels(source, target / codeWidth),
1849
+ (target) => resizePixels(source, target / codeWidth, grey),
1677
1850
  size,
1678
1851
  dimension,
1679
1852
  (result) => matches(result, expected)