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
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { For, Match, Switch } from 'solid-js';
|
|
2
|
+
/** One `<defs>` gradient in user-space units, as `sceneToSVGString` writes it. */
|
|
3
|
+
export function GradientDef(props) {
|
|
4
|
+
const stops = () => (<For each={props.paint.stops} keyed={false}>
|
|
5
|
+
{(stop) => <stop offset={stop()[0]} stop-color={stop()[1]}/>}
|
|
6
|
+
</For>);
|
|
7
|
+
return (<Switch>
|
|
8
|
+
<Match when={props.paint.type === 'linear' && props.paint}>
|
|
9
|
+
{(p) => (<linearGradient id={props.id} gradientUnits="userSpaceOnUse" x1={p().x1} y1={p().y1} x2={p().x2} y2={p().y2}>
|
|
10
|
+
{stops()}
|
|
11
|
+
</linearGradient>)}
|
|
12
|
+
</Match>
|
|
13
|
+
<Match when={props.paint.type === 'radial' && props.paint}>
|
|
14
|
+
{(p) => (<radialGradient id={props.id} gradientUnits="userSpaceOnUse" cx={p().cx} cy={p().cy} r={p().r}>
|
|
15
|
+
{stops()}
|
|
16
|
+
</radialGradient>)}
|
|
17
|
+
</Match>
|
|
18
|
+
</Switch>);
|
|
19
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { Show, omit } from 'solid-js';
|
|
2
|
+
import { QRCodeCanvas } from './QRCodeCanvas.jsx';
|
|
3
|
+
import { QRCodeSVG } from './QRCodeSVG.jsx';
|
|
4
|
+
/** Renders a QR code with the renderer that `renderAs` names. Default 'svg'. */
|
|
5
|
+
export function QRCode(props) {
|
|
6
|
+
const rest = omit(props, 'renderAs');
|
|
7
|
+
return (<Show when={props.renderAs === 'canvas'} fallback={<QRCodeSVG {...rest}/>}>
|
|
8
|
+
<QRCodeCanvas {...rest}/>
|
|
9
|
+
</Show>);
|
|
10
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { isDev } from '@solidjs/web';
|
|
2
|
+
import { createEffect, createMemo, createSignal, omit } from 'solid-js';
|
|
3
|
+
import { optionKeys } from '../core/options.js';
|
|
4
|
+
import { ariaLabel, outputSize } from '../core/output.js';
|
|
5
|
+
import { createColorScheme } from '../primitives/createColorScheme.js';
|
|
6
|
+
import { createPixelRatio } from '../primitives/createPixelRatio.js';
|
|
7
|
+
import { createQRCode } from '../primitives/createQRCode.js';
|
|
8
|
+
import { drawScene } from '../render/canvas.js';
|
|
9
|
+
import { colorResolver } from '../render/color.js';
|
|
10
|
+
import { loadImage } from '../render/image.js';
|
|
11
|
+
/**
|
|
12
|
+
* Renders a QR code to a canvas sized for the device pixel ratio.
|
|
13
|
+
* It redraws when `prefers-color-scheme` changes, since CSS colours may depend on it.
|
|
14
|
+
*/
|
|
15
|
+
export function QRCodeCanvas(props) {
|
|
16
|
+
const rest = omit(props, ...optionKeys, 'onReady', 'repaint', 'imageTimeout');
|
|
17
|
+
const { scene } = createQRCode(props);
|
|
18
|
+
const ratio = createPixelRatio();
|
|
19
|
+
const scheme = createColorScheme();
|
|
20
|
+
const src = createMemo(() => props.image?.src, { name: 'qr.imageSrc' });
|
|
21
|
+
const crossOrigin = createMemo(() => props.image?.crossOrigin, { name: 'qr.crossOrigin' });
|
|
22
|
+
const imageTimeout = createMemo(() => props.imageTimeout, { name: 'qr.imageTimeout' });
|
|
23
|
+
const [loaded, setLoaded] = createSignal();
|
|
24
|
+
let canvas;
|
|
25
|
+
createEffect(() => [src(), crossOrigin(), imageTimeout()], ([src, crossOrigin, timeout]) => {
|
|
26
|
+
if (!src)
|
|
27
|
+
return;
|
|
28
|
+
const controller = new AbortController();
|
|
29
|
+
void loadImage({ src, crossOrigin }, { timeout, signal: controller.signal, warn: isDev }).then((image) => {
|
|
30
|
+
if (!controller.signal.aborted)
|
|
31
|
+
setLoaded({ src, image: image ?? 'error' });
|
|
32
|
+
});
|
|
33
|
+
return () => controller.abort();
|
|
34
|
+
});
|
|
35
|
+
createEffect(() => {
|
|
36
|
+
const result = loaded();
|
|
37
|
+
return {
|
|
38
|
+
scene: scene(),
|
|
39
|
+
ratio: ratio(),
|
|
40
|
+
// Read only to redraw: the canvas resolves CSS colours at draw time.
|
|
41
|
+
scheme: scheme(),
|
|
42
|
+
repaint: props.repaint,
|
|
43
|
+
size: props.size,
|
|
44
|
+
image: result && result.src === src() ? result.image : undefined,
|
|
45
|
+
settled: !src() || result?.src === src(),
|
|
46
|
+
onReady: props.onReady,
|
|
47
|
+
};
|
|
48
|
+
}, {
|
|
49
|
+
// A user effect logs compute errors; a throwing handler escalates them to <Errored>.
|
|
50
|
+
error: (err) => {
|
|
51
|
+
throw err;
|
|
52
|
+
},
|
|
53
|
+
effect: ({ scene, ratio, size, image, settled, onReady }) => {
|
|
54
|
+
const output = outputSize(scene, size);
|
|
55
|
+
canvas.width = Math.round(output.width * ratio);
|
|
56
|
+
canvas.height = Math.round(output.height * ratio);
|
|
57
|
+
canvas.style.width = `${output.width}px`;
|
|
58
|
+
canvas.style.height = `${output.height}px`;
|
|
59
|
+
const ctx = canvas.getContext('2d');
|
|
60
|
+
if (!ctx)
|
|
61
|
+
throw new Error('[qrcodesolid] No 2D canvas context.');
|
|
62
|
+
drawScene(ctx, scene, {
|
|
63
|
+
scale: canvas.width / scene.width,
|
|
64
|
+
image: image === 'error' ? undefined : image,
|
|
65
|
+
resolveColor: colorResolver(canvas),
|
|
66
|
+
});
|
|
67
|
+
if (settled)
|
|
68
|
+
onReady?.(canvas);
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
return (<canvas ref={canvas} role="img" id={props.id} {...rest} aria-label={ariaLabel(props, true)}/>);
|
|
72
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { isDev } from '@solidjs/web';
|
|
2
|
+
import { For, Show, createMemo, createUniqueId, omit } from 'solid-js';
|
|
3
|
+
import { optionKeys } from '../core/options.js';
|
|
4
|
+
import { ariaLabel, outputSize } from '../core/output.js';
|
|
5
|
+
import { createQRCode } from '../primitives/createQRCode.js';
|
|
6
|
+
import { isRectilinear } from '../render/svg-string.js';
|
|
7
|
+
import { coord } from '../shapes/types.js';
|
|
8
|
+
import { GradientDef } from './GradientDef.jsx';
|
|
9
|
+
/** Renders a QR code as inline SVG. The markup matches `sceneToSVGString`. */
|
|
10
|
+
export function QRCodeSVG(props) {
|
|
11
|
+
const rest = omit(props, ...optionKeys);
|
|
12
|
+
const { scene } = createQRCode(props);
|
|
13
|
+
const uniqueId = createUniqueId();
|
|
14
|
+
// Ids must start with a letter to work as CSS selectors.
|
|
15
|
+
const prefix = () => props.id ?? `qr-${uniqueId}`;
|
|
16
|
+
const output = () => outputSize(scene(), props.size);
|
|
17
|
+
const fill = (id, paint) => typeof paint === 'string' ? paint : `url(#${prefix()}-${id})`;
|
|
18
|
+
const gradientsOf = (painted) => painted.filter((p) => typeof p[1] !== 'string');
|
|
19
|
+
// `sceneToSVGString` writes layer gradients, then the image clip, then text gradients.
|
|
20
|
+
const layerGradients = createMemo(() => gradientsOf(scene().layers.map((l) => [l.id, l.fill])));
|
|
21
|
+
const textGradients = createMemo(() => gradientsOf(scene().texts.map((t, i) => [`text-${i}`, t.fill])));
|
|
22
|
+
const gradientDefs = (gradients) => (<For each={gradients} keyed={false}>
|
|
23
|
+
{(g) => <GradientDef id={`${prefix()}-${g()[0]}`} paint={g()[1]}/>}
|
|
24
|
+
</For>);
|
|
25
|
+
const image = () => scene().image;
|
|
26
|
+
const clipId = () => `${prefix()}-image-clip`;
|
|
27
|
+
return (<svg xmlns="http://www.w3.org/2000/svg" id={props.id} role="img" aria-labelledby={props.title ? `${prefix()}-title` : undefined} aria-label={ariaLabel(props, false)} viewBox={`0 0 ${coord(scene().width)} ${coord(scene().height)}`} width={coord(output().width)} height={coord(output().height)} shape-rendering={scene().layers.every((l) => isRectilinear(l.d)) ? 'crispEdges' : undefined} {...rest}>
|
|
28
|
+
<Show when={props.title}>{(title) => <title id={`${prefix()}-title`}>{title()}</title>}</Show>
|
|
29
|
+
<Show when={layerGradients().length > 0 || textGradients().length > 0 || image()}>
|
|
30
|
+
<defs>
|
|
31
|
+
{gradientDefs(layerGradients())}
|
|
32
|
+
<Show when={image()}>
|
|
33
|
+
{(img) => (<clipPath id={clipId()}>
|
|
34
|
+
<rect x={coord(img().x)} y={coord(img().y)} width={coord(img().width)} height={coord(img().height)} rx={coord(img().radius)} ry={coord(img().radius)}/>
|
|
35
|
+
</clipPath>)}
|
|
36
|
+
</Show>
|
|
37
|
+
{gradientDefs(textGradients())}
|
|
38
|
+
</defs>
|
|
39
|
+
</Show>
|
|
40
|
+
<For each={scene().layers} keyed={false}>
|
|
41
|
+
{(layer) => (<path d={layer().d} fill={fill(layer().id, layer().fill)} fill-rule={layer().fillRule}/>)}
|
|
42
|
+
</For>
|
|
43
|
+
<Show when={image()}>
|
|
44
|
+
{(img) => (<image href={img().href} x={coord(img().x)} y={coord(img().y)} width={coord(img().width)} height={coord(img().height)} opacity={img().opacity} preserveAspectRatio="xMidYMid meet" clip-path={`url(#${clipId()})`} onError={() => {
|
|
45
|
+
if (isDev)
|
|
46
|
+
console.warn(`[qrcodesolid] Failed to load image: ${img().href}`);
|
|
47
|
+
}}
|
|
48
|
+
// The JSX types lack SVG `<image crossorigin>`, though SVG 2 defines it.
|
|
49
|
+
{...{ crossorigin: img().crossOrigin }}/>)}
|
|
50
|
+
</Show>
|
|
51
|
+
<For each={scene().texts} keyed={false}>
|
|
52
|
+
{(text, i) => (<text x={coord(text().x)} y={coord(text().y)} font-size={coord(text().fontSize)} font-family={text().fontFamily} font-weight={text().fontWeight} fill={fill(`text-${i}`, text().fill)} text-anchor="middle" dominant-baseline="central">
|
|
53
|
+
{text().text}
|
|
54
|
+
</text>)}
|
|
55
|
+
</For>
|
|
56
|
+
</svg>);
|
|
57
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
export function toCaptionShape(caption) {
|
|
2
|
+
if (!caption)
|
|
3
|
+
return undefined;
|
|
4
|
+
const { color: _color, ...shape } = caption;
|
|
5
|
+
return shape;
|
|
6
|
+
}
|
|
7
|
+
export const sameCaptionShape = (a, b) => a === b ||
|
|
8
|
+
(!!a &&
|
|
9
|
+
!!b &&
|
|
10
|
+
a.text === b.text &&
|
|
11
|
+
a.position === b.position &&
|
|
12
|
+
a.fontSize === b.fontSize &&
|
|
13
|
+
a.fontFamily === b.fontFamily &&
|
|
14
|
+
a.fontWeight === b.fontWeight);
|
|
15
|
+
const minFontSize = 1;
|
|
16
|
+
/** East Asian wide ranges and the main emoji blocks, by code point. */
|
|
17
|
+
const isWide = (c) => (c >= 0x1100 && c <= 0x115f) ||
|
|
18
|
+
(c >= 0x2e80 && c <= 0xa4cf) ||
|
|
19
|
+
(c >= 0xac00 && c <= 0xd7a3) ||
|
|
20
|
+
(c >= 0xf900 && c <= 0xfaff) ||
|
|
21
|
+
(c >= 0xfe30 && c <= 0xfe4f) ||
|
|
22
|
+
(c >= 0xff00 && c <= 0xff60) ||
|
|
23
|
+
(c >= 0xffe0 && c <= 0xffe6) ||
|
|
24
|
+
(c >= 0x1f300 && c <= 0x1faff) ||
|
|
25
|
+
(c >= 0x20000 && c <= 0x3fffd);
|
|
26
|
+
// shortcut: assumes a wide glyph is 1 em and others 0.6 em, measure real text if users report misses.
|
|
27
|
+
function estimateTextWidth(text, fontSize) {
|
|
28
|
+
let [chars, wide] = [0, 0];
|
|
29
|
+
for (const char of text) {
|
|
30
|
+
chars++;
|
|
31
|
+
if (isWide(char.codePointAt(0)))
|
|
32
|
+
wide++;
|
|
33
|
+
}
|
|
34
|
+
// One multiply keeps a 0.6 em sum exact; repeated adds drift past the fit.
|
|
35
|
+
return ((chars - wide) * 0.6 + wide) * fontSize;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Lowers `fontSize` until the text fits `width`, but not below 1 module.
|
|
39
|
+
* `overflows` is true when the text is still too wide at that size.
|
|
40
|
+
*/
|
|
41
|
+
export function fitFontSize(text, fontSize, width) {
|
|
42
|
+
const fit = width / estimateTextWidth(text, 1);
|
|
43
|
+
if (fontSize <= fit)
|
|
44
|
+
return { fontSize, overflows: false };
|
|
45
|
+
const fitted = Math.max(fit, Math.min(fontSize, minFontSize));
|
|
46
|
+
return { fontSize: fitted, overflows: fitted > fit };
|
|
47
|
+
}
|
|
48
|
+
/** The dev warning for `subject` when its fitted text still overflows `width`, else undefined. */
|
|
49
|
+
export function overflowWarning(subject, text, fitted, width, space) {
|
|
50
|
+
if (!fitted.overflows)
|
|
51
|
+
return undefined;
|
|
52
|
+
const wide = Math.round(estimateTextWidth(text, fitted.fontSize));
|
|
53
|
+
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.`;
|
|
54
|
+
}
|
|
55
|
+
/** Adds a text band above or below the layout. Long text shrinks to fit the layout width. */
|
|
56
|
+
export function layoutCaption({ width, height, qr }, caption) {
|
|
57
|
+
const fitted = fitFontSize(caption.text, caption.fontSize ?? 2, width);
|
|
58
|
+
const { fontSize } = fitted;
|
|
59
|
+
const warning = overflowWarning('caption', caption.text, fitted, width, 'the code with its margin');
|
|
60
|
+
const band = fontSize * 1.75;
|
|
61
|
+
const top = caption.position === 'top';
|
|
62
|
+
return {
|
|
63
|
+
layout: { width, height: height + band, qr: top ? { ...qr, y: qr.y + band } : qr },
|
|
64
|
+
texts: [
|
|
65
|
+
{
|
|
66
|
+
text: caption.text,
|
|
67
|
+
x: width / 2,
|
|
68
|
+
y: (top ? 0 : height) + band / 2,
|
|
69
|
+
fontSize,
|
|
70
|
+
fontFamily: caption.fontFamily ?? 'system-ui, sans-serif',
|
|
71
|
+
fontWeight: caption.fontWeight ?? 'normal',
|
|
72
|
+
paint: 'caption',
|
|
73
|
+
},
|
|
74
|
+
],
|
|
75
|
+
warnings: warning ? [warning] : [],
|
|
76
|
+
};
|
|
77
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** The CSS named colours as 6-digit hex. Only `parseColor`, a dev-only module, reads it. */
|
|
2
|
+
const table = 'aliceblue f0f8ff antiquewhite faebd7 aqua 00ffff aquamarine 7fffd4 azure f0ffff beige f5f5dc ' +
|
|
3
|
+
'bisque ffe4c4 black 000000 blanchedalmond ffebcd blue 0000ff blueviolet 8a2be2 brown a52a2a ' +
|
|
4
|
+
'burlywood deb887 cadetblue 5f9ea0 chartreuse 7fff00 chocolate d2691e coral ff7f50 ' +
|
|
5
|
+
'cornflowerblue 6495ed cornsilk fff8dc crimson dc143c cyan 00ffff darkblue 00008b ' +
|
|
6
|
+
'darkcyan 008b8b darkgoldenrod b8860b darkgray a9a9a9 darkgreen 006400 darkgrey a9a9a9 ' +
|
|
7
|
+
'darkkhaki bdb76b darkmagenta 8b008b darkolivegreen 556b2f darkorange ff8c00 ' +
|
|
8
|
+
'darkorchid 9932cc darkred 8b0000 darksalmon e9967a darkseagreen 8fbc8f ' +
|
|
9
|
+
'darkslateblue 483d8b darkslategray 2f4f4f darkslategrey 2f4f4f darkturquoise 00ced1 ' +
|
|
10
|
+
'darkviolet 9400d3 deeppink ff1493 deepskyblue 00bfff dimgray 696969 dimgrey 696969 ' +
|
|
11
|
+
'dodgerblue 1e90ff firebrick b22222 floralwhite fffaf0 forestgreen 228b22 fuchsia ff00ff ' +
|
|
12
|
+
'gainsboro dcdcdc ghostwhite f8f8ff gold ffd700 goldenrod daa520 gray 808080 green 008000 ' +
|
|
13
|
+
'greenyellow adff2f grey 808080 honeydew f0fff0 hotpink ff69b4 indianred cd5c5c ' +
|
|
14
|
+
'indigo 4b0082 ivory fffff0 khaki f0e68c lavender e6e6fa lavenderblush fff0f5 ' +
|
|
15
|
+
'lawngreen 7cfc00 lemonchiffon fffacd lightblue add8e6 lightcoral f08080 lightcyan e0ffff ' +
|
|
16
|
+
'lightgoldenrodyellow fafad2 lightgray d3d3d3 lightgreen 90ee90 lightgrey d3d3d3 ' +
|
|
17
|
+
'lightpink ffb6c1 lightsalmon ffa07a lightseagreen 20b2aa lightskyblue 87cefa ' +
|
|
18
|
+
'lightslategray 778899 lightslategrey 778899 lightsteelblue b0c4de lightyellow ffffe0 ' +
|
|
19
|
+
'lime 00ff00 limegreen 32cd32 linen faf0e6 magenta ff00ff maroon 800000 ' +
|
|
20
|
+
'mediumaquamarine 66cdaa mediumblue 0000cd mediumorchid ba55d3 mediumpurple 9370db ' +
|
|
21
|
+
'mediumseagreen 3cb371 mediumslateblue 7b68ee mediumspringgreen 00fa9a ' +
|
|
22
|
+
'mediumturquoise 48d1cc mediumvioletred c71585 midnightblue 191970 mintcream f5fffa ' +
|
|
23
|
+
'mistyrose ffe4e1 moccasin ffe4b5 navajowhite ffdead navy 000080 oldlace fdf5e6 ' +
|
|
24
|
+
'olive 808000 olivedrab 6b8e23 orange ffa500 orangered ff4500 orchid da70d6 ' +
|
|
25
|
+
'palegoldenrod eee8aa palegreen 98fb98 paleturquoise afeeee palevioletred db7093 ' +
|
|
26
|
+
'papayawhip ffefd5 peachpuff ffdab9 peru cd853f pink ffc0cb plum dda0dd powderblue b0e0e6 ' +
|
|
27
|
+
'purple 800080 rebeccapurple 663399 red ff0000 rosybrown bc8f8f royalblue 4169e1 ' +
|
|
28
|
+
'saddlebrown 8b4513 salmon fa8072 sandybrown f4a460 seagreen 2e8b57 seashell fff5ee ' +
|
|
29
|
+
'sienna a0522d silver c0c0c0 skyblue 87ceeb slateblue 6a5acd slategray 708090 ' +
|
|
30
|
+
'slategrey 708090 snow fffafa springgreen 00ff7f steelblue 4682b4 tan d2b48c teal 008080 ' +
|
|
31
|
+
'thistle d8bfd8 tomato ff6347 turquoise 40e0d0 violet ee82ee wheat f5deb3 white ffffff ' +
|
|
32
|
+
'whitesmoke f5f5f5 yellow ffff00 yellowgreen 9acd32';
|
|
33
|
+
const words = table.split(' ');
|
|
34
|
+
export const colorNames = new Map(words.flatMap((word, i) => (i % 2 === 0 ? [[word, `#${words[i + 1]}`]] : [])));
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { colorNames } from './color-names.js';
|
|
2
|
+
const alphaPart = String.raw `(?:\s*[,/]\s*([\d.]+)(%)?)?\s*\)$`;
|
|
3
|
+
const rgbPattern = new RegExp(String.raw `^rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)` + alphaPart);
|
|
4
|
+
const hslPattern = new RegExp(String.raw `^hsla?\(\s*(-?[\d.]+)(?:deg)?[\s,]+([\d.]+)%[\s,]+([\d.]+)%` + alphaPart);
|
|
5
|
+
const isOpaque = (alpha, percent) => alpha === undefined || Number(alpha) >= (percent ? 100 : 1);
|
|
6
|
+
/** HSL with hue in degrees and saturation and lightness in 0-1, to 0-255 channels. */
|
|
7
|
+
function hslToRgb(hue, saturation, lightness) {
|
|
8
|
+
const a = saturation * Math.min(lightness, 1 - lightness);
|
|
9
|
+
return [0, 8, 4].map((n) => {
|
|
10
|
+
const k = (n + hue / 30) % 12;
|
|
11
|
+
return Math.round(255 * (lightness - a * Math.max(-1, Math.min(k - 3, 9 - k, 1))));
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Parses #rgb, #rrggbb, rgb(), hsl() and CSS named colours to 0-255 channels.
|
|
16
|
+
* Returns null for anything else, and for a colour that is not opaque.
|
|
17
|
+
* `warnings.ts` imports it as `#color-parse`: the `development` condition resolves here, and any
|
|
18
|
+
* other build gets `color-parse-empty.ts`, so production bundles skip the named-colour table.
|
|
19
|
+
*/
|
|
20
|
+
export function parseColor(paint) {
|
|
21
|
+
if (typeof paint !== 'string')
|
|
22
|
+
return null;
|
|
23
|
+
const s = paint.trim().toLowerCase();
|
|
24
|
+
const named = colorNames.get(s);
|
|
25
|
+
if (named)
|
|
26
|
+
return parseColor(named);
|
|
27
|
+
const hex = /^#([\da-f]{3}|[\da-f]{6})$/.exec(s)?.[1];
|
|
28
|
+
if (hex) {
|
|
29
|
+
const full = hex.length === 3 ? [...hex].map((c) => c + c).join('') : hex;
|
|
30
|
+
return [0, 2, 4].map((i) => parseInt(full.slice(i, i + 2), 16));
|
|
31
|
+
}
|
|
32
|
+
const rgb = rgbPattern.exec(s);
|
|
33
|
+
if (rgb)
|
|
34
|
+
return isOpaque(rgb[4], rgb[5]) ? rgb.slice(1, 4).map(Number) : null;
|
|
35
|
+
const hsl = hslPattern.exec(s);
|
|
36
|
+
if (!hsl || !isOpaque(hsl[4], hsl[5]))
|
|
37
|
+
return null;
|
|
38
|
+
const hue = ((Number(hsl[1]) % 360) + 360) % 360;
|
|
39
|
+
const clamp = (v) => Math.min(1, Math.max(0, Number(v) / 100));
|
|
40
|
+
return hslToRgb(hue, clamp(hsl[2]), clamp(hsl[3]));
|
|
41
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import qrcodegen from './qrcodegen.js';
|
|
2
|
+
const { QrCode, QrSegment } = qrcodegen;
|
|
3
|
+
export const Region = { Data: 0, Finder: 1, Alignment: 2, Timing: 3, Format: 4 };
|
|
4
|
+
export class QRCapacityError extends Error {
|
|
5
|
+
version;
|
|
6
|
+
level;
|
|
7
|
+
dataLength;
|
|
8
|
+
constructor(version, level,
|
|
9
|
+
/** Sum of segment character counts (characters or bytes, by mode). */
|
|
10
|
+
dataLength) {
|
|
11
|
+
super(`Data too long for QR version ${version} at level ${level}`);
|
|
12
|
+
this.version = version;
|
|
13
|
+
this.level = level;
|
|
14
|
+
this.dataLength = dataLength;
|
|
15
|
+
this.name = 'QRCapacityError';
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
const eccByLevel = {
|
|
19
|
+
L: QrCode.Ecc.LOW,
|
|
20
|
+
M: QrCode.Ecc.MEDIUM,
|
|
21
|
+
Q: QrCode.Ecc.QUARTILE,
|
|
22
|
+
H: QrCode.Ecc.HIGH,
|
|
23
|
+
};
|
|
24
|
+
const levelByOrdinal = ['L', 'M', 'Q', 'H'];
|
|
25
|
+
export function isDark(m, x, y) {
|
|
26
|
+
return x >= 0 && y >= 0 && x < m.size && y < m.size && m.dark[y * m.size + x] === 1;
|
|
27
|
+
}
|
|
28
|
+
function makeSegments(value) {
|
|
29
|
+
if (typeof value === 'string')
|
|
30
|
+
return QrSegment.makeSegments(value);
|
|
31
|
+
return value.flatMap((v) => QrSegment.makeSegments(v));
|
|
32
|
+
}
|
|
33
|
+
function markRegions(qr) {
|
|
34
|
+
const { size, version } = qr;
|
|
35
|
+
const region = new Uint8Array(size * size);
|
|
36
|
+
const inFinder = (x, y) => (x < 8 && y < 8) || (x >= size - 8 && y < 8) || (x < 8 && y >= size - 8);
|
|
37
|
+
for (let y = 0; y < size; y++) {
|
|
38
|
+
for (let x = 0; x < size; x++) {
|
|
39
|
+
let r = Region.Data;
|
|
40
|
+
if (inFinder(x, y))
|
|
41
|
+
r = Region.Finder;
|
|
42
|
+
else if ((y === 8 && x !== 6 && (x <= 8 || x >= size - 8)) ||
|
|
43
|
+
(x === 8 && y !== 6 && (y <= 8 || y >= size - 8)))
|
|
44
|
+
r = Region.Format;
|
|
45
|
+
else if (version >= 7 &&
|
|
46
|
+
((x < 6 && y >= size - 11 && y < size - 8) || (y < 6 && x >= size - 11 && x < size - 8)))
|
|
47
|
+
r = Region.Format;
|
|
48
|
+
else if (x === 6 || y === 6)
|
|
49
|
+
r = Region.Timing;
|
|
50
|
+
region[y * size + x] = r;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const pos = qr.getAlignmentPatternPositions();
|
|
54
|
+
const last = pos.length - 1;
|
|
55
|
+
pos.forEach((cy, i) => pos.forEach((cx, j) => {
|
|
56
|
+
if ((i === 0 && (j === 0 || j === last)) || (i === last && j === 0))
|
|
57
|
+
return;
|
|
58
|
+
for (let dy = -2; dy <= 2; dy++)
|
|
59
|
+
for (let dx = -2; dx <= 2; dx++)
|
|
60
|
+
region[(cy + dy) * size + cx + dx] = Region.Alignment;
|
|
61
|
+
}));
|
|
62
|
+
return region;
|
|
63
|
+
}
|
|
64
|
+
const cacheSize = 16;
|
|
65
|
+
/** Recent matrices by input, oldest first: a Map keeps insertion order. */
|
|
66
|
+
const cache = new Map();
|
|
67
|
+
/**
|
|
68
|
+
* Encodes `value` into a module matrix, without Solid.
|
|
69
|
+
* Repeat calls with the same input return the cached object; see `QRMatrix`.
|
|
70
|
+
* `level` defaults to `'L'` here. The components default to `'M'`, or `'Q'` with a logo.
|
|
71
|
+
* @throws {QRCapacityError} when the data does not fit `maxVersion`.
|
|
72
|
+
* @throws {RangeError} when `minVersion` exceeds `maxVersion`, or a version or mask is out of range.
|
|
73
|
+
*/
|
|
74
|
+
export function encode(value, options = {}) {
|
|
75
|
+
const { level = 'L', minVersion = 1, maxVersion = 40, mask = -1, boostLevel = true } = options;
|
|
76
|
+
const key = JSON.stringify([value, level, minVersion, maxVersion, mask, boostLevel]);
|
|
77
|
+
const hit = cache.get(key);
|
|
78
|
+
if (hit) {
|
|
79
|
+
cache.delete(key);
|
|
80
|
+
cache.set(key, hit);
|
|
81
|
+
return hit;
|
|
82
|
+
}
|
|
83
|
+
const matrix = encodeUncached(value, level, minVersion, maxVersion, mask, boostLevel);
|
|
84
|
+
cache.set(key, matrix);
|
|
85
|
+
if (cache.size > cacheSize)
|
|
86
|
+
cache.delete(cache.keys().next().value);
|
|
87
|
+
return matrix;
|
|
88
|
+
}
|
|
89
|
+
function encodeUncached(value, level, minVersion, maxVersion, mask, boostLevel) {
|
|
90
|
+
if (minVersion > maxVersion)
|
|
91
|
+
throw new RangeError(`minVersion (${minVersion}) must not exceed maxVersion (${maxVersion})`);
|
|
92
|
+
const segments = makeSegments(value);
|
|
93
|
+
let qr;
|
|
94
|
+
try {
|
|
95
|
+
qr = QrCode.encodeSegments(segments, eccByLevel[level], minVersion, maxVersion, mask, boostLevel);
|
|
96
|
+
}
|
|
97
|
+
catch (e) {
|
|
98
|
+
if (e instanceof RangeError && e.message === 'Data too long') {
|
|
99
|
+
const dataLength = segments.reduce((n, s) => n + s.numChars, 0);
|
|
100
|
+
throw new QRCapacityError(maxVersion, level, dataLength);
|
|
101
|
+
}
|
|
102
|
+
throw e;
|
|
103
|
+
}
|
|
104
|
+
const { size } = qr;
|
|
105
|
+
const dark = new Uint8Array(size * size);
|
|
106
|
+
qr.getModules().forEach((row, y) => row.forEach((on, x) => (dark[y * size + x] = on ? 1 : 0)));
|
|
107
|
+
return Object.freeze({
|
|
108
|
+
size,
|
|
109
|
+
version: qr.version,
|
|
110
|
+
level: levelByOrdinal[qr.errorCorrectionLevel.ordinal],
|
|
111
|
+
mask: qr.mask,
|
|
112
|
+
dark,
|
|
113
|
+
region: markRegions(qr),
|
|
114
|
+
finders: Object.freeze([
|
|
115
|
+
Object.freeze([0, 0]),
|
|
116
|
+
Object.freeze([size - 7, 0]),
|
|
117
|
+
Object.freeze([0, size - 7]),
|
|
118
|
+
]),
|
|
119
|
+
});
|
|
120
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { Region } from './encode.js';
|
|
2
|
+
/**
|
|
3
|
+
* The largest share of all modules (size squared) that the excavated box may cover, per level,
|
|
4
|
+
* as `[versions 1-6, versions 7+]`. The box is the image plus padding, rounded outward.
|
|
5
|
+
* About 75% of the smallest box share that jsQR and ZXing both decoded on versions 2-15,
|
|
6
|
+
* with two values and the square and dots shapes. L is not recommended with a logo: its budget
|
|
7
|
+
* fits a tiny logo at best, so most L logos are reduced or dropped.
|
|
8
|
+
*/
|
|
9
|
+
export const maxLogoArea = {
|
|
10
|
+
L: [0.022, 0.022],
|
|
11
|
+
M: [0.03, 0.07],
|
|
12
|
+
Q: [0.072, 0.088],
|
|
13
|
+
H: [0.116, 0.07],
|
|
14
|
+
};
|
|
15
|
+
/** A logo narrower than this many modules is dropped, not drawn over modules. */
|
|
16
|
+
const minLogoWidth = 2;
|
|
17
|
+
function place(n, image, size) {
|
|
18
|
+
const aspect = image.aspect ?? 1;
|
|
19
|
+
const padding = image.excavate === false ? 0 : (image.padding ?? 1);
|
|
20
|
+
const width = size * n;
|
|
21
|
+
const height = width / aspect;
|
|
22
|
+
const [x, y] = [(n - width) / 2, (n - height) / 2];
|
|
23
|
+
const cells = {
|
|
24
|
+
x0: Math.floor(x - padding),
|
|
25
|
+
y0: Math.floor(y - padding),
|
|
26
|
+
x1: Math.ceil(x + width + padding),
|
|
27
|
+
y1: Math.ceil(y + height + padding),
|
|
28
|
+
};
|
|
29
|
+
return { x, y, width, height, cells };
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* True when the box stays in budget and covers only data cells. From version 7 an alignment
|
|
33
|
+
* pattern sits at the centre, so there the box may also cover alignment cells.
|
|
34
|
+
*/
|
|
35
|
+
function fits(m, c, budget) {
|
|
36
|
+
if (c.x0 < 0 || c.y0 < 0 || c.x1 > m.size || c.y1 > m.size)
|
|
37
|
+
return false;
|
|
38
|
+
if ((c.x1 - c.x0) * (c.y1 - c.y0) > budget * m.size * m.size)
|
|
39
|
+
return false;
|
|
40
|
+
const allowed = (r) => r === Region.Data || (m.version >= 7 && r === Region.Alignment);
|
|
41
|
+
for (let y = c.y0; y < c.y1; y++)
|
|
42
|
+
for (let x = c.x0; x < c.x1; x++)
|
|
43
|
+
if (!allowed(m.region[y * m.size + x]))
|
|
44
|
+
return false;
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The largest logo width fraction, up to `image.size`, whose box fits the level budget and
|
|
49
|
+
* covers only data cells. Returns 0 when no logo fits.
|
|
50
|
+
*/
|
|
51
|
+
export function clampImageSize(matrix, image) {
|
|
52
|
+
const budget = maxLogoArea[matrix.level][matrix.version >= 7 ? 1 : 0];
|
|
53
|
+
const ok = (size) => fits(matrix, place(matrix.size, image, size).cells, budget);
|
|
54
|
+
const size = image.size ?? 0.2;
|
|
55
|
+
if (ok(size))
|
|
56
|
+
return size;
|
|
57
|
+
// The box only grows with size, so bisection finds the edge.
|
|
58
|
+
let [lo, hi] = [0, size];
|
|
59
|
+
for (let i = 0; i < 24; i++) {
|
|
60
|
+
const mid = (lo + hi) / 2;
|
|
61
|
+
if (ok(mid))
|
|
62
|
+
lo = mid;
|
|
63
|
+
else
|
|
64
|
+
hi = mid;
|
|
65
|
+
}
|
|
66
|
+
return lo * matrix.size < minLogoWidth ? 0 : lo;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Centres the logo on the code, in scene units with the code box at the origin, or returns
|
|
70
|
+
* undefined when it cannot fit. `cells` is empty when `excavate` is false.
|
|
71
|
+
*/
|
|
72
|
+
export function logoBox(matrix, margin, image) {
|
|
73
|
+
const size = clampImageSize(matrix, image);
|
|
74
|
+
if (!size)
|
|
75
|
+
return undefined;
|
|
76
|
+
const { x, y, width, height, cells } = place(matrix.size, image, size);
|
|
77
|
+
const box = {
|
|
78
|
+
href: image.src,
|
|
79
|
+
x: x + margin,
|
|
80
|
+
y: y + margin,
|
|
81
|
+
width,
|
|
82
|
+
height,
|
|
83
|
+
radius: Math.min(0.5, image.radius ?? 0) * Math.min(width, height),
|
|
84
|
+
opacity: image.opacity ?? 1,
|
|
85
|
+
cells: image.excavate === false ? { x0: 0, y0: 0, x1: 0, y1: 0 } : cells,
|
|
86
|
+
};
|
|
87
|
+
if (image.crossOrigin !== undefined)
|
|
88
|
+
box.crossOrigin = image.crossOrigin;
|
|
89
|
+
return box;
|
|
90
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { toCaptionShape } from './caption.js';
|
|
2
|
+
import { square } from '../shapes/modules.js';
|
|
3
|
+
// `satisfies` fails the build when a key is added to QRCodeOptions but not here.
|
|
4
|
+
const optionKeySet = {
|
|
5
|
+
value: true,
|
|
6
|
+
size: true,
|
|
7
|
+
level: true,
|
|
8
|
+
margin: true,
|
|
9
|
+
fg: true,
|
|
10
|
+
bg: true,
|
|
11
|
+
modules: true,
|
|
12
|
+
finder: true,
|
|
13
|
+
image: true,
|
|
14
|
+
caption: true,
|
|
15
|
+
frame: true,
|
|
16
|
+
title: true,
|
|
17
|
+
id: true,
|
|
18
|
+
encoding: true,
|
|
19
|
+
};
|
|
20
|
+
/** The option props, which the components keep off the DOM element. */
|
|
21
|
+
export const optionKeys = Object.keys(optionKeySet);
|
|
22
|
+
export const defaults = {
|
|
23
|
+
size: 128,
|
|
24
|
+
margin: 4,
|
|
25
|
+
fg: 'var(--qr-fg, #000)',
|
|
26
|
+
bg: 'var(--qr-bg, #fff)',
|
|
27
|
+
};
|
|
28
|
+
/** The finder shape without its colours. */
|
|
29
|
+
export const toFinderShape = (finder = {}) => ({
|
|
30
|
+
outer: finder.outer,
|
|
31
|
+
inner: finder.inner,
|
|
32
|
+
});
|
|
33
|
+
/**
|
|
34
|
+
* The paint-free part of the design, with defaults applied. Reads no colour field.
|
|
35
|
+
* Pass `finder` and `caption` to keep it from reading the options that also hold colours.
|
|
36
|
+
*/
|
|
37
|
+
export function toGeometryDesign(options, finder = toFinderShape(options.finder), caption = toCaptionShape(options.caption)) {
|
|
38
|
+
return {
|
|
39
|
+
margin: options.margin ?? defaults.margin,
|
|
40
|
+
modules: options.modules ?? square,
|
|
41
|
+
finder,
|
|
42
|
+
image: options.image,
|
|
43
|
+
caption,
|
|
44
|
+
frame: options.frame,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/** The paints, with defaults applied. */
|
|
48
|
+
export function toPaints(options) {
|
|
49
|
+
return {
|
|
50
|
+
fg: options.fg ?? defaults.fg,
|
|
51
|
+
bg: options.bg ?? defaults.bg,
|
|
52
|
+
finder: options.finder?.color,
|
|
53
|
+
finderInner: options.finder?.innerColor,
|
|
54
|
+
caption: options.caption?.color,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { defaults } from './options.js';
|
|
2
|
+
/** The size of a drawing in CSS pixels. `size` is the width; the height keeps the scene ratio. */
|
|
3
|
+
export const outputSize = (scene, size = defaults.size) => ({
|
|
4
|
+
width: size,
|
|
5
|
+
height: (size * scene.height) / scene.width,
|
|
6
|
+
});
|
|
7
|
+
/** A JSX attribute may hold `false` to remove it, so only a non-empty string counts. */
|
|
8
|
+
const text = (value) => typeof value === 'string' && value ? value : undefined;
|
|
9
|
+
/**
|
|
10
|
+
* The `aria-label` for a drawing, or undefined when another attribute names it.
|
|
11
|
+
* An SVG names itself through its `<title>`; a canvas has no such element,
|
|
12
|
+
* so with `titleIsLabel` the title becomes its label.
|
|
13
|
+
*/
|
|
14
|
+
export function ariaLabel(props, titleIsLabel) {
|
|
15
|
+
const [title, label, labelledby] = [
|
|
16
|
+
text(props.title),
|
|
17
|
+
text(props['aria-label']),
|
|
18
|
+
text(props['aria-labelledby']),
|
|
19
|
+
];
|
|
20
|
+
if (titleIsLabel)
|
|
21
|
+
return title ?? label ?? (labelledby ? undefined : 'QR code');
|
|
22
|
+
return title || label || labelledby ? undefined : 'QR code';
|
|
23
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/** Rounds to 4 decimals; `+ 0` turns -0 into 0. */
|
|
2
|
+
const round = (v) => Math.round(v * 1e4) / 1e4 + 0;
|
|
3
|
+
// Canvas `addColorStop` throws outside 0..1.
|
|
4
|
+
const clamp = (v) => Math.min(1, Math.max(0, v));
|
|
5
|
+
function placeStops(stops) {
|
|
6
|
+
if (stops.length < 2)
|
|
7
|
+
throw new RangeError(`A gradient needs at least 2 stops, got ${stops.length}.`);
|
|
8
|
+
const last = stops.length - 1;
|
|
9
|
+
return stops.map((s, i) => (typeof s === 'string' ? [round(i / last), s] : [clamp(s[0]), s[1]]));
|
|
10
|
+
}
|
|
11
|
+
/** Maps a paint to user-space gradient coordinates over `box`. */
|
|
12
|
+
export function placePaint(paint, box) {
|
|
13
|
+
if (typeof paint === 'string')
|
|
14
|
+
return paint;
|
|
15
|
+
const half = box.size / 2;
|
|
16
|
+
const [cx, cy] = [box.x + half, box.y + half];
|
|
17
|
+
const stops = placeStops(paint.stops);
|
|
18
|
+
if (paint.type === 'radial')
|
|
19
|
+
return { type: 'radial', cx, cy, r: half, stops };
|
|
20
|
+
const angle = ((paint.rotate ?? 0) * Math.PI) / 180;
|
|
21
|
+
const [dx, dy] = [Math.cos(angle) * half, Math.sin(angle) * half];
|
|
22
|
+
return {
|
|
23
|
+
type: 'linear',
|
|
24
|
+
x1: round(cx - dx),
|
|
25
|
+
y1: round(cy - dy),
|
|
26
|
+
x2: round(cx + dx),
|
|
27
|
+
y2: round(cy + dy),
|
|
28
|
+
stops,
|
|
29
|
+
};
|
|
30
|
+
}
|