Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
1954 lines (1685 loc) · 63.1 KB
/
Copy pathscript.js
File metadata and controls
1954 lines (1685 loc) · 63.1 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
// --- Mobile Debug Overlay (Runs only when ?debug=true is present in the URL query string) ---
(function() {
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.has("debug")) {
const debugOverlay = document.createElement("div");
debugOverlay.style.position = "fixed";
debugOverlay.style.bottom = "0";
debugOverlay.style.left = "0";
debugOverlay.style.width = "100%";
debugOverlay.style.maxHeight = "180px";
debugOverlay.style.overflowY = "auto";
debugOverlay.style.backgroundColor = "rgba(0, 0, 0, 0.9)";
debugOverlay.style.color = "#ff4d4d";
debugOverlay.style.fontSize = "11px";
debugOverlay.style.fontFamily = "monospace";
debugOverlay.style.padding = "8px";
debugOverlay.style.zIndex = "999999";
debugOverlay.style.borderTop = "2px solid #ff4d4d";
debugOverlay.id = "mobile-debug-overlay";
// Create clear button
const clearBtn = document.createElement("button");
clearBtn.innerText = "Clear logs";
clearBtn.style.position = "absolute";
clearBtn.style.top = "2px";
clearBtn.style.right = "8px";
clearBtn.style.backgroundColor = "#ff4d4d";
clearBtn.style.color = "#000";
clearBtn.style.border = "none";
clearBtn.style.padding = "2px 6px";
clearBtn.style.fontSize = "9px";
clearBtn.style.borderRadius = "3px";
clearBtn.style.cursor = "pointer";
clearBtn.onclick = (e) => {
e.stopPropagation();
debugOverlay.innerHTML = "";
debugOverlay.appendChild(clearBtn);
};
debugOverlay.appendChild(clearBtn);
document.body.appendChild(debugOverlay);
const logToOverlay = (msg) => {
const line = document.createElement("div");
line.innerText = `[${new Date().toLocaleTimeString()}] ${msg}`;
line.style.borderBottom = "1px solid rgba(255,255,255,0.1)";
line.style.padding = "2px 0";
debugOverlay.appendChild(line);
debugOverlay.scrollTop = debugOverlay.scrollHeight;
};
window.addEventListener("error", (e) => {
logToOverlay(`ERROR: ${e.message} at ${e.filename}:${e.lineno}`);
});
window.addEventListener("unhandledrejection", (e) => {
logToOverlay(`REJECTION: ${e.reason}`);
});
const originalConsoleError = console.error;
console.error = function(...args) {
logToOverlay(`CONSOLE.ERROR: ${args.join(" ")}`);
originalConsoleError.apply(console, args);
};
const originalConsoleLog = console.log;
console.log = function(...args) {
logToOverlay(`LOG: ${args.join(" ")}`);
originalConsoleLog.apply(console, args);
};
logToOverlay("Debugger initialized. URL: " + window.location.href);
}
})();
// --- Safe LocalStorage Wrapper (Prevents DOMException crashes in Private Browsing / embedded webviews) ---
const safeStorage = {
getItem(key) {
try {
return localStorage.getItem(key);
} catch (e) {
console.warn("localStorage.getItem failed for key:", key, e);
return null;
}
},
setItem(key, value) {
try {
localStorage.setItem(key, value);
return true;
} catch (e) {
console.warn("localStorage.setItem failed for key:", key, e);
return false;
}
},
removeItem(key) {
try {
localStorage.removeItem(key);
return true;
} catch (e) {
console.warn("localStorage.removeItem failed for key:", key, e);
return false;
}
}
};
// --- State Management ---
const DEFAULT_CONFIG = {
names: "Sofia & Russell",
date: "2026-10-08T17:00:00",
location: "Marchand Ranch, Cañon City, CO",
tagline: "We're getting hitched! Please join us to celebrate our love as we take this exciting next step in our journey.",
theme: "ivory",
webhookUrl: "https://script.google.com/macros/s/AKfycbzvR7KAfAh2Jld9AAloryj9W8npzj3S2DcH-TWJJPdD-T59W2h7yF4lzRw2BWws-_hW/exec"
};
let config = { ...DEFAULT_CONFIG };
let rsvps = [];
// Web Audio API Context and Synthesizer Nodes
let audioCtx = null;
let masterGain = null;
let isAudioPlaying = false;
let loopTimer = null;
let scheduledNodes = [];
let delayNodeL = null;
let delayNodeR = null;
let feedbackGainL = null;
let feedbackGainR = null;
let convolverNode = null;
let reverbGain = null;
let preDelayNode = null;
let schedulerInterval = null;
let violinFilterL = null, violinFilterR = null;
let violaFilterL = null, violaFilterR = null;
let celloFilterL = null, celloFilterR = null;
let globalBowingLFO = null, globalBowingGain = null;
// Canvas Particles
let canvas = null;
let ctx = null;
let animationId = null;
let particles = [];
// Initialize configuration, particles, and RSVPs
document.addEventListener("DOMContentLoaded", () => {
loadConfig();
document.getElementById("wedding-date-preview").innerText = "TBA";
loadRSVPs();
initCanvas();
setupEventListeners();
startCountdown();
renderRSVPTable();
// Show edit cog and share button ONLY if the visitor is accessing from localhost/127.0.0.1 (development)
// or if their public IP strictly matches your editor IP address (198.181.63.200).
const editBtn = document.getElementById("edit-btn");
const shareBtn = document.getElementById("share-btn");
if (editBtn) editBtn.style.display = "none";
if (shareBtn) shareBtn.style.display = "none";
const urlParams = new URLSearchParams(window.location.search);
const isEditorParam = urlParams.has("edit") || urlParams.has("admin");
if (isEditorParam) {
safeStorage.setItem("wedding_is_editor", "true");
}
const isLocalhost = window.location.hostname === "localhost" ||
window.location.hostname === "127.0.0.1" ||
window.location.protocol === "file:";
if (isLocalhost) {
const isEditor = isEditorParam || safeStorage.getItem("wedding_is_editor") === "true";
if (isEditor) {
if (editBtn) editBtn.style.display = "flex";
if (shareBtn) shareBtn.style.display = "flex";
}
} else {
// Production: Strictly require the IP check to pass, preventing bypass via URL params or localStorage on other IPs
fetch("https://api.ipify.org?format=json")
.then(res => res.json())
.then(data => {
if (data.ip === "198.181.63.200") {
if (editBtn) editBtn.style.display = "flex";
if (shareBtn) shareBtn.style.display = "flex";
}
})
.catch(err => console.log("IP validation check omitted or blocked"));
}
});
// --- Configuration Persistence ---
function loadConfig() {
const saved = safeStorage.getItem("wedding_save_the_date_config");
if (saved) {
try {
config = { ...DEFAULT_CONFIG, ...JSON.parse(saved) };
// Migrate old placeholder defaults automatically
if (config.names === "Sophia & Julian" || config.names === "Sophia and Julian" || config.date === "2026-09-19T17:00:00") {
config = { ...DEFAULT_CONFIG };
saveConfig();
}
// Migrate old tagline automatically
if (config.tagline === "Are getting married! Please join us to celebrate our love and new beginnings." ||
config.tagline === "Are getting hitched! Please join us to celebrate our love and the next step this exciting new journey." ||
config.tagline === "Are getting hitched! Please join us to celebrate our love as we take this exciting next step in our journey." ||
config.tagline.includes("Are getting hitched") ||
config.tagline.includes("Are getting married") ||
config.tagline.includes("Sofia & Russell Are getting hitched") ||
config.tagline.includes("Sofia & Russell We're getting hitched")) {
config.tagline = DEFAULT_CONFIG.tagline;
saveConfig();
}
// Migrate empty or old broken webhooks to the new default automatically
if (!config.webhookUrl ||
config.webhookUrl.includes("AKfycbwQr7MGf-06CBBWKcyMp2C46CnkeyTUoY7O68nplw1wdQ3wmeYxEGpNMP20yDhetPUJ") ||
config.webhookUrl.includes("AKfycbyBoqhvZzJRmMYdBirtLQr_3_nPNWvFYxQG6_UUrafPjlSycjUF8uCyDqgVEIxkU9yj") ||
config.webhookUrl.includes("AKfycbxYoL9g8ccwMuXLYnjOOXxHdIyIsgma0nydzhcGZMmsOoOBYntceaDlk2V2TToS9Apo")) {
config.webhookUrl = DEFAULT_CONFIG.webhookUrl;
saveConfig();
}
} catch (e) {
config = { ...DEFAULT_CONFIG };
}
} else {
config = { ...DEFAULT_CONFIG };
}
// Set values on UI
document.getElementById("couple-names-preview").innerHTML = formatNames(config.names);
document.getElementById("wedding-date-preview").innerText = formatDate(config.date);
document.getElementById("wedding-location-preview").innerText = config.location;
document.getElementById("wedding-tagline-preview").innerText = config.tagline;
// Set theme on body
document.body.setAttribute("data-theme", config.theme);
// Populate Studio Inputs
document.getElementById("input-names").value = config.names;
document.getElementById("input-date").value = config.date;
document.getElementById("input-location").value = config.location;
document.getElementById("input-tagline").value = config.tagline;
document.getElementById("input-webhook").value = config.webhookUrl || "";
// Select theme swatch in sidebar
document.querySelectorAll(".theme-opt").forEach(opt => {
if (opt.getAttribute("data-theme-val") === config.theme) {
opt.classList.add("active");
} else {
opt.classList.remove("active");
}
});
resetParticles();
}
function saveConfig() {
safeStorage.setItem("wedding_save_the_date_config", JSON.stringify(config));
}
function formatNames(nameStr) {
if (!nameStr) return "";
// Format "A & B" or "A and B" to put the "&" on its own italicized line
const parts = nameStr.split(/\s+&\s+|\s+and\s+/i);
if (parts.length === 2) {
return `${escapeHtml(parts[0])} <span class="and">&</span> ${escapeHtml(parts[1])}`;
}
return escapeHtml(nameStr);
}
function formatDate(dateStr) {
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
const d = parseDate(dateStr);
if (isNaN(d.getTime())) return "October 8, 2026";
return d.toLocaleDateString('en-US', options);
}
function escapeHtml(unsafe) {
return String(unsafe ?? "")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function parseDate(dateStr) {
if (!dateStr) return new Date();
// Safari / iOS date string parsing compatibility: replace dash with slash and T with space
const cleaned = dateStr.replace(/-/g, "/").replace("T", " ");
const d = new Date(cleaned);
if (!isNaN(d.getTime())) return d;
// Fallback manual parser for ISO-like strings (e.g. YYYY-MM-DDTHH:mm:ss)
const parts = dateStr.split(/[-T:\s]/);
if (parts.length >= 3) {
const year = parseInt(parts[0], 10);
const month = parseInt(parts[1], 10) - 1;
const day = parseInt(parts[2], 10);
const hours = parseInt(parts[3], 10) || 0;
const minutes = parseInt(parts[4], 10) || 0;
const seconds = parseInt(parts[5], 10) || 0;
return new Date(year, month, day, hours, minutes, seconds);
}
return new Date(dateStr);
}
// --- Event Listeners Setup ---
function setupEventListeners() {
// Toggle Design Studio Panel
const editBtn = document.getElementById("edit-btn");
const closeBtn = document.getElementById("close-btn");
const overlay = document.getElementById("studio-overlay");
const panel = document.getElementById("studio-panel");
function openStudio() {
overlay.classList.add("active");
panel.classList.add("active");
}
function closeStudio() {
overlay.classList.remove("active");
panel.classList.remove("active");
}
if (editBtn) editBtn.addEventListener("click", openStudio);
if (closeBtn) closeBtn.addEventListener("click", closeStudio);
if (overlay) overlay.addEventListener("click", closeStudio);
// Audio Control
const audioBtn = document.getElementById("audio-btn");
audioBtn.addEventListener("click", toggleAudio);
// Design Studio Input Updates (Live Preview)
document.getElementById("input-names").addEventListener("input", (e) => {
config.names = e.target.value || "Sofia & Russell";
document.getElementById("couple-names-preview").innerHTML = formatNames(config.names);
saveConfig();
});
document.getElementById("input-date").addEventListener("input", (e) => {
config.date = e.target.value || "2026-10-08T17:00:00";
document.getElementById("wedding-date-preview").innerText = formatDate(config.date);
startCountdown();
saveConfig();
});
document.getElementById("input-location").addEventListener("input", (e) => {
config.location = e.target.value || "Marchand Ranch, Cañon City, CO";
document.getElementById("wedding-location-preview").innerText = config.location;
saveConfig();
});
document.getElementById("input-tagline").addEventListener("input", (e) => {
config.tagline = e.target.value || DEFAULT_CONFIG.tagline;
document.getElementById("wedding-tagline-preview").innerText = config.tagline;
saveConfig();
});
document.getElementById("input-webhook").addEventListener("input", (e) => {
config.webhookUrl = e.target.value.trim();
saveConfig();
});
// Theme Picker
document.querySelectorAll(".theme-opt").forEach(opt => {
opt.addEventListener("click", () => {
document.querySelectorAll(".theme-opt").forEach(o => o.classList.remove("active"));
opt.classList.add("active");
const chosenTheme = opt.getAttribute("data-theme-val");
config.theme = chosenTheme;
document.body.setAttribute("data-theme", chosenTheme);
saveConfig();
resetParticles();
});
});
// RSVP Form submission
const rsvpForm = document.getElementById("rsvp-form");
rsvpForm.addEventListener("submit", (e) => {
e.preventDefault();
const guestName = document.getElementById("guest-name").value.trim();
const guestEmail = document.getElementById("guest-email").value.trim();
const guestPhone = document.getElementById("guest-phone").value.trim();
const guestAddress = document.getElementById("guest-address").value.trim();
const guestAttendance = document.getElementById("guest-attendance").value;
const guestPlusOne = document.getElementById("guest-plusone").checked;
const guestKids = parseInt(document.getElementById("guest-kids").value, 10) || 0;
if (!guestName || !guestEmail || !guestPhone || !guestAddress) return;
const rsvpObj = {
name: guestName,
email: guestEmail,
phone: guestPhone,
address: guestAddress,
status: guestAttendance,
plusOne: guestPlusOne ? "Yes" : "No",
kids: String(guestKids),
timestamp: new Date().toLocaleString()
};
rsvps.push(rsvpObj);
safeStorage.setItem("wedding_rsvps", JSON.stringify(rsvps));
renderRSVPTable();
// Send to Google Sheets if Webhook is defined
if (config.webhookUrl) {
fetch(config.webhookUrl, {
method: "POST",
mode: "no-cors",
headers: {
"Content-Type": "text/plain;charset=utf-8"
},
body: JSON.stringify(rsvpObj)
}).catch(err => console.error("Error syncing with Google Sheets:", err));
}
// Show success state
rsvpForm.style.display = "none";
const successMsg = document.getElementById("rsvp-success-message");
successMsg.style.display = "block";
successMsg.innerHTML = `<strong>Thank you, ${escapeHtml(guestName)}!</strong><br>Your RSVP has been saved. We'll send update details to ${escapeHtml(guestEmail)}.`;
});
// RSVP CSV Export
document.getElementById("export-csv-btn").addEventListener("click", exportRSVPsCSV);
// Card Image Export
document.getElementById("download-img-btn").addEventListener("click", downloadCardImage);
// Photo Uploader Change
document.getElementById("input-photo").addEventListener("change", (e) => {
const file = e.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(event) {
const couplePhoto2 = document.getElementById("couple-photo-2") || document.getElementById("couple-photo");
if (couplePhoto2) {
couplePhoto2.src = event.target.result;
}
};
reader.readAsDataURL(file);
}
});
// Lock Editor (Switch to Guest View)
const lockEditorBtn = document.getElementById("lock-editor-btn");
if (lockEditorBtn) {
lockEditorBtn.addEventListener("click", () => {
safeStorage.removeItem("wedding_is_editor");
// Redirect to clean URL without parameters so editor is locked/hidden
window.location.href = window.location.href.split('?')[0];
});
}
// Setup Share Modal Dialog listeners
setupShareEventListeners();
}
// --- Live Countdown ---
let countdownInterval = null;
function startCountdown() {
if (countdownInterval) clearInterval(countdownInterval);
const daysVal = document.getElementById("days");
const hoursVal = document.getElementById("hours");
const minutesVal = document.getElementById("minutes");
const secondsVal = document.getElementById("seconds");
function update() {
const targetDate = parseDate(config.date).getTime();
const now = new Date().getTime();
const distance = targetDate - now;
if (distance < 0) {
daysVal.innerText = "00";
hoursVal.innerText = "00";
minutesVal.innerText = "00";
secondsVal.innerText = "00";
clearInterval(countdownInterval);
return;
}
const d = Math.floor(distance / (1000 * 60 * 60 * 24));
const h = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const m = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const s = Math.floor((distance % (1000 * 60)) / 1000);
daysVal.innerText = String(d).padStart(2, '0');
hoursVal.innerText = String(h).padStart(2, '0');
minutesVal.innerText = String(m).padStart(2, '0');
secondsVal.innerText = String(s).padStart(2, '0');
}
update();
countdownInterval = setInterval(update, 1000);
}
// --- RSVP Table & Local Database Logic ---
function loadRSVPs() {
const saved = safeStorage.getItem("wedding_rsvps");
if (saved) {
try {
rsvps = JSON.parse(saved);
} catch (e) {
rsvps = [];
}
}
}
function renderRSVPTable() {
const listBody = document.getElementById("rsvp-list-body");
if (!listBody) return;
listBody.innerHTML = "";
if (rsvps.length === 0) {
listBody.innerHTML = "<tr><td colspan='7' style='text-align:center;'>No RSVPs yet</td></tr>";
return;
}
rsvps.forEach(rsvp => {
const tr = document.createElement("tr");
tr.innerHTML = `
<td>${escapeHtml(rsvp.name)}</td>
<td>${escapeHtml(rsvp.email)}</td>
<td>${escapeHtml(rsvp.phone || "")}</td>
<td>${escapeHtml(rsvp.address || "")}</td>
<td><span style="font-weight:600; color:var(--accent-color);">${escapeHtml(rsvp.status)}</span></td>
<td>${escapeHtml(rsvp.plusOne || "No")}</td>
<td>${escapeHtml(rsvp.kids !== undefined ? rsvp.kids : "0")}</td>
`;
listBody.appendChild(tr);
});
}
function exportRSVPsCSV() {
if (rsvps.length === 0) {
alert("No RSVPs to export.");
return;
}
let csvContent = "data:text/csv;charset=utf-8,Name,Email,Phone,Address,Attendance,Plus One,Kids,Timestamp\n";
rsvps.forEach(r => {
const row = `"${r.name.replace(/"/g, '""')}","${r.email.replace(/"/g, '""')}","${(r.phone || "").replace(/"/g, '""')}","${(r.address || "").replace(/"/g, '""')}","${r.status}","${r.plusOne || "No"}","${r.kids !== undefined ? r.kids : 0}","${r.timestamp}"`;
csvContent += row + "\n";
});
const encodedUri = encodeURI(csvContent);
const link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", `wedding_rsvps_${new Date().toISOString().slice(0,10)}.csv`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
// String Ensemble Melody System (Web Audio API)
const NOTE_FREQS = {
// Octave 2 (Cello lower range)
"C2": 65.41, "C#2": 69.30, "Db2": 69.30, "D2": 73.42, "D#2": 77.78, "Eb2": 77.78, "E2": 82.41, "F2": 87.31, "F#2": 92.50, "Gb2": 92.50, "G2": 98.00, "G#2": 103.83, "Ab2": 103.83, "A2": 110.00, "A#2": 116.54, "Bb2": 116.54, "B2": 123.47,
// Octave 3 (Viola and Cello middle range)
"C3": 130.81, "C#3": 138.59, "Db3": 138.59, "D3": 146.83, "D#3": 155.56, "Eb3": 155.56, "E3": 164.81, "F3": 174.61, "F#3": 185.00, "Gb3": 185.00, "G3": 196.00, "G#3": 207.65, "Ab3": 207.65, "A3": 220.00, "A#3": 233.08, "Bb3": 233.08, "B3": 246.94,
// Octave 4 (Violin and Viola range)
"C4": 261.63, "C#4": 277.18, "D4": 293.66, "D#4": 311.13, "Eb4": 311.13, "E4": 329.63, "F4": 349.23, "F#4": 369.99, "G4": 392.00, "G#4": 415.30, "A4": 440.00, "A#4": 466.16, "Bb4": 466.16, "B4": 493.88,
// Octave 5 (Violin higher range)
"C5": 523.25, "C#5": 554.37, "D5": 587.33, "D#5": 622.25, "Eb5": 622.25, "E5": 659.25, "F5": 698.46
};
// Violin melody line
const MELODY = [
// Measure 1
{ note: "F4", beat: 0.0, duration: 0.9 },
{ note: "Bb4", beat: 1.0, duration: 0.65 },
{ note: "Bb4", beat: 1.75, duration: 0.2 },
// Measure 2
{ note: "Bb4", beat: 2.0, duration: 1.4 },
// Measure 3
{ note: "F4", beat: 4.0, duration: 0.9 },
{ note: "C5", beat: 5.0, duration: 0.65 },
{ note: "A4", beat: 5.75, duration: 0.2 },
// Measure 4
{ note: "Bb4", beat: 6.0, duration: 1.4 },
// Measure 5
{ note: "F4", beat: 8.0, duration: 0.9 },
{ note: "Bb4", beat: 9.0, duration: 0.65 },
{ note: "Eb5", beat: 9.75, duration: 0.2 },
// Measure 6
{ note: "Eb5", beat: 10.0, duration: 0.9 },
{ note: "D5", beat: 11.0, duration: 0.4 },
{ note: "C5", beat: 11.75, duration: 0.2 },
// Measure 7
{ note: "Bb4", beat: 12.0, duration: 0.9 },
{ note: "A4", beat: 13.0, duration: 0.65 },
{ note: "Bb4", beat: 13.75, duration: 0.2 },
// Measure 8
{ note: "C5", beat: 14.0, duration: 1.4 },
// Measure 9
{ note: "F4", beat: 16.0, duration: 0.9 },
{ note: "Bb4", beat: 17.0, duration: 0.65 },
{ note: "Bb4", beat: 17.75, duration: 0.2 },
// Measure 10
{ note: "Bb4", beat: 18.0, duration: 1.4 },
// Measure 11
{ note: "F4", beat: 20.0, duration: 0.9 },
{ note: "C5", beat: 21.0, duration: 0.65 },
{ note: "A4", beat: 21.75, duration: 0.2 },
// Measure 12
{ note: "Bb4", beat: 22.0, duration: 1.4 },
// Measure 13
{ note: "F4", beat: 24.0, duration: 0.9 },
{ note: "Bb4", beat: 25.0, duration: 0.65 },
{ note: "D5", beat: 25.75, duration: 0.2 },
// Measure 14
{ note: "F5", beat: 26.0, duration: 0.9 },
{ note: "D5", beat: 27.0, duration: 0.65 },
{ note: "Bb4", beat: 27.75, duration: 0.2 },
// Measure 15
{ note: "G4", beat: 28.0, duration: 0.9 },
{ note: "C5", beat: 29.0, duration: 0.65 },
{ note: "D5", beat: 29.75, duration: 0.2 },
// Measure 16
{ note: "Bb4", beat: 30.0, duration: 1.4 }
];
// Viola harmony backing line
const VIOLA_LINE = [
// Measure 1 & 2
{ note: "D3", beat: 0.0, duration: 3.8 },
// Measure 3 & 4
{ note: "C3", beat: 4.0, duration: 1.8 },
{ note: "C3", beat: 5.75, duration: 0.2 },
{ note: "D3", beat: 6.0, duration: 1.8 },
// Measure 5 & 6
{ note: "D3", beat: 8.0, duration: 1.8 },
{ note: "G3", beat: 10.0, duration: 1.8 },
// Measure 7 & 8
{ note: "A3", beat: 12.0, duration: 1.8 },
{ note: "A3", beat: 14.0, duration: 1.8 },
// Measure 9 & 10
{ note: "D3", beat: 16.0, duration: 3.8 },
// Measure 11 & 12
{ note: "C3", beat: 20.0, duration: 1.8 },
{ note: "C3", beat: 21.75, duration: 0.2 },
{ note: "D3", beat: 22.0, duration: 1.8 },
// Measure 13 & 14
{ note: "D3", beat: 24.0, duration: 1.8 },
{ note: "F3", beat: 26.0, duration: 1.8 },
// Measure 15 & 16
{ note: "G3", beat: 28.0, duration: 1.8 },
{ note: "D3", beat: 30.0, duration: 1.8 }
];
// Cello bass backing line
const CELLO_LINE = [
// Measure 1 & 2
{ note: "Bb2", beat: 0.0, duration: 3.8 },
// Measure 3 & 4
{ note: "F2", beat: 4.0, duration: 1.8 },
{ note: "F2", beat: 5.75, duration: 0.2 },
{ note: "Bb2", beat: 6.0, duration: 1.8 },
// Measure 5 & 6
{ note: "Bb2", beat: 8.0, duration: 1.8 },
{ note: "Eb2", beat: 10.0, duration: 1.8 },
// Measure 7 & 8
{ note: "F2", beat: 12.0, duration: 1.8 },
{ note: "F2", beat: 14.0, duration: 1.8 },
// Measure 9 & 10
{ note: "Bb2", beat: 16.0, duration: 3.8 },
// Measure 11 & 12
{ note: "F2", beat: 20.0, duration: 1.8 },
{ note: "F2", beat: 21.75, duration: 0.2 },
{ note: "Bb2", beat: 22.0, duration: 1.8 },
// Measure 13 & 14
{ note: "Bb2", beat: 24.0, duration: 1.8 },
{ note: "Bb2", beat: 26.0, duration: 1.8 },
// Measure 15 & 16
{ note: "Eb2", beat: 28.0, duration: 1.8 },
{ note: "Bb2", beat: 30.0, duration: 1.8 }
];
const LOOP_DURATION_BEATS = 32;
function createCathedralImpulseResponse(audioCtx, duration = 3.6, decay = 2.4) {
let sampleRate = audioCtx.sampleRate || 44100;
if (isNaN(sampleRate) || sampleRate <= 0) {
sampleRate = 44100;
}
const length = Math.max(1000, Math.floor(sampleRate * duration));
try {
const impulse = audioCtx.createBuffer(2, length, sampleRate);
const left = impulse.getChannelData(0);
const right = impulse.getChannelData(1);
let lastOutL = 0;
let lastOutR = 0;
for (let i = 0; i < length; i++) {
// Generate stereo de-correlated white noise
const noiseL = Math.random() * 2 - 1;
const noiseR = Math.random() * 2 - 1;
// Exponential envelope decay
const envelope = Math.exp(-i / (sampleRate * (decay / 6.0)));
// Simulate high-frequency absorption over time using a 1-pole lowpass filter
// that gets progressively dampening as the tail decays
const progress = i / length;
const alpha = 0.04 + 0.92 * progress;
lastOutL = (1 - alpha) * lastOutL + alpha * noiseL;
lastOutR = (1 - alpha) * lastOutR + alpha * noiseR;
left[i] = lastOutL * envelope * 0.70;
right[i] = lastOutR * envelope * 0.70;
}
return impulse;
} catch (err) {
console.error("Failed to create impulse response buffer:", err);
return null;
}
}
function initAudioContext() {
try {
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
// Safari AudioContext initialization workaround (Double-Initialize trick)
try {
const tempCtx = new AudioContextClass();
if (tempCtx.close) {
tempCtx.close().catch(() => {});
}
} catch (e) {
console.warn("Safari double-initialize workaround temp context failed:", e);
}
audioCtx = new AudioContextClass();
// Track state change to keep UI in sync if the OS suspends or interrupts the context
let previousState = audioCtx.state;
audioCtx.addEventListener("statechange", () => {
const currentState = audioCtx.state;
if (currentState === "suspended" || currentState === "interrupted") {
if (previousState === "running" && isAudioPlaying) {
isAudioPlaying = false;
const audioBtn = document.getElementById("audio-btn");
if (audioBtn) audioBtn.classList.remove("active");
if (schedulerInterval) {
clearInterval(schedulerInterval);
schedulerInterval = null;
}
scheduledNodes.forEach(node => {
try { node.stop(); } catch (e) {}
});
scheduledNodes = [];
}
}
previousState = currentState;
});
// iOS Web Audio API Unlocker (play a tiny silent buffer matching sampleRate to avoid NotSupportedError on Safari)
try {
let unlockSR = audioCtx.sampleRate || 44100;
if (isNaN(unlockSR) || unlockSR <= 0) {
unlockSR = 44100;
}
const silentBuffer = audioCtx.createBuffer(1, 1, unlockSR);
const silentSource = audioCtx.createBufferSource();
silentSource.buffer = silentBuffer;
silentSource.connect(audioCtx.destination);
if (silentSource.start) silentSource.start(0);
} catch (unlockErr) {
console.warn("Failed to play silent Web Audio unlock buffer:", unlockErr);
}
masterGain = audioCtx.createGain();
masterGain.gain.value = 0.35;
masterGain.connect(audioCtx.destination);
// 1. Setup Procedural Cathedral Convolution Reverb Send Effect
convolverNode = audioCtx.createConvolver();
try {
const impulseBuffer = createCathedralImpulseResponse(audioCtx, 4.0, 2.8);
if (impulseBuffer) {
convolverNode.buffer = impulseBuffer;
}
} catch (convolverErr) {
console.warn("Failed to initialize convolver buffer statically:", convolverErr);
}
preDelayNode = audioCtx.createDelay(0.5);
preDelayNode.delayTime.value = 0.050; // 50ms pre-delay
reverbGain = audioCtx.createGain();
reverbGain.gain.value = 0.32; // 32% wet mix
// Connect convolution reverb chain
preDelayNode.connect(convolverNode);
convolverNode.connect(reverbGain);
reverbGain.connect(masterGain);
// 2. Setup Stereo Ping-Pong Delay as a subtle secondary echo texture
delayNodeL = audioCtx.createDelay(1.0);
delayNodeR = audioCtx.createDelay(1.0);
delayNodeL.delayTime.value = 0.35;
delayNodeR.delayTime.value = 0.50;
feedbackGainL = audioCtx.createGain();
feedbackGainR = audioCtx.createGain();
feedbackGainL.gain.value = 0.40;
feedbackGainR.gain.value = 0.40;
delayNodeL.connect(feedbackGainL);
feedbackGainL.connect(delayNodeR);
delayNodeR.connect(feedbackGainR);
feedbackGainR.connect(delayNodeL);
let panDelayL = null;
let panDelayR = null;
try {
if (audioCtx.createStereoPanner) {
panDelayL = audioCtx.createStereoPanner();
panDelayR = audioCtx.createStereoPanner();
}
} catch (e) {
console.warn("Delay channel stereo panners failed to create/initialize:", e);
}
const delayDryWet = audioCtx.createGain();
delayDryWet.gain.value = 0.06; // Subtle 6% wet ping-pong echo
if (panDelayL && panDelayR) {
panDelayL.pan.value = -0.8;
panDelayR.pan.value = 0.8;
delayNodeL.connect(panDelayL);
panDelayL.connect(delayDryWet);
delayNodeR.connect(panDelayR);
panDelayR.connect(delayDryWet);
} else {
delayNodeL.connect(delayDryWet);
delayNodeR.connect(delayDryWet);
}
delayDryWet.connect(masterGain);
// 3. Setup Global Channel Strips (Consolidated click-free processing)
// Violin Channel strip (L/R): Lowpass -> Highshelf EQ -> Lowshelf EQ -> Output
violinFilterL = audioCtx.createBiquadFilter();
violinFilterL.type = "lowpass";
violinFilterL.frequency.value = 1400;
violinFilterL.Q.value = 1.0;
violinFilterR = audioCtx.createBiquadFilter();
violinFilterR.type = "lowpass";
violinFilterR.frequency.value = 1400;
violinFilterR.Q.value = 1.0;
const violinHighL = audioCtx.createBiquadFilter();
violinHighL.type = "highshelf";
violinHighL.frequency.value = 6000;
violinHighL.gain.value = 3.5;
const violinHighR = audioCtx.createBiquadFilter();
violinHighR.type = "highshelf";
violinHighR.frequency.value = 6000;
violinHighR.gain.value = 3.5;
const violinLowL = audioCtx.createBiquadFilter();
violinLowL.type = "lowshelf";
violinLowL.frequency.value = 200;
violinLowL.gain.value = -4.0;
const violinLowR = audioCtx.createBiquadFilter();
violinLowR.type = "lowshelf";
violinLowR.frequency.value = 200;
violinLowR.gain.value = -4.0;
violinFilterL.connect(violinHighL);
violinHighL.connect(violinLowL);
violinLowL.connect(masterGain);
if (preDelayNode) violinLowL.connect(preDelayNode);
violinFilterR.connect(violinHighR);
violinHighR.connect(violinLowR);
violinLowR.connect(masterGain);
if (preDelayNode) violinLowR.connect(preDelayNode);
// Viola Channel strip (L/R): Lowpass -> Mid Warmth EQ -> Output
violaFilterL = audioCtx.createBiquadFilter();
violaFilterL.type = "lowpass";
violaFilterL.frequency.value = 950;
violaFilterL.Q.value = 1.0;
violaFilterR = audioCtx.createBiquadFilter();
violaFilterR.type = "lowpass";
violaFilterR.frequency.value = 950;
violaFilterR.Q.value = 1.0;
const violaPeakL = audioCtx.createBiquadFilter();
violaPeakL.type = "peaking";
violaPeakL.frequency.value = 250;
violaPeakL.Q.value = 1.0;
violaPeakL.gain.value = 2.5;
const violaPeakR = audioCtx.createBiquadFilter();
violaPeakR.type = "peaking";
violaPeakR.frequency.value = 250;
violaPeakR.Q.value = 1.0;
violaPeakR.gain.value = 2.5;
violaFilterL.connect(violaPeakL);
violaPeakL.connect(masterGain);
if (preDelayNode) violaPeakL.connect(preDelayNode);
violaFilterR.connect(violaPeakR);
violaPeakR.connect(masterGain);
if (preDelayNode) violaPeakR.connect(preDelayNode);
// Cello Channel strip (L/R): Lowpass -> Bass Boost EQ -> Highshelf EQ -> Output
celloFilterL = audioCtx.createBiquadFilter();
celloFilterL.type = "lowpass";
celloFilterL.frequency.value = 650;
celloFilterL.Q.value = 1.0;
celloFilterR = audioCtx.createBiquadFilter();
celloFilterR.type = "lowpass";
celloFilterR.frequency.value = 650;
celloFilterR.Q.value = 1.0;
const celloPeakL = audioCtx.createBiquadFilter();
celloPeakL.type = "peaking";
celloPeakL.frequency.value = 90;
celloPeakL.Q.value = 1.2;
celloPeakL.gain.value = 4.5;
const celloPeakR = audioCtx.createBiquadFilter();
celloPeakR.type = "peaking";
celloPeakR.frequency.value = 90;
celloPeakR.Q.value = 1.2;
celloPeakR.gain.value = 4.5;
const celloHighL = audioCtx.createBiquadFilter();
celloHighL.type = "highshelf";
celloHighL.frequency.value = 4000;
celloHighL.gain.value = -3.0;
const celloHighR = audioCtx.createBiquadFilter();
celloHighR.type = "highshelf";
celloHighR.frequency.value = 4000;
celloHighR.gain.value = -3.0;
celloFilterL.connect(celloPeakL);
celloPeakL.connect(celloHighL);
celloHighL.connect(masterGain);
if (preDelayNode) celloHighL.connect(preDelayNode);
celloFilterR.connect(celloPeakR);
celloPeakR.connect(celloHighR);
celloHighR.connect(masterGain);
if (preDelayNode) celloHighR.connect(preDelayNode);
// 4. Setup Global Bowing Pressure Modulation LFO
globalBowingLFO = audioCtx.createOscillator();
globalBowingLFO.type = "sine";
globalBowingLFO.frequency.value = 0.28; // 0.28Hz slow breathing
globalBowingGain = audioCtx.createGain();
globalBowingGain.gain.value = 110; // Modulate cutoffs ±110Hz
globalBowingLFO.connect(globalBowingGain);
// Connect modulator to all Lowpass filter cutoffs
globalBowingGain.connect(violinFilterL.frequency);
globalBowingGain.connect(violinFilterR.frequency);
globalBowingGain.connect(violaFilterL.frequency);
globalBowingGain.connect(violaFilterR.frequency);
globalBowingGain.connect(celloFilterL.frequency);
globalBowingGain.connect(celloFilterR.frequency);
globalBowingLFO.start();
} catch (err) {
console.error("Failed to initialize Web Audio API:", err);
}
}
function triggerStringNoteScheduled(freq, startTime, duration, instrument = "violin") {
if (!audioCtx) return null;