-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1300 lines (1144 loc) · 49.4 KB
/
script.js
File metadata and controls
1300 lines (1144 loc) · 49.4 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
// Custom Select Component with full ARIA support
function createCustomSelect(parent, options, defaultValue, id, labelText) {
const wrapper = ce("div.custom-select", parent);
if (id) wrapper.id = id;
// Generate unique IDs for ARIA references
const baseId = id || `select-${Math.random().toString(36).substr(2, 9)}`;
const listboxId = `${baseId}-listbox`;
const labelId = `${baseId}-label`;
// Find the preceding label element and give it an ID for aria-labelledby
const precedingLabel = parent.querySelector("label:last-of-type");
if (precedingLabel && !precedingLabel.id) {
precedingLabel.id = labelId;
}
const trigger = ce("button.custom-select-trigger", wrapper, {
type: "button",
textContent: options.find(o => o.value === defaultValue)?.label || options[0]?.label || ""
});
// ARIA attributes for trigger (combobox pattern)
trigger.setAttribute("role", "combobox");
trigger.setAttribute("aria-haspopup", "listbox");
trigger.setAttribute("aria-expanded", "false");
trigger.setAttribute("aria-controls", listboxId);
if (precedingLabel) {
trigger.setAttribute("aria-labelledby", labelId);
}
const dropdown = ce("div.custom-select-dropdown", wrapper);
dropdown.id = listboxId;
dropdown.setAttribute("role", "listbox");
if (precedingLabel) {
dropdown.setAttribute("aria-labelledby", labelId);
}
let currentValue = defaultValue || options[0]?.value;
const changeListeners = [];
// Helper to update ARIA attributes
function updateAriaSelected() {
dropdown.querySelectorAll(".custom-select-option").forEach(o => {
const isSelected = o.dataset.value === currentValue;
o.setAttribute("aria-selected", isSelected ? "true" : "false");
o.classList.toggle("selected", isSelected);
});
// Update aria-activedescendant
const selectedOption = dropdown.querySelector(`[data-value="${currentValue}"]`);
if (selectedOption) {
trigger.setAttribute("aria-activedescendant", selectedOption.id);
}
}
options.forEach((opt, index) => {
const optionId = `${baseId}-option-${index}`;
const option = ce("div.custom-select-option", dropdown, {
textContent: opt.label
});
option.id = optionId;
option.dataset.value = opt.value;
option.setAttribute("role", "option");
option.setAttribute("aria-selected", opt.value === currentValue ? "true" : "false");
if (opt.value === currentValue) {
option.classList.add("selected");
trigger.setAttribute("aria-activedescendant", optionId);
}
option.addEventListener("click", () => {
currentValue = opt.value;
trigger.textContent = opt.label;
// Update selected state
updateAriaSelected();
// Close dropdown
wrapper.classList.remove("open");
trigger.setAttribute("aria-expanded", "false");
// Return focus to trigger
trigger.focus();
// Fire change event
changeListeners.forEach(fn => fn());
});
});
// Toggle dropdown
trigger.addEventListener("click", (e) => {
e.stopPropagation();
if (trigger.getAttribute("aria-disabled") === "true") return;
// Close other dropdowns
document.querySelectorAll(".custom-select.open").forEach(s => {
if (s !== wrapper) {
s.classList.remove("open");
s.querySelector(".custom-select-trigger")?.setAttribute("aria-expanded", "false");
}
});
const isOpen = wrapper.classList.toggle("open");
trigger.setAttribute("aria-expanded", isOpen ? "true" : "false");
});
// Keyboard navigation
trigger.addEventListener("keydown", (e) => {
if (trigger.getAttribute("aria-disabled") === "true") return;
const isOpen = wrapper.classList.contains("open");
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault();
const currentIndex = options.findIndex(o => o.value === currentValue);
let newIndex;
if (e.key === "ArrowDown") {
newIndex = Math.min(currentIndex + 1, options.length - 1);
} else {
newIndex = Math.max(currentIndex - 1, 0);
}
if (newIndex !== currentIndex) {
const newOpt = options[newIndex];
currentValue = newOpt.value;
trigger.textContent = newOpt.label;
updateAriaSelected();
changeListeners.forEach(fn => fn());
}
} else if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
const nowOpen = wrapper.classList.toggle("open");
trigger.setAttribute("aria-expanded", nowOpen ? "true" : "false");
} else if (e.key === "Escape") {
if (isOpen) {
wrapper.classList.remove("open");
trigger.setAttribute("aria-expanded", "false");
}
} else if (e.key === "Home") {
e.preventDefault();
if (options.length > 0) {
currentValue = options[0].value;
trigger.textContent = options[0].label;
updateAriaSelected();
changeListeners.forEach(fn => fn());
}
} else if (e.key === "End") {
e.preventDefault();
if (options.length > 0) {
currentValue = options[options.length - 1].value;
trigger.textContent = options[options.length - 1].label;
updateAriaSelected();
changeListeners.forEach(fn => fn());
}
}
});
return {
get value() { return currentValue; },
set value(v) {
const opt = options.find(o => o.value === v);
if (opt) {
const changed = v !== currentValue;
currentValue = v;
trigger.textContent = opt.label;
updateAriaSelected();
if (changed) changeListeners.forEach(fn => fn());
}
},
addEventListener(event, fn) {
if (event === "change") {
changeListeners.push(fn);
}
},
element: wrapper,
trigger: trigger
};
}
// Close dropdowns when clicking outside
document.addEventListener("click", () => {
document.querySelectorAll(".custom-select.open").forEach(s => {
s.classList.remove("open");
s.querySelector(".custom-select-trigger")?.setAttribute("aria-expanded", "false");
});
});
// Build the UI
const container = ce("div.container", document.body);
container.setAttribute("role", "main");
container.setAttribute("aria-label", "QR Code Generator");
// Header
const header = ce("header", container);
ce("h1", header, { textContent: "QR Generator" });
ce("p", header, { textContent: "Generate QR codes instantly" });
// Input Card
const inputCard = ce("div.card", container);
const inputSection = ce("div.input-section", inputCard);
// Type selector
const typeGroup = ce("div.option-group.full-width", inputSection);
ce("label", typeGroup, { textContent: "Type" });
const typeSelect = createCustomSelect(typeGroup, [
{ value: "text", label: "Text / URL" },
{ value: "wifi", label: "WiFi" },
{ value: "email", label: "Email" },
{ value: "phone", label: "Phone" },
{ value: "sms", label: "SMS" },
{ value: "vcard", label: "Contact (vCard)" },
{ value: "geo", label: "Location" },
{ value: "bitcoin", label: "Bitcoin" },
{ value: "sepa", label: "SEPA Payment" },
{ value: "paypal", label: "PayPal" },
{ value: "event", label: "Calendar Event" }
], "text", "type-select");
// Dynamic form container
const formContainer = ce("div.form-container", inputSection);
// PayPal currency data with locale-based sorting
const PAYPAL_CURRENCIES = [
{ code: "AUD", name: "Australian Dollar", decimals: 2 },
{ code: "BRL", name: "Brazilian Real", decimals: 2 },
{ code: "CAD", name: "Canadian Dollar", decimals: 2 },
{ code: "CHF", name: "Swiss Franc", decimals: 2 },
{ code: "CNY", name: "Chinese Renminbi", decimals: 2 },
{ code: "CZK", name: "Czech Koruna", decimals: 2 },
{ code: "DKK", name: "Danish Krone", decimals: 2 },
{ code: "EUR", name: "Euro", decimals: 2 },
{ code: "GBP", name: "British Pound", decimals: 2 },
{ code: "HKD", name: "Hong Kong Dollar", decimals: 2 },
{ code: "HUF", name: "Hungarian Forint", decimals: 0 },
{ code: "ILS", name: "Israeli Shekel", decimals: 2 },
{ code: "JPY", name: "Japanese Yen", decimals: 0 },
{ code: "MXN", name: "Mexican Peso", decimals: 2 },
{ code: "MYR", name: "Malaysian Ringgit", decimals: 2 },
{ code: "NOK", name: "Norwegian Krone", decimals: 2 },
{ code: "NZD", name: "New Zealand Dollar", decimals: 2 },
{ code: "PHP", name: "Philippine Peso", decimals: 2 },
{ code: "PLN", name: "Polish Złoty", decimals: 2 },
{ code: "SEK", name: "Swedish Krona", decimals: 2 },
{ code: "SGD", name: "Singapore Dollar", decimals: 2 },
{ code: "THB", name: "Thai Baht", decimals: 2 },
{ code: "TWD", name: "New Taiwan Dollar", decimals: 0 },
{ code: "USD", name: "US Dollar", decimals: 2 }
];
const LOCALE_CURRENCY_MAP = {
AU: "AUD", BR: "BRL", CA: "CAD", CH: "CHF",
CN: "CNY", CZ: "CZK", DK: "DKK", GB: "GBP",
HK: "HKD", HU: "HUF", IL: "ILS", JP: "JPY",
MX: "MXN", MY: "MYR", NO: "NOK", NZ: "NZD",
PH: "PHP", PL: "PLN", SE: "SEK", SG: "SGD",
TH: "THB", TW: "TWD", US: "USD",
DE: "EUR", AT: "EUR", FR: "EUR", ES: "EUR",
IT: "EUR", NL: "EUR", BE: "EUR", FI: "EUR",
IE: "EUR", PT: "EUR", GR: "EUR", LU: "EUR",
SK: "EUR", SI: "EUR", EE: "EUR", LV: "EUR",
LT: "EUR", CY: "EUR", MT: "EUR", HR: "EUR"
};
function getLocaleCurrency() {
const lang = navigator.language || navigator.languages?.[0] || "en-US";
const country = lang.split("-")[1]?.toUpperCase();
return (country && LOCALE_CURRENCY_MAP[country]) || "EUR";
}
function getSortedCurrencyOptions() {
const localeCurrency = getLocaleCurrency();
const result = [];
const added = new Set();
if (localeCurrency !== "EUR" && localeCurrency !== "USD") {
const c = PAYPAL_CURRENCIES.find(x => x.code === localeCurrency);
if (c) { result.push(c); added.add(c.code); }
}
if (!added.has("EUR")) { result.push(PAYPAL_CURRENCIES.find(x => x.code === "EUR")); added.add("EUR"); }
if (!added.has("USD")) { result.push(PAYPAL_CURRENCIES.find(x => x.code === "USD")); added.add("USD"); }
PAYPAL_CURRENCIES.filter(c => !added.has(c.code))
.sort((a, b) => a.code.localeCompare(b.code))
.forEach(c => result.push(c));
return result.map(c => ({ value: c.code, label: `${c.code} \u2014 ${c.name}` }));
}
function getCurrencyDecimals(code) {
return PAYPAL_CURRENCIES.find(c => c.code === code)?.decimals ?? 2;
}
const paypalCurrencyOptions = getSortedCurrencyOptions();
// Form definitions
const forms = {
text: [
{ id: "text-content", label: "Content", type: "textarea", placeholder: "Enter text, URL, or any content..." }
],
wifi: [
{ id: "wifi-ssid", label: "Network Name (SSID)", type: "text", placeholder: "MyNetwork" },
{ id: "wifi-password", label: "Password", type: "text", placeholder: "Password (leave empty if open)" },
{ id: "wifi-security", label: "Security", type: "select", options: [
{ value: "WPA", label: "WPA/WPA2" },
{ value: "WEP", label: "WEP" },
{ value: "nopass", label: "None (Open)" }
]},
{ id: "wifi-hidden", label: "Hidden Network", type: "checkbox" }
],
email: [
{ id: "email-to", label: "To", type: "text", placeholder: "recipient@example.com" },
{ id: "email-subject", label: "Subject", type: "text", placeholder: "Subject line" },
{ id: "email-body", label: "Body", type: "textarea", placeholder: "Email content..." }
],
phone: [
{ id: "phone-number", label: "Phone Number", type: "tel", placeholder: "+1234567890" }
],
sms: [
{ id: "sms-number", label: "Phone Number", type: "tel", placeholder: "+1234567890" },
{ id: "sms-message", label: "Message", type: "textarea", placeholder: "Your message..." }
],
vcard: [
{ id: "vcard-firstname", label: "First Name", type: "text", placeholder: "John" },
{ id: "vcard-lastname", label: "Last Name", type: "text", placeholder: "Doe" },
{ id: "vcard-phone", label: "Phone", type: "tel", placeholder: "+1234567890" },
{ id: "vcard-email", label: "Email", type: "text", placeholder: "john@example.com" },
{ id: "vcard-org", label: "Organization", type: "text", placeholder: "Company Inc." },
{ id: "vcard-title", label: "Job Title", type: "text", placeholder: "Developer" },
{ id: "vcard-url", label: "Website", type: "text", placeholder: "https://example.com" }
],
geo: [
{ id: "geo-lat", label: "Latitude", type: "text", placeholder: "52.5200" },
{ id: "geo-lon", label: "Longitude", type: "text", placeholder: "13.4050" }
],
bitcoin: [
{ id: "btc-address", label: "Address", type: "text", placeholder: "bc1q..." },
{ id: "btc-amount", label: "Amount (BTC)", type: "text", placeholder: "0.001 (optional)" },
{ id: "btc-label", label: "Label", type: "text", placeholder: "Recipient name (optional)" },
{ id: "btc-message", label: "Message", type: "text", placeholder: "Payment description (optional)" }
],
sepa: [
{ id: "sepa-format", label: "Format", type: "select", options: [
{ value: "epc002", label: "GiroCode (EPC v002)" },
{ value: "epc001", label: "EPC v001 (Legacy)" },
{ value: "bezahlcode", label: "BezahlCode (Legacy)" }
]},
{ id: "sepa-name", label: "Recipient", type: "text", placeholder: "Max Mustermann" },
{ id: "sepa-iban", label: "IBAN", type: "text", placeholder: "DE89370400440532013000" },
{ id: "sepa-bic", label: "BIC", type: "text", placeholder: "COBADEFFXXX (optional)" },
{ id: "sepa-amount", label: "Amount (EUR)", type: "text", placeholder: "10.00" },
{ id: "sepa-reftype", label: "Reference Type", type: "select", options: [
{ value: "unstructured", label: "Remittance Text" },
{ value: "structured", label: "Structured Reference" }
]},
{ id: "sepa-reference", label: "Remittance Text", type: "text", placeholder: "Invoice 2024-001 (optional, max 140)" }
],
paypal: [
{ id: "paypal-format", label: "Format", type: "select", options: [
{ value: "paypalme", label: "PayPal.me" },
{ value: "paypalemail", label: "PayPal Email (Legacy)" }
]},
{ id: "paypal-recipient", label: "Username", type: "text", placeholder: "YourPayPalUsername" },
{ id: "paypal-amount", label: "Amount", type: "text", placeholder: "10.00 (optional)" },
{ id: "paypal-currency", label: "Currency", type: "select", options: paypalCurrencyOptions },
{ id: "paypal-description", label: "Description", type: "text", placeholder: "Payment description (optional, max 127)" }
],
event: [
{ id: "event-title", label: "Title", type: "text", placeholder: "Team Meeting" },
{ id: "event-start", label: "Start", type: "datetime-local" },
{ id: "event-end", label: "End", type: "datetime-local" },
{ id: "event-location", label: "Location", type: "text", placeholder: "Conference Room (optional)" },
{ id: "event-description", label: "Description", type: "textarea", placeholder: "Event details (optional)" }
]
};
// Store form field references
let formFields = {};
function renderForm(type) {
formContainer.innerHTML = "";
formFields = {};
const fields = forms[type];
fields.forEach(field => {
const group = ce("div.form-group", formContainer);
if (field.type === "checkbox") {
const checkGroup = ce("div.checkbox-group", group);
const input = ce("input#" + field.id, checkGroup, { type: "checkbox" });
ce("label", checkGroup, { textContent: field.label, htmlFor: field.id });
formFields[field.id] = input;
} else if (field.type === "select") {
ce("label", group, { textContent: field.label });
const select = createCustomSelect(group, field.options, field.options[0]?.value, field.id);
formFields[field.id] = select;
} else if (field.type === "textarea") {
ce("label", group, { textContent: field.label, htmlFor: field.id });
const textarea = ce("textarea#" + field.id, group, { placeholder: field.placeholder || "", spellcheck: false });
formFields[field.id] = textarea;
} else {
ce("label", group, { textContent: field.label, htmlFor: field.id });
const input = ce("input#" + field.id, group, { type: field.type, placeholder: field.placeholder || "" });
formFields[field.id] = input;
}
});
// Add event listeners to all form fields
Object.values(formFields).forEach(field => {
if (field.addEventListener) {
field.addEventListener("input", () => {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(generate, 300);
});
field.addEventListener("change", () => {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(generate, 300);
});
}
if (field.tagName) {
field.addEventListener("keydown", e => {
if (e.ctrlKey && e.key === "Enter") {
e.preventDefault();
generate();
}
});
}
});
// Type-specific setup (validation, dynamic labels, counters)
if (type === "sepa") setupSepaForm();
if (type === "paypal") setupPaypalForm();
// Focus first field
const firstField = Object.values(formFields)[0];
if (firstField?.focus) firstField.focus();
}
function setupSepaForm() {
// Byte counter
const byteCounter = ce("div.sepa-byte-counter", formContainer);
byteCounter.textContent = "0 / 331 bytes";
const formatSelect = formFields["sepa-format"];
const refTypeSelect = formFields["sepa-reftype"];
const refField = formFields["sepa-reference"];
const refLabel = refField.parentElement.querySelector("label");
const bicField = formFields["sepa-bic"];
const bicLabel = bicField.parentElement.querySelector("label");
// Reference type toggle — updates label and placeholder
function updateRefType() {
const isStructured = refTypeSelect.value === "structured";
refLabel.textContent = isStructured ? "Structured Reference" : "Remittance Text";
refField.placeholder = isStructured
? "RF48 5000 0556 3149 (max 35)"
: "Invoice 2024-001 (optional, max 140)";
refField.maxLength = isStructured ? 35 : 140;
}
refTypeSelect.addEventListener("change", updateRefType);
// Format change — BIC required/optional, byte counter visibility
function updateFormat() {
const fmt = formatSelect.value;
const bicRequired = fmt !== "epc002";
bicLabel.textContent = bicRequired ? "BIC (required)" : "BIC";
bicField.placeholder = bicRequired ? "COBADEFFXXX" : "COBADEFFXXX (optional)";
byteCounter.style.display = fmt === "bezahlcode" ? "none" : "";
}
formatSelect.addEventListener("change", () => {
updateFormat();
updateEclState();
});
// Byte counter update via global helper
function updateByteCounter() {
updateSepaByteCounter("sepa", getQRData());
}
// Hook byte counter to all field changes
Object.values(formFields).forEach(field => {
if (field.addEventListener) {
field.addEventListener("input", updateByteCounter);
field.addEventListener("change", updateByteCounter);
}
});
// IBAN validation
const ibanField = formFields["sepa-iban"];
ibanField.addEventListener("input", () => {
const val = ibanField.value.replace(/\s/g, "").toUpperCase();
const valid = !val || /^[A-Z]{2}\d{2}[A-Z0-9]{4,30}$/.test(val);
ibanField.classList.toggle("field-error", !valid);
});
// Amount validation
const amountField = formFields["sepa-amount"];
amountField.addEventListener("input", () => {
const val = amountField.value.trim();
if (!val) { amountField.classList.remove("field-error"); return; }
const num = parseFloat(val);
const valid = !isNaN(num) && num >= 0.01 && num <= 999999999.99 && /^\d+(\.\d{1,2})?$/.test(val);
amountField.classList.toggle("field-error", !valid);
});
}
function setupPaypalForm() {
const formatSelect = formFields["paypal-format"];
const recipientField = formFields["paypal-recipient"];
const recipientLabel = recipientField.parentElement.querySelector("label");
const amountField = formFields["paypal-amount"];
const currencySelect = formFields["paypal-currency"];
const descriptionField = formFields["paypal-description"];
const descriptionGroup = descriptionField.parentElement;
currencySelect.value = getLocaleCurrency();
const hint = ce("div.form-hint", formContainer);
const urlCounter = ce("div.paypal-url-counter", formContainer);
function updateFormat() {
const isMe = formatSelect.value === "paypalme";
recipientLabel.textContent = isMe ? "Username" : "Email Address";
recipientField.placeholder = isMe ? "YourPayPalUsername" : "your@paypal-email.com";
recipientField.maxLength = isMe ? 20 : 254;
descriptionGroup.style.display = isMe ? "none" : "";
hint.textContent = isMe
? "Amount is a suggestion \u2014 the payer can change it."
: "Uses your PayPal account email. Supports a description.";
urlCounter.style.display = isMe ? "none" : "";
updateUrlCounter();
}
function updateCurrency() {
const code = currencySelect.value;
const dec = code ? getCurrencyDecimals(code) : 2;
amountField.placeholder = dec === 0 ? "100 (optional, no decimals)" : "10.00 (optional)";
validateAmount();
}
function validateAmount() {
const val = amountField.value.trim();
if (!val) { amountField.classList.remove("field-error"); return; }
const code = currencySelect.value;
const dec = code ? getCurrencyDecimals(code) : 2;
const num = parseFloat(val);
const valid = dec === 0
? !isNaN(num) && num >= 1 && /^\d+$/.test(val)
: !isNaN(num) && num >= 0.01 && /^\d+(\.\d{1,2})?$/.test(val);
amountField.classList.toggle("field-error", !valid);
}
function validateRecipient() {
const val = recipientField.value.trim();
if (!val) { recipientField.classList.remove("field-error"); return; }
const valid = formatSelect.value === "paypalme"
? /^[a-zA-Z0-9]{1,20}$/.test(val)
: /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val);
recipientField.classList.toggle("field-error", !valid);
}
function updateUrlCounter() {
if (formatSelect.value === "paypalme") { urlCounter.style.display = "none"; return; }
urlCounter.style.display = "";
const url = getQRData();
const len = url.length;
urlCounter.textContent = `${len} chars`;
}
amountField.addEventListener("keydown", (e) => {
const code = currencySelect.value;
const dec = code ? getCurrencyDecimals(code) : 2;
if (dec === 0 && (e.key === "." || e.key === ",")) e.preventDefault();
});
descriptionField.maxLength = 127;
formatSelect.addEventListener("change", () => { updateFormat(); validateRecipient(); });
currencySelect.addEventListener("change", updateCurrency);
amountField.addEventListener("input", validateAmount);
recipientField.addEventListener("input", validateRecipient);
Object.values(formFields).forEach(field => {
if (field.addEventListener) {
field.addEventListener("input", updateUrlCounter);
field.addEventListener("change", updateUrlCounter);
}
});
updateFormat();
updateCurrency();
}
function getQRData() {
const type = typeSelect.value;
switch (type) {
case "text":
return formFields["text-content"]?.value?.trim() || "";
case "wifi": {
const ssid = formFields["wifi-ssid"]?.value?.trim() || "";
const password = formFields["wifi-password"]?.value || "";
const security = formFields["wifi-security"]?.value || "WPA";
const hidden = formFields["wifi-hidden"]?.checked ? "true" : "false";
if (!ssid) return "";
return `WIFI:T:${security};S:${ssid};P:${password};H:${hidden};;`;
}
case "email": {
const to = formFields["email-to"]?.value?.trim() || "";
const subject = formFields["email-subject"]?.value?.trim() || "";
const body = formFields["email-body"]?.value?.trim() || "";
if (!to) return "";
let mailto = `mailto:${encodeURIComponent(to)}`;
const params = [];
if (subject) params.push(`subject=${encodeURIComponent(subject)}`);
if (body) params.push(`body=${encodeURIComponent(body)}`);
if (params.length) mailto += "?" + params.join("&");
return mailto;
}
case "phone": {
const number = formFields["phone-number"]?.value?.trim() || "";
if (!number) return "";
return `tel:${number}`;
}
case "sms": {
const number = formFields["sms-number"]?.value?.trim() || "";
const message = formFields["sms-message"]?.value?.trim() || "";
if (!number) return "";
let sms = `sms:${number}`;
if (message) sms += `?body=${encodeURIComponent(message)}`;
return sms;
}
case "vcard": {
const firstName = formFields["vcard-firstname"]?.value?.trim() || "";
const lastName = formFields["vcard-lastname"]?.value?.trim() || "";
const phone = formFields["vcard-phone"]?.value?.trim() || "";
const email = formFields["vcard-email"]?.value?.trim() || "";
const org = formFields["vcard-org"]?.value?.trim() || "";
const title = formFields["vcard-title"]?.value?.trim() || "";
const url = formFields["vcard-url"]?.value?.trim() || "";
if (!firstName && !lastName) return "";
let vcard = "BEGIN:VCARD\nVERSION:3.0\n";
vcard += `N:${lastName};${firstName};;;\n`;
vcard += `FN:${firstName} ${lastName}\n`;
if (phone) vcard += `TEL:${phone}\n`;
if (email) vcard += `EMAIL:${email}\n`;
if (org) vcard += `ORG:${org}\n`;
if (title) vcard += `TITLE:${title}\n`;
if (url) vcard += `URL:${url}\n`;
vcard += "END:VCARD";
return vcard;
}
case "geo": {
const lat = formFields["geo-lat"]?.value?.trim() || "";
const lon = formFields["geo-lon"]?.value?.trim() || "";
if (!lat || !lon) return "";
return `geo:${lat},${lon}`;
}
case "bitcoin": {
const address = formFields["btc-address"]?.value?.trim() || "";
if (!address) return "";
let uri = `bitcoin:${address}`;
const params = [];
const amount = formFields["btc-amount"]?.value?.trim();
const label = formFields["btc-label"]?.value?.trim();
const message = formFields["btc-message"]?.value?.trim();
if (amount) params.push(`amount=${amount}`);
if (label) params.push(`label=${encodeURIComponent(label)}`);
if (message) params.push(`message=${encodeURIComponent(message)}`);
if (params.length) uri += "?" + params.join("&");
return uri;
}
case "sepa": {
const format = formFields["sepa-format"]?.value || "epc002";
const name = formFields["sepa-name"]?.value?.trim() || "";
const iban = formFields["sepa-iban"]?.value?.trim().replace(/\s/g, "").toUpperCase() || "";
if (!name || !iban) return "";
const bic = formFields["sepa-bic"]?.value?.trim().toUpperCase() || "";
const amount = formFields["sepa-amount"]?.value?.trim() || "";
const refType = formFields["sepa-reftype"]?.value || "unstructured";
const reference = formFields["sepa-reference"]?.value?.trim() || "";
// BIC required for v001
if (format === "epc001" && !bic) return "";
// BezahlCode: bank://singlepaymentsepa URI
if (format === "bezahlcode") {
const params = new URLSearchParams();
params.set("name", name);
params.set("iban", iban);
if (bic) params.set("bic", bic);
if (amount) params.set("amount", amount.replace(".", ","));
if (reference) params.set("reason", reference);
return `bank://singlepaymentsepa?${params.toString()}`;
}
// EPC v001 or v002
const version = format === "epc001" ? "001" : "002";
const amountStr = amount ? `EUR${amount}` : "";
const structRef = refType === "structured" ? reference : "";
const unstructRef = refType === "unstructured" ? reference : "";
const lines = [
"BCD", version, "1", "SCT",
bic, name, iban, amountStr,
"", structRef, unstructRef, ""
];
// Trim trailing empty lines (spec: no trailing LF after last filled line)
while (lines.length > 0 && lines[lines.length - 1] === "") {
lines.pop();
}
return lines.join("\n");
}
case "paypal": {
const format = formFields["paypal-format"]?.value || "paypalme";
const recipient = formFields["paypal-recipient"]?.value?.trim() || "";
if (!recipient) return "";
const amount = formFields["paypal-amount"]?.value?.trim() || "";
const currency = formFields["paypal-currency"]?.value || "";
if (format === "paypalme") {
let url = `https://paypal.me/${recipient}`;
if (amount) {
url += `/${amount}`;
if (currency) url += currency;
}
return url;
} else {
const description = formFields["paypal-description"]?.value?.trim() || "";
let url = `https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=${encodeURIComponent(recipient)}`;
if (amount) url += `&amount=${amount}`;
if (currency) url += `¤cy_code=${currency}`;
if (description) url += `&item_name=${encodeURIComponent(description)}`;
return url;
}
}
case "event": {
const title = formFields["event-title"]?.value?.trim() || "";
const start = formFields["event-start"]?.value || "";
if (!title || !start) return "";
const end = formFields["event-end"]?.value || "";
const location = formFields["event-location"]?.value?.trim() || "";
const description = formFields["event-description"]?.value?.trim() || "";
const fmtDate = (d) => d.replace(/[-:]/g, "") + "00";
let vcal = "BEGIN:VCALENDAR\nVERSION:2.0\nBEGIN:VEVENT";
vcal += `\nSUMMARY:${title}`;
vcal += `\nDTSTART:${fmtDate(start)}`;
if (end) vcal += `\nDTEND:${fmtDate(end)}`;
if (location) vcal += `\nLOCATION:${location}`;
if (description) vcal += `\nDESCRIPTION:${description}`;
vcal += "\nEND:VEVENT\nEND:VCALENDAR";
return vcal;
}
default:
return "";
}
}
// Options
const options = ce("div.options", inputSection);
const sizeGroup = ce("div.option-group", options);
ce("label", sizeGroup, { textContent: "Size" });
const sizeSelect = createCustomSelect(sizeGroup, [
{ value: "1", label: "Pixel-perfect" },
{ value: "4", label: "Small" },
{ value: "8", label: "Medium" },
{ value: "12", label: "Large" },
{ value: "16", label: "Extra Large" }
], "8", "size-select");
const errorGroup = ce("div.option-group", options);
ce("label", errorGroup, { textContent: "Error Correction" });
const errorSelect = createCustomSelect(errorGroup, [
{ value: "L", label: "Low (7%)" },
{ value: "M", label: "Medium (15%)" },
{ value: "Q", label: "Quartile (25%)" },
{ value: "H", label: "High (30%)" }
], "L", "error-select");
// EPC override checkbox (hidden by default, shown for SEPA EPC formats)
const epcOverrideGroup = ce("div.checkbox-group.epc-override", errorGroup);
const epcOverrideCheckbox = ce("input#epc-override", epcOverrideGroup, { type: "checkbox", checked: true });
ce("label", epcOverrideGroup, { textContent: "EPC override (Medium)", htmlFor: "epc-override" });
epcOverrideGroup.style.display = "none";
const outlineGroup = ce("div.option-group", options);
ce("label", outlineGroup, { textContent: "Outline" });
const outlineSelect = createCustomSelect(outlineGroup, [
{ value: "0", label: "None" },
{ value: "1", label: "1 unit" },
{ value: "2", label: "2 units" },
{ value: "4", label: "4 units" }
], "1", "outline-select");
// Output Card
const outputCard = ce("div.card", container);
outputCard.setAttribute("aria-label", "QR Code Output");
const outputSection = ce("div.output-section", outputCard);
const qrContainer = ce("div.qr-container", outputSection);
qrContainer.setAttribute("role", "img");
qrContainer.setAttribute("aria-label", "QR code preview area");
// Status element for screen reader announcements
const statusAnnouncer = ce("div", outputSection, { className: "sr-only" });
statusAnnouncer.setAttribute("role", "status");
statusAnnouncer.setAttribute("aria-live", "polite");
statusAnnouncer.setAttribute("aria-atomic", "true");
const placeholder = ce("div.qr-placeholder", qrContainer, { textContent: "Your QR code will appear here" });
placeholder.setAttribute("aria-hidden", "true");
const img = ce("img", qrContainer, { alt: "Generated QR Code", style: { display: "none" } });
const actions = ce("div.actions", outputSection);
actions.setAttribute("role", "group");
actions.setAttribute("aria-label", "QR code actions");
const generateBtn = ce("button.btn-primary", actions, { textContent: "Generate" });
const downloadBtn = ce("button.btn-secondary", actions, { textContent: "Download", disabled: true });
downloadBtn.setAttribute("aria-describedby", "download-hint");
ce("div.keyboard-hint", outputSection, { innerHTML: "Press <kbd>Ctrl</kbd> + <kbd>Enter</kbd> to generate" });
// Footer
const footer = ce("footer", container);
footer.innerHTML = 'Made by <a href="https://contact.gottz.de" target="_blank">GottZ</a> · <a href="https://github.com/GottZ/QR-Generator" target="_blank">GitHub</a>';
// QR Generation Logic
qrcode.stringToBytes = qrcode.stringToBytesFuncs["UTF-8"];
let lastGenerated = null;
let debounceTimer;
function updateSepaByteCounter(type, payload) {
const el = document.querySelector(".sepa-byte-counter");
if (!el || type !== "sepa") return;
const fmt = formFields["sepa-format"]?.value;
if (fmt === "bezahlcode") { el.style.display = "none"; return; }
el.style.display = "";
if (!payload) {
el.textContent = "0 / 331 bytes";
el.classList.remove("over-limit");
return;
}
const bytes = new TextEncoder().encode(payload).length;
el.textContent = `${bytes} / 331 bytes`;
el.classList.toggle("over-limit", bytes > 331);
}
function generate() {
const text = getQRData();
const type = typeSelect.value;
if (!text) {
img.style.display = "none";
placeholder.textContent = "Your QR code will appear here";
placeholder.style.display = "block";
downloadBtn.disabled = true;
lastGenerated = null;
qrContainer.setAttribute("aria-label", "QR code preview area - empty");
updateSepaByteCounter(type, "");
return;
}
try {
const size = parseInt(sizeSelect.value, 10);
const isEpc = type === "sepa" && formFields["sepa-format"]?.value !== "bezahlcode";
const epcForceM = isEpc && epcOverrideCheckbox.checked;
const errorLevel = epcForceM ? "M" : errorSelect.value;
const outline = parseInt(outlineSelect.value, 10);
const qr = qrcode(0, errorLevel);
qr.addData(text);
qr.make();
// margin parameter is in pixels, so multiply by cell size
const dataUrl = qr.createDataURL(size, outline * size);
img.src = dataUrl;
img.style.display = "block";
placeholder.style.display = "none";
downloadBtn.disabled = false;
// Generate descriptive alt text based on QR type
const typeLabels = {
text: "text content",
wifi: "WiFi network credentials",
email: "email link",
phone: "phone number",
sms: "SMS message",
vcard: "contact card",
geo: "geographic location",
bitcoin: "Bitcoin payment address",
sepa: "SEPA payment",
paypal: "PayPal payment link",
event: "calendar event"
};
const altText = `Generated QR code containing ${typeLabels[type] || "data"}`;
img.alt = altText;
qrContainer.setAttribute("aria-label", altText);
// Announce to screen readers
statusAnnouncer.textContent = `QR code generated successfully for ${typeLabels[type] || "your content"}`;
lastGenerated = { dataUrl, text };
// Update SEPA byte counter (also needed after programmatic value setting)
updateSepaByteCounter(type, text);
} catch (e) {
placeholder.textContent = "Content too long for QR code";
placeholder.style.display = "block";
img.style.display = "none";
downloadBtn.disabled = true;
lastGenerated = null;
qrContainer.setAttribute("aria-label", "QR code preview area - error");
statusAnnouncer.textContent = "Error: Content is too long for QR code";
}
}
function download() {
if (!lastGenerated) return;
const link = document.createElement("a");
link.download = "qrcode.png";
link.href = lastGenerated.dataUrl;
link.click();
}
// ECL override — only relevant for SEPA EPC formats (spec requires M)
function updateEclState() {
const isEpc = typeSelect.value === "sepa" && formFields["sepa-format"]?.value !== "bezahlcode";
const overrideActive = epcOverrideCheckbox.checked;
epcOverrideGroup.style.display = isEpc ? "" : "none";
if (isEpc && overrideActive) {
errorSelect.element.classList.add("disabled");
errorSelect.trigger.setAttribute("aria-disabled", "true");
errorSelect.trigger.tabIndex = -1;
} else {
errorSelect.element.classList.remove("disabled");
errorSelect.trigger.removeAttribute("aria-disabled");
errorSelect.trigger.tabIndex = 0;
}
}
epcOverrideCheckbox.addEventListener("change", () => {
updateEclState();
generate();
});
// Event Listeners
generateBtn.addEventListener("click", generate);
downloadBtn.addEventListener("click", download);
typeSelect.addEventListener("change", () => {
renderForm(typeSelect.value);
updateEclState();
generate();
});
sizeSelect.addEventListener("change", generate);
errorSelect.addEventListener("change", generate);
outlineSelect.addEventListener("change", generate);
// Query parameter API + Share target handling
function handleQueryParams(params) {
const type = params.get("type");
if (!forms[type]) return;
typeSelect.value = type;
renderForm(type);
// Global options
if (params.has("size")) sizeSelect.value = params.get("size");
if (params.has("error")) errorSelect.value = params.get("error");
if (params.has("outline")) outlineSelect.value = params.get("outline");
if (params.has("epc_override")) epcOverrideCheckbox.checked = params.get("epc_override") !== "false";
// Field mapping: param name → formFields key
const fieldMap = {
text: { content: "text-content" },
wifi: { ssid: "wifi-ssid", password: "wifi-password", security: "wifi-security", hidden: "wifi-hidden" },
email: { to: "email-to", subject: "email-subject", body: "email-body" },
phone: { number: "phone-number" },
sms: { number: "sms-number", message: "sms-message" },
vcard: { firstname: "vcard-firstname", lastname: "vcard-lastname", phone: "vcard-phone", email: "vcard-email", org: "vcard-org", title: "vcard-title", url: "vcard-url" },