@journey-to-code/symbology 0.0.0-stage → 0.2.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 +59 -3
- package/components/symbology-code.zb +129 -0
- package/dist/symbology-code.d.ts +25 -0
- package/dist/symbology-code.js +415 -0
- package/package.json +52 -4
- package/qr.d.ts +78 -0
- package/qr.js +197 -0
- package/symbology.wasm +0 -0
package/README.md
CHANGED
|
@@ -1,3 +1,59 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# @journey-to-code/symbology
|
|
2
|
+
|
|
3
|
+
Dependency-free QR and linear barcode encoding and decoding, with a Rust
|
|
4
|
+
WebAssembly implementation and an optional Zubra-built custom element.
|
|
5
|
+
|
|
6
|
+
## Install
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
npm install @journey-to-code/symbology
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
The package includes the WebAssembly binary. Load it with no URL or pass an
|
|
13
|
+
alternate source:
|
|
14
|
+
|
|
15
|
+
```js
|
|
16
|
+
import { loadQr } from '@journey-to-code/symbology';
|
|
17
|
+
|
|
18
|
+
const symbology = await loadQr();
|
|
19
|
+
const code = symbology.encode('https://example.com');
|
|
20
|
+
const svg = symbology.svg(code);
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
`loadQr` also accepts WASM bytes, a `Response`, a `WebAssembly.Module`, or a
|
|
24
|
+
URL. Encoding supports QR, Code 128, Code 39, and EAN-13. The decoder reads
|
|
25
|
+
QR frames and linear-barcode scanlines or frames.
|
|
26
|
+
|
|
27
|
+
## Custom element
|
|
28
|
+
|
|
29
|
+
Import the widget once from a JavaScript entry point that resolves npm
|
|
30
|
+
package imports (for example, your bundler entry point):
|
|
31
|
+
|
|
32
|
+
```js
|
|
33
|
+
import '@journey-to-code/symbology/symbology-code';
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Then use it in HTML:
|
|
37
|
+
|
|
38
|
+
```html
|
|
39
|
+
<symbology-code format="qr" value="https://example.com"></symbology-code>
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
The element offers a format picker, editable content, SVG preview, and
|
|
43
|
+
download. `format` accepts `qr`, `code128`, `code39`, or `ean13`; `value`
|
|
44
|
+
sets the initial content. It is authored in Zubra and distributed as a
|
|
45
|
+
standalone custom element, so applications do not need Zubra or its runtime.
|
|
46
|
+
|
|
47
|
+
## Build from source
|
|
48
|
+
|
|
49
|
+
Packing the package runs its build automatically. Building requires Rust with
|
|
50
|
+
the `wasm32-unknown-unknown` target and Node.js 20 or newer:
|
|
51
|
+
|
|
52
|
+
```sh
|
|
53
|
+
npm run build
|
|
54
|
+
npm test
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Zubra is a development dependency used to compile
|
|
58
|
+
[`components/symbology-code.zb`](./components/symbology-code.zb); it is not a
|
|
59
|
+
runtime dependency of the published package.
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
<script>
|
|
2
|
+
import { loadQr } from '../qr.js'
|
|
3
|
+
|
|
4
|
+
let api
|
|
5
|
+
let svgWidth = 0
|
|
6
|
+
let svgHeight = 0
|
|
7
|
+
let viewBox = '0 0 0 0'
|
|
8
|
+
let path = ''
|
|
9
|
+
let svgMarkup = ''
|
|
10
|
+
let error = ''
|
|
11
|
+
let loading = true
|
|
12
|
+
|
|
13
|
+
async function initialize() {
|
|
14
|
+
try {
|
|
15
|
+
api = await loadQr()
|
|
16
|
+
loading = false
|
|
17
|
+
generate()
|
|
18
|
+
} catch (cause) {
|
|
19
|
+
error = cause instanceof Error ? cause.message : String(cause)
|
|
20
|
+
loading = false
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function generate() {
|
|
25
|
+
if (!api) return
|
|
26
|
+
try {
|
|
27
|
+
const code = format === 'qr' ? api.encode(value) : api.encodeBarcode(format, value)
|
|
28
|
+
const modules = code.modules
|
|
29
|
+
path = ''
|
|
30
|
+
if (format === 'qr') {
|
|
31
|
+
svgWidth = code.size + 8
|
|
32
|
+
svgHeight = svgWidth
|
|
33
|
+
for (let y = 0; y < code.size; y++) {
|
|
34
|
+
for (let x = 0; x < code.size; x++) {
|
|
35
|
+
if (!modules[y * code.size + x]) continue
|
|
36
|
+
let run = 1
|
|
37
|
+
while (x + run < code.size && modules[y * code.size + x + run]) run++
|
|
38
|
+
path += `M${x + 4} ${y + 4}h${run}v1h-${run}z`
|
|
39
|
+
x += run - 1
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
} else {
|
|
43
|
+
svgWidth = code.width
|
|
44
|
+
svgHeight = 60
|
|
45
|
+
let x = 0
|
|
46
|
+
while (x < code.width) {
|
|
47
|
+
if (!modules[x]) {
|
|
48
|
+
x++
|
|
49
|
+
continue
|
|
50
|
+
}
|
|
51
|
+
let run = 1
|
|
52
|
+
while (x + run < code.width && modules[x + run]) run++
|
|
53
|
+
path += `M${x} 0h${run}v${svgHeight}h-${run}z`
|
|
54
|
+
x += run
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
viewBox = `0 0 ${svgWidth} ${svgHeight}`
|
|
58
|
+
svgMarkup = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${viewBox}" shape-rendering="crispEdges"><rect width="${svgWidth}" height="${svgHeight}" fill="#fff"/><path d="${path}" fill="#000"/></svg>`
|
|
59
|
+
error = ''
|
|
60
|
+
} catch (cause) {
|
|
61
|
+
path = ''
|
|
62
|
+
svgMarkup = ''
|
|
63
|
+
error = cause instanceof Error ? cause.message : String(cause)
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function download(event) {
|
|
68
|
+
event.preventDefault()
|
|
69
|
+
if (!svgMarkup) return
|
|
70
|
+
const url = URL.createObjectURL(new Blob([svgMarkup], { type: 'image/svg+xml' }))
|
|
71
|
+
const link = document.createElement('a')
|
|
72
|
+
link.href = url
|
|
73
|
+
link.download = `symbology-${format}.svg`
|
|
74
|
+
link.click()
|
|
75
|
+
setTimeout(() => URL.revokeObjectURL(url), 0)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function setFormat(event) {
|
|
79
|
+
format = event.currentTarget.value
|
|
80
|
+
generate()
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function setValue(event) {
|
|
84
|
+
value = event.currentTarget.value
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
initialize()
|
|
88
|
+
</script>
|
|
89
|
+
<style>
|
|
90
|
+
:host { color: #17241f; font: 14px/1.5 system-ui, sans-serif; }
|
|
91
|
+
form { display: grid; gap: 12px; max-width: 28rem; }
|
|
92
|
+
label { display: grid; gap: 5px; font-size: 12px; font-weight: 600; }
|
|
93
|
+
select, textarea, button { box-sizing: border-box; font: inherit; }
|
|
94
|
+
select, textarea { width: 100%; padding: 9px; border: 1px solid #cbd1c7; border-radius: 4px; background: white; }
|
|
95
|
+
textarea { min-height: 76px; resize: vertical; }
|
|
96
|
+
button { padding: 10px 14px; border: 0; border-radius: 4px; background: #c9ef5b; color: #17241f; cursor: pointer; font-weight: 700; }
|
|
97
|
+
svg { display: block; width: min(100%, 24rem); max-height: 24rem; margin-top: 18px; background: white; }
|
|
98
|
+
a { display: inline-block; margin-top: 12px; color: #314c15; }
|
|
99
|
+
p { color: #59645d; }
|
|
100
|
+
</style>
|
|
101
|
+
<symbology-code format="qr" value="https://example.com">
|
|
102
|
+
<form onsubmit={(event) => { event.preventDefault(); generate() }}>
|
|
103
|
+
<label>Format
|
|
104
|
+
<select value={format} onchange={setFormat}>
|
|
105
|
+
<option value="qr">QR code</option>
|
|
106
|
+
<option value="code128">Code 128</option>
|
|
107
|
+
<option value="code39">Code 39</option>
|
|
108
|
+
<option value="ean13">EAN-13</option>
|
|
109
|
+
</select>
|
|
110
|
+
</label>
|
|
111
|
+
<label>Content
|
|
112
|
+
<textarea value={value} oninput={setValue}></textarea>
|
|
113
|
+
</label>
|
|
114
|
+
<button type="submit">Generate code</button>
|
|
115
|
+
</form>
|
|
116
|
+
<p role="status">{loading ? 'Loading the Symbology engine…' : error || 'Ready'}</p>
|
|
117
|
+
<svg
|
|
118
|
+
xmlns="http://www.w3.org/2000/svg"
|
|
119
|
+
viewBox={viewBox}
|
|
120
|
+
role="img"
|
|
121
|
+
aria-label={`Generated ${format} code`}
|
|
122
|
+
shape-rendering="crispEdges"
|
|
123
|
+
hidden={!path}
|
|
124
|
+
>
|
|
125
|
+
<rect width={svgWidth} height={svgHeight} fill="#fff"></rect>
|
|
126
|
+
<path d={path} fill="#000"></path>
|
|
127
|
+
</svg>
|
|
128
|
+
<a href="#" onclick={download} hidden={!path}>Download SVG</a>
|
|
129
|
+
</symbology-code>
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Generated by zubra from symbology-code.zb. Do not edit.
|
|
2
|
+
|
|
3
|
+
export declare class SymbologyCode extends HTMLElement {
|
|
4
|
+
/** Attribute `format`. Default: `"qr"`. */
|
|
5
|
+
format: string;
|
|
6
|
+
/** Attribute `value`. Default: `"https://example.com"`. */
|
|
7
|
+
value: string;
|
|
8
|
+
/** Resolves once pending prop changes have reached the DOM. */
|
|
9
|
+
readonly updateComplete: Promise<void>;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** The props of `<symbology-code>`, for frameworks and wrappers. */
|
|
13
|
+
export interface SymbologyCodeProps {
|
|
14
|
+
format?: string;
|
|
15
|
+
value?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export declare const tag: "symbology-code";
|
|
19
|
+
export default SymbologyCode;
|
|
20
|
+
|
|
21
|
+
declare global {
|
|
22
|
+
interface HTMLElementTagNameMap {
|
|
23
|
+
"symbology-code": SymbologyCode;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,415 @@
|
|
|
1
|
+
// Generated by zubra from symbology-code.zb (--emit element). Do not edit: change the .zb file.
|
|
2
|
+
//
|
|
3
|
+
// A standard custom element: a class that extends HTMLElement, registered with
|
|
4
|
+
// customElements.define(), with no framework and nothing to install. Each part of the component
|
|
5
|
+
// is here as the platform does it. What the platform doesn't do for light DOM is in small helpers
|
|
6
|
+
// after the class.
|
|
7
|
+
|
|
8
|
+
import { loadQr } from '../qr.js';
|
|
9
|
+
|
|
10
|
+
const HTMLElement = globalThis.HTMLElement ?? class {}; // on a server, nothing to extend
|
|
11
|
+
export const tag = "symbology-code";
|
|
12
|
+
|
|
13
|
+
// The component's styles: one stylesheet, shared by every symbology-code on the page (made when the
|
|
14
|
+
// first one connects, since a server that imports this module has no CSSStyleSheet).
|
|
15
|
+
let sheet = null;
|
|
16
|
+
const css = `@layer theme, base, components, utilities;
|
|
17
|
+
@layer components {
|
|
18
|
+
@scope (symbology-code) to ([data-zb-slotted="symbology-code"]) {
|
|
19
|
+
:scope { color: #17241f; font: 14px/1.5 system-ui, sans-serif; }
|
|
20
|
+
form { display: grid; gap: 12px; max-width: 28rem; }
|
|
21
|
+
label { display: grid; gap: 5px; font-size: 12px; font-weight: 600; }
|
|
22
|
+
select, textarea, button { box-sizing: border-box; font: inherit; }
|
|
23
|
+
select, textarea { width: 100%; padding: 9px; border: 1px solid #cbd1c7; border-radius: 4px; background: white; }
|
|
24
|
+
textarea { min-height: 76px; resize: vertical; }
|
|
25
|
+
button { padding: 10px 14px; border: 0; border-radius: 4px; background: #c9ef5b; color: #17241f; cursor: pointer; font-weight: 700; }
|
|
26
|
+
svg { display: block; width: min(100%, 24rem); max-height: 24rem; margin-top: 18px; background: white; }
|
|
27
|
+
a { display: inline-block; margin-top: 12px; color: #314c15; }
|
|
28
|
+
p { color: #59645d; }
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
`;
|
|
32
|
+
|
|
33
|
+
export class SymbologyCode extends HTMLElement {
|
|
34
|
+
/** The attributes this element watches: attributeChangedCallback runs when one changes. */
|
|
35
|
+
static observedAttributes = ["format", "value"];
|
|
36
|
+
/** What framework adapters (@zubra/runtime/react, /vue) read to wrap this element. */
|
|
37
|
+
static zubra = {
|
|
38
|
+
tag,
|
|
39
|
+
props: {
|
|
40
|
+
format: { attribute: "format", default: "qr", required: false },
|
|
41
|
+
value: { attribute: "value", default: "https://example.com", required: false },
|
|
42
|
+
},
|
|
43
|
+
events: [],
|
|
44
|
+
slots: [],
|
|
45
|
+
shadow: false,
|
|
46
|
+
form: false,
|
|
47
|
+
element: true,
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
// ElementInternals: the element's form value and validity, and :state() for CSS.
|
|
51
|
+
#internals = this.attachInternals();
|
|
52
|
+
// The props, each starting at its default; #given has the ones set from outside.
|
|
53
|
+
#props = { format: "qr", value: "https://example.com" };
|
|
54
|
+
#given = new Set();
|
|
55
|
+
// What brings the DOM up to date: one function for each spot that changes.
|
|
56
|
+
#updates = [];
|
|
57
|
+
#pending = null;
|
|
58
|
+
#started = false;
|
|
59
|
+
|
|
60
|
+
constructor() {
|
|
61
|
+
super();
|
|
62
|
+
// A property set before this class was defined sits on the element itself, hiding the
|
|
63
|
+
// accessor below: take it over.
|
|
64
|
+
for (const prop of ["format", "value"]) {
|
|
65
|
+
if (Object.hasOwn(this, prop)) {
|
|
66
|
+
const value = this[prop];
|
|
67
|
+
delete this[prop];
|
|
68
|
+
this[prop] = value;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// ---- props: properties, and attributes that set them
|
|
74
|
+
|
|
75
|
+
get format() {
|
|
76
|
+
return this.#props.format;
|
|
77
|
+
}
|
|
78
|
+
set format(value) {
|
|
79
|
+
this.#given.add("format");
|
|
80
|
+
if (Object.is(value, this.#props.format)) return;
|
|
81
|
+
this.#props.format = value;
|
|
82
|
+
this.#requestUpdate();
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
get value() {
|
|
86
|
+
return this.#props.value;
|
|
87
|
+
}
|
|
88
|
+
set value(value) {
|
|
89
|
+
this.#given.add("value");
|
|
90
|
+
if (Object.is(value, this.#props.value)) return;
|
|
91
|
+
this.#props.value = value;
|
|
92
|
+
this.#requestUpdate();
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
attributeChangedCallback(name, previous, raw) {
|
|
96
|
+
// raw is the attribute's text, or null once it's removed.
|
|
97
|
+
switch (name) {
|
|
98
|
+
case "format":
|
|
99
|
+
this.format = raw ?? "qr";
|
|
100
|
+
break;
|
|
101
|
+
case "value":
|
|
102
|
+
this.value = raw ?? "https://example.com";
|
|
103
|
+
break;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// ---- lifecycle
|
|
108
|
+
|
|
109
|
+
connectedCallback() {
|
|
110
|
+
// The styles go to the root the element is in: the document, or a shadow root it's inside.
|
|
111
|
+
const root = this.getRootNode();
|
|
112
|
+
if (root.adoptedStyleSheets) {
|
|
113
|
+
if (!sheet) {
|
|
114
|
+
sheet = new CSSStyleSheet();
|
|
115
|
+
sheet.replaceSync(css);
|
|
116
|
+
}
|
|
117
|
+
if (!root.adoptedStyleSheets.includes(sheet)) root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
|
|
118
|
+
}
|
|
119
|
+
if (!this.#started) this.#start();
|
|
120
|
+
this.#update();
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
#start() {
|
|
124
|
+
// Props a framework's server rendering wrote as JSON (zb-props), before it sets them as properties.
|
|
125
|
+
let given;
|
|
126
|
+
try {
|
|
127
|
+
given = JSON.parse(this.getAttribute("zb-props"));
|
|
128
|
+
} catch {
|
|
129
|
+
// none
|
|
130
|
+
}
|
|
131
|
+
for (const name in given) if (Object.hasOwn(this.#props, name) && !this.#given.has(name)) this[name] = given[name];
|
|
132
|
+
const content = this.#setup();
|
|
133
|
+
for (const update of this.#updates) update(); // filled in before it's on the page
|
|
134
|
+
this.replaceChildren(content);
|
|
135
|
+
this.#started = true;
|
|
136
|
+
this.#internals.states?.add("hydrated"); // :state(hydrated), for CSS
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// The component's <script> and template, set up once per element. Props are read as
|
|
140
|
+
// element.name; state (a let) is name.value. Returns the template's nodes.
|
|
141
|
+
#setup() {
|
|
142
|
+
const element = this;
|
|
143
|
+
// The hooks the script uses (from @zubra/runtime in the source), made for this element.
|
|
144
|
+
const state = (initial) => createState(initial, () => this.#requestUpdate());
|
|
145
|
+
|
|
146
|
+
// ---- <script>
|
|
147
|
+
const api = state(undefined)
|
|
148
|
+
const svgWidth = state(0)
|
|
149
|
+
const svgHeight = state(0)
|
|
150
|
+
const viewBox = state('0 0 0 0')
|
|
151
|
+
const path = state('')
|
|
152
|
+
const svgMarkup = state('')
|
|
153
|
+
const error = state('')
|
|
154
|
+
const loading = state(true)
|
|
155
|
+
|
|
156
|
+
async function initialize() {
|
|
157
|
+
try {
|
|
158
|
+
api.value = await loadQr()
|
|
159
|
+
loading.value = false
|
|
160
|
+
generate()
|
|
161
|
+
} catch (cause) {
|
|
162
|
+
error.value = cause instanceof Error ? cause.message : String(cause)
|
|
163
|
+
loading.value = false
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function generate() {
|
|
168
|
+
if (!api.value) return
|
|
169
|
+
try {
|
|
170
|
+
const code = element.format === 'qr' ? api.value.encode(element.value) : api.value.encodeBarcode(element.format, element.value)
|
|
171
|
+
const modules = code.modules
|
|
172
|
+
path.value = ''
|
|
173
|
+
if (element.format === 'qr') {
|
|
174
|
+
svgWidth.value = code.size + 8
|
|
175
|
+
svgHeight.value = svgWidth.value
|
|
176
|
+
for (let y = 0; y < code.size; y++) {
|
|
177
|
+
for (let x = 0; x < code.size; x++) {
|
|
178
|
+
if (!modules[y * code.size + x]) continue
|
|
179
|
+
let run = 1
|
|
180
|
+
while (x + run < code.size && modules[y * code.size + x + run]) run++
|
|
181
|
+
path.value += `M${x + 4} ${y + 4}h${run}v1h-${run}z`
|
|
182
|
+
x += run - 1
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
} else {
|
|
186
|
+
svgWidth.value = code.width
|
|
187
|
+
svgHeight.value = 60
|
|
188
|
+
let x = 0
|
|
189
|
+
while (x < code.width) {
|
|
190
|
+
if (!modules[x]) {
|
|
191
|
+
x++
|
|
192
|
+
continue
|
|
193
|
+
}
|
|
194
|
+
let run = 1
|
|
195
|
+
while (x + run < code.width && modules[x + run]) run++
|
|
196
|
+
path.value += `M${x} 0h${run}v${svgHeight.value}h-${run}z`
|
|
197
|
+
x += run
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
viewBox.value = `0 0 ${svgWidth.value} ${svgHeight.value}`
|
|
201
|
+
svgMarkup.value = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${viewBox.value}" shape-rendering="crispEdges"><rect width="${svgWidth.value}" height="${svgHeight.value}" fill="#fff"/><path d="${path.value}" fill="#000"/></svg>`
|
|
202
|
+
error.value = ''
|
|
203
|
+
} catch (cause) {
|
|
204
|
+
path.value = ''
|
|
205
|
+
svgMarkup.value = ''
|
|
206
|
+
error.value = cause instanceof Error ? cause.message : String(cause)
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function download(event) {
|
|
211
|
+
event.preventDefault()
|
|
212
|
+
if (!svgMarkup.value) return
|
|
213
|
+
const url = URL.createObjectURL(new Blob([svgMarkup.value], { type: 'image/svg+xml' }))
|
|
214
|
+
const link = document.createElement('a')
|
|
215
|
+
link.href = url
|
|
216
|
+
link.download = `symbology-${element.format}.svg`
|
|
217
|
+
link.click()
|
|
218
|
+
setTimeout(() => URL.revokeObjectURL(url), 0)
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function setFormat(event) {
|
|
222
|
+
element.format = event.currentTarget.value
|
|
223
|
+
generate()
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function setValue(event) {
|
|
227
|
+
element.value = event.currentTarget.value
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
initialize()
|
|
231
|
+
|
|
232
|
+
// ---- the template: its nodes, and how each changing spot is kept up to date
|
|
233
|
+
const content = clone(`
|
|
234
|
+
<form>
|
|
235
|
+
<label>Format
|
|
236
|
+
<select>
|
|
237
|
+
<option value="qr">QR code</option>
|
|
238
|
+
<option value="code128">Code 128</option>
|
|
239
|
+
<option value="code39">Code 39</option>
|
|
240
|
+
<option value="ean13">EAN-13</option>
|
|
241
|
+
</select>
|
|
242
|
+
</label>
|
|
243
|
+
<label>Content
|
|
244
|
+
<textarea></textarea>
|
|
245
|
+
</label>
|
|
246
|
+
<button type="submit">Generate code</button>
|
|
247
|
+
</form>
|
|
248
|
+
<p role="status"></p>
|
|
249
|
+
<svg xmlns="http://www.w3.org/2000/svg" role="img" shape-rendering="crispEdges">
|
|
250
|
+
<rect fill="#fff"></rect>
|
|
251
|
+
<path fill="#000"></path>
|
|
252
|
+
</svg>
|
|
253
|
+
<a href="#">Download SVG</a>
|
|
254
|
+
`);
|
|
255
|
+
const form = content.children[0];
|
|
256
|
+
form.addEventListener("submit", (event) => { event.preventDefault(); generate() });
|
|
257
|
+
const select = form.children[0].children[0];
|
|
258
|
+
select.addEventListener("change", setFormat);
|
|
259
|
+
const textarea = form.children[1].children[0];
|
|
260
|
+
textarea.addEventListener("input", setValue);
|
|
261
|
+
const p = content.children[1];
|
|
262
|
+
const svg = content.children[2];
|
|
263
|
+
const rect = svg.children[0];
|
|
264
|
+
const path2 = svg.children[1];
|
|
265
|
+
const a = content.children[3];
|
|
266
|
+
a.addEventListener("click", download);
|
|
267
|
+
this.#updates = [
|
|
268
|
+
bind(() => element.format, (value) => $setValue(select, value)),
|
|
269
|
+
bind(() => element.value, (value) => $setValue(textarea, value)),
|
|
270
|
+
bind(() => (loading.value ? "Loading the Symbology engine…" : (error.value || "Ready")) ?? "", (value) => (p.textContent = value)),
|
|
271
|
+
bind(() => viewBox.value, (value) => attribute(svg, "viewBox", value)),
|
|
272
|
+
bind(() => `Generated ${element.format} code`, (value) => attribute(svg, "aria-label", value)),
|
|
273
|
+
bind(() => !(path.value), (value) => svg.toggleAttribute("hidden", Boolean(value))),
|
|
274
|
+
bind(() => svgWidth.value, (value) => attribute(rect, "width", value)),
|
|
275
|
+
bind(() => svgHeight.value, (value) => attribute(rect, "height", value)),
|
|
276
|
+
bind(() => path.value, (value) => attribute(path2, "d", value)),
|
|
277
|
+
bind(() => !(path.value), (value) => a.toggleAttribute("hidden", Boolean(value))),
|
|
278
|
+
];
|
|
279
|
+
return content;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// ---- updates: changes are batched, and applied together in a microtask
|
|
283
|
+
|
|
284
|
+
#requestUpdate() {
|
|
285
|
+
this.#pending ??= Promise.resolve().then(() => this.#update());
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
#update() {
|
|
289
|
+
this.#pending = null;
|
|
290
|
+
// Off the page, nothing updates; it catches up when it's back (connectedCallback).
|
|
291
|
+
if (!this.#started || !this.isConnected) return;
|
|
292
|
+
for (const update of this.#updates) update();
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Resolves once pending changes are on the page. */
|
|
296
|
+
get updateComplete() {
|
|
297
|
+
return this.#pending ?? Promise.resolve();
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** Fires one of the element's events: it bubbles; a before… event can be cancelled. */
|
|
301
|
+
#fire(name, detail) {
|
|
302
|
+
return this.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, cancelable: name.startsWith("before") }));
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// ---- helpers
|
|
307
|
+
|
|
308
|
+
/** Keeps one spot in the DOM up to date: `write` runs when `read` gives a value it hasn't had. */
|
|
309
|
+
function bind(read, write) {
|
|
310
|
+
let last = bind; // nothing written yet
|
|
311
|
+
return () => {
|
|
312
|
+
const value = read();
|
|
313
|
+
if (Object.is(value, last)) return;
|
|
314
|
+
const previous = last === bind ? undefined : last;
|
|
315
|
+
write((last = value), previous);
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** An attribute from a value: null, undefined and false remove it. */
|
|
320
|
+
function attribute(node, name, value) {
|
|
321
|
+
if (value == null || value === false) {
|
|
322
|
+
node.removeAttribute(name);
|
|
323
|
+
} else if (typeof value === "object") {
|
|
324
|
+
console.error(`zubra: cannot write an object to the "${name}" attribute`, value);
|
|
325
|
+
node.removeAttribute(name);
|
|
326
|
+
} else {
|
|
327
|
+
node.setAttribute(name, value);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* A form field's value: the property (what's shown and submitted), not the attribute (which is
|
|
333
|
+
* only its starting value).
|
|
334
|
+
*/
|
|
335
|
+
function $setValue(node, value) {
|
|
336
|
+
const text = String(value ?? "");
|
|
337
|
+
if (node.value !== text) node.value = text;
|
|
338
|
+
// A <select>'s options may come from a list inside it that renders after this: again once they're there.
|
|
339
|
+
if (node.localName === "select" && node.value !== text) queueMicrotask(() => { if (node.value !== text) node.value = text; });
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** Markup, parsed once into a <template>; each call returns a fresh copy of its nodes. */
|
|
343
|
+
const templates = new Map();
|
|
344
|
+
function clone(markup) {
|
|
345
|
+
let template = templates.get(markup);
|
|
346
|
+
if (!template) {
|
|
347
|
+
template = document.createElement("template");
|
|
348
|
+
template.innerHTML = markup;
|
|
349
|
+
templates.set(markup, template);
|
|
350
|
+
}
|
|
351
|
+
return template.content.cloneNode(true);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// While a computed() or an effect runs: what it reads. Each entry reads the same value again, so
|
|
355
|
+
// it can tell later whether anything it depends on has changed.
|
|
356
|
+
let reads = null;
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* State: a value that updates the element when it's set, or (an array or plain object) changed
|
|
360
|
+
* in place: push, splice and nested writes count. `.value` reads and sets it; so do `.get()` and
|
|
361
|
+
* `.set()`.
|
|
362
|
+
*/
|
|
363
|
+
function createState(initial, changed) {
|
|
364
|
+
let version = 0;
|
|
365
|
+
const proxies = new WeakMap(); // this state's own, so the same object in two states tells each
|
|
366
|
+
const bump = () => {
|
|
367
|
+
version++;
|
|
368
|
+
changed();
|
|
369
|
+
};
|
|
370
|
+
const deep = (value) => {
|
|
371
|
+
if (!value || typeof value !== "object" || !(Array.isArray(value) || Object.getPrototypeOf(value) === Object.prototype)) return value;
|
|
372
|
+
let proxy = proxies.get(value);
|
|
373
|
+
if (!proxy) {
|
|
374
|
+
proxy = new Proxy(value, {
|
|
375
|
+
get: (target, key, receiver) => deep(Reflect.get(target, key, receiver)),
|
|
376
|
+
set: (target, key, next, receiver) => {
|
|
377
|
+
const same = Object.is(target[key], next);
|
|
378
|
+
const done = Reflect.set(target, key, next, receiver);
|
|
379
|
+
if (!same) bump();
|
|
380
|
+
return done;
|
|
381
|
+
},
|
|
382
|
+
deleteProperty: (target, key) => {
|
|
383
|
+
const done = Reflect.deleteProperty(target, key);
|
|
384
|
+
bump();
|
|
385
|
+
return done;
|
|
386
|
+
},
|
|
387
|
+
});
|
|
388
|
+
proxies.set(value, proxy);
|
|
389
|
+
}
|
|
390
|
+
return proxy;
|
|
391
|
+
};
|
|
392
|
+
let value = deep(initial);
|
|
393
|
+
const read = () => version;
|
|
394
|
+
return {
|
|
395
|
+
get value() {
|
|
396
|
+
reads?.push(read);
|
|
397
|
+
return value;
|
|
398
|
+
},
|
|
399
|
+
set value(next) {
|
|
400
|
+
if (Object.is(next, value)) return;
|
|
401
|
+
value = deep(next);
|
|
402
|
+
bump();
|
|
403
|
+
},
|
|
404
|
+
get() {
|
|
405
|
+
return this.value;
|
|
406
|
+
},
|
|
407
|
+
set(next) {
|
|
408
|
+
this.value = next;
|
|
409
|
+
},
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// Register the element (a server import, with no customElements, defines nothing).
|
|
414
|
+
if (globalThis.customElements && !customElements.get(tag)) customElements.define(tag, SymbologyCode);
|
|
415
|
+
export default SymbologyCode;
|
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@journey-to-code/symbology",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Dependency-free QR and linear barcode encoding and decoding in Rust, JavaScript, and a Zubra web component",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "https://github.com/journey-to-code-org/symbology.git",
|
|
10
|
+
"directory": "js"
|
|
11
|
+
},
|
|
12
|
+
"keywords": [
|
|
13
|
+
"qr",
|
|
14
|
+
"barcode",
|
|
15
|
+
"symbology",
|
|
16
|
+
"webassembly",
|
|
17
|
+
"web-component",
|
|
18
|
+
"zubra"
|
|
19
|
+
],
|
|
20
|
+
"publishConfig": {
|
|
21
|
+
"access": "public"
|
|
22
|
+
},
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./qr.d.ts",
|
|
26
|
+
"import": "./qr.js"
|
|
27
|
+
},
|
|
28
|
+
"./symbology-code": {
|
|
29
|
+
"types": "./dist/symbology-code.d.ts",
|
|
30
|
+
"import": "./dist/symbology-code.js"
|
|
31
|
+
},
|
|
32
|
+
"./symbology.wasm": "./symbology.wasm"
|
|
33
|
+
},
|
|
34
|
+
"types": "./qr.d.ts",
|
|
35
|
+
"files": [
|
|
36
|
+
"qr.js",
|
|
37
|
+
"qr.d.ts",
|
|
38
|
+
"symbology.wasm",
|
|
39
|
+
"dist/",
|
|
40
|
+
"components/"
|
|
41
|
+
],
|
|
42
|
+
"engines": {
|
|
43
|
+
"node": ">=20"
|
|
44
|
+
},
|
|
45
|
+
"scripts": {
|
|
46
|
+
"build": "node scripts/build.mjs",
|
|
47
|
+
"prepack": "npm run build",
|
|
48
|
+
"test": "node --test --test-concurrency=1 'test/*.test.js'"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@zubra/compiler": "5.9.2",
|
|
52
|
+
"playwright-core": "^1.65.0"
|
|
53
|
+
}
|
|
54
|
+
}
|
package/qr.d.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
export type QrErrorCode = 'empty' | 'too-long' | 'not-found' | 'unsupported' | 'uncorrectable' | 'malformed' | 'bad-frame' | 'frame-too-large';
|
|
2
|
+
export type BarcodeErrorCode = 'empty' | 'invalid-input' | 'invalid-length' | 'invalid-checksum' | 'bad-scanline' | 'not-found';
|
|
3
|
+
export type BarcodeType = 'code128' | 'code39' | 'ean13';
|
|
4
|
+
|
|
5
|
+
export class QrError extends Error {
|
|
6
|
+
readonly code: QrErrorCode;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export class BarcodeError extends Error {
|
|
10
|
+
readonly code: BarcodeErrorCode;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** `modules` is `size * size` bytes, row-major, 1 dark, without the quiet zone. */
|
|
14
|
+
export interface Code {
|
|
15
|
+
size: number;
|
|
16
|
+
modules: Uint8Array;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** An 8-bit grayscale frame, one byte per pixel, row-major. */
|
|
20
|
+
export interface Frame {
|
|
21
|
+
width: number;
|
|
22
|
+
height: number;
|
|
23
|
+
luma: Uint8Array;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** A linear barcode row, including its quiet zones. */
|
|
27
|
+
export interface LinearCode {
|
|
28
|
+
type: BarcodeType;
|
|
29
|
+
width: number;
|
|
30
|
+
modules: Uint8Array;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface DecodedBarcode {
|
|
34
|
+
type: BarcodeType;
|
|
35
|
+
data: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export type DetectedCode =
|
|
39
|
+
| { type: 'qr'; data: Uint8Array }
|
|
40
|
+
| DecodedBarcode;
|
|
41
|
+
|
|
42
|
+
export interface SvgOptions {
|
|
43
|
+
/** Quiet zone in modules. Default 4. */
|
|
44
|
+
margin?: number;
|
|
45
|
+
dark?: string;
|
|
46
|
+
/** `'transparent'` or `''` for no background. Default `'#fff'`. */
|
|
47
|
+
light?: string;
|
|
48
|
+
/** Gives the image a name for screen readers; without it the SVG is hidden from them. */
|
|
49
|
+
title?: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface BarcodeSvgOptions {
|
|
53
|
+
/** Bar height in module units. Default 60. */
|
|
54
|
+
height?: number;
|
|
55
|
+
/** Extra white margin outside the encoded quiet zones. Default 0. */
|
|
56
|
+
margin?: number;
|
|
57
|
+
dark?: string;
|
|
58
|
+
light?: string;
|
|
59
|
+
title?: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface Qr {
|
|
63
|
+
encode(input: string | Uint8Array | ArrayBuffer): Code;
|
|
64
|
+
decode(frame: Frame): Uint8Array;
|
|
65
|
+
decodeText(frame: Frame): string;
|
|
66
|
+
svg(code: Code | string | Uint8Array, options?: SvgOptions): string;
|
|
67
|
+
encodeBarcode(format: BarcodeType, input: string | Uint8Array | ArrayBuffer): LinearCode;
|
|
68
|
+
encodeCode128(input: string | Uint8Array | ArrayBuffer): LinearCode;
|
|
69
|
+
encodeCode39(input: string | Uint8Array | ArrayBuffer): LinearCode;
|
|
70
|
+
encodeEan13(input: string | Uint8Array | ArrayBuffer): LinearCode;
|
|
71
|
+
decodeBarcodeScanline(luma: Uint8Array): DecodedBarcode;
|
|
72
|
+
scanFrame(frame: Frame): DetectedCode;
|
|
73
|
+
barcodeSvg(code: LinearCode, options?: BarcodeSvgOptions): string;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function loadQr(source?: BufferSource | Response | WebAssembly.Module | string | URL): Promise<Qr>;
|
|
77
|
+
export function svg(code: Code, options?: SvgOptions): string;
|
|
78
|
+
export function barcodeSvg(code: LinearCode, options?: BarcodeSvgOptions): string;
|
package/qr.js
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
// QR codes from the crate's WebAssembly build, the same on a server and in a browser.
|
|
2
|
+
//
|
|
3
|
+
// const qr = await loadQr(wasm); // bytes, a Response, a WebAssembly.Module, or a URL
|
|
4
|
+
// const code = qr.encode('https://potomac.solutions/t/8F3K'); // { size, modules }
|
|
5
|
+
// qr.svg(code); // an <svg> string, for a page or an email
|
|
6
|
+
// qr.decode({ width, height, luma }); // Uint8Array; qr.decodeText(...) for a string
|
|
7
|
+
// const bars = qr.encodeCode128('Ticket-42'); // { type, width, modules }
|
|
8
|
+
// qr.scanFrame({ width, height, luma }); // first QR or linear code found
|
|
9
|
+
//
|
|
10
|
+
// No dependencies. Errors are QrError, with `code` one of: empty, too-long, not-found,
|
|
11
|
+
// unsupported, uncorrectable, malformed, bad-frame, frame-too-large.
|
|
12
|
+
|
|
13
|
+
const CODES = [null, 'empty', 'too-long', 'not-found', 'unsupported', 'uncorrectable', 'malformed', 'bad-frame', 'frame-too-large'];
|
|
14
|
+
const MATRIX_HEADER = 12;
|
|
15
|
+
const BARCODE_FORMATS = { code128: 1, code39: 2, ean13: 3 };
|
|
16
|
+
const BARCODE_CODES = ['empty', 'invalid-input', 'invalid-length', 'invalid-checksum', 'bad-scanline', 'not-found'];
|
|
17
|
+
|
|
18
|
+
export class QrError extends Error {
|
|
19
|
+
constructor(code) {
|
|
20
|
+
super(`qr: ${code}`);
|
|
21
|
+
this.name = 'QrError';
|
|
22
|
+
this.code = code;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export class BarcodeError extends Error {
|
|
27
|
+
constructor(code) {
|
|
28
|
+
super(`barcode: ${code}`);
|
|
29
|
+
this.name = 'BarcodeError';
|
|
30
|
+
this.code = code;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function instantiate(source) {
|
|
35
|
+
if (source instanceof WebAssembly.Module) return WebAssembly.instantiate(source, {});
|
|
36
|
+
if (typeof Response !== 'undefined' && source instanceof Response) {
|
|
37
|
+
if (WebAssembly.instantiateStreaming && source.headers.get('content-type')?.startsWith('application/wasm')) {
|
|
38
|
+
return (await WebAssembly.instantiateStreaming(source, {})).instance;
|
|
39
|
+
}
|
|
40
|
+
source = await source.arrayBuffer();
|
|
41
|
+
} else if (typeof source === 'string' || source instanceof URL) {
|
|
42
|
+
const url = new URL(source, globalThis.location?.href);
|
|
43
|
+
if (url.protocol === 'file:') {
|
|
44
|
+
const { readFile } = await import('node:fs/promises');
|
|
45
|
+
source = await readFile(url);
|
|
46
|
+
} else {
|
|
47
|
+
return instantiate(await fetch(url));
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return (await WebAssembly.instantiate(source, {})).instance;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Load the WebAssembly build. Pass its bytes, a fetch Response, a compiled Module, or a URL. */
|
|
54
|
+
export async function loadQr(source) {
|
|
55
|
+
source ??= new URL('./symbology.wasm', import.meta.url);
|
|
56
|
+
const { exports: wasm } = await instantiate(source);
|
|
57
|
+
for (const name of ['memory', 'qr_alloc', 'qr_free', 'qr_encode', 'qr_result_ptr', 'qr_result_len']) {
|
|
58
|
+
if (!(name in wasm)) throw new TypeError(`loadQr: this isn't the qr build (no ${name})`);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const call = (fn, input, ...args) => {
|
|
62
|
+
if (!fn) throw new TypeError('This WebAssembly build does not provide that operation');
|
|
63
|
+
const pointer = wasm.qr_alloc(input.length);
|
|
64
|
+
try {
|
|
65
|
+
new Uint8Array(wasm.memory.buffer, pointer, input.length).set(input);
|
|
66
|
+
const status = fn(pointer, input.length, ...args);
|
|
67
|
+
if (status >= 20 && status <= 25) throw new BarcodeError(BARCODE_CODES[status - 20]);
|
|
68
|
+
if (status !== 0) throw new QrError(CODES[status] ?? `error-${status}`);
|
|
69
|
+
// Copy out: the next call (or a memory.grow) invalidates the view.
|
|
70
|
+
return new Uint8Array(wasm.memory.buffer, wasm.qr_result_ptr(), wasm.qr_result_len()).slice();
|
|
71
|
+
} finally {
|
|
72
|
+
wasm.qr_free(pointer, input.length);
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
const bytesOf = (input) => (typeof input === 'string' ? new TextEncoder().encode(input) : input instanceof Uint8Array ? input : new Uint8Array(input));
|
|
76
|
+
|
|
77
|
+
/** Encode text (as UTF-8) or bytes. `modules` is `size * size` bytes, row-major, 1 dark; no quiet zone. */
|
|
78
|
+
function encode(input) {
|
|
79
|
+
const matrix = call(wasm.qr_encode, bytesOf(input));
|
|
80
|
+
const size = new DataView(matrix.buffer).getUint32(8, true);
|
|
81
|
+
return { size, modules: matrix.subarray(MATRIX_HEADER) };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Read the payload out of an 8-bit grayscale frame: `{ width, height, luma }`, one byte per pixel. */
|
|
85
|
+
function decode({ width, height, luma }) {
|
|
86
|
+
if (!wasm.qr_decode) throw new TypeError('decode: this build has no decoder (built without the decode feature)');
|
|
87
|
+
const input = new Uint8Array(8 + luma.length);
|
|
88
|
+
const view = new DataView(input.buffer);
|
|
89
|
+
view.setUint32(0, width, true);
|
|
90
|
+
view.setUint32(4, height, true);
|
|
91
|
+
input.set(luma, 8);
|
|
92
|
+
return call(wasm.qr_decode, input);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Encode a linear barcode; format is `code128`, `code39`, or `ean13`. */
|
|
96
|
+
function encodeBarcode(format, input) {
|
|
97
|
+
const id = BARCODE_FORMATS[format];
|
|
98
|
+
if (!id) throw new TypeError(`encodeBarcode: unsupported format ${format}`);
|
|
99
|
+
if (!wasm.qr_barcode_encode) throw new TypeError('encodeBarcode: unsupported by this WebAssembly build');
|
|
100
|
+
const bytes = call(wasm.qr_barcode_encode, bytesOf(input), id);
|
|
101
|
+
if (new TextDecoder().decode(bytes.subarray(0, 4)) !== 'KBC1' || bytes.length < 9) {
|
|
102
|
+
throw new TypeError('encodeBarcode: invalid response from WebAssembly');
|
|
103
|
+
}
|
|
104
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
105
|
+
const width = view.getUint32(5, true);
|
|
106
|
+
if (bytes[4] !== id || bytes.length !== 9 + width) {
|
|
107
|
+
throw new TypeError('encodeBarcode: invalid response from WebAssembly');
|
|
108
|
+
}
|
|
109
|
+
return { type: format, width, modules: bytes.slice(9) };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Decode an 8-bit grayscale scanline into `{ type, data }`. */
|
|
113
|
+
function decodeBarcodeScanline(luma) {
|
|
114
|
+
if (!wasm.qr_barcode_scanline) throw new TypeError('decodeBarcodeScanline: this build has no decoder (built without the decode feature)');
|
|
115
|
+
const result = call(wasm.qr_barcode_scanline, bytesOf(luma));
|
|
116
|
+
return decodedBarcode(result);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Scan a grayscale frame and return the first detected QR or linear code. */
|
|
120
|
+
function scanFrame({ width, height, luma }) {
|
|
121
|
+
if (!wasm.qr_scan) throw new TypeError('scanFrame: this build has no decoder (built without the decode feature)');
|
|
122
|
+
const input = new Uint8Array(8 + luma.length);
|
|
123
|
+
const view = new DataView(input.buffer);
|
|
124
|
+
view.setUint32(0, width, true);
|
|
125
|
+
view.setUint32(4, height, true);
|
|
126
|
+
input.set(luma, 8);
|
|
127
|
+
const result = call(wasm.qr_scan, input);
|
|
128
|
+
if (result.length === 0) throw new TypeError('scanFrame: empty response from WebAssembly');
|
|
129
|
+
if (result[0] === 0) return { type: 'qr', data: result.slice(1) };
|
|
130
|
+
return decodedBarcode(result);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
return {
|
|
134
|
+
encode,
|
|
135
|
+
decode,
|
|
136
|
+
decodeText: (frame) => new TextDecoder().decode(decode(frame)),
|
|
137
|
+
svg: (code, options) => svg(typeof code === 'string' || code instanceof Uint8Array ? encode(code) : code, options),
|
|
138
|
+
encodeBarcode,
|
|
139
|
+
encodeCode128: (input) => encodeBarcode('code128', input),
|
|
140
|
+
encodeCode39: (input) => encodeBarcode('code39', input),
|
|
141
|
+
encodeEan13: (input) => encodeBarcode('ean13', input),
|
|
142
|
+
decodeBarcodeScanline,
|
|
143
|
+
scanFrame,
|
|
144
|
+
barcodeSvg,
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function decodedBarcode(result) {
|
|
149
|
+
const type = Object.keys(BARCODE_FORMATS).find((format) => BARCODE_FORMATS[format] === result[0]);
|
|
150
|
+
if (!type) throw new TypeError(`Unknown barcode type from WebAssembly: ${result[0]}`);
|
|
151
|
+
return { type, data: new TextDecoder().decode(result.subarray(1)) };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* An SVG of a code, with a quiet zone of `margin` modules (4 is the standard). One path, a run
|
|
156
|
+
* of dark modules per segment, so it stays small and crisp at any size.
|
|
157
|
+
*/
|
|
158
|
+
export function svg({ size, modules }, { margin = 4, dark = '#000', light = '#fff', title = '' } = {}) {
|
|
159
|
+
const side = size + 2 * margin;
|
|
160
|
+
let path = '';
|
|
161
|
+
for (let y = 0; y < size; y++) {
|
|
162
|
+
for (let x = 0; x < size; x++) {
|
|
163
|
+
if (!modules[y * size + x]) continue;
|
|
164
|
+
let run = 1;
|
|
165
|
+
while (x + run < size && modules[y * size + x + run]) run++;
|
|
166
|
+
path += `M${x + margin} ${y + margin}h${run}v1h-${run}z`;
|
|
167
|
+
x += run - 1;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
const escape = (text) => String(text).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);
|
|
171
|
+
return (
|
|
172
|
+
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${side} ${side}" shape-rendering="crispEdges"${title ? ` role="img" aria-label="${escape(title)}"` : ' aria-hidden="true"'}>` +
|
|
173
|
+
(title ? `<title>${escape(title)}</title>` : '') +
|
|
174
|
+
(light && light !== 'transparent' ? `<rect width="${side}" height="${side}" fill="${escape(light)}"/>` : '') +
|
|
175
|
+
`<path fill="${escape(dark)}" d="${path}"/></svg>`
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Render a linear barcode row as SVG. Encoded rows already include quiet zones. */
|
|
180
|
+
export function barcodeSvg({ width, modules }, { height = 60, margin = 0, dark = '#000', light = '#fff', title = '' } = {}) {
|
|
181
|
+
const side = width + 2 * margin;
|
|
182
|
+
let path = '';
|
|
183
|
+
for (let x = 0; x < width; x++) {
|
|
184
|
+
if (!modules[x]) continue;
|
|
185
|
+
let run = 1;
|
|
186
|
+
while (x + run < width && modules[x + run]) run++;
|
|
187
|
+
path += `M${x + margin} ${margin}v${height}h${run}v-${height}z`;
|
|
188
|
+
x += run - 1;
|
|
189
|
+
}
|
|
190
|
+
const escape = (text) => String(text).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);
|
|
191
|
+
return (
|
|
192
|
+
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${side} ${height + 2 * margin}" shape-rendering="crispEdges"${title ? ` role="img" aria-label="${escape(title)}"` : ' aria-hidden="true"'}>` +
|
|
193
|
+
(title ? `<title>${escape(title)}</title>` : '') +
|
|
194
|
+
(light && light !== 'transparent' ? `<rect width="${side}" height="${height + 2 * margin}" fill="${escape(light)}"/>` : '') +
|
|
195
|
+
`<path fill="${escape(dark)}" d="${path}"/></svg>`
|
|
196
|
+
);
|
|
197
|
+
}
|
package/symbology.wasm
ADDED
|
Binary file
|