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,123 @@
|
|
|
1
|
+
export const browserIO = {
|
|
2
|
+
fetch: (input, init) => fetch(input, init),
|
|
3
|
+
makeImage: () => (typeof Image === 'undefined' ? undefined : new Image()),
|
|
4
|
+
decodeBlob: (blob) => createImageBitmap(blob),
|
|
5
|
+
};
|
|
6
|
+
const timeoutDefault = 10_000;
|
|
7
|
+
const maxBytesDefault = 2 * 1024 * 1024;
|
|
8
|
+
/**
|
|
9
|
+
* Fetches the image with the CORS mode an `<img crossorigin>` would use.
|
|
10
|
+
* Rejects on a timeout, a cancel, an HTTP error, a body over `maxBytes`, or a non-image body.
|
|
11
|
+
*/
|
|
12
|
+
export async function fetchImage(image, limits = {}, io = browserIO) {
|
|
13
|
+
const { timeout = timeoutDefault, maxBytes = maxBytesDefault, signal } = limits;
|
|
14
|
+
const credentials = image.crossOrigin === 'use-credentials' ? 'include' : 'same-origin';
|
|
15
|
+
const controller = new AbortController();
|
|
16
|
+
const timer = setTimeout(() => controller.abort(new Error(`Timed out after ${timeout} ms`)), timeout);
|
|
17
|
+
const cancel = () => controller.abort(signal?.reason);
|
|
18
|
+
signal?.addEventListener('abort', cancel, { once: true });
|
|
19
|
+
const tooLarge = (bytes) => new Error(`Image is ${bytes} bytes, over the ${maxBytes} byte limit`);
|
|
20
|
+
try {
|
|
21
|
+
signal?.throwIfAborted();
|
|
22
|
+
const response = await io.fetch(image.src, {
|
|
23
|
+
mode: 'cors',
|
|
24
|
+
credentials,
|
|
25
|
+
signal: controller.signal,
|
|
26
|
+
});
|
|
27
|
+
if (!response.ok)
|
|
28
|
+
throw new Error(`HTTP ${response.status}`);
|
|
29
|
+
const length = Number(response.headers.get('content-length'));
|
|
30
|
+
if (length > maxBytes) {
|
|
31
|
+
controller.abort();
|
|
32
|
+
throw tooLarge(length);
|
|
33
|
+
}
|
|
34
|
+
const blob = await readBody(response, maxBytes, (bytes) => {
|
|
35
|
+
controller.abort();
|
|
36
|
+
return tooLarge(bytes);
|
|
37
|
+
});
|
|
38
|
+
if (!blob.type.startsWith('image/'))
|
|
39
|
+
throw new Error(`Not an image: ${blob.type || 'no type'}`);
|
|
40
|
+
return blob;
|
|
41
|
+
}
|
|
42
|
+
finally {
|
|
43
|
+
clearTimeout(timer);
|
|
44
|
+
signal?.removeEventListener('abort', cancel);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** Reads the body, and stops once it passes `maxBytes`, so a huge logo is never held whole. */
|
|
48
|
+
async function readBody(response, maxBytes, tooLarge) {
|
|
49
|
+
if (!response.body) {
|
|
50
|
+
const blob = await response.blob();
|
|
51
|
+
if (blob.size > maxBytes)
|
|
52
|
+
throw tooLarge(blob.size);
|
|
53
|
+
return blob;
|
|
54
|
+
}
|
|
55
|
+
const reader = response.body.getReader();
|
|
56
|
+
const chunks = [];
|
|
57
|
+
let bytes = 0;
|
|
58
|
+
for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
|
|
59
|
+
bytes += chunk.value.byteLength;
|
|
60
|
+
if (bytes > maxBytes) {
|
|
61
|
+
reader.cancel().catch(() => { });
|
|
62
|
+
throw tooLarge(bytes);
|
|
63
|
+
}
|
|
64
|
+
chunks.push(chunk.value);
|
|
65
|
+
}
|
|
66
|
+
return new Blob(chunks, { type: response.headers.get('content-type') ?? '' });
|
|
67
|
+
}
|
|
68
|
+
/** Loads the image, or returns undefined when it fails: the code draws without it. */
|
|
69
|
+
export async function loadImage(image, limits = {}, io = browserIO) {
|
|
70
|
+
const { timeout = timeoutDefault, signal, warn = true } = limits;
|
|
71
|
+
try {
|
|
72
|
+
signal?.throwIfAborted();
|
|
73
|
+
// A DOM image keeps the component's CORS rules: no crossOrigin taints, it does not fail.
|
|
74
|
+
const img = io.makeImage();
|
|
75
|
+
if (!img)
|
|
76
|
+
return await io.decodeBlob(await fetchImage(image, limits, io));
|
|
77
|
+
if (image.crossOrigin !== undefined)
|
|
78
|
+
img.crossOrigin = image.crossOrigin;
|
|
79
|
+
img.src = image.src;
|
|
80
|
+
let timer;
|
|
81
|
+
let stop = () => { };
|
|
82
|
+
const cancelled = new Promise((_resolve, reject) => {
|
|
83
|
+
timer = setTimeout(() => reject(new Error(`Timed out after ${timeout} ms`)), timeout);
|
|
84
|
+
const onAbort = () => reject(signal?.reason);
|
|
85
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
86
|
+
stop = () => signal?.removeEventListener('abort', onAbort);
|
|
87
|
+
});
|
|
88
|
+
// `decode()` may throw before the race attaches a handler to `cancelled`.
|
|
89
|
+
cancelled.catch(() => { });
|
|
90
|
+
try {
|
|
91
|
+
await Promise.race([img.decode(), cancelled]);
|
|
92
|
+
}
|
|
93
|
+
catch (err) {
|
|
94
|
+
img.src = '';
|
|
95
|
+
throw err;
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
clearTimeout(timer);
|
|
99
|
+
stop();
|
|
100
|
+
}
|
|
101
|
+
return img;
|
|
102
|
+
}
|
|
103
|
+
catch (err) {
|
|
104
|
+
if (warn && !signal?.aborted)
|
|
105
|
+
console.warn(`[qrcodesolid] Failed to load image: ${image.src}`, err);
|
|
106
|
+
return undefined;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
export async function blobToDataURL(blob) {
|
|
110
|
+
if (typeof FileReader !== 'undefined')
|
|
111
|
+
return new Promise((resolve, reject) => {
|
|
112
|
+
const reader = new FileReader();
|
|
113
|
+
reader.onload = () => resolve(reader.result);
|
|
114
|
+
reader.onerror = () => reject(reader.error);
|
|
115
|
+
reader.readAsDataURL(blob);
|
|
116
|
+
});
|
|
117
|
+
const bytes = new Uint8Array(await blob.arrayBuffer());
|
|
118
|
+
let binary = '';
|
|
119
|
+
// Chunks keep String.fromCharCode under the engine's argument limit.
|
|
120
|
+
for (let i = 0; i < bytes.length; i += 0x8000)
|
|
121
|
+
binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
122
|
+
return `data:${blob.type || 'application/octet-stream'};base64,${btoa(binary)}`;
|
|
123
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { coord } from '../shapes/types.js';
|
|
2
|
+
const entities = {
|
|
3
|
+
'&': '&',
|
|
4
|
+
'<': '<',
|
|
5
|
+
'>': '>',
|
|
6
|
+
'"': '"',
|
|
7
|
+
"'": ''',
|
|
8
|
+
};
|
|
9
|
+
const escape = (s) => s.replace(/[&<>"']/g, (c) => entities[c]);
|
|
10
|
+
/** Square-only scenes contain no curves or diagonals, so crisp edges cannot hurt them. */
|
|
11
|
+
export const isRectilinear = (d) => /^[MHVhvZz\d .-]*$/.test(d);
|
|
12
|
+
function gradient(id, paint) {
|
|
13
|
+
const stops = paint.stops
|
|
14
|
+
.map(([offset, color]) => `<stop offset="${offset}" stop-color="${escape(color)}"/>`)
|
|
15
|
+
.join('');
|
|
16
|
+
const attrs = paint.type === 'linear'
|
|
17
|
+
? `x1="${paint.x1}" y1="${paint.y1}" x2="${paint.x2}" y2="${paint.y2}"`
|
|
18
|
+
: `cx="${paint.cx}" cy="${paint.cy}" r="${paint.r}"`;
|
|
19
|
+
const tag = paint.type === 'linear' ? 'linearGradient' : 'radialGradient';
|
|
20
|
+
return `<${tag} id="${escape(id)}" gradientUnits="userSpaceOnUse" ${attrs}>${stops}</${tag}>`;
|
|
21
|
+
}
|
|
22
|
+
/** Serialises a scene to a standalone SVG document string. */
|
|
23
|
+
export function sceneToSVGString(scene, options) {
|
|
24
|
+
const { width, height, image } = scene;
|
|
25
|
+
const defs = [];
|
|
26
|
+
const fill = (id, paint) => {
|
|
27
|
+
if (typeof paint === 'string')
|
|
28
|
+
return escape(paint);
|
|
29
|
+
const ref = `${options.idPrefix}-${id}`;
|
|
30
|
+
defs.push(gradient(ref, paint));
|
|
31
|
+
return `url(#${escape(ref)})`;
|
|
32
|
+
};
|
|
33
|
+
const body = scene.layers.map((layer) => {
|
|
34
|
+
const rule = layer.fillRule ? ` fill-rule="${layer.fillRule}"` : '';
|
|
35
|
+
return `<path d="${escape(layer.d)}" fill="${fill(layer.id, layer.fill)}"${rule}/>`;
|
|
36
|
+
});
|
|
37
|
+
if (image) {
|
|
38
|
+
const clip = `${options.idPrefix}-image-clip`;
|
|
39
|
+
const box = `x="${coord(image.x)}" y="${coord(image.y)}" width="${coord(image.width)}" height="${coord(image.height)}"`;
|
|
40
|
+
const r = coord(image.radius);
|
|
41
|
+
defs.push(`<clipPath id="${escape(clip)}"><rect ${box} rx="${r}" ry="${r}"/></clipPath>`);
|
|
42
|
+
const crossOrigin = image.crossOrigin === undefined ? '' : ` crossorigin="${image.crossOrigin}"`;
|
|
43
|
+
body.push(`<image href="${escape(image.href)}" ${box} opacity="${image.opacity}" preserveAspectRatio="xMidYMid meet" clip-path="url(#${escape(clip)})"${crossOrigin}/>`);
|
|
44
|
+
}
|
|
45
|
+
scene.texts.forEach((t, i) => {
|
|
46
|
+
const font = `font-size="${coord(t.fontSize)}" font-family="${escape(t.fontFamily)}" font-weight="${escape(String(t.fontWeight))}"`;
|
|
47
|
+
body.push(`<text x="${coord(t.x)}" y="${coord(t.y)}" ${font} fill="${fill(`text-${i}`, t.fill)}" text-anchor="middle" dominant-baseline="central">${escape(t.text)}</text>`);
|
|
48
|
+
});
|
|
49
|
+
const crisp = scene.layers.every((l) => isRectilinear(l.d))
|
|
50
|
+
? ' shape-rendering="crispEdges"'
|
|
51
|
+
: '';
|
|
52
|
+
const title = options.title ? `<title>${escape(options.title)}</title>` : '';
|
|
53
|
+
const head = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${coord(width)} ${coord(height)}" width="${coord(options.size)}" height="${coord((options.size * height) / width)}"${crisp}>`;
|
|
54
|
+
return `${head}${title}${defs.length ? `<defs>${defs.join('')}</defs>` : ''}${body.join('')}</svg>`;
|
|
55
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { isDark, Region } from '../core/encode.js';
|
|
2
|
+
import { defineLayerShape, coord } from './types.js';
|
|
3
|
+
const inset = 0.1;
|
|
4
|
+
const radius = 0.5 - inset;
|
|
5
|
+
/** Pill for one run of `length` cells. `cross` is the cell column (or row), `start` the run origin. */
|
|
6
|
+
const pill = (vertical, cross, start, length) => {
|
|
7
|
+
const c0 = cross + inset;
|
|
8
|
+
const c1 = cross + 1 - inset;
|
|
9
|
+
const s0 = start + radius;
|
|
10
|
+
const s1 = start + length - radius;
|
|
11
|
+
const p = (c, s) => vertical ? `${coord(c)} ${coord(s)}` : `${coord(s)} ${coord(c)}`;
|
|
12
|
+
const arc = `A${radius} ${radius} 0 0 ${vertical ? 1 : 0}`;
|
|
13
|
+
return `M${p(c0, s0)}${arc} ${p(c1, s0)}L${p(c1, s1)}${arc} ${p(c0, s1)}z`;
|
|
14
|
+
};
|
|
15
|
+
function bars(vertical) {
|
|
16
|
+
return defineLayerShape(({ matrix: m, include, offset }) => {
|
|
17
|
+
const on = (a, b) => {
|
|
18
|
+
const [x, y] = vertical ? [a, b] : [b, a];
|
|
19
|
+
return include(x, y) && isDark(m, x, y);
|
|
20
|
+
};
|
|
21
|
+
const solid = (a, b) => {
|
|
22
|
+
const [x, y] = vertical ? [a, b] : [b, a];
|
|
23
|
+
return m.region[y * m.size + x] === Region.Alignment;
|
|
24
|
+
};
|
|
25
|
+
let d = '';
|
|
26
|
+
for (let a = 0; a < m.size; a++) {
|
|
27
|
+
let b = 0;
|
|
28
|
+
while (b < m.size) {
|
|
29
|
+
if (!on(a, b)) {
|
|
30
|
+
b++;
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
const start = b;
|
|
34
|
+
if (solid(a, b)) {
|
|
35
|
+
b++;
|
|
36
|
+
const [x, y] = vertical ? [a, start] : [start, a];
|
|
37
|
+
d += `M${coord(x + offset.x)} ${coord(y + offset.y)}h1v1h-1z`;
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
while (b < m.size && on(a, b) && !solid(a, b))
|
|
41
|
+
b++;
|
|
42
|
+
const cross = (vertical ? offset.x : offset.y) + a;
|
|
43
|
+
d += pill(vertical, cross, (vertical ? offset.y : offset.x) + start, b - start);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return d;
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
export const verticalBars = bars(true);
|
|
50
|
+
export const horizontalBars = bars(false);
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { coord } from './types.js';
|
|
2
|
+
export const rect = (x, y, w, h, radius) => {
|
|
3
|
+
const r = Math.max(0, Math.min(radius, w / 2, h / 2));
|
|
4
|
+
if (r === 0)
|
|
5
|
+
return `M${coord(x)} ${coord(y)}h${coord(w)}v${coord(h)}h-${coord(w)}z`;
|
|
6
|
+
const [rc, sw, sh] = [coord(r), coord(w - 2 * r), coord(h - 2 * r)];
|
|
7
|
+
const arc = (dx, dy) => `a${rc} ${rc} 0 0 1 ${dx} ${dy}`;
|
|
8
|
+
return (`M${coord(x + r)} ${coord(y)}h${sw}${arc(rc, rc)}v${sh}${arc(`-${rc}`, rc)}` +
|
|
9
|
+
`h-${sw}${arc(`-${rc}`, `-${rc}`)}v-${sh}${arc(rc, `-${rc}`)}z`);
|
|
10
|
+
};
|
|
11
|
+
const circle = (cx, cy, r) => `M${coord(cx - r)} ${coord(cy)}a${r} ${r} 0 1 0 ${coord(2 * r)} 0a${r} ${r} 0 1 0 -${coord(2 * r)} 0z`;
|
|
12
|
+
/** Outer presets are two subpaths (contour + hole); the layer fills with `evenodd`. */
|
|
13
|
+
export const finderOuter = {
|
|
14
|
+
square: (x, y) => rect(x, y, 7, 7, 0) + rect(x + 1, y + 1, 5, 5, 0),
|
|
15
|
+
rounded: (x, y) => rect(x, y, 7, 7, 2) + rect(x + 1, y + 1, 5, 5, 1),
|
|
16
|
+
circle: (x, y) => circle(x + 3.5, y + 3.5, 3.5) + circle(x + 3.5, y + 3.5, 2.5),
|
|
17
|
+
};
|
|
18
|
+
export const finderInner = {
|
|
19
|
+
square: (x, y) => rect(x + 2, y + 2, 3, 3, 0),
|
|
20
|
+
rounded: (x, y) => rect(x + 2, y + 2, 3, 3, 0.8),
|
|
21
|
+
dot: (x, y) => circle(x + 3.5, y + 3.5, 1.6),
|
|
22
|
+
diamond: (x, y) => `M${coord(x + 3.5)} ${coord(y + 1.5)}L${coord(x + 5.5)} ${coord(y + 3.5)}L${coord(x + 3.5)} ${coord(y + 5.5)}L${coord(x + 1.5)} ${coord(y + 3.5)}z`,
|
|
23
|
+
};
|
|
24
|
+
export function getFinder(style) {
|
|
25
|
+
const { outer = 'square', inner = 'square' } = style;
|
|
26
|
+
return {
|
|
27
|
+
outer: typeof outer === 'function' ? outer : finderOuter[outer],
|
|
28
|
+
inner: typeof inner === 'function' ? inner : finderInner[inner],
|
|
29
|
+
};
|
|
30
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { fitFontSize, overflowWarning } from '../core/caption.js';
|
|
2
|
+
import { rect } from './finders.js';
|
|
3
|
+
const fontFamily = 'system-ui, sans-serif';
|
|
4
|
+
/** Moves the code by `pad` and grows the layout by `pad` on every side. */
|
|
5
|
+
const grow = ({ width, height, qr }, pad) => ({
|
|
6
|
+
width: width + 2 * pad,
|
|
7
|
+
height: height + 2 * pad,
|
|
8
|
+
qr: { ...qr, x: qr.x + pad, y: qr.y + pad },
|
|
9
|
+
});
|
|
10
|
+
/** A ring of `width` modules around the code. Default colour is fg. */
|
|
11
|
+
export function border(o = {}) {
|
|
12
|
+
const { width: w = 1, radius = 0, color = 'fg' } = o;
|
|
13
|
+
return (inner) => {
|
|
14
|
+
const layout = grow(inner, w);
|
|
15
|
+
const d = rect(0, 0, layout.width, layout.height, radius) +
|
|
16
|
+
rect(w, w, inner.width, inner.height, Math.max(radius - w, 0));
|
|
17
|
+
return {
|
|
18
|
+
layout,
|
|
19
|
+
paths: [{ id: 'frame-border', d, fillRule: 'evenodd', paint: color }],
|
|
20
|
+
texts: [],
|
|
21
|
+
};
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/** A rounded panel `padding` modules wider than the code on every side. */
|
|
25
|
+
export function card(o = {}) {
|
|
26
|
+
const { padding = 2, radius = 2, color = '#fff' } = o;
|
|
27
|
+
return (inner) => {
|
|
28
|
+
const layout = grow(inner, padding);
|
|
29
|
+
const d = rect(0, 0, layout.width, layout.height, radius);
|
|
30
|
+
return { layout, paths: [{ id: 'frame-card', d, paint: color }], texts: [] };
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* A band with a label above or below the code, outside its quiet zone.
|
|
35
|
+
* Long text shrinks to fit the width, down to 1 module, and the band shrinks with it.
|
|
36
|
+
*/
|
|
37
|
+
export function banner(o) {
|
|
38
|
+
const { text, position = 'bottom', color = '#000', textColor = '#fff' } = o;
|
|
39
|
+
return ({ width, height, qr }) => {
|
|
40
|
+
const fitted = fitFontSize(text, o.fontSize ?? 2, width);
|
|
41
|
+
const { fontSize } = fitted;
|
|
42
|
+
const warning = overflowWarning('banner text', text, fitted, width, 'the banner');
|
|
43
|
+
const band = fontSize * 2;
|
|
44
|
+
const top = position === 'top';
|
|
45
|
+
const y = top ? 0 : height;
|
|
46
|
+
const label = {
|
|
47
|
+
text,
|
|
48
|
+
x: width / 2,
|
|
49
|
+
y: y + band / 2,
|
|
50
|
+
fontSize,
|
|
51
|
+
fontFamily,
|
|
52
|
+
fontWeight: 'bold',
|
|
53
|
+
paint: textColor,
|
|
54
|
+
};
|
|
55
|
+
return {
|
|
56
|
+
layout: { width, height: height + band, qr: top ? { ...qr, y: qr.y + band } : qr },
|
|
57
|
+
paths: [{ id: 'frame-banner', d: rect(0, y, width, band, 0), paint: color }],
|
|
58
|
+
texts: [label],
|
|
59
|
+
warnings: warning ? [warning] : [],
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { isDark } from '../core/encode.js';
|
|
2
|
+
import { defineLayerShape, defineModuleShape, coord } from './types.js';
|
|
3
|
+
/** Square modules, merged into one subpath per horizontal run. */
|
|
4
|
+
export const square = defineLayerShape(({ matrix: m, include, offset }) => {
|
|
5
|
+
let d = '';
|
|
6
|
+
for (let y = 0; y < m.size; y++) {
|
|
7
|
+
let x = 0;
|
|
8
|
+
while (x < m.size) {
|
|
9
|
+
if (!(include(x, y) && isDark(m, x, y))) {
|
|
10
|
+
x++;
|
|
11
|
+
continue;
|
|
12
|
+
}
|
|
13
|
+
const start = x;
|
|
14
|
+
while (x < m.size && include(x, y) && isDark(m, x, y))
|
|
15
|
+
x++;
|
|
16
|
+
const len = x - start;
|
|
17
|
+
d += `M${coord(start + offset.x)} ${coord(y + offset.y)}h${len}v1h-${len}z`;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return d;
|
|
21
|
+
});
|
|
22
|
+
const cell = (x, y) => `M${coord(x)} ${coord(y)}h1v1h-1z`;
|
|
23
|
+
export const dots = defineModuleShape(({ x, y, alignment }) => {
|
|
24
|
+
if (alignment)
|
|
25
|
+
return cell(x, y);
|
|
26
|
+
const r = 0.4;
|
|
27
|
+
return `M${coord(x + 0.5 - r)} ${coord(y + 0.5)}a${r} ${r} 0 1 0 ${coord(2 * r)} 0a${r} ${r} 0 1 0 -${coord(2 * r)} 0z`;
|
|
28
|
+
});
|
|
29
|
+
export const diamond = defineModuleShape(({ x, y, alignment }) => alignment
|
|
30
|
+
? cell(x, y)
|
|
31
|
+
: `M${coord(x + 0.5)} ${coord(y)}L${coord(x + 1)} ${coord(y + 0.5)}L${coord(x + 0.5)} ${coord(y + 1)}L${coord(x)} ${coord(y + 0.5)}z`);
|
|
32
|
+
/** A corner is round only when both orthogonal neighbours on that side are not drawn. */
|
|
33
|
+
export const rounded = defineModuleShape(({ x, y, neighbors: { n, e, s, w } }) => {
|
|
34
|
+
const [tl, tr, br, bl] = [!n && !w, !n && !e, !s && !e, !s && !w].map((round) => round ? 0.5 : 0);
|
|
35
|
+
const arc = (to, r) => r ? `A.5 .5 0 0 1 ${coord(to[0])} ${coord(to[1])}` : '';
|
|
36
|
+
return (`M${coord(x + tl)} ${coord(y)}H${coord(x + 1 - tr)}${arc([x + 1, y + tr], tr)}` +
|
|
37
|
+
`V${coord(y + 1 - br)}${arc([x + 1 - br, y + 1], br)}H${coord(x + bl)}${arc([x, y + 1 - bl], bl)}` +
|
|
38
|
+
`V${coord(y + tl)}${arc([x + tl, y], tl)}z`);
|
|
39
|
+
});
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export function defineModuleShape(draw) {
|
|
2
|
+
return { kind: 'module', draw };
|
|
3
|
+
}
|
|
4
|
+
export function defineLayerShape(draw) {
|
|
5
|
+
return { kind: 'layer', draw };
|
|
6
|
+
}
|
|
7
|
+
/** Formats a path coordinate without float noise: 3 decimals, trailing zeros trimmed. */
|
|
8
|
+
export const coord = (v) => String(Math.round(v * 1000) / 1000 + 0);
|
package/llms.txt
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# qrcodesolid
|
|
2
|
+
|
|
3
|
+
> QR code components for Solid 2 (`solid-js` 2, `@solidjs/web` 2). SVG and canvas renderers with
|
|
4
|
+
> the same output, module and finder shapes, gradients, a logo with a scan guard, captions,
|
|
5
|
+
> frames, headless export functions, and payload helpers in `qrcodesolid/payload`. ESM only, no
|
|
6
|
+
> runtime dependencies, SSR-safe. MIT.
|
|
7
|
+
|
|
8
|
+
Full docs: https://github.com/rizaleow/qrcodesolid/tree/main/packages/qrcodesolid#readme
|
|
9
|
+
|
|
10
|
+
## Solid 2 usage rules
|
|
11
|
+
|
|
12
|
+
- Pass values, not accessors: `<QRCodeSVG value={url()} />`, never `value={url}`.
|
|
13
|
+
- Do not destructure props. Pass the props object to `createQRCode(props)` so it stays reactive.
|
|
14
|
+
- `solid-js` 2 names only: `createEffect(compute, apply)`, `onSettled`, `<Errored>`, `<Loading>`,
|
|
15
|
+
`omit`/`merge`. DOM APIs come from `@solidjs/web`. JSX: `"jsxImportSource": "@solidjs/web"`.
|
|
16
|
+
- Too-long data throws `QRCapacityError` during render; catch it with `<Errored>`.
|
|
17
|
+
|
|
18
|
+
## Components
|
|
19
|
+
|
|
20
|
+
- `QRCode`: `renderAs?: 'svg' | 'canvas'` (default `'svg'`), else the props of the chosen renderer.
|
|
21
|
+
- `QRCodeSVG`: inline `<svg>`. Extra attributes pass through.
|
|
22
|
+
- `QRCodeCanvas`: `<canvas>` sized for `devicePixelRatio`, redraws on zoom and on a
|
|
23
|
+
`prefers-color-scheme` change. `repaint` takes any value; a new value redraws. `onReady(canvas)` runs
|
|
24
|
+
after a draw once the image has loaded or failed. `imageTimeout` (ms, default 10000) bounds the
|
|
25
|
+
image load. Extra attributes pass through.
|
|
26
|
+
|
|
27
|
+
## Options (QRCodeOptions, shared by components, createQRCode and export)
|
|
28
|
+
|
|
29
|
+
- `value: string | string[]` (required); array items encode in order, each in its own mode
|
|
30
|
+
- `size = 128` (CSS px)
|
|
31
|
+
- `level: 'L' | 'M' | 'Q' | 'H'` = `'M'`, or `'Q'` when `image` is set
|
|
32
|
+
- `margin = 4` (modules; qrcode.react and qrcode.vue default to 0)
|
|
33
|
+
- `fg: Paint = 'var(--qr-fg, #000)'`, `bg: Paint = 'var(--qr-bg, #fff)'`; `bg: 'transparent'` draws no background
|
|
34
|
+
- `modules: ShapeInput = square`
|
|
35
|
+
- `finder: { outer?: 'square' | 'rounded' | 'circle' | FinderPart, inner?: 'square' | 'rounded' | 'dot' | 'diamond' | FinderPart, color?: Paint, innerColor?: Paint }`; colours default to fg
|
|
36
|
+
- `image: { src, size = 0.2, aspect = 1, padding = 1, radius = 0, excavate = true, opacity = 1, crossOrigin? }`; `size` is a fraction of the code width without margin
|
|
37
|
+
- `caption: { text, position?: 'top' | 'bottom', fontSize = 2, fontFamily?, fontWeight?, color? = fg }`; text estimated wider than the code with its margin shrinks to fit, down to 1 module, and the band shrinks with it (`banner` text too)
|
|
38
|
+
- `frame: FramePlugin | readonly FramePlugin[]` (`border()`, `card()`, `banner({ text })` or custom); an array applies from the inside out, so `[border(), banner({ text })]` bands the border
|
|
39
|
+
- `title` (accessible name, same rules on SVG and canvas: a non-empty `title` wins over `aria-label`, a user `aria-labelledby` outranks both and drops the default; with none the name is `QR code`), `id` (element id and def id prefix)
|
|
40
|
+
- `encoding: { minVersion?, maxVersion?, mask? (-1 best, 0-7), boostLevel? }`; with an image, minVersion defaults to 2 (capped at maxVersion)
|
|
41
|
+
|
|
42
|
+
`Paint = string | { type: 'linear', rotate?: number, stops } | { type: 'radial', stops }`, where
|
|
43
|
+
`stops` is an array of `GradientStop = string | [offset, colour]`: at least two stops, checked at runtime (fewer throws a `RangeError`).
|
|
44
|
+
Gradients span the QR box (code plus margin), including frame and caption paints.
|
|
45
|
+
|
|
46
|
+
## Shapes
|
|
47
|
+
|
|
48
|
+
- Module presets: `square`, `dots`, `rounded`, `diamond`, `verticalBars`, `horizontalBars`.
|
|
49
|
+
- `defineModuleShape((ctx: ModuleContext) => pathData)`: one dark cell. `ctx` has `x`, `y` (scene
|
|
50
|
+
units, 1 per module), `neighbors: { n, e, s, w }`, `alignment` (draw alignment cells solid).
|
|
51
|
+
A plain function is also accepted.
|
|
52
|
+
- `defineLayerShape(({ matrix, include, offset }: LayerContext) => pathData)`: the whole layer. `include(x, y)` is
|
|
53
|
+
false for finders and the logo area; add `offset` to matrix coords.
|
|
54
|
+
- `FinderPart = (x, y) => pathData`, origin at the 7x7 pattern's top-left. Outer fills `evenodd`.
|
|
55
|
+
- `getFinder(style: FinderStyle): FinderParts` returns `{ outer, inner }`. `PlacedPaint` (type of `Layer.fill`) is a colour or a gradient in absolute coordinates. `CrossOrigin = '' | 'anonymous' | 'use-credentials'`.
|
|
56
|
+
- Evidence: every module preset x finder pair x level decodes with ZXing in tests; jsQR decodes
|
|
57
|
+
every module preset with the default finder. Decode custom shapes before shipping.
|
|
58
|
+
|
|
59
|
+
## Frames
|
|
60
|
+
|
|
61
|
+
- `border({ width = 1, radius = 0, color = fg })`, `card({ padding = 2, radius = 2, color = '#fff' })`,
|
|
62
|
+
`banner({ text, position = 'bottom', color = '#000', textColor = '#fff', fontSize = 2 })`.
|
|
63
|
+
- `FramePlugin = (layout: Layout) => { layout, paths, texts }`. It may move `layout.qr` and grow
|
|
64
|
+
the layout, never resize `qr`. A path `paint` is a `Paint` or a `PaintKey`
|
|
65
|
+
(`'fg' | 'bg' | 'finder' | 'finderInner' | 'caption'`).
|
|
66
|
+
|
|
67
|
+
## Scan guard
|
|
68
|
+
|
|
69
|
+
- The logo box (image plus padding) may cover only a per-level share of modules (an internal
|
|
70
|
+
budget, not an export) and only data cells (and the centre alignment pattern from version 7). Short values give small codes, so the logo shrinks, or is dropped under 2
|
|
71
|
+
modules wide. Raise `encoding.minVersion` for a larger logo. Level L is not recommended with a logo.
|
|
72
|
+
- Dev builds warn on a reduced or dropped logo, contrast under 3:1 or fg lighter than bg (opaque `#hex`, `rgb()`, `hsl()` and named colours; the parser loads only under the `development` condition), margin under 2, and a caption estimated wider than the code at the minimum font size.
|
|
73
|
+
|
|
74
|
+
## Colours and theming
|
|
75
|
+
|
|
76
|
+
- Defaults read `--qr-fg` and `--qr-bg`; `currentColor` works.
|
|
77
|
+
- `QRCodeSVG` keeps `var()` in markup: CSS-only theme changes apply at once.
|
|
78
|
+
- `QRCodeCanvas` resolves colours at draw time. It redraws on a `prefers-color-scheme` change; for a
|
|
79
|
+
class-based theme pass the theme as `repaint={theme()}`. `createColorScheme()` is that accessor.
|
|
80
|
+
|
|
81
|
+
## Export (from `qrcodesolid`)
|
|
82
|
+
|
|
83
|
+
- `toSVGString(options & { resolveColors?: boolean })`: keeps `var()` unless `resolveColors`. Runs in Node.
|
|
84
|
+
- `toScene(options)`, `toCanvas(options & { scale? }, canvas?)`, `toPNGBlob(options & { scale? })`,
|
|
85
|
+
`toDataURL(options, 'image/png' | 'image/svg+xml')`, `download(options, filename = 'qrcode.png')`
|
|
86
|
+
(`.svg` saves SVG), `copyToClipboard(options)` (PNG).
|
|
87
|
+
- Raster output, data URLs and downloaded SVG resolve colours to the `var()` fallback;
|
|
88
|
+
`currentColor` becomes `#000`. The `element` option resolves them against that element.
|
|
89
|
+
- Downloaded and data-URL SVG embed the logo as a data URL (CORS fetch, follows `crossOrigin`);
|
|
90
|
+
if the fetch fails they keep the URL and warn. `toSVGString` keeps the URL.
|
|
91
|
+
- DOM: a non-CORS cross-origin logo taints the canvas, so `toPNGBlob` rejects with `SecurityError`.
|
|
92
|
+
Worker: the logo is fetched in CORS mode and dropped if that fails.
|
|
93
|
+
- Logo fetches abort after `imageTimeout` ms (default 10000) and reject over `imageMaxBytes`
|
|
94
|
+
(default 2 MB, by `Content-Length` and body size); every export function takes both. The
|
|
95
|
+
fetch warnings stay in production.
|
|
96
|
+
|
|
97
|
+
## Headless
|
|
98
|
+
|
|
99
|
+
- `createQRCode(props)` returns accessors `{ matrix, geometry, scene }`.
|
|
100
|
+
- `encode(value, { level, minVersion, maxVersion, mask, boostLevel })` returns `QRMatrix`
|
|
101
|
+
(`size`, `version`, `level`, `mask`, `dark`, `region`, `finders`). `encode` defaults to level `'L'`, not the
|
|
102
|
+
components' `'M'`. `minVersion > maxVersion` throws `RangeError`.
|
|
103
|
+
- `drawScene(ctx, scene, { scale, image?, resolveColor })` draws on a 2D context.
|
|
104
|
+
- `sceneToSVGString(scene, { size, idPrefix, title? })` serialises a scene; `resolveSceneColors(scene, element?)`
|
|
105
|
+
replaces `var()` and `currentColor` paints.
|
|
106
|
+
|
|
107
|
+
## Payloads (`qrcodesolid/payload`)
|
|
108
|
+
|
|
109
|
+
`wifi({ ssid, password?, auth?, hidden? })`, `vcard({ name: { first?, last? }, org?, title?, phone?, email?, url?, address?, note? })`,
|
|
110
|
+
`mecard({ name, ... })`, `mailto({ to, subject?, body?, cc?, bcc? })`, `sms({ to, body? })`,
|
|
111
|
+
`tel(number)`, `geo({ lat, lng, altitude?, query? })`, `event({ title, start, end?, location?, description?, allDay? })`.
|
|
112
|
+
|
|
113
|
+
## SSR
|
|
114
|
+
|
|
115
|
+
`QRCodeSVG` renders on the server with ids from `createUniqueId` (stable on hydration).
|
|
116
|
+
`QRCodeCanvas` renders an empty canvas on the server and draws in the browser. The `solid` export
|
|
117
|
+
condition ships JSX source; otherwise Node gets an SSR build and browsers a DOM build.
|
package/package.json
CHANGED
|
@@ -1,10 +1,99 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "qrcodesolid",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "QR code components for Solid 2: shapes, gradients, logo, caption, frames and headless export",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"canvas",
|
|
7
|
+
"qr",
|
|
8
|
+
"qr-code",
|
|
9
|
+
"qrcode",
|
|
10
|
+
"solid",
|
|
11
|
+
"solid-js",
|
|
12
|
+
"solidjs",
|
|
13
|
+
"svg"
|
|
14
|
+
],
|
|
15
|
+
"homepage": "https://github.com/rizaleow/qrcodesolid/tree/main/packages/qrcodesolid#readme",
|
|
16
|
+
"bugs": {
|
|
17
|
+
"url": "https://github.com/rizaleow/qrcodesolid/issues"
|
|
18
|
+
},
|
|
5
19
|
"license": "MIT",
|
|
6
|
-
"author": {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
20
|
+
"author": {
|
|
21
|
+
"name": "Rizal Rinaldi",
|
|
22
|
+
"url": "https://github.com/rizaleow"
|
|
23
|
+
},
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "git+https://github.com/rizaleow/qrcodesolid.git",
|
|
27
|
+
"directory": "packages/qrcodesolid"
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"dist",
|
|
31
|
+
"README.md",
|
|
32
|
+
"LICENSE",
|
|
33
|
+
"llms.txt",
|
|
34
|
+
"skills"
|
|
35
|
+
],
|
|
36
|
+
"type": "module",
|
|
37
|
+
"sideEffects": false,
|
|
38
|
+
"imports": {
|
|
39
|
+
"#color-parse": {
|
|
40
|
+
"types": "./dist/color-parse.d.ts",
|
|
41
|
+
"development": "./dist/color-parse.js",
|
|
42
|
+
"default": "./dist/color-parse-empty.js"
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
"exports": {
|
|
46
|
+
".": {
|
|
47
|
+
"types": "./dist/index.d.ts",
|
|
48
|
+
"solid": "./dist/source/index.js",
|
|
49
|
+
"node": "./dist/server.js",
|
|
50
|
+
"default": "./dist/index.js"
|
|
51
|
+
},
|
|
52
|
+
"./payload": {
|
|
53
|
+
"types": "./dist/payload.d.ts",
|
|
54
|
+
"default": "./dist/payload.js"
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
"publishConfig": {
|
|
58
|
+
"access": "public"
|
|
59
|
+
},
|
|
60
|
+
"scripts": {
|
|
61
|
+
"build": "tsdown && tsc -p tsconfig.source.json",
|
|
62
|
+
"test": "vitest run --project unit --project dom --project ssr",
|
|
63
|
+
"test:browser": "vitest run --project browser",
|
|
64
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
65
|
+
"bench": "vitest bench --run --project 'unit (bench)' --reporter=verbose",
|
|
66
|
+
"size": "size-limit",
|
|
67
|
+
"lint:pkg": "publint && attw --pack . --profile esm-only && bun scripts/check-source-imports.js && node scripts/check-color-parse.js"
|
|
68
|
+
},
|
|
69
|
+
"devDependencies": {
|
|
70
|
+
"@arethetypeswrong/cli": "^0.18.5",
|
|
71
|
+
"@resvg/resvg-js": "^2.6.2",
|
|
72
|
+
"@size-limit/preset-small-lib": "^14.3.0",
|
|
73
|
+
"@solidjs/diagnostics": "^2.0.4",
|
|
74
|
+
"@solidjs/testing-library": "1.0.0-rc.2",
|
|
75
|
+
"@solidjs/vite-plugin": "^3.0.1",
|
|
76
|
+
"@solidjs/web": "^2.0.4",
|
|
77
|
+
"@testing-library/jest-dom": "^7.0.1",
|
|
78
|
+
"@vitest/browser-playwright": "^5.1.2",
|
|
79
|
+
"jsdom": "^31.0.1",
|
|
80
|
+
"jsqr": "^1.4.0",
|
|
81
|
+
"playwright": "^1.65.2",
|
|
82
|
+
"publint": "^0.3.25",
|
|
83
|
+
"size-limit": "^14.3.0",
|
|
84
|
+
"solid-js": "^2.0.4",
|
|
85
|
+
"tsdown": "^0.23.8",
|
|
86
|
+
"typescript": "^7.0.2",
|
|
87
|
+
"unplugin-solid": "^3.0.0",
|
|
88
|
+
"vite": "^8.4.1",
|
|
89
|
+
"vitest": "^5.1.2",
|
|
90
|
+
"zxing-wasm": "3"
|
|
91
|
+
},
|
|
92
|
+
"peerDependencies": {
|
|
93
|
+
"@solidjs/web": "^2.0.4",
|
|
94
|
+
"solid-js": "^2.0.4"
|
|
95
|
+
},
|
|
96
|
+
"engines": {
|
|
97
|
+
"node": ">=20"
|
|
98
|
+
}
|
|
10
99
|
}
|