@journey-to-code/symbology 0.0.0-stage → 0.3.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.
@@ -0,0 +1,837 @@
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
+ import { styledQr, PRESETS } from '../style.js';
10
+
11
+ const HTMLElement = globalThis.HTMLElement ?? class {}; // on a server, nothing to extend
12
+ export const tag = "symbology-code";
13
+
14
+ // The component's styles: one stylesheet, shared by every symbology-code on the page (made when the
15
+ // first one connects, since a server that imports this module has no CSSStyleSheet).
16
+ let sheet = null;
17
+ const css = `@layer theme, base, components, utilities;
18
+ @layer components {
19
+ @scope (symbology-code) to ([data-zb-slotted="symbology-code"]) {
20
+ :scope { color: #17241f; font: 14px/1.5 system-ui, sans-serif; }
21
+ form { display: grid; gap: 12px; max-width: 28rem; }
22
+ label { display: grid; gap: 5px; font-size: 12px; font-weight: 600; }
23
+ select, textarea, button { box-sizing: border-box; font: inherit; }
24
+ select, textarea { width: 100%; padding: 9px; border: 1px solid #cbd1c7; border-radius: 4px; background: white; }
25
+ textarea { min-height: 76px; resize: vertical; }
26
+ button { padding: 10px 14px; border: 0; border-radius: 4px; background: #c9ef5b; color: #17241f; cursor: pointer; font-weight: 700; }
27
+ svg { display: block; width: min(100%, 24rem); max-height: 24rem; margin-top: 18px; background: white; }
28
+ .art svg { background: transparent; }
29
+ [hidden] { display: none !important; }
30
+ a { display: inline-block; margin-top: 12px; color: #314c15; }
31
+ p { color: #59645d; }
32
+ .row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
33
+ input[type="file"] { font: inherit; font-size: 12px; font-weight: 400; }
34
+ .text-button { justify-self: start; padding: 0; background: none; color: #59645d; font-size: 12px; font-weight: 400; text-decoration: underline; }
35
+ .verdict { color: #3b5a10; font-weight: 600; }
36
+ .notes { margin: 6px 0 0; color: #8a3a2c; font-size: 12px; white-space: pre-line; }
37
+ }
38
+ }
39
+ `;
40
+
41
+ export class SymbologyCode extends HTMLElement {
42
+ /** The attributes this element watches: attributeChangedCallback runs when one changes. */
43
+ static observedAttributes = ["format", "value", "preset", "logo", "logo-size", "cta", "qr-style", "controls"];
44
+ /** What framework adapters (@zubra/runtime/react, /vue) read to wrap this element. */
45
+ static zubra = {
46
+ tag,
47
+ props: {
48
+ format: { attribute: "format", default: "qr", required: false },
49
+ value: { attribute: "value", default: "https://example.com", required: false },
50
+ preset: { attribute: "preset", default: "", required: false },
51
+ logo: { attribute: "logo", default: "", required: false },
52
+ logoSize: { attribute: "logo-size", default: "", required: false },
53
+ cta: { attribute: "cta", default: "", required: false },
54
+ qrStyle: { attribute: "qr-style", default: {}, required: false },
55
+ controls: { attribute: "controls", default: "full", required: false },
56
+ },
57
+ events: [],
58
+ slots: [],
59
+ shadow: false,
60
+ form: false,
61
+ element: true,
62
+ };
63
+
64
+ // ElementInternals: the element's form value and validity, and :state() for CSS.
65
+ #internals = this.attachInternals();
66
+ // The props, each starting at its default; #given has the ones set from outside.
67
+ #props = { format: "qr", value: "https://example.com", preset: "", logo: "", logoSize: "", cta: "", qrStyle: {}, controls: "full" };
68
+ #given = new Set();
69
+ // What brings the DOM up to date: one function for each spot that changes.
70
+ #updates = [];
71
+ #pending = null;
72
+ #started = false;
73
+
74
+ constructor() {
75
+ super();
76
+ // A property set before this class was defined sits on the element itself, hiding the
77
+ // accessor below: take it over.
78
+ for (const prop of ["format", "value", "preset", "logo", "logoSize", "cta", "qrStyle", "controls"]) {
79
+ if (Object.hasOwn(this, prop)) {
80
+ const value = this[prop];
81
+ delete this[prop];
82
+ this[prop] = value;
83
+ }
84
+ }
85
+ }
86
+
87
+ // ---- props: properties, and attributes that set them
88
+
89
+ get format() {
90
+ return this.#props.format;
91
+ }
92
+ set format(value) {
93
+ this.#given.add("format");
94
+ if (Object.is(value, this.#props.format)) return;
95
+ this.#props.format = value;
96
+ this.#requestUpdate();
97
+ }
98
+
99
+ get value() {
100
+ return this.#props.value;
101
+ }
102
+ set value(value) {
103
+ this.#given.add("value");
104
+ if (Object.is(value, this.#props.value)) return;
105
+ this.#props.value = value;
106
+ this.#requestUpdate();
107
+ }
108
+
109
+ get preset() {
110
+ return this.#props.preset;
111
+ }
112
+ set preset(value) {
113
+ this.#given.add("preset");
114
+ if (Object.is(value, this.#props.preset)) return;
115
+ this.#props.preset = value;
116
+ this.#requestUpdate();
117
+ }
118
+
119
+ get logo() {
120
+ return this.#props.logo;
121
+ }
122
+ set logo(value) {
123
+ this.#given.add("logo");
124
+ if (Object.is(value, this.#props.logo)) return;
125
+ this.#props.logo = value;
126
+ this.#requestUpdate();
127
+ }
128
+
129
+ get logoSize() {
130
+ return this.#props.logoSize;
131
+ }
132
+ set logoSize(value) {
133
+ this.#given.add("logoSize");
134
+ if (Object.is(value, this.#props.logoSize)) return;
135
+ this.#props.logoSize = value;
136
+ this.#requestUpdate();
137
+ }
138
+
139
+ get cta() {
140
+ return this.#props.cta;
141
+ }
142
+ set cta(value) {
143
+ this.#given.add("cta");
144
+ if (Object.is(value, this.#props.cta)) return;
145
+ this.#props.cta = value;
146
+ this.#requestUpdate();
147
+ }
148
+
149
+ get qrStyle() {
150
+ return this.#props.qrStyle;
151
+ }
152
+ set qrStyle(value) {
153
+ this.#given.add("qrStyle");
154
+ if (Object.is(value, this.#props.qrStyle)) return;
155
+ this.#props.qrStyle = value;
156
+ this.#requestUpdate();
157
+ }
158
+
159
+ get controls() {
160
+ return this.#props.controls;
161
+ }
162
+ set controls(value) {
163
+ this.#given.add("controls");
164
+ if (Object.is(value, this.#props.controls)) return;
165
+ this.#props.controls = value;
166
+ this.#requestUpdate();
167
+ }
168
+
169
+ attributeChangedCallback(name, previous, raw) {
170
+ // raw is the attribute's text, or null once it's removed.
171
+ switch (name) {
172
+ case "format":
173
+ this.format = raw ?? "qr";
174
+ break;
175
+ case "value":
176
+ this.value = raw ?? "https://example.com";
177
+ break;
178
+ case "preset":
179
+ this.preset = raw ?? "";
180
+ break;
181
+ case "logo":
182
+ this.logo = raw ?? "";
183
+ break;
184
+ case "logo-size":
185
+ this.logoSize = raw ?? "";
186
+ break;
187
+ case "cta":
188
+ this.cta = raw ?? "";
189
+ break;
190
+ case "qr-style":
191
+ this.qrStyle = raw === null ? {} : fromJson(raw, {});
192
+ break;
193
+ case "controls":
194
+ this.controls = raw ?? "full";
195
+ break;
196
+ }
197
+ }
198
+
199
+ // ---- lifecycle
200
+
201
+ connectedCallback() {
202
+ // The styles go to the root the element is in: the document, or a shadow root it's inside.
203
+ const root = this.getRootNode();
204
+ if (root.adoptedStyleSheets) {
205
+ if (!sheet) {
206
+ sheet = new CSSStyleSheet();
207
+ sheet.replaceSync(css);
208
+ }
209
+ if (!root.adoptedStyleSheets.includes(sheet)) root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
210
+ }
211
+ if (!this.#started) this.#start();
212
+ this.#update();
213
+ }
214
+
215
+ #start() {
216
+ // Props a framework's server rendering wrote as JSON (zb-props), before it sets them as properties.
217
+ let given;
218
+ try {
219
+ given = JSON.parse(this.getAttribute("zb-props"));
220
+ } catch {
221
+ // none
222
+ }
223
+ for (const name in given) if (Object.hasOwn(this.#props, name) && !this.#given.has(name)) this[name] = given[name];
224
+ const content = this.#setup();
225
+ for (const update of this.#updates) update(); // filled in before it's on the page
226
+ this.replaceChildren(content);
227
+ this.#started = true;
228
+ this.#internals.states?.add("hydrated"); // :state(hydrated), for CSS
229
+ }
230
+
231
+ // The component's <script> and template, set up once per element. Props are read as
232
+ // element.name; state (a let) is name.value. Returns the template's nodes.
233
+ #setup() {
234
+ const element = this;
235
+ // The hooks the script uses (from @zubra/runtime in the source), made for this element.
236
+ const state = (initial) => createState(initial, () => this.#requestUpdate());
237
+
238
+ // ---- <script>
239
+ const api = state(undefined)
240
+ const svgWidth = state(0)
241
+ const svgHeight = state(0)
242
+ const viewBox = state('0 0 0 0')
243
+ const path = state('')
244
+ const svgMarkup = state('')
245
+ const error = state('')
246
+ const loading = state(true)
247
+ const art = state(null)
248
+ const styled = state(false)
249
+ const verdict = state('')
250
+ const notes = state('')
251
+ const chosenPreset = state('')
252
+ const uploadedLogo = state(null)
253
+ const fetchedLogo = state(null)
254
+ const logoNote = state('')
255
+ const presetNames = Object.keys(PRESETS)
256
+ const MAX_LOGO_BYTES = 150000
257
+
258
+ async function initialize() {
259
+ try {
260
+ api.value = await loadQr()
261
+ chosenPreset.value = element.preset
262
+ await fetchLogo()
263
+ loading.value = false
264
+ generate()
265
+ } catch (cause) {
266
+ error.value = cause instanceof Error ? cause.message : String(cause)
267
+ loading.value = false
268
+ }
269
+ }
270
+
271
+ function readAsDataUrl(blob) {
272
+ return new Promise((resolve, reject) => {
273
+ const reader = new FileReader()
274
+ reader.onload = () => resolve(reader.result)
275
+ reader.onerror = () => reject(reader.error)
276
+ reader.readAsDataURL(blob)
277
+ })
278
+ }
279
+
280
+ async function logoFrom(blob) {
281
+ if (blob.size > MAX_LOGO_BYTES) throw new Error(`the logo is over ${MAX_LOGO_BYTES / 1000} kB`)
282
+ if (blob.type === 'image/svg+xml') return { svg: await blob.text() }
283
+ return { href: await readAsDataUrl(blob) }
284
+ }
285
+
286
+ async function fetchLogo() {
287
+ fetchedLogo.value = null
288
+ logoNote.value = ''
289
+ if (!element.logo) return
290
+ try {
291
+ if (element.logo.startsWith('data:image/svg+xml;utf8,')) {
292
+ fetchedLogo.value = { svg: decodeURIComponent(element.logo.slice(element.logo.indexOf(',') + 1)) }
293
+ } else if (element.logo.startsWith('data:')) {
294
+ fetchedLogo.value = { href: element.logo }
295
+ } else {
296
+ const response = await fetch(new URL(element.logo, document.baseURI))
297
+ if (!response.ok) throw new Error(`${response.status} ${response.statusText}`.trim())
298
+ fetchedLogo.value = await logoFrom(await response.blob())
299
+ }
300
+ } catch (cause) {
301
+ logoNote.value = `Logo not loaded: ${cause instanceof Error ? cause.message : String(cause)}`
302
+ }
303
+ }
304
+
305
+ function wantsStyle() {
306
+ return Boolean(chosenPreset.value || uploadedLogo.value || fetchedLogo.value || element.cta || Object.keys(element.qrStyle ?? {}).length)
307
+ }
308
+
309
+ function currentStyle() {
310
+ const base = element.qrStyle && typeof element.qrStyle === 'object' ? element.qrStyle : {}
311
+ const style = { ...base, title: base.title ?? `QR code for ${element.value}` }
312
+ if (chosenPreset.value) style.preset = chosenPreset.value
313
+ const image = uploadedLogo.value ?? fetchedLogo.value
314
+ if (image) {
315
+ const size = Number(element.logoSize)
316
+ style.logo = { ...(base.logo ?? {}), ...image, ...(size > 0 ? { size } : {}) }
317
+ }
318
+ if (element.cta) style.frame = { ...(base.frame ?? {}), text: element.cta }
319
+ return style
320
+ }
321
+
322
+ function paint(markup) {
323
+ if (art.value) art.value.innerHTML = markup
324
+ }
325
+
326
+ function generateStyled() {
327
+ const { svg, report } = styledQr(api.value, element.value, currentStyle())
328
+ styled.value = true
329
+ path.value = ''
330
+ const lines = [...report.errors, ...report.warnings]
331
+ if (logoNote.value) lines.unshift(logoNote.value)
332
+ notes.value = lines.join('\n')
333
+ if (report.ok) {
334
+ svgMarkup.value = svg
335
+ verdict.value = `Scans · level ${report.level}, version ${report.version} · print at least ${report.print.minWidthMm} mm wide`
336
+ error.value = ''
337
+ } else {
338
+ svgMarkup.value = ''
339
+ verdict.value = ''
340
+ error.value = 'This design would not scan reliably.'
341
+ }
342
+ paint(svgMarkup.value)
343
+ }
344
+
345
+ function generate() {
346
+ if (!api.value) return
347
+ if (element.format === 'qr' && wantsStyle()) {
348
+ generateStyled()
349
+ return
350
+ }
351
+ styled.value = false
352
+ verdict.value = ''
353
+ notes.value = logoNote.value
354
+ paint('')
355
+ try {
356
+ const code = element.format === 'qr' ? api.value.encode(element.value) : api.value.encodeBarcode(element.format, element.value)
357
+ const modules = code.modules
358
+ path.value = ''
359
+ if (element.format === 'qr') {
360
+ svgWidth.value = code.size + 8
361
+ svgHeight.value = svgWidth.value
362
+ for (let y = 0; y < code.size; y++) {
363
+ for (let x = 0; x < code.size; x++) {
364
+ if (!modules[y * code.size + x]) continue
365
+ let run = 1
366
+ while (x + run < code.size && modules[y * code.size + x + run]) run++
367
+ path.value += `M${x + 4} ${y + 4}h${run}v1h-${run}z`
368
+ x += run - 1
369
+ }
370
+ }
371
+ } else {
372
+ svgWidth.value = code.width
373
+ svgHeight.value = 60
374
+ let x = 0
375
+ while (x < code.width) {
376
+ if (!modules[x]) {
377
+ x++
378
+ continue
379
+ }
380
+ let run = 1
381
+ while (x + run < code.width && modules[x + run]) run++
382
+ path.value += `M${x} 0h${run}v${svgHeight.value}h-${run}z`
383
+ x += run
384
+ }
385
+ }
386
+ viewBox.value = `0 0 ${svgWidth.value} ${svgHeight.value}`
387
+ 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>`
388
+ error.value = ''
389
+ } catch (cause) {
390
+ path.value = ''
391
+ svgMarkup.value = ''
392
+ error.value = cause instanceof Error ? cause.message : String(cause)
393
+ }
394
+ }
395
+
396
+ function download(event) {
397
+ event.preventDefault()
398
+ if (!svgMarkup.value) return
399
+ const url = URL.createObjectURL(new Blob([svgMarkup.value], { type: 'image/svg+xml' }))
400
+ const link = document.createElement('a')
401
+ link.href = url
402
+ link.download = styled.value ? 'symbology-qr-styled.svg' : `symbology-${element.format}.svg`
403
+ link.click()
404
+ setTimeout(() => URL.revokeObjectURL(url), 0)
405
+ }
406
+
407
+ function setFormat(event) {
408
+ element.format = event.currentTarget.value
409
+ generate()
410
+ }
411
+
412
+ function setValue(event) {
413
+ element.value = event.currentTarget.value
414
+ }
415
+
416
+ function setPreset(event) {
417
+ chosenPreset.value = event.currentTarget.value
418
+ generate()
419
+ }
420
+
421
+ async function uploadLogo(event) {
422
+ const file = event.currentTarget.files?.[0]
423
+ if (!file) return
424
+ try {
425
+ uploadedLogo.value = await logoFrom(file)
426
+ logoNote.value = ''
427
+ } catch (cause) {
428
+ uploadedLogo.value = null
429
+ logoNote.value = `Logo not used: ${cause instanceof Error ? cause.message : String(cause)}`
430
+ }
431
+ generate()
432
+ }
433
+
434
+ function clearLogo() {
435
+ uploadedLogo.value = null
436
+ generate()
437
+ }
438
+
439
+ initialize()
440
+
441
+ // ---- the template: its nodes, and how each changing spot is kept up to date
442
+ const content = clone(`
443
+ <form>
444
+ <label>Format
445
+ <select>
446
+ <option value="qr">QR code</option>
447
+ <option value="code128">Code 128</option>
448
+ <option value="code39">Code 39</option>
449
+ <option value="ean13">EAN-13</option>
450
+ </select>
451
+ </label>
452
+ <label>Content
453
+ <textarea></textarea>
454
+ </label>
455
+ <!--if--><!--/if-->
456
+ <!--if--><!--/if-->
457
+ <button type="submit">Generate code</button>
458
+ </form>
459
+ <p role="status"><!--text--><!--if--><!--/if--></p>
460
+ <!--if--><!--/if-->
461
+ <div class="art" role="img"></div>
462
+ <svg xmlns="http://www.w3.org/2000/svg" role="img" shape-rendering="crispEdges">
463
+ <rect fill="#fff"></rect>
464
+ <path fill="#000"></path>
465
+ </svg>
466
+ <a href="#">Download SVG</a>
467
+ `);
468
+ const form = content.children[0];
469
+ form.addEventListener("submit", (event) => { event.preventDefault(); generate() });
470
+ const select = form.children[0].children[0];
471
+ select.addEventListener("change", setFormat);
472
+ const textarea = form.children[1].children[0];
473
+ textarea.addEventListener("input", setValue);
474
+ const loadingText = new Text();
475
+ content.children[1].childNodes[0].replaceWith(loadingText);
476
+ const art2 = content.children[2];
477
+ art.value = art2;
478
+ const svg2 = content.children[3];
479
+ const rect = svg2.children[0];
480
+ const path2 = svg2.children[1];
481
+ const a = content.children[4];
482
+ a.addEventListener("click", download);
483
+ this.#updates = [
484
+ bind(() => element.format, (value) => $setValue(select, value)),
485
+ bind(() => element.value, (value) => $setValue(textarea, value)),
486
+ // <zb-if test={(format === "qr") && (controls !== "basic")}>
487
+ when(form.childNodes[5], form.childNodes[6], () => (element.format === "qr") && (element.controls !== "basic"), [() => {
488
+ const branch = clone(`<div class="row">
489
+ <label>Style
490
+ <select>
491
+ <option value="">Plain</option>
492
+ <!--each--><!--/each-->
493
+ </select>
494
+ </label>
495
+ <label>Logo
496
+ <input type="file" accept="image/svg+xml,image/png,image/jpeg,image/webp">
497
+ </label>
498
+ </div>`);
499
+ const select2 = branch.children[0].children[0].children[0];
500
+ select2.addEventListener("change", setPreset);
501
+ const input = branch.children[0].children[1].children[0];
502
+ input.addEventListener("change", uploadLogo);
503
+ const updates2 = [
504
+ bind(() => chosenPreset.value, (value) => $setValue(select2, value)),
505
+ // <zb-each items={presetNames} as="name" key={name}>
506
+ list(select2.childNodes[3], select2.childNodes[4], () => presetNames, (name, index) => name, (name, index) => {
507
+ const row = clone(`
508
+ <option></option>
509
+ `);
510
+ const option = row.children[0];
511
+ const updates = [
512
+ bind(() => name, (value) => $setValue(option, value)),
513
+ bind(() => name ?? "", (value) => (option.textContent = value)),
514
+ ];
515
+ return { nodes: row, update(next, at) { name = next; index = at; for (const update of updates) update(); } };
516
+ }),
517
+ ];
518
+ return { nodes: branch, update() { for (const update of updates2) update(); } };
519
+ }, null]),
520
+ // <zb-if test={uploadedLogo}>
521
+ when(form.childNodes[8], form.childNodes[9], () => uploadedLogo.value, [() => {
522
+ const branch2 = clone(`<button type="button" class="text-button">Remove uploaded logo</button>`);
523
+ const textButton = branch2.children[0];
524
+ textButton.addEventListener("click", clearLogo);
525
+ return { nodes: branch2, update() { } };
526
+ }, null]),
527
+ bind(() => (loading.value ? "Loading the Symbology engine…" : (error.value || (styled.value ? "" : "Ready"))) ?? "", (value) => (loadingText.data = value)),
528
+ // <zb-if test={verdict}>
529
+ when(content.children[1].childNodes[1], content.children[1].childNodes[2], () => verdict.value, [() => {
530
+ const branch3 = clone(`<span class="verdict"></span>`);
531
+ const verdict2 = branch3.children[0];
532
+ const updates3 = [
533
+ bind(() => verdict.value ?? "", (value) => (verdict2.textContent = value)),
534
+ ];
535
+ return { nodes: branch3, update() { for (const update of updates3) update(); } };
536
+ }, null]),
537
+ // <zb-if test={notes}>
538
+ when(content.childNodes[5], content.childNodes[6], () => notes.value, [() => {
539
+ const branch4 = clone(`<p class="notes"></p>`);
540
+ const notes2 = branch4.children[0];
541
+ const updates4 = [
542
+ bind(() => notes.value ?? "", (value) => (notes2.textContent = value)),
543
+ ];
544
+ return { nodes: branch4, update() { for (const update of updates4) update(); } };
545
+ }, null]),
546
+ bind(() => `QR code for ${element.value}`, (value) => attribute(art2, "aria-label", value)),
547
+ bind(() => !(styled.value) || !(svgMarkup.value), (value) => art2.toggleAttribute("hidden", Boolean(value))),
548
+ bind(() => viewBox.value, (value) => attribute(svg2, "viewBox", value)),
549
+ bind(() => `Generated ${element.format} code`, (value) => attribute(svg2, "aria-label", value)),
550
+ bind(() => !(path.value), (value) => svg2.toggleAttribute("hidden", Boolean(value))),
551
+ bind(() => svgWidth.value, (value) => attribute(rect, "width", value)),
552
+ bind(() => svgHeight.value, (value) => attribute(rect, "height", value)),
553
+ bind(() => path.value, (value) => attribute(path2, "d", value)),
554
+ bind(() => !(svgMarkup.value), (value) => a.toggleAttribute("hidden", Boolean(value))),
555
+ ];
556
+ return content;
557
+ }
558
+
559
+ // ---- updates: changes are batched, and applied together in a microtask
560
+
561
+ #requestUpdate() {
562
+ this.#pending ??= Promise.resolve().then(() => this.#update());
563
+ }
564
+
565
+ #update() {
566
+ this.#pending = null;
567
+ // Off the page, nothing updates; it catches up when it's back (connectedCallback).
568
+ if (!this.#started || !this.isConnected) return;
569
+ for (const update of this.#updates) update();
570
+ }
571
+
572
+ /** Resolves once pending changes are on the page. */
573
+ get updateComplete() {
574
+ return this.#pending ?? Promise.resolve();
575
+ }
576
+
577
+ /** Fires one of the element's events: it bubbles; a before… event can be cancelled. */
578
+ #fire(name, detail) {
579
+ return this.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, cancelable: name.startsWith("before") }));
580
+ }
581
+ }
582
+
583
+ // ---- helpers
584
+
585
+ /** Keeps one spot in the DOM up to date: `write` runs when `read` gives a value it hasn't had. */
586
+ function bind(read, write) {
587
+ let last = bind; // nothing written yet
588
+ return () => {
589
+ const value = read();
590
+ if (Object.is(value, last)) return;
591
+ const previous = last === bind ? undefined : last;
592
+ write((last = value), previous);
593
+ };
594
+ }
595
+
596
+ /** An attribute from a value: null, undefined and false remove it. */
597
+ function attribute(node, name, value) {
598
+ if (value == null || value === false) {
599
+ node.removeAttribute(name);
600
+ } else if (typeof value === "object") {
601
+ console.error(`zubra: cannot write an object to the "${name}" attribute`, value);
602
+ node.removeAttribute(name);
603
+ } else {
604
+ node.setAttribute(name, value);
605
+ }
606
+ }
607
+
608
+ /**
609
+ * A form field's value: the property (what's shown and submitted), not the attribute (which is
610
+ * only its starting value).
611
+ */
612
+ function $setValue(node, value) {
613
+ const text = String(value ?? "");
614
+ if (node.value !== text) node.value = text;
615
+ // A <select>'s options may come from a list inside it that renders after this: again once they're there.
616
+ if (node.localName === "select" && node.value !== text) queueMicrotask(() => { if (node.value !== text) node.value = text; });
617
+ }
618
+
619
+ /** Puts a node in place (the platform's insertBefore, not one an element overrides for its slots). */
620
+ function insert(parent, node, before) {
621
+ return Node.prototype.insertBefore.call(parent, node, before);
622
+ }
623
+
624
+ /** Moves a node already on the page, keeping its focus and state where the browser can (moveBefore). */
625
+ function move(parent, node, before) {
626
+ try {
627
+ if (Element.prototype.moveBefore && node.isConnected && parent.isConnected) return parent.moveBefore(node, before);
628
+ } catch {
629
+ // not movable in one step: insert it
630
+ }
631
+ return insert(parent, node, before);
632
+ }
633
+
634
+ /**
635
+ * <zb-each>: a row per item, between two markers. Rows are matched by key, so a row that stays
636
+ * keeps its nodes (and its focus), and moves only when it's out of order. `create(item, index)`
637
+ * makes a row: its nodes, and how to bring them up to date. With `animate`, `leave` and `glide`
638
+ * come too: removed rows leave, and the rows that stay glide to their new places.
639
+ */
640
+ function list(start, end, read, key, create, leave, glide) {
641
+ let rows = new Map();
642
+ const nodesOf = (row) => {
643
+ const nodes = [];
644
+ for (let node = row.first; node; node = node.nextSibling) {
645
+ nodes.push(node);
646
+ if (node === row.last) break;
647
+ }
648
+ return nodes;
649
+ };
650
+ // The indexes of a longest increasing run of `sequence` (negative entries never count): the rows
651
+ // already in order, which needn't move.
652
+ const inOrder = (sequence) => {
653
+ const tails = [];
654
+ const previous = [];
655
+ sequence.forEach((value, index) => {
656
+ if (value < 0) return;
657
+ let low = 0;
658
+ let high = tails.length;
659
+ while (low < high) {
660
+ const middle = (low + high) >> 1;
661
+ if (sequence[tails[middle]] < value) low = middle + 1;
662
+ else high = middle;
663
+ }
664
+ previous[index] = low > 0 ? tails[low - 1] : -1;
665
+ tails[low] = index;
666
+ });
667
+ const kept = new Set();
668
+ for (let index = tails.length ? tails[tails.length - 1] : -1; index >= 0; index = previous[index]) kept.add(index);
669
+ return kept;
670
+ };
671
+ const update = () => {
672
+ const parent = start.parentNode;
673
+ const items = [...(read() ?? [])];
674
+ const ids = items.map((item, index) => key(item, index));
675
+ const seen = new Set();
676
+ ids.forEach((id, index) => {
677
+ if (seen.has(id)) {
678
+ console.error("zubra: duplicate zb-each key", id, `(row ${index + 1}); that row is not keyed`);
679
+ ids[index] = Symbol("duplicate");
680
+ }
681
+ seen.add(ids[index]);
682
+ });
683
+ for (const [id, row] of rows) {
684
+ if (seen.has(id)) continue;
685
+ if (leave) leave(nodesOf(row), true);
686
+ else for (const node of nodesOf(row)) node.remove();
687
+ }
688
+ const was = new Map([...rows.values()].map((row, index) => [row, index]));
689
+ const next = new Map();
690
+ const order = items.map((item, index) => {
691
+ const id = ids[index];
692
+ let row = rows.get(id);
693
+ if (!row) {
694
+ const { nodes, update } = create(item, index);
695
+ // A row is everything from its first node to its last, with what a list inside it adds later.
696
+ row = { first: nodes.firstChild, last: nodes.lastChild, update, nodes };
697
+ update(item, index); // filled in before it's on the page
698
+ }
699
+ next.set(id, row);
700
+ row.update(item, index);
701
+ return row;
702
+ });
703
+ // The longest run of rows still in their old order stays put; every other row goes before the
704
+ // row after it, from the end. A swap moves two rows, not the rows between them.
705
+ const stay = inOrder(order.map((row) => was.get(row) ?? -1));
706
+ let before = end;
707
+ for (let index = order.length - 1; index >= 0; index--) {
708
+ const row = order[index];
709
+ if (row.nodes) {
710
+ insert(parent, row.nodes, before); // a new row, from its fragment
711
+ delete row.nodes;
712
+ } else if (!stay.has(index)) {
713
+ for (const node of nodesOf(row)) move(parent, node, before);
714
+ }
715
+ before = row.first;
716
+ }
717
+ rows = next;
718
+ };
719
+ if (!glide) return update;
720
+ const elements = () => [...rows.values()].flatMap((row) => nodesOf(row).filter((node) => node.nodeType === 1));
721
+ return () => glide(elements(), update);
722
+ }
723
+
724
+ /**
725
+ * <zb-if>: the branch whose condition holds, between two markers, rebuilt only when that changes.
726
+ * With `animate`, `leave` comes too: the branch going away leaves, beside the one replacing it.
727
+ */
728
+ function when(start, end, read, branches, leaving, leave) {
729
+ let shown = -1;
730
+ let update = null;
731
+ return () => {
732
+ const index = read() ? 0 : 1;
733
+ if (index !== shown) {
734
+ shown = index;
735
+ leaving?.(start, end); // slotted content inside goes back to wait, not away
736
+ if (leave && start.nextSibling !== end) {
737
+ const nodes = [];
738
+ for (let node = start.nextSibling; node !== end; node = node.nextSibling) nodes.push(node);
739
+ nodes[nodes.length - 1].after(start); // the region starts after them now
740
+ leave(nodes);
741
+ }
742
+ while (start.nextSibling !== end) start.nextSibling.remove();
743
+ update = null;
744
+ if (branches[index]) {
745
+ const branch = branches[index]();
746
+ branch.update(); // filled in before it's on the page
747
+ insert(end.parentNode, branch.nodes, end);
748
+ update = branch.update;
749
+ }
750
+ }
751
+ update?.();
752
+ };
753
+ }
754
+
755
+ /** Markup, parsed once into a <template>; each call returns a fresh copy of its nodes. */
756
+ const templates = new Map();
757
+ function clone(markup) {
758
+ let template = templates.get(markup);
759
+ if (!template) {
760
+ template = document.createElement("template");
761
+ template.innerHTML = markup;
762
+ templates.set(markup, template);
763
+ }
764
+ return template.content.cloneNode(true);
765
+ }
766
+
767
+ /** An attribute that holds JSON (how arrays and objects are written as attributes), or `fallback`. */
768
+ function fromJson(raw, fallback) {
769
+ try {
770
+ return JSON.parse(raw);
771
+ } catch {
772
+ return fallback;
773
+ }
774
+ }
775
+
776
+ // While a computed() or an effect runs: what it reads. Each entry reads the same value again, so
777
+ // it can tell later whether anything it depends on has changed.
778
+ let reads = null;
779
+
780
+ /**
781
+ * State: a value that updates the element when it's set, or (an array or plain object) changed
782
+ * in place: push, splice and nested writes count. `.value` reads and sets it; so do `.get()` and
783
+ * `.set()`.
784
+ */
785
+ function createState(initial, changed) {
786
+ let version = 0;
787
+ const proxies = new WeakMap(); // this state's own, so the same object in two states tells each
788
+ const bump = () => {
789
+ version++;
790
+ changed();
791
+ };
792
+ const deep = (value) => {
793
+ if (!value || typeof value !== "object" || !(Array.isArray(value) || Object.getPrototypeOf(value) === Object.prototype)) return value;
794
+ let proxy = proxies.get(value);
795
+ if (!proxy) {
796
+ proxy = new Proxy(value, {
797
+ get: (target, key, receiver) => deep(Reflect.get(target, key, receiver)),
798
+ set: (target, key, next, receiver) => {
799
+ const same = Object.is(target[key], next);
800
+ const done = Reflect.set(target, key, next, receiver);
801
+ if (!same) bump();
802
+ return done;
803
+ },
804
+ deleteProperty: (target, key) => {
805
+ const done = Reflect.deleteProperty(target, key);
806
+ bump();
807
+ return done;
808
+ },
809
+ });
810
+ proxies.set(value, proxy);
811
+ }
812
+ return proxy;
813
+ };
814
+ let value = deep(initial);
815
+ const read = () => version;
816
+ return {
817
+ get value() {
818
+ reads?.push(read);
819
+ return value;
820
+ },
821
+ set value(next) {
822
+ if (Object.is(next, value)) return;
823
+ value = deep(next);
824
+ bump();
825
+ },
826
+ get() {
827
+ return this.value;
828
+ },
829
+ set(next) {
830
+ this.value = next;
831
+ },
832
+ };
833
+ }
834
+
835
+ // Register the element (a server import, with no customElements, defines nothing).
836
+ if (globalThis.customElements && !customElements.get(tag)) customElements.define(tag, SymbologyCode);
837
+ export default SymbologyCode;