-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcreate.html
More file actions
1014 lines (930 loc) · 35.5 KB
/
Copy pathcreate.html
File metadata and controls
1014 lines (930 loc) · 35.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sythos Barcode Suite — Create</title>
<!--
Sythos Barcode Suite — example
Copyright (c) 2026 Sythos
SPDX-FileCopyrightText: 2026 Sythos (https://www.sythos.net)
SPDX-License-Identifier: MIT
Loads the IIFE bundle with a plain <script> tag, so this page works when
opened straight from disk (file://). No server, no build step, no modules.
-->
<style>
:root {
--bg: #10131a;
--panel: #181c26;
--line: #262c3a;
--ink: #e6e9f0;
--muted: #8b93a7;
--accent: #5ac8fa;
--danger: #ff6b6b;
color-scheme: dark;
}
@media (prefers-color-scheme: light) {
:root {
--bg: #f5f6f8; --panel: #ffffff; --line: #dfe3ea;
--ink: #171a21; --muted: #666e80; --accent: #0a84c4;
color-scheme: light;
}
}
* { box-sizing: border-box; }
body {
margin: 0; padding: 24px;
font: 15px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
background: var(--bg); color: var(--ink);
}
header { max-width: 1100px; margin: 0 auto 20px; }
h1 { font-size: 20px; margin: 0 0 4px; letter-spacing: -0.01em; }
.sub { color: var(--muted); font-size: 13px; }
.sub a { color: var(--accent); }
.layout {
max-width: 1100px; margin: 0 auto;
display: grid; grid-template-columns: 340px 1fr; gap: 20px;
align-items: start;
}
@media (max-width: 800px) { .layout { grid-template-columns: 1fr; } }
.panel {
background: var(--panel); border: 1px solid var(--line);
border-radius: 12px; padding: 18px;
}
label { display: block; font-size: 12px; color: var(--muted); margin: 14px 0 5px;
text-transform: uppercase; letter-spacing: 0.05em; }
label:first-child { margin-top: 0; }
input, select, textarea {
width: 100%; padding: 9px 11px; font: inherit; font-size: 14px;
background: var(--bg); color: var(--ink);
border: 1px solid var(--line); border-radius: 8px;
}
input[type=color] { padding: 3px; height: 38px; }
input[type=checkbox] { width: auto; height: 18px; padding: 0; margin: 4px 0 0;
accent-color: var(--accent); }
textarea { resize: vertical; min-height: 74px; font-family: ui-monospace, monospace; font-size: 13px; }
.row { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
.btns { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 18px; }
button {
flex: 1; min-width: 108px; padding: 10px 14px; font: inherit; font-weight: 600;
font-size: 13px; cursor: pointer; border-radius: 8px;
border: 1px solid var(--line); background: var(--bg); color: var(--ink);
}
button.primary { background: var(--accent); border-color: var(--accent); color: #051019; }
button:hover { filter: brightness(1.12); }
#stage {
min-height: 300px; display: flex; align-items: center; justify-content: center;
position: relative; padding: 24px; background: #fff; border-radius: 8px; overflow: auto;
}
#stage canvas { max-width: 100%; height: auto; image-rendering: pixelated; }
#stage .frame-art-preview {
position: absolute; z-index: 2; display: none; pointer-events: none;
object-fit: cover; object-position: center; transform-origin: center;
}
.meta {
margin-top: 14px; font-family: ui-monospace, monospace; font-size: 12px;
color: var(--muted); display: flex; gap: 16px; flex-wrap: wrap;
}
.meta b { color: var(--ink); font-weight: 600; }
.error {
margin-top: 14px; padding: 10px 12px; border-radius: 8px; font-size: 13px;
background: rgba(255,107,107,0.12); border: 1px solid var(--danger); color: var(--danger);
}
.hint { font-size: 12px; color: var(--muted); margin-top: 6px; }
/* Content-type builder. The generated fields live in #ctFields; the wrappers
below would otherwise trip `label:first-child` and lose their top margin. */
#plainWrap > label:first-child,
#ctWrap > label:first-child,
#ctFields > label:first-child,
#payloadWrap > label:first-child { margin-top: 14px; }
#ctFields > .row { margin-top: 14px; }
.payload {
font-family: ui-monospace, monospace; font-size: 12px; line-height: 1.45;
white-space: pre-wrap; word-break: break-all;
padding: 9px 11px; min-height: 38px; max-height: 168px; overflow: auto;
background: var(--bg); color: var(--ink);
border: 1px solid var(--line); border-radius: 8px;
}
.payload:empty::before { content: "(empty)"; color: var(--muted); }
</style>
</head>
<body>
<header>
<h1>Create a barcode</h1>
<p class="sub">
Sythos Barcode Suite — 100% original JavaScript, zero dependencies, MIT.
See also <a href="read.html">read.html</a>.
</p>
</header>
<div class="layout">
<div class="panel">
<label for="format">Format</label>
<select id="format"></select>
<p class="hint" id="formatHint"></p>
<div id="ctWrap">
<label for="ctype">Content type</label>
<select id="ctype"></select>
</div>
<div id="ctFields"></div>
<div id="plainWrap">
<label for="text">Content</label>
<textarea id="text">https://www.sythos.net/</textarea>
</div>
<div id="payloadWrap">
<label for="payloadOut">Encoded payload</label>
<div class="payload" id="payloadOut" tabindex="0"></div>
<p class="hint" id="payloadLen"></p>
</div>
<div id="qrOpts">
<div class="row">
<div>
<label for="ecc">Error correction</label>
<select id="ecc">
<option value="L">L — 7%</option>
<option value="M" selected>M — 15%</option>
<option value="Q">Q — 25%</option>
<option value="H">H — 30%</option>
</select>
</div>
<div>
<label for="version">Version</label>
<select id="version"><option value="">Auto</option></select>
</div>
</div>
</div>
<div id="frameOpts" style="display:none">
<p class="hint">FrameQR Code</p>
<label for="frameCanvasShape">Canvas shape</label>
<select id="frameCanvasShape">
<option value="square" selected>Square</option>
<option value="circle">Circle</option>
<option value="diamond">Diamond</option>
</select>
<label for="frameCanvasSize">Canvas size (QR modules)</label>
<input type="number" id="frameCanvasSize" value="5" min="1" step="2">
<label for="frameCanvasUrl">Remote canvas image</label>
<input type="url" id="frameCanvasUrl" value="https://www.sythos.net/favicon.ico">
<p class="hint" id="frameArtworkStatus">
Fallback: https://www.sythos.net/apple-touch-icon.png. The asset is never copied locally.
CORS is required to include remote artwork in PNG output.
</p>
</div>
<div class="row">
<div>
<label for="scale">Scale (px/module)</label>
<input type="number" id="scale" value="6" min="1" max="40">
</div>
<div>
<label for="margin">Quiet zone</label>
<input type="number" id="margin" value="4" min="0" max="20">
</div>
</div>
<div class="row">
<div>
<label for="dark">Dark</label>
<input type="color" id="dark" value="#000000">
</div>
<div>
<label for="light">Light</label>
<input type="color" id="light" value="#ffffff">
</div>
</div>
<div class="btns">
<button class="primary" id="download-png">Download PNG</button>
<button id="download-svg">Download SVG</button>
</div>
</div>
<div class="panel">
<div id="stage">
<canvas id="canvas"></canvas>
<img id="frameArtworkPreview" class="frame-art-preview" alt="" aria-hidden="true">
</div>
<div class="meta" id="meta"></div>
<div id="err"></div>
</div>
</div>
<script src="../bundle/sythos-barcode.js"></script>
<script>
(function () {
'use strict';
var B = window.SythosBarcode;
var el = function (id) { return document.getElementById(id); };
var formatSel = el('format');
var canvas = el('canvas');
var stage = el('stage');
var frameArtworkPreview = el('frameArtworkPreview');
var frameArtworkState = {
image: null,
url: '',
cors: false,
status: 'idle',
request: ''
};
// Sensible sample content per format, so switching format never lands the
// user on an "invalid payload" error they have to reverse-engineer.
var SAMPLES = {
qr: 'https://www.sythos.net/',
datamatrix: 'Data Matrix ECC 200',
aztec: 'Aztec Code — UTF-8 👋',
pdf417: 'PDF417 sample payload',
microqr: '12345',
rmqr: 'rMQR sample payload',
frameqr: 'https://www.sythos.net/',
ean13: '5901234123457',
ean8: '96385074',
upca: '036000291452',
upce: '01234565',
code128: 'ABC-123456',
gs1128: '0101234567890128',
code39: 'SYTHOS-39',
code93: 'SYTHOS93',
itf: '12345678',
itf14: '12345678901231',
codabar: 'A12345A',
code11: '123456',
msi: '1234567',
pharmacode: '1234'
};
/* ---8<--- payload builders --- (unit-tested from a scratch Node script that
extracts this exact block out of the file, so the tests never drift from
the shipped code). Everything between the sentinels must stay dependency
free: no DOM, no closures over outer state.
The escaping conventions genuinely differ and must not be shared:
- WIFI / MECARD backslash-escape \ ; , : "
- vCard / vEvent backslash-escape \ ; , and newline -> \n, but NOT ':'
(escaping the colon there would corrupt every "URL:https://..." value).
*/
function ctTrim(s) {
return String(s === null || s === undefined ? '' : s).replace(/^\s+|\s+$/g, '');
}
function ctStr(s) {
return String(s === null || s === undefined ? '' : s);
}
/** WIFI: / MECARD: value escaping — backslash before \ ; , : and " */
function escWifi(s) {
return ctStr(s).replace(/([\\;,:"])/g, '\\$1');
}
/** vCard 3.0 / iCalendar TEXT value escaping — \ ; , and newlines. No colon. */
function escVCardText(s) {
var out = ctStr(s);
out = out.replace(/\\/g, '\\\\');
out = out.replace(/;/g, '\\;');
out = out.replace(/,/g, '\\,');
out = out.replace(/\r\n|\r|\n/g, '\\n');
return out;
}
/** "2026-09-01T14:00" (or with seconds) -> "20260901T140000" */
function icalStamp(s) {
var raw = ctTrim(s);
if (!raw) return '';
var cleaned = raw.replace(/[^0-9T]/g, '');
var parts = cleaned.split('T');
var date = parts[0] || '';
var time = parts.length > 1 ? parts[1] : '';
if (!date) return '';
while (time.length < 6) { time += '0'; }
return date + 'T' + time.substring(0, 6);
}
function buildPlain(v) {
return ctStr(v.text);
}
function buildUrl(v) {
var u = ctTrim(v.url);
if (!u) return '';
// Scheme test, not a "://" test: mailto:, tel: and geo: have no slashes.
if (!/^[a-zA-Z][a-zA-Z0-9+.\-]*:/.test(u)) u = 'https://' + u;
return u;
}
function buildEmail(v) {
var to = ctTrim(v.to);
var subject = ctStr(v.subject);
var body = ctStr(v.body);
var params = [];
if (ctTrim(subject)) params.push('subject=' + encodeURIComponent(subject));
if (ctTrim(body)) params.push('body=' + encodeURIComponent(body));
// The address itself is not percent-encoded: "@" must survive.
return 'mailto:' + to + (params.length ? '?' + params.join('&') : '');
}
function buildPhone(v) {
return 'tel:' + ctTrim(v.number);
}
function buildSms(v) {
return 'SMSTO:' + ctTrim(v.number) + ':' + ctStr(v.message);
}
function buildWifi(v) {
var enc = ctTrim(v.encryption) || 'WPA';
var out = 'WIFI:T:' + enc + ';S:' + escWifi(v.ssid) + ';';
if (enc !== 'nopass') out += 'P:' + escWifi(v.password) + ';';
if (v.hidden === true || v.hidden === 'true') out += 'H:true;';
return out + ';';
}
function buildVCard(v) {
var first = ctTrim(v.first);
var last = ctTrim(v.last);
var lines = ['BEGIN:VCARD', 'VERSION:3.0'];
// The ";" in N: is structural — escape each component, then join.
lines.push('N:' + escVCardText(last) + ';' + escVCardText(first));
var fnParts = [];
if (first) fnParts.push(first);
if (last) fnParts.push(last);
lines.push('FN:' + escVCardText(fnParts.join(' ')));
if (ctTrim(v.org)) lines.push('ORG:' + escVCardText(ctTrim(v.org)));
if (ctTrim(v.title)) lines.push('TITLE:' + escVCardText(ctTrim(v.title)));
if (ctTrim(v.phone)) lines.push('TEL:' + escVCardText(ctTrim(v.phone)));
if (ctTrim(v.email)) lines.push('EMAIL:' + escVCardText(ctTrim(v.email)));
if (ctTrim(v.url)) lines.push('URL:' + escVCardText(ctTrim(v.url)));
// ADR is 7 structural components; a free-text address goes in "street".
if (ctTrim(v.address)) lines.push('ADR:;;' + escVCardText(ctTrim(v.address)) + ';;;;');
lines.push('END:VCARD');
return lines.join('\r\n');
}
function buildMecard(v) {
var segs = [];
if (ctTrim(v.name)) segs.push('N:' + escWifi(ctTrim(v.name)));
if (ctTrim(v.phone)) segs.push('TEL:' + escWifi(ctTrim(v.phone)));
if (ctTrim(v.email)) segs.push('EMAIL:' + escWifi(ctTrim(v.email)));
if (ctTrim(v.url)) segs.push('URL:' + escWifi(ctTrim(v.url)));
var out = 'MECARD:';
for (var i = 0; i < segs.length; i++) { out += segs[i] + ';'; }
return out + ';';
}
function buildGeo(v) {
var lat = ctTrim(v.lat);
var lon = ctTrim(v.lon);
var alt = ctTrim(v.alt);
var out = 'geo:' + lat + ',' + lon;
if (alt) out += ',' + alt;
return out;
}
function buildEvent(v) {
var lines = ['BEGIN:VEVENT'];
if (ctTrim(v.summary)) lines.push('SUMMARY:' + escVCardText(ctTrim(v.summary)));
if (ctTrim(v.location)) lines.push('LOCATION:' + escVCardText(ctTrim(v.location)));
var dtStart = icalStamp(v.start);
var dtEnd = icalStamp(v.end);
if (dtStart) lines.push('DTSTART:' + dtStart);
if (dtEnd) lines.push('DTEND:' + dtEnd);
lines.push('END:VEVENT');
return lines.join('\r\n');
}
var PAYLOAD_BUILDERS = {
text: buildPlain,
url: buildUrl,
email: buildEmail,
phone: buildPhone,
sms: buildSms,
wifi: buildWifi,
vcard: buildVCard,
mecard: buildMecard,
geo: buildGeo,
event: buildEvent
};
/* ---8<--- end payload builders --- */
// Data-driven field definitions. `kind` maps straight onto the control that
// gets created; `half` pairs a field with the next one in a .row grid.
// Every default is a literal (never derived from `new Date()`) so the page
// and its unit tests agree, and so no type ever opens in an error state.
var CONTENT_TYPES = [
{
type: 'text', label: 'Plain text',
fields: [
{ id: 'text', label: 'Text', kind: 'textarea', value: 'https://www.sythos.net/' }
]
},
{
type: 'url', label: 'URL',
fields: [
{ id: 'url', label: 'URL', kind: 'url', value: 'https://www.sythos.net/',
placeholder: 'example.com (https:// added if missing)' }
]
},
{
type: 'email', label: 'Email',
fields: [
{ id: 'to', label: 'To', kind: 'email', value: 'hello@example.com' },
{ id: 'subject', label: 'Subject', kind: 'text', value: 'Hello from a QR code' },
{ id: 'body', label: 'Body', kind: 'textarea', value: 'Scanned your code — let’s talk.' }
]
},
{
type: 'phone', label: 'Phone',
fields: [
{ id: 'number', label: 'Phone number', kind: 'tel', value: '+390212345678' }
]
},
{
type: 'sms', label: 'SMS',
fields: [
{ id: 'number', label: 'Phone number', kind: 'tel', value: '+390212345678' },
{ id: 'message', label: 'Message', kind: 'textarea', value: 'Hello!' }
]
},
{
type: 'wifi', label: 'Wi-Fi network',
fields: [
{ id: 'ssid', label: 'Network name (SSID)', kind: 'text', value: 'Sythos-Guest' },
{ id: 'password', label: 'Password', kind: 'text', value: 'correct horse' },
{ id: 'encryption', label: 'Encryption', kind: 'select', value: 'WPA', options: [
{ value: 'WPA', label: 'WPA / WPA2 / WPA3' },
{ value: 'WEP', label: 'WEP' },
{ value: 'nopass', label: 'None (open)' }
] },
{ id: 'hidden', label: 'Hidden network', kind: 'checkbox', value: false }
]
},
{
type: 'vcard', label: 'Contact (vCard)',
fields: [
{ id: 'first', label: 'First name', kind: 'text', value: 'Ada', half: true },
{ id: 'last', label: 'Last name', kind: 'text', value: 'Lovelace', half: true },
{ id: 'org', label: 'Organisation', kind: 'text', value: 'Analytical Engines' },
{ id: 'title', label: 'Title', kind: 'text', value: 'Mathematician' },
{ id: 'phone', label: 'Phone', kind: 'tel', value: '+390212345678' },
{ id: 'email', label: 'Email', kind: 'email', value: 'ada@example.com' },
{ id: 'url', label: 'Website', kind: 'url', value: 'https://example.com' },
{ id: 'address', label: 'Address', kind: 'text', value: '12 Baker Street, London' }
]
},
{
type: 'mecard', label: 'Contact (MeCard)',
fields: [
{ id: 'name', label: 'Name', kind: 'text', value: 'Lovelace,Ada' },
{ id: 'phone', label: 'Phone', kind: 'tel', value: '+390212345678' },
{ id: 'email', label: 'Email', kind: 'email', value: 'ada@example.com' },
{ id: 'url', label: 'Website', kind: 'url', value: 'https://example.com' }
]
},
{
type: 'geo', label: 'Geo location',
fields: [
{ id: 'lat', label: 'Latitude', kind: 'number', step: 'any', value: '45.4642', half: true },
{ id: 'lon', label: 'Longitude', kind: 'number', step: 'any', value: '9.1900', half: true },
{ id: 'alt', label: 'Altitude (m, optional)', kind: 'number', step: 'any', value: '' }
]
},
{
type: 'event', label: 'Calendar event',
fields: [
{ id: 'summary', label: 'Summary', kind: 'text', value: 'Sythos Barcode Suite 1.0' },
{ id: 'location', label: 'Location', kind: 'text', value: 'Milano, Italy' },
{ id: 'start', label: 'Start', kind: 'datetime-local', value: '2026-09-01T14:00', half: true },
{ id: 'end', label: 'End', kind: 'datetime-local', value: '2026-09-01T15:30', half: true }
]
}
];
var ctypeSel = el('ctype');
var ctFieldsEl = el('ctFields');
var ctType = CONTENT_TYPES[0].type;
// One value bag per content type, seeded from the defaults, so switching
// away and back inside a session never loses what was typed.
var ctValues = {};
CONTENT_TYPES.forEach(function (def) {
var bag = {};
def.fields.forEach(function (f) {
bag[f.id] = (f.kind === 'checkbox')
? (f.value === true)
: (f.value === null || f.value === undefined ? '' : String(f.value));
});
ctValues[def.type] = bag;
var o = document.createElement('option');
o.value = def.type;
o.textContent = def.label;
ctypeSel.appendChild(o);
});
ctypeSel.value = ctType;
function ctDef(typeId) {
var found = CONTENT_TYPES.filter(function (d) { return d.type === typeId; });
return found.length ? found[0] : CONTENT_TYPES[0];
}
function ctFieldId(typeId, fieldId) {
// Prefixed so generated ids can never collide with the page's own
// (#text, #scale, #margin, #version, …).
return 'ct-' + typeId + '-' + fieldId;
}
function ctLabel(typeId, f) {
var lab = document.createElement('label');
lab.setAttribute('for', ctFieldId(typeId, f.id));
lab.textContent = f.label;
return lab;
}
function ctControl(typeId, f, bag) {
var input;
if (f.kind === 'textarea') {
input = document.createElement('textarea');
input.rows = f.rows || 3;
} else if (f.kind === 'select') {
input = document.createElement('select');
(f.options || []).forEach(function (opt) {
var o = document.createElement('option');
o.value = opt.value;
o.textContent = opt.label;
input.appendChild(o);
});
} else {
input = document.createElement('input');
// Unknown types (datetime-local on ancient engines) degrade to text.
try { input.type = f.kind; } catch (e) { input.type = 'text'; }
if (f.step) input.setAttribute('step', f.step);
}
input.id = ctFieldId(typeId, f.id);
if (f.placeholder) input.setAttribute('placeholder', f.placeholder);
if (f.kind === 'checkbox') {
input.checked = bag[f.id] === true;
} else {
input.value = bag[f.id] === null || bag[f.id] === undefined ? '' : String(bag[f.id]);
}
return input;
}
function ctCell(typeId, f, bag) {
var cell = document.createElement('div');
cell.appendChild(ctLabel(typeId, f));
cell.appendChild(ctControl(typeId, f, bag));
return cell;
}
function ctRender() {
var def = ctDef(ctType);
var bag = ctValues[def.type];
while (ctFieldsEl.firstChild) ctFieldsEl.removeChild(ctFieldsEl.firstChild);
var fields = def.fields;
var i = 0;
while (i < fields.length) {
var f = fields[i];
var next = (i + 1 < fields.length) ? fields[i + 1] : null;
if (f.half && next && next.half) {
var row = document.createElement('div');
row.className = 'row';
row.appendChild(ctCell(def.type, f, bag));
row.appendChild(ctCell(def.type, next, bag));
ctFieldsEl.appendChild(row);
i += 2;
} else {
ctFieldsEl.appendChild(ctLabel(def.type, f));
ctFieldsEl.appendChild(ctControl(def.type, f, bag));
i += 1;
}
}
}
function ctSync() {
var def = ctDef(ctType);
var bag = ctValues[def.type];
def.fields.forEach(function (f) {
var node = document.getElementById(ctFieldId(def.type, f.id));
if (!node) return;
bag[f.id] = (f.kind === 'checkbox') ? !!node.checked : node.value;
});
}
function currentPayload() {
var isQRLike = formatSel.value === 'qr' || formatSel.value === 'frameqr';
if (!isQRLike) return el('text').value;
if (ctType === 'text') return el('text').value;
var build = PAYLOAD_BUILDERS[ctType];
return build ? build(ctValues[ctType]) : '';
}
var formats = B.listFormats();
formats.forEach(function (f) {
var o = document.createElement('option');
o.value = f.id;
o.textContent = f.label + (f.canWrite ? '' : ' (unavailable)');
o.disabled = !f.canWrite;
formatSel.appendChild(o);
});
formatSel.value = formats.some(function (f) { return f.id === 'qr' && f.canWrite; })
? 'qr' : 'ean13';
var versionSel = el('version');
for (var v = 1; v <= 40; v++) {
var o = document.createElement('option');
o.value = String(v);
o.textContent = 'Version ' + v + ' (' + (17 + 4 * v) + '×' + (17 + 4 * v) + ')';
versionSel.appendChild(o);
}
var lastMatrix = null;
function currentOptions() {
var options = {
format: formatSel.value,
ecc: el('ecc').value,
version: el('version').value ? Number(el('version').value) : undefined,
checkDigit: true
};
if (formatSel.value === 'frameqr') {
options.ecc = 'H';
options.canvas = {
shape: el('frameCanvasShape').value,
size: Math.max(1, Number(el('frameCanvasSize').value) || 5)
};
}
return options;
}
function frameArtworkOptions() {
var primary = String(el('frameCanvasUrl').value || '').trim();
return {
primary: primary || 'https://www.sythos.net/favicon.ico',
fallback: 'https://www.sythos.net/apple-touch-icon.png'
};
}
function frameArtworkStatus(text) {
el('frameArtworkStatus').textContent = text;
}
function loadFrameImage() {
if (formatSel.value !== 'frameqr') {
frameArtworkState.image = null;
frameArtworkState.status = 'idle';
frameArtworkPreview.style.display = 'none';
return;
}
var urls = frameArtworkOptions();
var request = urls.primary + '\n' + urls.fallback;
if (frameArtworkState.request === request && frameArtworkState.image) return;
frameArtworkState.request = request;
frameArtworkState.image = null;
frameArtworkState.url = '';
frameArtworkState.cors = false;
frameArtworkState.status = 'loading';
frameArtworkStatus('Loading remote artwork (CORS first; preview fallback if CORS is unavailable)…');
var candidates = [urls.primary, urls.fallback]
.filter(function (url, index, all) { return url && all.indexOf(url) === index; });
var candidateIndex = 0;
function attempt(url, cors) {
var image = new Image();
if (cors) image.crossOrigin = 'anonymous';
image.onload = function () {
if (request !== frameArtworkState.request) return;
frameArtworkState.image = image;
frameArtworkState.url = url;
frameArtworkState.cors = cors;
frameArtworkState.status = cors ? 'ready' : 'preview-only';
frameArtworkStatus(cors
? 'Remote artwork loaded with CORS and will be embedded in PNG output.'
: 'Remote artwork is preview-only because the server did not allow CORS; PNG/SVG downloads keep the QR modules.');
renderFrameArtwork();
};
image.onerror = function () {
if (request !== frameArtworkState.request) return;
if (cors) {
// A no-CORS retry still permits an in-page preview without tainting
// the QR canvas, while keeping export behaviour deterministic.
attempt(url, false);
return;
}
candidateIndex += 1;
if (candidateIndex < candidates.length) {
attempt(candidates[candidateIndex], true);
return;
}
frameArtworkState.status = 'missing';
frameArtworkStatus('Remote artwork could not be loaded; the QR canvas remains usable without a local asset.');
renderFrameArtwork();
};
image.src = url;
}
if (candidates.length) attempt(candidates[0], true);
else frameArtworkState.status = 'missing';
}
function renderOptions() {
return {
scale: Math.max(1, Number(el('scale').value) || 6),
margin: Math.max(0, Number(el('margin').value) || 0),
dark: el('dark').value,
light: el('light').value
};
}
function frameArtworkGeometry(matrix, options) {
var frame = matrix && matrix.frameqr && matrix.frameqr.canvas;
if (!frame) return null;
var scale = options.scale;
var margin = options.margin;
var rotated = frame.angle === 90 || frame.angle === 270;
var width = (rotated ? frame.height : frame.width) * scale;
var height = (rotated ? frame.width : frame.height) * scale;
return {
frame: frame,
centerX: (margin + frame.centerX + 0.5) * scale,
centerY: (margin + frame.centerY + 0.5) * scale,
width: width,
height: height,
angle: frame.angle || 0
};
}
function clipFrameShape(ctx, geometry) {
var frame = geometry.frame;
var halfWidth = geometry.width / 2;
var halfHeight = geometry.height / 2;
ctx.beginPath();
if (frame.shape === 'circle') {
ctx.ellipse(0, 0, halfWidth, halfHeight, 0, 0, Math.PI * 2);
} else if (frame.shape === 'diamond') {
ctx.moveTo(0, -halfHeight);
ctx.lineTo(halfWidth, 0);
ctx.lineTo(0, halfHeight);
ctx.lineTo(-halfWidth, 0);
ctx.closePath();
} else {
ctx.rect(-halfWidth, -halfHeight, geometry.width, geometry.height);
}
ctx.clip();
}
function imageIsCorsSafe(image) {
try {
var probe = document.createElement('canvas');
probe.width = 1;
probe.height = 1;
var ctx = probe.getContext('2d');
if (!ctx) return false;
ctx.drawImage(image, 0, 0, 1, 1);
ctx.getImageData(0, 0, 1, 1);
return true;
} catch (e) {
return false;
}
}
function positionFramePreview(geometry) {
var image = frameArtworkState.image;
if (!image || !geometry) {
frameArtworkPreview.style.display = 'none';
return;
}
var stageRect = stage.getBoundingClientRect();
var canvasRect = canvas.getBoundingClientRect();
var scaleX = canvas.width ? canvasRect.width / canvas.width : 1;
var scaleY = canvas.height ? canvasRect.height / canvas.height : 1;
var left = canvasRect.left - stageRect.left + (geometry.centerX - geometry.width / 2) * scaleX;
var top = canvasRect.top - stageRect.top + (geometry.centerY - geometry.height / 2) * scaleY;
frameArtworkPreview.src = image.src;
frameArtworkPreview.alt = 'Remote canvas artwork';
frameArtworkPreview.style.left = left + 'px';
frameArtworkPreview.style.top = top + 'px';
frameArtworkPreview.style.width = geometry.width * scaleX + 'px';
frameArtworkPreview.style.height = geometry.height * scaleY + 'px';
frameArtworkPreview.style.clipPath = geometry.frame.shape === 'circle'
? 'ellipse(50% 50% at 50% 50%)'
: geometry.frame.shape === 'diamond'
? 'polygon(50% 0, 100% 50%, 50% 100%, 0 50%)'
: 'inset(0)';
frameArtworkPreview.style.transform = 'rotate(' + geometry.angle + 'deg)';
frameArtworkPreview.style.display = 'block';
}
function renderFrameArtwork() {
var isFrameQR = formatSel.value === 'frameqr';
var geometry = frameArtworkGeometry(lastMatrix, renderOptions());
if (!isFrameQR || !geometry || !frameArtworkState.image) {
frameArtworkPreview.style.display = 'none';
return;
}
if (!frameArtworkState.cors || !imageIsCorsSafe(frameArtworkState.image)) {
frameArtworkState.cors = false;
if (frameArtworkState.status !== 'preview-only') {
frameArtworkState.status = 'preview-only';
frameArtworkStatus('Remote artwork is preview-only because the server did not allow CORS; PNG/SVG downloads keep the QR modules.');
}
positionFramePreview(geometry);
return;
}
frameArtworkPreview.style.display = 'none';
var ctx = canvas.getContext('2d');
if (!ctx) return;
var image = frameArtworkState.image;
var imageWidth = image.naturalWidth || image.width || geometry.width;
var imageHeight = image.naturalHeight || image.height || geometry.height;
var coverScale = Math.max(geometry.width / imageWidth, geometry.height / imageHeight);
ctx.save();
ctx.translate(geometry.centerX, geometry.centerY);
ctx.rotate((geometry.angle * Math.PI) / 180);
clipFrameShape(ctx, geometry);
ctx.drawImage(
image,
-imageWidth * coverScale / 2,
-imageHeight * coverScale / 2,
imageWidth * coverScale,
imageHeight * coverScale
);
ctx.restore();
}
// User-supplied strings never go through innerHTML.
function showError(msg) {
var box = el('err');
while (box.firstChild) box.removeChild(box.firstChild);
if (!msg) return;
var d = document.createElement('div');
d.className = 'error';
d.textContent = msg;
box.appendChild(d);
}
function update() {
var isQR = formatSel.value === 'qr' || formatSel.value === 'frameqr';
var isFrameQR = formatSel.value === 'frameqr';
el('qrOpts').style.display = isQR ? '' : 'none';
el('frameOpts').style.display = isFrameQR ? '' : 'none';
el('ctWrap').style.display = isQR ? '' : 'none';
ctFieldsEl.style.display = isQR ? '' : 'none';
el('payloadWrap').style.display = isQR ? '' : 'none';
el('plainWrap').style.display = isQR ? 'none' : '';
el('ecc').disabled = isFrameQR;
if (isFrameQR) el('ecc').value = 'H';
var info = formats.filter(function (f) { return f.id === formatSel.value; })[0];
el('formatHint').textContent = info
? (info.kind + ' · ' + (info.canRead ? 'this suite can also read it' : 'write-only in this build'))
: '';
var payload = currentPayload();
el('payloadOut').textContent = payload;
el('payloadLen').textContent = payload.length + ' character' + (payload.length === 1 ? '' : 's');
showError('');
try {
lastMatrix = B.encode(payload, currentOptions());
} catch (e) {
lastMatrix = null;
showError(String(e && e.message ? e.message : e));
el('meta').innerHTML = '';
frameArtworkPreview.style.display = 'none';
var ctx = canvas.getContext('2d');
canvas.width = 10; canvas.height = 10;
if (ctx) ctx.clearRect(0, 0, 10, 10);
return;
}
// Frame artwork is composited through a 2D context; do not commit the
// canvas to WebGL first because a canvas can own only one context type.
var renderOpts = renderOptions();
var out = isFrameQR
? { backend: B.toCanvas(lastMatrix, canvas, renderOpts) ? '2d' : 'none' }
: B.renderToCanvasAuto(lastMatrix, canvas, renderOpts);
if (isFrameQR) {
loadFrameImage();
renderFrameArtwork();
} else {
frameArtworkPreview.style.display = 'none';
}
el('meta').innerHTML =
'<span>modules <b>' + lastMatrix.width + '×' + lastMatrix.height + '</b></span>' +
'<span>pixels <b>' + canvas.width + '×' + canvas.height + '</b></span>' +
'<span>backend <b>' + out.backend + '</b></span>' +
'<span>bytes in <b>' + payload.length + '</b></span>';
}
function saveBlob(blob, name) {
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.download = name;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
setTimeout(function () { URL.revokeObjectURL(url); }, 1000);
}
el('download-svg').addEventListener('click', function () {
if (!lastMatrix) return;
var svg = B.toSVG(lastMatrix, renderOptions());
if (formatSel.value === 'frameqr' && frameArtworkState.image) {
frameArtworkStatus('SVG export contains the QR profile only; external artwork remains a remote preview and is not copied locally.');
}
saveBlob(new Blob([svg], { type: 'image/svg+xml' }), formatSel.value + '.svg');
});
el('download-png').addEventListener('click', function () {
if (!lastMatrix) return;
if (formatSel.value === 'frameqr' && frameArtworkState.cors) {
try {
canvas.toBlob(function (blob) {
if (blob) {
saveBlob(blob, formatSel.value + '.png');
return;
}
frameArtworkStatus('PNG export could not include remote artwork; exporting the QR profile without a local asset.');
B.toPNG(lastMatrix, renderOptions()).then(function (bytes) {
saveBlob(new Blob([bytes], { type: 'image/png' }), formatSel.value + '.png');
});
}, 'image/png');
return;
} catch (e) {
frameArtworkStatus('PNG export could not include remote artwork; exporting the QR profile without a local asset.');
}
}
B.toPNG(lastMatrix, renderOptions()).then(function (bytes) {
saveBlob(new Blob([bytes], { type: 'image/png' }), formatSel.value + '.png');
});
});
formatSel.addEventListener('change', function () {
if (SAMPLES[formatSel.value]) el('text').value = SAMPLES[formatSel.value];
update();
});
ctypeSel.addEventListener('change', function () {
ctSync(); // keep whatever was typed under the old type
ctType = ctypeSel.value;
ctRender();
update();
});
// Delegated: the generated controls are replaced wholesale on every type
// switch, so listeners live on the container instead. Both events bubble.
ctFieldsEl.addEventListener('input', function () { ctSync(); update(); });
ctFieldsEl.addEventListener('change', function () { ctSync(); update(); });
['text', 'ecc', 'version', 'scale', 'margin', 'dark', 'light'].forEach(function (id) {
el(id).addEventListener('input', update);
el(id).addEventListener('change', update);
});