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,141 @@
|
|
|
1
|
+
import { Region, isDark } from './encode.js';
|
|
2
|
+
import { layoutCaption } from './caption.js';
|
|
3
|
+
import { logoBox } from './logo.js';
|
|
4
|
+
import { translatePath } from './path.js';
|
|
5
|
+
import { placePaint } from './paint.js';
|
|
6
|
+
import { getFinder } from '../shapes/finders.js';
|
|
7
|
+
import { coord } from '../shapes/types.js';
|
|
8
|
+
const toShape = (input) => typeof input === 'function' ? { kind: 'module', draw: input } : input;
|
|
9
|
+
function drawModules(m, shape, offset, cut) {
|
|
10
|
+
const excavated = (x, y) => !!cut && x >= cut.x0 && x < cut.x1 && y >= cut.y0 && y < cut.y1;
|
|
11
|
+
const include = (x, y) => x >= 0 &&
|
|
12
|
+
y >= 0 &&
|
|
13
|
+
x < m.size &&
|
|
14
|
+
y < m.size &&
|
|
15
|
+
m.region[y * m.size + x] !== Region.Finder &&
|
|
16
|
+
!excavated(x, y);
|
|
17
|
+
if (shape.kind === 'layer')
|
|
18
|
+
return shape.draw({ matrix: m, include, offset });
|
|
19
|
+
const on = (x, y) => include(x, y) && isDark(m, x, y);
|
|
20
|
+
let d = '';
|
|
21
|
+
for (let y = 0; y < m.size; y++)
|
|
22
|
+
for (let x = 0; x < m.size; x++) {
|
|
23
|
+
if (!on(x, y))
|
|
24
|
+
continue;
|
|
25
|
+
const neighbors = { n: on(x, y - 1), e: on(x + 1, y), s: on(x, y + 1), w: on(x - 1, y) };
|
|
26
|
+
const alignment = m.region[y * m.size + x] === Region.Alignment;
|
|
27
|
+
const context = { x: x + offset.x, y: y + offset.y, neighbors, alignment };
|
|
28
|
+
d += shape.draw(context);
|
|
29
|
+
}
|
|
30
|
+
return d;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Applies the frames from the inside out. Each frame's paths and texts move with the code
|
|
34
|
+
* when an outer frame moves it. Outer frames draw first, so inner ones paint over them.
|
|
35
|
+
*/
|
|
36
|
+
function applyFrames(content, frame) {
|
|
37
|
+
const frames = typeof frame === 'function' ? [frame] : (frame ?? []);
|
|
38
|
+
const results = frames.reduce((done, plugin) => [...done, plugin(done.at(-1)?.layout ?? content)], []);
|
|
39
|
+
const layout = results.at(-1)?.layout ?? content;
|
|
40
|
+
const ids = new Set();
|
|
41
|
+
const paths = [];
|
|
42
|
+
const texts = [];
|
|
43
|
+
const warnings = results.flatMap((result) => result.warnings ?? []);
|
|
44
|
+
for (const result of [...results].reverse()) {
|
|
45
|
+
const [dx, dy] = [layout.qr.x - result.layout.qr.x, layout.qr.y - result.layout.qr.y];
|
|
46
|
+
for (const path of result.paths) {
|
|
47
|
+
// A frame used twice would repeat its ids, and the SVG gradient ids with them.
|
|
48
|
+
let id = path.id;
|
|
49
|
+
for (let n = 2; ids.has(id); n++)
|
|
50
|
+
id = `${path.id}-${n}`;
|
|
51
|
+
ids.add(id);
|
|
52
|
+
paths.push({ ...path, id, d: translatePath(path.d, dx, dy) });
|
|
53
|
+
}
|
|
54
|
+
texts.unshift(...result.texts.map((t) => ({ ...t, x: t.x + dx, y: t.y + dy })));
|
|
55
|
+
}
|
|
56
|
+
return { layout, paths, texts, warnings };
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Builds paint-free path data. Colour changes only need `paintScene`.
|
|
60
|
+
* The layout composes code, then caption, then frames: the frames wrap the caption.
|
|
61
|
+
* Layer order: frame layers, then `bg` over the code and caption, then modules and finders.
|
|
62
|
+
* Texts follow every layer: the caption, then frame texts.
|
|
63
|
+
*/
|
|
64
|
+
export function buildGeometry(matrix, design) {
|
|
65
|
+
const size = matrix.size + 2 * design.margin;
|
|
66
|
+
const base = { width: size, height: size, qr: { x: 0, y: 0, size } };
|
|
67
|
+
const captioned = design.caption
|
|
68
|
+
? layoutCaption(base, design.caption)
|
|
69
|
+
: { layout: base, texts: [], warnings: [] };
|
|
70
|
+
const content = captioned.layout;
|
|
71
|
+
const framed = applyFrames(content, design.frame);
|
|
72
|
+
const layout = framed.layout;
|
|
73
|
+
// The frame moves the code; the bg and caption move with it.
|
|
74
|
+
const [dx, dy] = [layout.qr.x - content.qr.x, layout.qr.y - content.qr.y];
|
|
75
|
+
const offset = { x: layout.qr.x + design.margin, y: layout.qr.y + design.margin };
|
|
76
|
+
const finder = getFinder(design.finder);
|
|
77
|
+
const corners = matrix.finders.map(([x, y]) => [x + offset.x, y + offset.y]);
|
|
78
|
+
const logo = design.image && logoBox(matrix, design.margin, design.image);
|
|
79
|
+
const [w, h] = [coord(content.width), coord(content.height)];
|
|
80
|
+
const geometry = {
|
|
81
|
+
...layout,
|
|
82
|
+
paths: [
|
|
83
|
+
...framed.paths,
|
|
84
|
+
{ id: 'bg', d: `M${coord(dx)} ${coord(dy)}h${w}v${h}h-${w}z`, paint: 'bg' },
|
|
85
|
+
{
|
|
86
|
+
id: 'modules',
|
|
87
|
+
d: drawModules(matrix, toShape(design.modules), offset, logo?.cells),
|
|
88
|
+
paint: 'fg',
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
id: 'finder-outer',
|
|
92
|
+
d: corners.map(([x, y]) => finder.outer(x, y)).join(''),
|
|
93
|
+
fillRule: 'evenodd',
|
|
94
|
+
paint: 'finder',
|
|
95
|
+
},
|
|
96
|
+
{
|
|
97
|
+
id: 'finder-inner',
|
|
98
|
+
d: corners.map(([x, y]) => finder.inner(x, y)).join(''),
|
|
99
|
+
paint: 'finderInner',
|
|
100
|
+
},
|
|
101
|
+
],
|
|
102
|
+
texts: [...captioned.texts.map((t) => ({ ...t, x: t.x + dx, y: t.y + dy })), ...framed.texts],
|
|
103
|
+
};
|
|
104
|
+
const warnings = [...captioned.warnings, ...(framed.warnings ?? [])];
|
|
105
|
+
if (warnings.length)
|
|
106
|
+
geometry.warnings = warnings;
|
|
107
|
+
if (logo) {
|
|
108
|
+
const { cells: _cells, x, y, ...rest } = logo;
|
|
109
|
+
geometry.image = { ...rest, x: x + layout.qr.x, y: y + layout.qr.y };
|
|
110
|
+
}
|
|
111
|
+
return geometry;
|
|
112
|
+
}
|
|
113
|
+
function pickPaint(key, paints) {
|
|
114
|
+
switch (key) {
|
|
115
|
+
case 'fg':
|
|
116
|
+
case 'bg':
|
|
117
|
+
return paints[key];
|
|
118
|
+
case 'finder':
|
|
119
|
+
return paints.finder ?? paints.fg;
|
|
120
|
+
case 'finderInner':
|
|
121
|
+
return paints.finderInner ?? paints.finder ?? paints.fg;
|
|
122
|
+
case 'caption':
|
|
123
|
+
return paints.caption ?? paints.fg;
|
|
124
|
+
default:
|
|
125
|
+
return key;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/** Places every paint over the qr box. Path strings are reused, not copied. */
|
|
129
|
+
export function paintScene(geometry, paints) {
|
|
130
|
+
const place = (key) => placePaint(pickPaint(key, paints), geometry.qr);
|
|
131
|
+
const layers = [];
|
|
132
|
+
for (const { id, d, fillRule, paint } of geometry.paths) {
|
|
133
|
+
const fill = place(paint);
|
|
134
|
+
if (fill === 'transparent' || !d)
|
|
135
|
+
continue;
|
|
136
|
+
layers.push(fillRule ? { id, d, fill, fillRule } : { id, d, fill });
|
|
137
|
+
}
|
|
138
|
+
const texts = geometry.texts.map(({ paint, ...text }) => ({ ...text, fill: place(paint) }));
|
|
139
|
+
const { width, height, image } = geometry;
|
|
140
|
+
return image ? { width, height, layers, image, texts } : { width, height, layers, texts };
|
|
141
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { encode } from './encode.js';
|
|
2
|
+
import { toGeometryDesign } from './options.js';
|
|
3
|
+
import { buildGeometry } from './scene.js';
|
|
4
|
+
/** An image covers modules, so it defaults to the stronger 'Q' level. */
|
|
5
|
+
function applyLevelDefault(level, hasImage) {
|
|
6
|
+
return level ?? (hasImage ? 'Q' : 'M');
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* The encode options for a code, with scan-safety defaults applied.
|
|
10
|
+
* With an image, `level` defaults to Q and `minVersion` to 2, capped by `maxVersion`.
|
|
11
|
+
*/
|
|
12
|
+
export function applyEncodingDefaults(options, hasImage) {
|
|
13
|
+
// A user maxVersion of 1 wins: the logo is dropped rather than the encode failing.
|
|
14
|
+
const lift = Math.min(2, options.encoding?.maxVersion ?? 40);
|
|
15
|
+
const minVersion = options.encoding?.minVersion ?? (hasImage ? lift : undefined);
|
|
16
|
+
return { ...options.encoding, minVersion, level: applyLevelDefault(options.level, hasImage) };
|
|
17
|
+
}
|
|
18
|
+
/** The matrix stage. `hasImage` is a parameter so a new image src does not re-encode. */
|
|
19
|
+
export const toMatrix = (options, hasImage = !!options.image) => encode(options.value, applyEncodingDefaults(options, hasImage));
|
|
20
|
+
/**
|
|
21
|
+
* The geometry stage. Pass `finder` and `caption` to keep it from reading the options
|
|
22
|
+
* that also hold colours.
|
|
23
|
+
*/
|
|
24
|
+
export const toGeometry = (matrix, options, finder, caption) => buildGeometry(matrix, toGeometryDesign(options, finder, caption));
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { clampImageSize } from './logo.js';
|
|
2
|
+
import { parseColor } from '#color-parse';
|
|
3
|
+
/** WCAG 2 relative luminance. */
|
|
4
|
+
function luminance(rgb) {
|
|
5
|
+
const [r, g, b] = rgb.map((v) => {
|
|
6
|
+
const c = v / 255;
|
|
7
|
+
return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
|
|
8
|
+
});
|
|
9
|
+
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
|
10
|
+
}
|
|
11
|
+
/** WCAG non-text contrast; a rough scan-safety floor. */
|
|
12
|
+
const minContrast = 3;
|
|
13
|
+
/** Lists scan risks in the options. The caller logs them in dev builds. */
|
|
14
|
+
export function devWarnings(o) {
|
|
15
|
+
const warnings = [];
|
|
16
|
+
const [fg, bg] = [parseColor(o.fg), parseColor(o.bg)];
|
|
17
|
+
if (fg && bg) {
|
|
18
|
+
const [fgLight, bgLight] = [luminance(fg), luminance(bg)];
|
|
19
|
+
const [hi, lo] = [Math.max(fgLight, bgLight), Math.min(fgLight, bgLight)];
|
|
20
|
+
const ratio = (hi + 0.05) / (lo + 0.05);
|
|
21
|
+
if (ratio < minContrast)
|
|
22
|
+
warnings.push(`Low contrast ${ratio.toFixed(2)}:1 between fg and bg; aim for ${minContrast}:1.`);
|
|
23
|
+
else if (fgLight > bgLight)
|
|
24
|
+
warnings.push('fg is lighter than bg: light-on-dark codes are not read by every scanner.');
|
|
25
|
+
}
|
|
26
|
+
if (o.margin < 2)
|
|
27
|
+
warnings.push(`A margin of ${o.margin} leaves too small a quiet zone; use at least 2.`);
|
|
28
|
+
if (o.image) {
|
|
29
|
+
const size = o.image.size ?? 0.2;
|
|
30
|
+
const clamped = clampImageSize(o.matrix, o.image);
|
|
31
|
+
const at = `at level ${o.matrix.level}, version ${o.matrix.version}`;
|
|
32
|
+
if (!clamped)
|
|
33
|
+
warnings.push(`The logo does not fit ${at}; it was dropped to keep the code scannable.`);
|
|
34
|
+
else if (clamped < size)
|
|
35
|
+
warnings.push(`The logo was reduced to ${clamped.toFixed(3)} to keep the code scannable ${at}.`);
|
|
36
|
+
}
|
|
37
|
+
return warnings;
|
|
38
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { toGeometry, toMatrix } from '../core/stages.js';
|
|
2
|
+
import { defaults, toPaints } from '../core/options.js';
|
|
3
|
+
import { outputSize } from '../core/output.js';
|
|
4
|
+
import { paintScene } from '../core/scene.js';
|
|
5
|
+
import { drawScene } from '../render/canvas.js';
|
|
6
|
+
import { colorResolver, resolveSceneColors } from '../render/color.js';
|
|
7
|
+
import { blobToDataURL, fetchImage, loadImage } from '../render/image.js';
|
|
8
|
+
import { sceneToSVGString } from '../render/svg-string.js';
|
|
9
|
+
const limitsOf = (o) => ({
|
|
10
|
+
timeout: o.imageTimeout,
|
|
11
|
+
maxBytes: o.imageMaxBytes,
|
|
12
|
+
});
|
|
13
|
+
/** The scene `createQRCode` derives, computed once without Solid. */
|
|
14
|
+
export function toScene(options) {
|
|
15
|
+
return paintScene(toGeometry(toMatrix(options), options), toPaints(options));
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* A standalone SVG document. Ids start with `options.id`, else `qr`.
|
|
19
|
+
* `resolveColors` replaces var() and currentColor, for files that have no page CSS.
|
|
20
|
+
* `element` then resolves them against a mounted element; a detached one is ignored.
|
|
21
|
+
*/
|
|
22
|
+
export function toSVGString(options) {
|
|
23
|
+
const scene = toScene(options);
|
|
24
|
+
return serialise(options.resolveColors ? resolveSceneColors(scene, options.element) : scene, options);
|
|
25
|
+
}
|
|
26
|
+
const serialise = (scene, options) => sceneToSVGString(scene, {
|
|
27
|
+
size: options.size ?? defaults.size,
|
|
28
|
+
idPrefix: options.id ?? 'qr',
|
|
29
|
+
title: options.title,
|
|
30
|
+
});
|
|
31
|
+
/** Inlines the logo as a data URL: a standalone SVG cannot load blob, relative or nested URLs. */
|
|
32
|
+
async function embedImage(scene, options) {
|
|
33
|
+
const { image } = options;
|
|
34
|
+
if (!scene.image || !image || image.src.startsWith('data:'))
|
|
35
|
+
return scene;
|
|
36
|
+
try {
|
|
37
|
+
const href = await blobToDataURL(await fetchImage(image, limitsOf(options)));
|
|
38
|
+
return { ...scene, image: { ...scene.image, href } };
|
|
39
|
+
}
|
|
40
|
+
catch (err) {
|
|
41
|
+
console.warn(`[qrcodesolid] Failed to embed image: ${image.src}. The SVG keeps the external URL.`, err);
|
|
42
|
+
return scene;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function makeCanvas(width, height) {
|
|
46
|
+
if (typeof OffscreenCanvas !== 'undefined')
|
|
47
|
+
return new OffscreenCanvas(width, height);
|
|
48
|
+
return Object.assign(document.createElement('canvas'), { width, height });
|
|
49
|
+
}
|
|
50
|
+
/** Draws the code onto `canvas`, or onto a new canvas, preferring OffscreenCanvas. */
|
|
51
|
+
export async function toCanvas(options, canvas) {
|
|
52
|
+
const scene = toScene(options);
|
|
53
|
+
const image = scene.image && options.image ? await loadImage(options.image, limitsOf(options)) : undefined;
|
|
54
|
+
const width = Math.round((options.size ?? defaults.size) * (options.scale ?? 1));
|
|
55
|
+
const height = Math.round(outputSize(scene, width).height);
|
|
56
|
+
const target = canvas ?? makeCanvas(width, height);
|
|
57
|
+
Object.assign(target, { width, height });
|
|
58
|
+
const ctx = target.getContext('2d');
|
|
59
|
+
if (!ctx)
|
|
60
|
+
throw new Error('[qrcodesolid] No 2D canvas context.');
|
|
61
|
+
drawScene(ctx, scene, {
|
|
62
|
+
scale: width / scene.width,
|
|
63
|
+
image,
|
|
64
|
+
resolveColor: colorResolver(options.element),
|
|
65
|
+
});
|
|
66
|
+
return target;
|
|
67
|
+
}
|
|
68
|
+
/** A PNG of the code. Rejects with a SecurityError when a cross-origin image taints it. */
|
|
69
|
+
export async function toPNGBlob(options) {
|
|
70
|
+
const canvas = await toCanvas(options);
|
|
71
|
+
if (!('toBlob' in canvas))
|
|
72
|
+
return canvas.convertToBlob({ type: 'image/png' });
|
|
73
|
+
return new Promise((resolve, reject) => canvas.toBlob((blob) => (blob ? resolve(blob) : reject(new Error('[qrcodesolid] PNG encoding failed.'))), 'image/png'));
|
|
74
|
+
}
|
|
75
|
+
/** A standalone SVG file: colours resolved and the logo embedded. */
|
|
76
|
+
async function toSVGFile(options) {
|
|
77
|
+
return serialise(resolveSceneColors(await embedImage(toScene(options), options), options.element), options);
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* A data URL of the code as PNG or SVG. SVG colours are resolved: a data URL has no page CSS.
|
|
81
|
+
* The SVG embeds the logo as a data URL, or keeps its URL when the fetch fails.
|
|
82
|
+
*/
|
|
83
|
+
export async function toDataURL(options, type = 'image/png') {
|
|
84
|
+
if (type === 'image/svg+xml')
|
|
85
|
+
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(await toSVGFile(options))}`;
|
|
86
|
+
return blobToDataURL(await toPNGBlob(options));
|
|
87
|
+
}
|
|
88
|
+
/** Saves the code as a file. A `.svg` filename saves SVG with the logo embedded, any other saves PNG. */
|
|
89
|
+
export async function download(options, filename = 'qrcode.png') {
|
|
90
|
+
const blob = filename.toLowerCase().endsWith('.svg')
|
|
91
|
+
? new Blob([await toSVGFile(options)], { type: 'image/svg+xml' })
|
|
92
|
+
: await toPNGBlob(options);
|
|
93
|
+
const url = URL.createObjectURL(blob);
|
|
94
|
+
const a = Object.assign(document.createElement('a'), { href: url, download: filename });
|
|
95
|
+
a.style.display = 'none';
|
|
96
|
+
document.body.append(a);
|
|
97
|
+
a.click();
|
|
98
|
+
a.remove();
|
|
99
|
+
// Revoke after the click task: some browsers start the download asynchronously.
|
|
100
|
+
setTimeout(() => URL.revokeObjectURL(url), 0);
|
|
101
|
+
}
|
|
102
|
+
export async function copyToClipboard(options) {
|
|
103
|
+
// Safari needs the promise, not the blob, to keep the user gesture.
|
|
104
|
+
await navigator.clipboard.write([new ClipboardItem({ 'image/png': toPNGBlob(options) })]);
|
|
105
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export { QRCode } from './components/QRCode.jsx';
|
|
2
|
+
export { QRCodeCanvas } from './components/QRCodeCanvas.jsx';
|
|
3
|
+
export { QRCodeSVG } from './components/QRCodeSVG.jsx';
|
|
4
|
+
export { createColorScheme } from './primitives/createColorScheme.js';
|
|
5
|
+
export { createPixelRatio } from './primitives/createPixelRatio.js';
|
|
6
|
+
export { createQRCode } from './primitives/createQRCode.js';
|
|
7
|
+
export { drawScene } from './render/canvas.js';
|
|
8
|
+
export { resolveSceneColors } from './render/color.js';
|
|
9
|
+
export { sceneToSVGString } from './render/svg-string.js';
|
|
10
|
+
export { copyToClipboard, download, toCanvas, toDataURL, toPNGBlob, toScene, toSVGString, } from './export/index.js';
|
|
11
|
+
export { encode, isDark, QRCapacityError, Region, } from './core/encode.js';
|
|
12
|
+
export { defineLayerShape, defineModuleShape, } from './shapes/types.js';
|
|
13
|
+
export { dots, diamond, rounded, square } from './shapes/modules.js';
|
|
14
|
+
export { horizontalBars, verticalBars } from './shapes/bars.js';
|
|
15
|
+
export { banner, border, card } from './shapes/frames.js';
|
|
16
|
+
export { finderInner, finderOuter, getFinder } from './shapes/finders.js';
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { escapeText, escapeWifi, toList } from './escape.js';
|
|
2
|
+
export function wifi(o) {
|
|
3
|
+
if (!o.ssid)
|
|
4
|
+
throw new TypeError('wifi: ssid is required');
|
|
5
|
+
const auth = o.auth ?? (o.password ? 'WPA' : 'nopass');
|
|
6
|
+
const password = o.password && auth !== 'nopass' ? `P:${escapeWifi(o.password)};` : '';
|
|
7
|
+
return `WIFI:T:${auth};S:${escapeWifi(o.ssid)};${password}${o.hidden ? 'H:true;' : ''};`;
|
|
8
|
+
}
|
|
9
|
+
export function vcard(o) {
|
|
10
|
+
const { first = '', last = '' } = o.name;
|
|
11
|
+
const lines = [
|
|
12
|
+
'BEGIN:VCARD',
|
|
13
|
+
'VERSION:3.0',
|
|
14
|
+
`N:${escapeText(last)};${escapeText(first)};;;`,
|
|
15
|
+
`FN:${escapeText([first, last].filter(Boolean).join(' '))}`,
|
|
16
|
+
];
|
|
17
|
+
const add = (key, value) => value && lines.push(`${key}:${escapeText(value)}`);
|
|
18
|
+
add('ORG', o.org);
|
|
19
|
+
add('TITLE', o.title);
|
|
20
|
+
for (const p of toList(o.phone))
|
|
21
|
+
add('TEL', p);
|
|
22
|
+
for (const e of toList(o.email))
|
|
23
|
+
add('EMAIL', e);
|
|
24
|
+
add('URL', o.url);
|
|
25
|
+
if (o.address)
|
|
26
|
+
lines.push(`ADR:;;${escapeText(o.address)};;;;`);
|
|
27
|
+
add('NOTE', o.note);
|
|
28
|
+
lines.push('END:VCARD');
|
|
29
|
+
return lines.join('\r\n');
|
|
30
|
+
}
|
|
31
|
+
export function mecard(o) {
|
|
32
|
+
const fields = [
|
|
33
|
+
['N', o.name],
|
|
34
|
+
['TEL', o.phone],
|
|
35
|
+
['EMAIL', o.email],
|
|
36
|
+
['URL', o.url],
|
|
37
|
+
['ADR', o.address],
|
|
38
|
+
['NOTE', o.note],
|
|
39
|
+
];
|
|
40
|
+
const body = fields.flatMap(([k, v]) => (v ? [`${k}:${escapeWifi(v)};`] : []));
|
|
41
|
+
return `MECARD:${body.join('')};`;
|
|
42
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { toList } from './escape.js';
|
|
2
|
+
const encode = (s) => encodeURIComponent(s).replace(/%40/g, '@');
|
|
3
|
+
export function mailto(o) {
|
|
4
|
+
const addresses = (v) => toList(v).map(encode).join(',');
|
|
5
|
+
const params = [
|
|
6
|
+
['subject', o.subject && encode(o.subject)],
|
|
7
|
+
['body', o.body && encode(o.body)],
|
|
8
|
+
['cc', o.cc && addresses(o.cc)],
|
|
9
|
+
['bcc', o.bcc && addresses(o.bcc)],
|
|
10
|
+
].flatMap(([k, v]) => (v ? [`${k}=${v}`] : []));
|
|
11
|
+
return `mailto:${addresses(o.to)}${params.length ? `?${params.join('&')}` : ''}`;
|
|
12
|
+
}
|
|
13
|
+
export const sms = (o) => `SMSTO:${o.to}${o.body ? `:${o.body}` : ''}`;
|
|
14
|
+
export function tel(number) {
|
|
15
|
+
const cleaned = number.replace(/[\s\-.()]/g, '');
|
|
16
|
+
if (!/^\+?\d+$/.test(cleaned))
|
|
17
|
+
throw new TypeError('tel: expected digits and a leading +');
|
|
18
|
+
return `tel:${cleaned}`;
|
|
19
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { escapeText } from './escape.js';
|
|
2
|
+
export function geo(o) {
|
|
3
|
+
if (!Number.isFinite(o.lat) || o.lat < -90 || o.lat > 90)
|
|
4
|
+
throw new TypeError('geo: bad lat');
|
|
5
|
+
if (!Number.isFinite(o.lng) || o.lng < -180 || o.lng > 180)
|
|
6
|
+
throw new TypeError('geo: bad lng');
|
|
7
|
+
if (o.altitude !== undefined && !Number.isFinite(o.altitude))
|
|
8
|
+
throw new TypeError('geo: bad altitude');
|
|
9
|
+
const alt = o.altitude === undefined ? '' : `,${o.altitude}`;
|
|
10
|
+
const query = o.query ? `?q=${encodeURIComponent(o.query)}` : '';
|
|
11
|
+
return `geo:${o.lat},${o.lng}${alt}${query}`;
|
|
12
|
+
}
|
|
13
|
+
function checked(d, name) {
|
|
14
|
+
if (!(d instanceof Date) || Number.isNaN(d.getTime()))
|
|
15
|
+
throw new TypeError(`event: bad ${name}`);
|
|
16
|
+
return d;
|
|
17
|
+
}
|
|
18
|
+
const stamp = (d) => d.toISOString().replace(/[-:]|\.\d{3}/g, '');
|
|
19
|
+
const pad = (n, width = 2) => String(n).padStart(width, '0');
|
|
20
|
+
// A date-only value is a calendar day, so it uses local fields, not the UTC day.
|
|
21
|
+
const day = (d) => `${pad(d.getFullYear(), 4)}${pad(d.getMonth() + 1)}${pad(d.getDate())}`;
|
|
22
|
+
export function event(o) {
|
|
23
|
+
const start = checked(o.start, 'start');
|
|
24
|
+
const end = o.end && checked(o.end, 'end');
|
|
25
|
+
const time = (key, d) => o.allDay ? `${key};VALUE=DATE:${day(d)}` : `${key}:${stamp(d)}`;
|
|
26
|
+
const lines = ['BEGIN:VEVENT', `SUMMARY:${escapeText(o.title)}`, time('DTSTART', start)];
|
|
27
|
+
if (o.allDay) {
|
|
28
|
+
// iCal all-day DTEND is exclusive: use the day after the last day.
|
|
29
|
+
const last = end ?? start;
|
|
30
|
+
lines.push(time('DTEND', new Date(last.getFullYear(), last.getMonth(), last.getDate() + 1)));
|
|
31
|
+
}
|
|
32
|
+
else if (end)
|
|
33
|
+
lines.push(time('DTEND', end));
|
|
34
|
+
if (o.location)
|
|
35
|
+
lines.push(`LOCATION:${escapeText(o.location)}`);
|
|
36
|
+
if (o.description)
|
|
37
|
+
lines.push(`DESCRIPTION:${escapeText(o.description)}`);
|
|
38
|
+
lines.push('END:VEVENT');
|
|
39
|
+
return lines.join('\r\n');
|
|
40
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { isServer } from '@solidjs/web';
|
|
2
|
+
import { createSignal, onSettled } from 'solid-js';
|
|
3
|
+
/** Tracks `prefers-color-scheme`. 'light' on the server and where `matchMedia` is missing. */
|
|
4
|
+
export function createColorScheme() {
|
|
5
|
+
if (isServer)
|
|
6
|
+
return () => 'light';
|
|
7
|
+
const [scheme, setScheme] = createSignal('light');
|
|
8
|
+
onSettled(() => {
|
|
9
|
+
if (typeof matchMedia !== 'function')
|
|
10
|
+
return;
|
|
11
|
+
const query = matchMedia('(prefers-color-scheme: dark)');
|
|
12
|
+
const onChange = () => setScheme(query.matches ? 'dark' : 'light');
|
|
13
|
+
onChange();
|
|
14
|
+
query.addEventListener('change', onChange);
|
|
15
|
+
return () => query.removeEventListener('change', onChange);
|
|
16
|
+
});
|
|
17
|
+
return scheme;
|
|
18
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { isServer } from '@solidjs/web';
|
|
2
|
+
import { createSignal, onSettled } from 'solid-js';
|
|
3
|
+
/** Tracks `devicePixelRatio`, which changes on zoom or a move to another screen. 1 on the server. */
|
|
4
|
+
export function createPixelRatio() {
|
|
5
|
+
if (isServer)
|
|
6
|
+
return () => 1;
|
|
7
|
+
const [ratio, setRatio] = createSignal(window.devicePixelRatio || 1);
|
|
8
|
+
onSettled(() => {
|
|
9
|
+
if (typeof matchMedia !== 'function')
|
|
10
|
+
return;
|
|
11
|
+
let query;
|
|
12
|
+
// A resolution query matches one ratio only, so re-arm it after each change.
|
|
13
|
+
const arm = () => {
|
|
14
|
+
query = matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);
|
|
15
|
+
query.addEventListener('change', onChange, { once: true });
|
|
16
|
+
};
|
|
17
|
+
const onChange = () => {
|
|
18
|
+
setRatio(window.devicePixelRatio || 1);
|
|
19
|
+
arm();
|
|
20
|
+
};
|
|
21
|
+
arm();
|
|
22
|
+
return () => query.removeEventListener('change', onChange);
|
|
23
|
+
});
|
|
24
|
+
return ratio;
|
|
25
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { isDev } from '@solidjs/web';
|
|
2
|
+
import { createEffect, createMemo } from 'solid-js';
|
|
3
|
+
import { sameCaptionShape, toCaptionShape } from '../core/caption.js';
|
|
4
|
+
import { toGeometry, toMatrix } from '../core/stages.js';
|
|
5
|
+
import { devWarnings } from '../core/warnings.js';
|
|
6
|
+
import { defaults, toFinderShape, toPaints } from '../core/options.js';
|
|
7
|
+
import { paintScene } from '../core/scene.js';
|
|
8
|
+
/**
|
|
9
|
+
* Derives the matrix, geometry and scene from options, which may be a reactive props object.
|
|
10
|
+
* A colour change repaints the scene only; it does not encode or rebuild paths.
|
|
11
|
+
*/
|
|
12
|
+
export function createQRCode(options) {
|
|
13
|
+
// A new image src must not re-encode, so the matrix tracks presence only.
|
|
14
|
+
const hasImage = createMemo(() => !!options.image);
|
|
15
|
+
const matrix = createMemo(() => toMatrix(options, hasImage()), { name: 'qr.matrix' });
|
|
16
|
+
// `finder={{ outer, color: c() }}` makes a new object per colour change; compare its shape only.
|
|
17
|
+
const finderShape = createMemo(() => toFinderShape(options.finder), {
|
|
18
|
+
name: 'qr.finderShape',
|
|
19
|
+
equals: (a, b) => a.outer === b.outer && a.inner === b.inner,
|
|
20
|
+
});
|
|
21
|
+
const captionShape = createMemo(() => toCaptionShape(options.caption), {
|
|
22
|
+
name: 'qr.captionShape',
|
|
23
|
+
equals: sameCaptionShape,
|
|
24
|
+
});
|
|
25
|
+
const geometry = createMemo(() => toGeometry(matrix(), options, finderShape(), captionShape()), {
|
|
26
|
+
name: 'qr.geometry',
|
|
27
|
+
});
|
|
28
|
+
const scene = createMemo(() => paintScene(geometry(), toPaints(options)), {
|
|
29
|
+
name: 'qr.scene',
|
|
30
|
+
});
|
|
31
|
+
if (isDev)
|
|
32
|
+
// Joined to a string so an unchanged message list does not log again.
|
|
33
|
+
createEffect(() => devWarnings({
|
|
34
|
+
fg: options.fg ?? defaults.fg,
|
|
35
|
+
bg: options.bg ?? defaults.bg,
|
|
36
|
+
margin: options.margin ?? defaults.margin,
|
|
37
|
+
image: options.image,
|
|
38
|
+
matrix: matrix(),
|
|
39
|
+
})
|
|
40
|
+
.concat(geometry().warnings ?? [])
|
|
41
|
+
.map((w) => `[qrcodesolid] ${w}`)
|
|
42
|
+
.join('\n'), (text) => {
|
|
43
|
+
if (text)
|
|
44
|
+
console.warn(text);
|
|
45
|
+
});
|
|
46
|
+
return { matrix, geometry, scene };
|
|
47
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
function fillStyle(ctx, paint, resolve) {
|
|
2
|
+
if (typeof paint === 'string')
|
|
3
|
+
return resolve(paint);
|
|
4
|
+
const gradient = paint.type === 'linear'
|
|
5
|
+
? ctx.createLinearGradient(paint.x1, paint.y1, paint.x2, paint.y2)
|
|
6
|
+
: ctx.createRadialGradient(paint.cx, paint.cy, 0, paint.cx, paint.cy, paint.r);
|
|
7
|
+
for (const [offset, color] of paint.stops)
|
|
8
|
+
gradient.addColorStop(offset, resolve(color));
|
|
9
|
+
return gradient;
|
|
10
|
+
}
|
|
11
|
+
function sourceSize(source) {
|
|
12
|
+
const s = source;
|
|
13
|
+
const width = s.naturalWidth || s.videoWidth || s.displayWidth || s.width;
|
|
14
|
+
const height = s.naturalHeight || s.videoHeight || s.displayHeight || s.height;
|
|
15
|
+
return typeof width === 'number' && typeof height === 'number' ? [width, height] : [0, 0];
|
|
16
|
+
}
|
|
17
|
+
/** Draws the image centred in its box at its own aspect ratio, like `xMidYMid meet`. */
|
|
18
|
+
function drawImage(ctx, source, box) {
|
|
19
|
+
const [w, h] = sourceSize(source);
|
|
20
|
+
const k = w && h ? Math.min(box.width / w, box.height / h) : 0;
|
|
21
|
+
const [dw, dh] = k ? [w * k, h * k] : [box.width, box.height];
|
|
22
|
+
ctx.save();
|
|
23
|
+
ctx.beginPath();
|
|
24
|
+
ctx.roundRect(box.x, box.y, box.width, box.height, box.radius);
|
|
25
|
+
ctx.clip();
|
|
26
|
+
ctx.globalAlpha = box.opacity;
|
|
27
|
+
ctx.drawImage(source, box.x + (box.width - dw) / 2, box.y + (box.height - dh) / 2, dw, dh);
|
|
28
|
+
ctx.restore();
|
|
29
|
+
}
|
|
30
|
+
/** Paints a scene onto a 2D context. The caller sizes and clears the canvas. */
|
|
31
|
+
export function drawScene(ctx, scene, options) {
|
|
32
|
+
ctx.setTransform(options.scale, 0, 0, options.scale, 0, 0);
|
|
33
|
+
for (const layer of scene.layers) {
|
|
34
|
+
ctx.fillStyle = fillStyle(ctx, layer.fill, options.resolveColor);
|
|
35
|
+
ctx.fill(new Path2D(layer.d), layer.fillRule ?? 'nonzero');
|
|
36
|
+
}
|
|
37
|
+
if (scene.image && options.image)
|
|
38
|
+
drawImage(ctx, options.image, scene.image);
|
|
39
|
+
ctx.textAlign = 'center';
|
|
40
|
+
ctx.textBaseline = 'middle';
|
|
41
|
+
for (const text of scene.texts) {
|
|
42
|
+
ctx.font = `${text.fontWeight} ${text.fontSize}px ${text.fontFamily}`;
|
|
43
|
+
ctx.fillStyle = fillStyle(ctx, text.fill, options.resolveColor);
|
|
44
|
+
ctx.fillText(text.text, text.x, text.y);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Follows nested `var(--x, fallback)` to the innermost fallback.
|
|
3
|
+
* A var with no fallback becomes black: canvas rejects a bare var() without a word.
|
|
4
|
+
*/
|
|
5
|
+
export function parseVarFallback(value) {
|
|
6
|
+
let v = value.trim();
|
|
7
|
+
while (v.startsWith('var(')) {
|
|
8
|
+
const comma = v.indexOf(',');
|
|
9
|
+
if (comma < 0)
|
|
10
|
+
return '#000';
|
|
11
|
+
v = v.slice(comma + 1, v.lastIndexOf(')')).trim();
|
|
12
|
+
}
|
|
13
|
+
return v;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Turns a CSS colour into one canvas accepts. With `el`, custom properties and
|
|
17
|
+
* `currentColor` resolve against `el` through a hidden probe child.
|
|
18
|
+
*/
|
|
19
|
+
export function resolveColor(value, el) {
|
|
20
|
+
if (el?.isConnected) {
|
|
21
|
+
const probe = document.createElement('span');
|
|
22
|
+
probe.style.color = value;
|
|
23
|
+
if (probe.style.color) {
|
|
24
|
+
probe.style.display = 'none';
|
|
25
|
+
el.appendChild(probe);
|
|
26
|
+
const color = getComputedStyle(probe).color;
|
|
27
|
+
probe.remove();
|
|
28
|
+
if (color)
|
|
29
|
+
return color;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const color = parseVarFallback(value);
|
|
33
|
+
return color === 'currentColor' ? '#000' : color;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* A `resolveColor` for one element that remembers each answer.
|
|
37
|
+
* Layers share colours, and each probe lookup adds an element to the page.
|
|
38
|
+
*/
|
|
39
|
+
export function colorResolver(el) {
|
|
40
|
+
const answers = new Map();
|
|
41
|
+
return (value) => {
|
|
42
|
+
if (!answers.has(value))
|
|
43
|
+
answers.set(value, resolveColor(value, el));
|
|
44
|
+
return answers.get(value);
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
function resolvePaintColors(paint, resolve) {
|
|
48
|
+
if (typeof paint === 'string')
|
|
49
|
+
return resolve(paint);
|
|
50
|
+
return { ...paint, stops: paint.stops.map(([offset, c]) => [offset, resolve(c)]) };
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Replaces var() and currentColor in every paint, for output that has no page CSS.
|
|
54
|
+
* With `el`, they resolve against it, as on a canvas drawn there. A detached `el` is ignored.
|
|
55
|
+
*/
|
|
56
|
+
export function resolveSceneColors(scene, el) {
|
|
57
|
+
const resolve = colorResolver(el);
|
|
58
|
+
return {
|
|
59
|
+
...scene,
|
|
60
|
+
layers: scene.layers.map((l) => ({ ...l, fill: resolvePaintColors(l.fill, resolve) })),
|
|
61
|
+
texts: scene.texts.map((t) => ({ ...t, fill: resolvePaintColors(t.fill, resolve) })),
|
|
62
|
+
};
|
|
63
|
+
}
|