-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1216 lines (1040 loc) · 38.8 KB
/
index.html
File metadata and controls
1216 lines (1040 loc) · 38.8 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" />
<title>QR Builder</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<button id="openSettingsBtn" class="btnsettings primary" title="QR Code Settings" >⚙️</button>
<header class="page-header">
<div class="title">QR Code Builder</div>
<div id="versionToggle" class="version">
Last Updated to v1.0.9 on 06/22/2025 Click for more information
</div>
<div class="spacer-small"></div>
<div class="tagline">Visually build your QR code—one block, one step at a time.</div>
<div class="spacer-small"></div>
</header>
<div class="layout">
<!-- ------------------ Left Sidebar ------------------ -->
<!-- Toolbox -->
<aside class="panel toolbox">
<div class="section">
<h3>Toolbox</h3>
<div class="toolbox-item text" draggable="true" data-type="text" title="Drag & drop to insert a "Text" block. Double-click to edit the text.">Text</div>
<div class="toolbox-item tab" draggable="true" data-type="tab" title="Drag & drop to insert a "Tab" block. Double-click to rename it.">⇥</div>
<div class="toolbox-item return" draggable="true" data-type="return" title="Drag & drop to insert a "Return" block. Double-click to rename it.">⏎</div>
</div>
<!-- Presets -->
<div class="section">
<h3>Build Area Presets</h3>
<select id="presetSelect" style="font-size: 14px;" title="Choose a saved preset."></select>
<button class="btn btn-primary" id="loadPresetBtn" title="Load the selected preset into the canvas.">Load</button>
<button class="btn btn-primary" id="savePresetBtn" title="Save the current build as a preset.">Save</button>
<button class="btn btn-danger" id="deletePresetBtn" title="Delete the selected preset.">Delete Preset</button>
<button class="btn btn-danger" id="clearBtn" title="Clear all blocks from the build area.">Clear Build Area</button>
</div>
<div class="section">
<h3>Other Tools From OffTheClockStudios</h3>
<button onclick="window.open('fuzzies.html', '_blank', 'noopener');" class="btn btn-primary">Fuzzies</button>
<button onclick="window.open('print.html', '_blank', 'noopener');" class="btn btn-primary">Print Pages</button>
<button onclick="window.open('print2.html', '_blank', 'noopener');" class="btn btn-primary">Print Cards</button>
</div>
</aside>
<!-- ------------------ Canvas Area / Build Area ------------------ -->
<div class="canvas">
<div class="canvas-header">Build Area</div>
<div class="canvas-info-group">
<div class="canvas-info">Drag blocks from the Toolbox</div>
<div class="canvas-info">and drop them into the zones below</div>
</div>
<div class="canvas-body" id="canvas"></div>
</div>
<!-- ------------------ Right Sidebar ------------------ -->
<aside class="panel right">
<!-- QR Preview -->
<div class="section">
<h3>Preview & Actions</h3>
<div class="qr-preview" id="qrPreview"></div>
<input id="qrLabelInput" type="text" title="Label for the QR code." placeholder="Optional QR label…" style="width: 85%; font-size: 14px; margin: 8px auto 0; display: block;" />
<!-- button groups -->
<div class="button-group" style="display:flex; gap:20px; justify-content:center; margin-top:8px;">
<button class="btn btn-blue" id="copyBtn" type="button" title="Copy the QR code to your clipboard.">Copy</button>
<button class="btn btn-debug" id="downloadBtn" type="button" title="Build & Download the QR code.">Download</button>
</div>
<div class="button-group" style="display:flex; gap:20px; justify-content:center; margin-top:8px;">
<button class="btn btn-primary" id="generateBtn" title="Build and display the QR code.">Build</button>
</div>
<button class="btn btn-debug" id="openBatchBtn">Batch Build (Testing)</button>
</div>
<!-- Footer (pinned to bottom) -->
<!-- Trash -->
<div class="right-footer">
<!-- Trash (scrollable) -->
<div class="garbage-content">
<div class="section">
<div class="garbage-drop" id="garbageDrop">Drop to Trash</div>
</div>
</aside>
<!-- the hidden changelog dialog -->
<dialog id="changelog" aria-labelledby="changelog-title">
<h2 id="changelog-title">What’s New in v1.0.9</h2>
<h3 id="changelog-recent">🆕 Recently Added:</h3>
<ul>
<li>Changelog popup so users can view recent updates</li>
<li>
Filename prompt when using the Download button to save QR codes
<ul>
<li>If a QR label is set, it will be used as the filename</li>
<li>If the QR label is blank, the filename defaults to the current preset name</li>
</ul>
</li>
<li>Print Pages & Print Cards HTML: Testing different endgame formats for the QR codes</li>
</ul>
<div class="spacer"></div>
<h3 id="changelog-qol">🔀 Quality of Life Improvements:</h3>
<ul>
<li>Fuzzies now opens in a new tab when clicked</li>
<li>Loading a preset will now automatically build the QR code</li>
<li>Presets are sorted A → Z, with defaults listed after your custom presets</li>
<li>The Download button now builds the QR code and prompts for a filename automatically</li>
</ul>
<!-- <div class="spacer"></div>
<h3 id="changelog-title">🗑️ Recently Removed:</h3>
<ul>
<li>...</li>
</ul>
<div class="spacer"></div>
<h3 id="changelog-title">🩹 Recently Fixed:</h3>
<ul>
<li>...</li>
</ul> -->
<div class="spacer"></div>
<button id="closeChangelog" type="button">Close</button>
</dialog>
<div id="jsonModal">
<h3>Paste Preset JSON</h3>
<textarea id="jsonInput" rows="18"></textarea>
<div class="json-modal-actions">
<button class="btn btn-primary" onclick="submitJSON()">Load</button>
<button class="btn btn-danger" onclick="closeJSONModal()">Cancel</button>
</div>
</div>
<!-- QR Settings Modal -->
<div id="settingsModal" style="display:none; position:fixed; top:15%; left:50%; transform:translateX(-50%); background:#fff; padding:20px; border:1px solid #ccc; border-radius:8px; z-index:10000; width:300px; box-shadow:0 4px 12px rgba(0,0,0,0.15);">
<h3>QR Code Settings</h3>
<!-- Links: inline and centered -->
<div style="text-align: center; margin-bottom: 12px;">
<a
href="https://github.com/OffTheClockStudios/QR-Code-Builder/tree/main"
target="_blank"
title="Visit the GitHub repository for QR Code Builder."
style="display: inline-block; margin: 0 8px; color: var(--color-tab-symbol); text-decoration: underline;"
>
Visit GitHub Page
</a>
<a
href="https://forms.office.com/r/BQ31NpaecJ"
target="_blank"
title="Submit feedback or preset requests."
style="display: inline-block; margin: 0 8px; color: var(--color-return-symbol); text-decoration: underline;"
>
Submit Feedback
</a>
</div>
<div style="margin-bottom:8px;">
<label for="widthInput">Width (px):</label>
<input id="widthInput" type="number" min="50" style="width:100%;" />
</div>
<div style="margin-bottom:8px;">
<label for="heightInput">Height (px):</label>
<input id="heightInput" type="number" min="50" style="width:100%;" />
</div>
<div style="margin-bottom:8px;">
<label for="versionSelect">Version (1–40):</label>
<input id="versionSelect" type="number" min="1" max="40" style="width:100%;" />
</div>
<div style="margin-bottom:8px;">
<label for="errorSelect">Error Level:</label>
<select id="errorSelect" style="width:100%;">
<option value="L">L (Lowest)</option>
<option value="M">M</option>
<option value="Q">Q</option>
<option value="H">H (Highest)</option>
</select>
</div>
<div style="margin-bottom:8px;">
<label for="darkColor">Dark Color:</label>
<input id="darkColor" type="color" style="width:100%;" />
</div>
<div style="margin-bottom:12px;">
<label for="lightColor">Light Color:</label>
<input id="lightColor" type="color" style="width:100%;" />
</div>
<div style="margin-bottom:8px;">
<label for="labelColorInput">Label Color:</label>
<input id="labelColorInput" type="color" style="width:100%;" />
</div>
<div class="checkbox-container" title="If enabled, the QR code image will be copied to clipboard after generation.">
<input type="checkbox" id="copyToggleInput">
<label for="copyToggleInput">Copy After Build</label>
</div>
<div class="spacer-small"></div>
<div class="checkbox-container" title="Enable advanced editing features like iterations.">
<input type="checkbox" id="advancedToggleInput"/>
<label for="advancedToggleInput">Advanced Mode</label>
</div>
<div class="spacer-small"></div>
<div class="spacer-small"></div>
<div style="text-align:right;">
<button class="btn btn-danger" id="resetSettingsBtn">Defaults</button>
<button class="btn btn-primary" id="saveSettingsBtn">Save</button>
</div>
</div>
<div id="settingsBackdrop" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.4); z-index:9999;"></div>
<!-- Batch QR Modal -->
<div id="batchModal" style="display:none; position:fixed; top:15%; left:50%; transform:translateX(-50%);
background:#fff; padding:20px; border:1px solid #ccc; border-radius:8px; z-index:10000;">
<h3>Batch Generate QR Codes</h3>
<p>Enter or paste QR contents with each line being one code. Blank lines are ignored.</p>
<label for="batchModeSelect">Mode:</label>
<select id="batchModeSelect" style="margin-bottom:8px; width:100%;">
<option value="standard">Standard (literal lines)</option>
<option value="escapes">Escape Sequences (\t, \n, \r)</option>
<option value="hexescapes">Hex Escapes (\xNN)</option>
<option value="unicode">Unicode Escapes (\uXXXX, \u{XXXXX})</option>
<option value="rawhex">Raw-Hex Mode (48656C6C6F → “Hello”)</option>
<option value="base64">Base64 Decode (SGVsbG8= → “Hello”)</option>
<!-- future modes here -->
</select>
<textarea id="batchInput" rows="10" style="width:100%; font-family:monospace;"></textarea>
<div style="margin-top:12px; text-align:right;">
<button class="btn btn-danger" id="closeBatchBtn">Cancel</button>
<button class="btn btn-primary" id="batchGenerateBtn">Build & Download</button>
</div>
</div>
<!-- Backdrop -->
<div id="batchBackdrop" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%;
background:rgba(0,0,0,0.4); z-index:9999;"></div>
</body>
<!-- link is for original testing js, made a copy to be independent and secure -->
<!-- <script src="qrcode.min.js"></script> -->
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script> -->
<script src="qrcode.min.js"></script>
<script>
//
const get = id => document.getElementById(id);
const show = id => get(id).style.display = 'block';
const hide = id => get(id).style.display = 'none';
function createEl(tag, {
className = '',
html = '',
text = '',
attrs = {},
on = {}
} = {}) {
const el = document.createElement(tag);
if (className) el.className = className;
if (html) el.innerHTML = html;
if (text) el.textContent = text;
for (const [k, v] of Object.entries(attrs)) el.setAttribute(k, v);
for (const [event, handler] of Object.entries(on)) el.addEventListener(event, handler);
return el;
}
// --- QR Settings Object & Defaults ---
const defaultQRSettings = {
width: 256,
height: 256,
typeNumber: 4,
correctLevel: QRCode.CorrectLevel.H,
colorDark: '#000000',
colorLight: '#ffffff',
labelColor: '#000000',
copyToggle: false,
advancedToggle: false
};
// --- Load persisted settings or use defaults ---
let qrSettings;
try {
const stored = localStorage.getItem('qrSettings');
qrSettings = stored ? JSON.parse(stored) : { ...defaultQRSettings };
} catch (e) {
console.warn('Failed to load QR settings from localStorage, using defaults', e);
qrSettings = { ...defaultQRSettings };
}
// --- DOM References ---
const openSettingsBtn = get('openSettingsBtn');
const settingsModal = get('settingsModal');
const settingsBackdrop = get('settingsBackdrop');
const widthInput = get('widthInput');
const heightInput = get('heightInput');
const versionSelect = get('versionSelect');
const errorSelect = get('errorSelect');
const darkColor = get('darkColor');
const lightColor = get('lightColor');
const labelColorInput = get('labelColorInput');
const copyToggleInput = get('copyToggleInput');
const advancedToggleInput = get('advancedToggleInput');
const saveSettingsBtn = get('saveSettingsBtn');
const resetSettingsBtn = get('resetSettingsBtn');
// --- Helpers to sync settings ↔ form ---
function applySettingsToForm(settings) {
widthInput.value = settings.width;
heightInput.value = settings.height;
versionSelect.value = settings.typeNumber;
errorSelect.value = Object.entries(QRCode.CorrectLevel)
.find(([k, v]) => v === settings.correctLevel)?.[0] || 'H';
darkColor.value = settings.colorDark;
lightColor.value = settings.colorLight;
labelColorInput.value = settings.labelColor;
copyToggleInput.checked = settings.copyToggle;
advancedToggleInput.checked = settings.advancedToggle;
}
function readSettingsFromForm() {
return {
width: parseInt(widthInput.value, 10),
height: parseInt(heightInput.value, 10),
typeNumber: Math.min(40, Math.max(1, parseInt(versionSelect.value, 10))),
correctLevel: QRCode.CorrectLevel[errorSelect.value],
colorDark: darkColor.value,
colorLight: lightColor.value,
labelColor: labelColorInput.value,
copyToggle: copyToggleInput.checked,
advancedToggle: advancedToggleInput.checked
};
}
// --- Open/Close Modal ---
openSettingsBtn.addEventListener('click', () => {
applySettingsToForm(qrSettings);
show('settingsModal');
show('settingsBackdrop');
});
settingsBackdrop.addEventListener('click', closeSettings);
function closeSettings() {
hide('settingsModal');
hide('settingsBackdrop');
}
// --- Save & Reset Handlers ---
saveSettingsBtn.addEventListener('click', () => {
qrSettings = readSettingsFromForm();
try {
localStorage.setItem('qrSettings', JSON.stringify(qrSettings));
} catch (e) {
console.warn('Failed to save QR settings to localStorage', e);
}
closeSettings();
});
resetSettingsBtn.addEventListener('click', () => {
qrSettings = { ...defaultQRSettings };
localStorage.setItem('qrSettings', JSON.stringify(qrSettings));
applySettingsToForm(qrSettings);
});
// DOM references for key interactive regions
const canvasEl = get('canvas');
const qrPreview = get('qrPreview');
const garbageDrop = get('garbageDrop');
const presetSelect = get('presetSelect');
/**
* BlockManager handles the current set of blocks displayed on the canvas.
* Provides methods to add, update, clear, and rebuild the canvas content.
*/
// === Constants ===
const DATA_INDEX = 'index';
const DATA_TYPE = 'text';
// === Helpers ===
// Display logic for a block's inner content
function getBlockDisplayHTML(data, isAdvanced) {
const typeSymbols = { tab: '⇥', return: '⏎' };
const symbol = typeSymbols[data.type] || '';
const label = data.label?.trim() || '';
const iter = (isAdvanced || data.iterations > 1)
? `<span class="iterations">×${data.iterations}</span>`
: '';
return symbol ? `${symbol} ${label} ${iter}` : `${label} ${iter}`;
}
// === BlockManager ===
const BlockManager = {
blocks: [],
add(type, label, pos = this.blocks.length) {
this.blocks.splice(pos, 0, { type, label, iterations: 1 });
this.rebuild();
},
update(idx, label, iterations) {
this.blocks[idx].label = label;
this.blocks[idx].iterations = iterations;
this.rebuild();
},
clear() {
this.blocks = [];
this.rebuild();
qrPreview.innerHTML = '';
},
rebuild(callback) {
canvasEl.innerHTML = '';
if (this.blocks.length === 0) {
canvasEl.append(Drag.createDropzone(0));
} else {
this.blocks.forEach((b, i) => {
canvasEl.append(Drag.createDropzone(i), Drag.createBlock(b, i));
});
canvasEl.append(Drag.createDropzone(this.blocks.length));
}
if (typeof callback === 'function') callback();
}
};
// === Drag ===
const Drag = {
createBlock(data, idx) {
const el = createEl('div', {
className: `block ${data.type}`,
html: getBlockDisplayHTML(data, qrSettings.advancedToggle),
attrs: { draggable: true }
});
el.ondragstart = e => {
e.dataTransfer.setData(DATA_INDEX, idx);
};
el.ondblclick = () => this.editBlock(idx, data);
return el;
},
createDropzone(pos) {
const dz = createEl('div', { className: 'dropzone' });
dz.ondragover = e => {
e.preventDefault();
dz.classList.add('drag-hover');
};
dz.ondragleave = () => {
dz.classList.remove('drag-hover');
};
dz.ondrop = e => {
e.preventDefault();
dz.classList.remove('drag-hover');
const fromRaw = e.dataTransfer.getData(DATA_INDEX);
const type = e.dataTransfer.getData(DATA_TYPE);
if (fromRaw !== '') {
const from = Number(fromRaw);
let to = pos;
if (from < to) to--;
const blk = BlockManager.blocks.splice(from, 1)[0];
BlockManager.blocks.splice(to, 0, blk);
} else if (type) {
const label =
type === 'text' ? prompt('Text:', '') || 'Text'
: type === 'tab' ? '\t'
: '\r';
BlockManager.add(type, label, pos);
}
BlockManager.rebuild();
};
return dz;
},
editBlock(idx, data) {
const isAdvanced = qrSettings.advancedToggle;
let { label, iterations = 1 } = data;
if (isAdvanced) {
const combined = prompt('Edit (label | iterations):', `${label} | ${iterations}`);
if (combined != null) {
const [newLabelRaw, iterRaw] = combined.split('|').map(s => s.trim());
const newLabel = newLabelRaw || label;
const newIterations = Math.max(1, parseInt(iterRaw)) || 1;
BlockManager.update(idx, newLabel, newIterations);
}
} else {
const newLabel = prompt('Edit label:', label);
if (newLabel != null) {
BlockManager.update(idx, newLabel, iterations);
}
}
}
};
// === Toolbox Drag Setup ===
document.querySelectorAll('.toolbox-item').forEach(it =>
it.addEventListener('dragstart', e =>
e.dataTransfer.setData(DATA_TYPE, it.dataset.type)
)
);
// === Trash Drop Setup ===
garbageDrop.ondragover = e => e.preventDefault();
garbageDrop.ondrop = e => {
e.preventDefault();
const idx = e.dataTransfer.getData(DATA_INDEX);
if (idx !== '') {
BlockManager.blocks.splice(idx, 1);
BlockManager.rebuild();
}
};
/**
* PresetsManager handles all logic related to managing default and user-defined presets.
* - Default presets are bundled into the app (read-only)
* - User presets are stored in localStorage under the key 'qrbuilder_presets'
* - The manager supports CRUD operations, import/export, and integration with the dropdown UI
*/
const PresetsManager = {
key: 'qrbuilder_presets',
// === Built-in (read-only) presets ===
defaultPresets: {
"ESSYM - Dept, Line, Shift": {
label: "ESSYM - Dept, Line, Shift",
blocks: [
{ type: "text", label: "052 - BSD", iterations: 1 },
{ type: "tab", label: "\t", iterations: 1 },
{ type: "return", label: "\r", iterations: 1 },
{ type: "text", label: "BSD", iterations: 1 },
{ type: "return", label: "\r", iterations: 1 },
{ type: "tab", label: "\t", iterations: 1 },
{ type: "return", label: "\r", iterations: 1 },
{ type: "text", label: "1st", iterations: 1 }
]
},
"ESSYM - Step #1": {
label: "",
blocks: [
{ type: "text", label: "Part Number", iterations: 1 },
{ type: "return", label: "\r", iterations: 1 }
]
},
"ESSYM - Step #2": {
label: "",
blocks: [
{ type: "return", label: "\r", iterations: 1 },
{ type: "text", label: "Defect Mode", iterations: 1 },
{ type: "return", label: "\r", iterations: 1 },
{ type: "text", label: "Defect Type", iterations: 1 },
{ type: "return", label: "\r", iterations: 2 },
{ type: "tab", label: "\t", iterations: 4 },
{ type: "text", label: "Comment", iterations: 1 }
]
},
"Preset Example": {
label: "",
blocks: [
{ type: "text", label: "Hello", iterations: 1 },
{ type: "return", label: "\r", iterations: 1 },
{ type: "text", label: "World", iterations: 1 }
]
}
},
// === Helpers ===
isDefault(name) {
return Object.hasOwn(this.defaultPresets, name);
},
isValidPreset(preset) {
return (
preset &&
typeof preset.label === 'string' &&
Array.isArray(preset.blocks) &&
preset.blocks.every(b =>
typeof b.type === 'string' &&
typeof b.label === 'string' &&
typeof b.iterations === 'number'
)
);
},
// === Storage ===
getUserPresets() {
return JSON.parse(localStorage.getItem(this.key) || '{}');
},
saveUserPresets(presets) {
localStorage.setItem(this.key, JSON.stringify(presets));
},
getAllPresets() {
return { ...this.defaultPresets, ...this.getUserPresets() };
},
// === UI Integration ===
refreshDropdown() {
const userPresets = this.getUserPresets();
const defaultPresets = this.defaultPresets;
const sortedUserNames = Object.keys(userPresets).sort((a, b) => a.localeCompare(b));
const sortedDefaultNames = Object.keys(defaultPresets).sort((a, b) => a.localeCompare(b));
presetSelect.innerHTML = '<option value="">Select a Preset</option>';
// Add user presets first
for (const name of sortedUserNames) {
const opt = createEl('option', {
text: name,
attrs: { value: name }
});
presetSelect.appendChild(opt);
}
// Optional: Visual separator between user and default presets
if (sortedUserNames.length && sortedDefaultNames.length) {
const divider = createEl('option', {
text: '—— Default Presets ——',
attrs: { disabled: true }
});
presetSelect.appendChild(divider);
}
// Add default presets next
for (const name of sortedDefaultNames) {
const opt = createEl('option', {
text: `⭐ ${name}`,
attrs: { value: name }
});
presetSelect.appendChild(opt);
}
},
exportPresetObject(name) {
const label = get('qrLabelInput')?.value.trim() || '';
return {
[name]: {
label,
blocks: JSON.parse(JSON.stringify(BlockManager.blocks))
}
};
},
saveCurrent() {
const name = prompt('Name this preset:');
if (!name) return;
if (this.isDefault(name)) {
alert('❌ Cannot overwrite a default preset. Use a new name.');
return;
}
const userPresets = this.getUserPresets();
userPresets[name] = this.exportPresetObject(name)[name];
this.saveUserPresets(userPresets);
this.refreshDropdown();
presetSelect.value = name;
},
deleteSelected() {
const name = presetSelect.value;
if (!name) return alert('Select a preset to delete.');
if (this.isDefault(name)) {
return alert('❌ Cannot delete a default preset.');
}
if (!confirm(`Delete user preset "${name}"?`)) return;
const presets = this.getUserPresets();
delete presets[name];
this.saveUserPresets(presets);
presetSelect.value = '';
this.refreshDropdown();
BlockManager.clear();
},
loadPreset(name, sourcePresets = null) {
const allPresets = sourcePresets || this.getAllPresets();
const preset = allPresets[name];
if (!this.isValidPreset(preset)) {
alert('❌ Invalid preset.');
return;
}
BlockManager.blocks = preset.blocks.map(b => ({
...b,
iterations: b.iterations || 1
}));
BlockManager.rebuild();
const labelInput = get('qrLabelInput');
if (labelInput) labelInput.value = preset.label || '';
// Auto-regenerate QR code
get('generateBtn').click();
},
copyToClipboardAsJSON(name) {
const allPresets = this.getAllPresets();
const preset = allPresets[name];
if (!this.isValidPreset(preset)) {
alert('❌ No valid preset found.');
return;
}
const json = {
[name]: {
label: preset.label || '',
blocks: preset.blocks.map(b => ({
type: b.type,
label: b.label,
iterations: b.iterations || 1
}))
}
};
const formatted = JSON.stringify(json, null, 2);
navigator.clipboard.writeText(formatted).then(() => {
alert("✅ JSON copied to clipboard!");
}).catch(err => {
console.error("Clipboard error:", err);
alert("❌ Failed to copy.");
});
},
importJSON(jsonString) {
try {
const parsed = JSON.parse(jsonString);
const name = Object.keys(parsed)[0];
const preset = parsed[name];
if (!this.isValidPreset(preset)) {
alert("❌ Invalid preset format.");
return;
}
const userPresets = this.getUserPresets();
userPresets[name] = preset;
this.saveUserPresets(userPresets);
this.refreshDropdown();
presetSelect.value = name;
this.loadPreset(name);
alert(`✅ Imported and loaded: ${name}`);
} catch (err) {
console.error(err);
alert("❌ Failed to parse JSON.");
}
},
preloadDefaults() {
this.refreshDropdown();
}
};
// === App Initialization ===
PresetsManager.preloadDefaults(); // Load default + user presets into the dropdown
BlockManager.rebuild(); // Render current canvas state (likely empty on first load)
// === Preset Controls ===
get('savePresetBtn').onclick = () => PresetsManager.saveCurrent();
get('loadPresetBtn').onclick = () => {
const name = presetSelect.value;
if (name) PresetsManager.loadPreset(name);
};
get('deletePresetBtn').onclick = () => PresetsManager.deleteSelected();
// === Advanced Mode Toggle ===
const advToggleInput = get('advancedToggleInput');
advToggleInput.addEventListener('change', e => {
// write back into your persisted settings
qrSettings.advancedToggle = e.target.checked;
localStorage.setItem('qrSettings', JSON.stringify(qrSettings));
// immediately update your canvas
BlockManager.rebuild();
});
// === Build QR Code ===
get('generateBtn').onclick = () => {
// Generate QR content from block list
const payload = BlockManager.blocks.map(b => {
const unit = b.type === 'tab' ? '\t'
: b.type === 'return' ? '\r'
: b.label;
return unit.repeat(b.iterations || 1);
}).join('');
const labelText = get('qrLabelInput')?.value.trim() || '';
const qrSize = 100;
const paddingAboveLabel = 10;
const labelFontSize = 14;
const labelAreaHeight = labelText ? labelFontSize + paddingAboveLabel : 0;
// Clear previous preview
qrPreview.innerHTML = '';
// Setup canvas (include label space)
const canvas = createEl('canvas');
canvas.width = qrSize;
canvas.height = qrSize + labelAreaHeight;
const ctx = canvas.getContext('2d');
// Generate QR code temporarily
const tmpDiv = createEl('div');
new QRCode(tmpDiv, {
text: payload,
width: qrSize,
height: qrSize,
typeNumber: qrSettings.typeNumber,
correctLevel: qrSettings.correctLevel,
colorDark: qrSettings.colorDark,
colorLight: qrSettings.colorLight
});
// Wait for QR to render, then draw it + optional label
setTimeout(() => {
const qrCanvas = tmpDiv.querySelector('canvas');
if (!qrCanvas) return;
// Draw QR image
ctx.drawImage(qrCanvas, 0, 0);
// Draw label below if present
if (labelText) {
ctx.font = `bold ${labelFontSize}px sans-serif`;
ctx.fillStyle = qrSettings.labelColor;
ctx.textAlign = 'center';
// Auto-resize font if label is too wide
let fontSize = labelFontSize;
ctx.font = `bold ${fontSize}px sans-serif`;
let textWidth = ctx.measureText(labelText).width;
while (textWidth > canvas.width && fontSize > 8) {
fontSize--;
ctx.font = `bold ${fontSize}px sans-serif`;
textWidth = ctx.measureText(labelText).width;
}
ctx.fillText(labelText, canvas.width / 2, qrSize + paddingAboveLabel + fontSize / 1.2);
}
// Output final QR image
const img = new Image();
img.src = canvas.toDataURL();
qrPreview.appendChild(img);
// Optionally copy to clipboard
if (qrSettings.copyToggle) {
canvas.toBlob(blob => {
const item = new ClipboardItem({ 'image/png': blob });
navigator.clipboard.write([item])
/* .then(() => alert('✅ QR Code copied to clipboard!'))
.catch(err => alert('❌ Failed to copy QR Code.')); */
});
}
}, 100);
};
// === Canvas Controls ===
get('clearBtn').onclick = () => {
if (confirm('Clear all blocks?')) BlockManager.clear();
};
// === JSON Debug/Experimental Tools ===
function copySelectedPresetJSON() {
const name = presetSelect.value;
if (!name) {
alert("Select a preset first.");
return;
}
PresetsManager.copyToClipboardAsJSON(name);
}
function openJSONModal() {
get('jsonInput').value = '';
get('jsonModal').style.display = 'block';
}
function closeJSONModal() {
get('jsonModal').style.display = 'none';
}
function submitJSON() {
const input = get('jsonInput').value;
closeJSONModal();
if (input) loadPresetFromJSON(input);
}
function loadPresetFromJSON(jsonString) {
PresetsManager.importJSON(jsonString);
}
// copy to clipboard
get('copyBtn').addEventListener('click', () => {
const img = document.querySelector('#qrPreview img');
if (!img) return alert('Generate a QR code first!');
fetch(img.src)
.then(res => res.blob())
.then(blob => {
const item = new ClipboardItem({ 'image/png': blob });
return navigator.clipboard.write([item]);
})
.then(() => alert('✅ Copied to clipboard!'))
.catch(err => alert('❌ Copy failed.'));
});
// build and download as PNG with prompt for filename
get('downloadBtn').addEventListener('click', () => {
// Trigger QR regeneration
get('generateBtn').click();
// Wait briefly to ensure the QR image is ready
setTimeout(() => {
const img = document.querySelector('#qrPreview img');
if (!img) return alert('Generate a QR code first!');
const labelValue = get('qrLabelInput').value.trim();
const presetName = presetSelect.value.trim();
let defaultName = 'qr-code';
if (labelValue !== '') {
defaultName = labelValue;
} else if (presetName && presetName !== 'Select a Preset') {
defaultName = presetName;
}
const filename = prompt("Enter filename for your QR code (without .png):", defaultName);
if (filename === null) return;
const finalName = filename.trim() === '' ? 'qr-code' : filename.trim();
const a = createEl('a', {
attrs: { href: img.src, download: `${finalName}.png` }
});
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}, 150); // Wait at least 100–200ms to ensure QR canvas is ready
});
/**
* Converts the current canvas build into a JavaScript object literal snippet,
*
* This uses a modal mult-line input field for creating and downloading batch QR codes
* The image filenames will be the contents of the lines, with each line being a new code
* This does not use the normal blocks, tabs, returns, just text lines
* Adding various modes for different use cases
*/
const openBatchBtn = get('openBatchBtn');
const batchModal = get('batchModal');
const batchBackdrop = get('batchBackdrop');
const closeBatchBtn = get('closeBatchBtn');
openBatchBtn.addEventListener('click', () => {
show('batchModal');
show('batchBackdrop');
});
closeBatchBtn.addEventListener('click', () => {
hide('batchModal');
hide('batchBackdrop');
});
// Helper: apply the chosen parsing mode to a raw line
function parseLine(raw, mode) {
switch (mode) {
case 'hexescapes':