-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
1488 lines (1411 loc) · 49 KB
/
main.js
File metadata and controls
1488 lines (1411 loc) · 49 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
(() => {
"use strict";
// Helpers
const $ = (sel, el = document) => el.querySelector(sel);
const $$ = (sel, el = document) => Array.from(el.querySelectorAll(sel));
const KEYS = {
ciSide: "ciSide",
electrodeCount: "electrodeCount",
volumeL: "volumeL",
volumeR: "volumeR",
beepDuration: "beepDuration",
beepReps: "beepReps",
semiKeyLabel: "semiKeyLabel",
// arrays per count
fLPrefix: "fL_",
fRPrefix: "fR_",
// per-row adjustments
adjLPrefix: "adjL_",
adjRPrefix: "adjR_",
// row selection set
selectedPrefix: "sel_",
};
// ---- storage helpers ----
function getF(count, side) {
const prefix = side === "L" ? KEYS.fLPrefix : KEYS.fRPrefix;
const key = prefix + count;
const raw = localStorage.getItem(key);
let fat;
if (raw) {
try {
fat = JSON.parse(raw);
if (Array.isArray(fat) && fat.length === Number(count)) return fat;
} catch {}
}
switch (count) {
case 12: // MED-EL
fat = [120, 235, 384, 579, 836, 1175,
1624, 2222, 3019, 4084, 5507, 7410];
break;
case 16: // Advanced Bionics
fat = [333, 455, 540, 642, 762, 906, 1076, 1278,
1518, 1803, 2142, 2544, 3022, 3590, 4264, 6665];
break;
case 22: // Cochlear (ACE high bin)
fat = [250, 375, 500, 625, 750, 875, 1000, 1125, 1250, 1500, 1750,
2000, 2250, 2625, 3000, 3500, 4000, 4625, 5250, 6000, 6875, 8000];
break;
default: // default log-spaced 200..8000 Hz
fat = logSpace(200, 8000, Number(count));
break;
}
localStorage.setItem(key, JSON.stringify(fat));
return fat;
}
function setF(count, side, arr) {
const prefix = side === "L" ? KEYS.fLPrefix : KEYS.fRPrefix;
localStorage.setItem(prefix + count, JSON.stringify(arr));
}
function getAdj(count, side) {
const prefix = side === "L" ? KEYS.adjLPrefix : KEYS.adjRPrefix;
const key = prefix + count;
const raw = localStorage.getItem(key);
if (raw) {
try {
const arr = JSON.parse(raw);
if (Array.isArray(arr) && arr.length === Number(count)) return arr;
} catch {}
}
const arr = new Array(Number(count)).fill(0);
localStorage.setItem(key, JSON.stringify(arr));
return arr;
}
function setAdj(count, side, arr) {
const prefix = side === "L" ? KEYS.adjLPrefix : KEYS.adjRPrefix;
localStorage.setItem(prefix + count, JSON.stringify(arr));
}
function getSelected(count) {
const raw = localStorage.getItem(KEYS.selectedPrefix + count);
if (!raw) return new Set();
try {
return new Set(JSON.parse(raw));
} catch {
return new Set();
}
}
function setSelected(count, set) {
localStorage.setItem(KEYS.selectedPrefix + count, JSON.stringify([...set]));
}
function logSpace(start, end, num) {
const out = [];
const a = Math.log10(start),
b = Math.log10(end);
for (let i = 0; i < num; i++)
out.push(Math.round(10 ** (a + ((b - a) * i) / (num - 1))));
return out;
}
function initControls() {
// CI side radios (L/R)
const storedSide = localStorage.getItem(KEYS.ciSide) || "R";
const sideRadios = $$('input[name="ciSide"]');
sideRadios.forEach((r) => {
r.checked = r.value === storedSide;
r.addEventListener("change", () => {
if (r.checked) localStorage.setItem(KEYS.ciSide, r.value);
renderTable();
});
});
// Electrode count radios (12/16/22)
const storedCount = localStorage.getItem(KEYS.electrodeCount) || "12";
const countRadios = $$('input[name="electrodeCount"]');
countRadios.forEach((r) => {
r.checked = r.value === storedCount;
r.addEventListener("change", () => {
if (r.checked) localStorage.setItem(KEYS.electrodeCount, r.value);
renderTable();
});
});
// Volumes & timing
const volL = $("#volumeL");
if (volL) {
volL.value = localStorage.getItem(KEYS.volumeL) || "75";
volL.addEventListener("input", () => {
localStorage.setItem(KEYS.volumeL, volL.value);
// live-update any active L+R for left ear
updateActiveBothGainsForEar("L");
});
}
const volR = $("#volumeR");
if (volR) {
volR.value = localStorage.getItem(KEYS.volumeR) || "75";
volR.addEventListener("input", () => {
localStorage.setItem(KEYS.volumeR, volR.value);
// live-update any active L+R for right ear
updateActiveBothGainsForEar("R");
});
}
const dur = $("#beepDuration");
if (dur) {
dur.value = localStorage.getItem(KEYS.beepDuration) || "500";
dur.addEventListener("change", () =>
localStorage.setItem(KEYS.beepDuration, dur.value)
);
}
const reps = $("#beepReps");
if (reps) {
reps.value = localStorage.getItem(KEYS.beepReps) || "3";
reps.addEventListener("change", () =>
localStorage.setItem(KEYS.beepReps, reps.value)
);
}
// Export / Import
const btnExport = $("#btnExport");
if (btnExport) btnExport.addEventListener("click", doExport);
const btnImport = $("#btnImport");
const importFile = $("#importFile");
if (btnImport && importFile)
btnImport.addEventListener("click", () => importFile.click());
if (importFile) importFile.addEventListener("change", doImport);
// Copy/Paste FAT actions
const btnCopyFAT = document.getElementById("btnCopyFAT");
if (btnCopyFAT) btnCopyFAT.addEventListener("click", doCopyFAT);
const btnPasteFAT = document.getElementById("btnPasteFAT");
if (btnPasteFAT) btnPasteFAT.addEventListener("click", doPasteFAT);
// Reset buttons
const btnResetAlign = $("#btnResetAlign");
if (btnResetAlign) btnResetAlign.addEventListener("click", resetAlignments);
const btnResetAll = $("#btnResetAll");
if (btnResetAll) btnResetAll.addEventListener("click", resetEverything);
// Help button
const btnHelp = $("#btnHelp");
if (btnHelp) btnHelp.addEventListener("click", showHelp);
const lnkInstructions = $("#lnkInstructions");
if (lnkInstructions)
lnkInstructions.addEventListener("click", (e) => {
e.preventDefault();
showHelp();
});
const btnHelpCloseIcon = $("#btnHelpCloseIcon");
if (btnHelpCloseIcon) btnHelpCloseIcon.addEventListener("click", hideHelp);
// Initial table render
renderTable();
// Try to detect the character mapped to the physical Semicolon key and update titles
initSemicolonLabel();
}
function getSemiLabel() {
const s = localStorage.getItem(KEYS.semiKeyLabel);
return s && s.length ? s : ";";
}
function formatSemiLabel(s) {
if (!s) return ";";
return s.toUpperCase();
}
function setSemiLabel(ch) {
if (!ch) return;
const c = String(ch);
try {
localStorage.setItem(KEYS.semiKeyLabel, c);
} catch {}
}
async function initSemicolonLabel() {
try {
if (navigator.keyboard && navigator.keyboard.getLayoutMap) {
const map = await navigator.keyboard.getLayoutMap();
const v = map && map.get("Semicolon");
if (v && typeof v === "string" && v.length) {
setSemiLabel(v);
updateSimulTitles(v);
}
}
} catch {}
}
function updateSimulTitles(label) {
const lab = formatSemiLabel(label || getSemiLabel());
document.querySelectorAll('.fat button[data-act="both"]').forEach((btn) => {
const base = "Simultaneous L+R";
const cur = btn.getAttribute("title") || base;
const next = cur.replace(/\s*\([^)]*\)\s*$/, "");
btn.setAttribute("title", `${next} (${lab})`);
});
}
function doExport() {
// Gather top-level settings
const settings = {
ciSide: localStorage.getItem(KEYS.ciSide) || "R",
electrodeCount: localStorage.getItem(KEYS.electrodeCount) || "12",
volumeL: localStorage.getItem(KEYS.volumeL) || "75",
volumeR: localStorage.getItem(KEYS.volumeR) || "75",
beepDuration: localStorage.getItem(KEYS.beepDuration) || "500",
beepReps: localStorage.getItem(KEYS.beepReps) || "3",
};
// Gather arrays from localStorage for all counts present
const arrays = { fL: {}, fR: {}, adjL: {}, adjR: {}, selected: {} };
for (let i = 0; i < localStorage.length; i++) {
const k = localStorage.key(i);
if (!k) continue;
const put = (bucket, count, val) => {
if (count) bucket[count] = val;
};
try {
if (k.startsWith(KEYS.fLPrefix)) {
const count = k.slice(KEYS.fLPrefix.length);
put(arrays.fL, count, JSON.parse(localStorage.getItem(k)));
} else if (k.startsWith(KEYS.fRPrefix)) {
const count = k.slice(KEYS.fRPrefix.length);
put(arrays.fR, count, JSON.parse(localStorage.getItem(k)));
} else if (k.startsWith(KEYS.adjLPrefix)) {
const count = k.slice(KEYS.adjLPrefix.length);
put(arrays.adjL, count, JSON.parse(localStorage.getItem(k)));
} else if (k.startsWith(KEYS.adjRPrefix)) {
const count = k.slice(KEYS.adjRPrefix.length);
put(arrays.adjR, count, JSON.parse(localStorage.getItem(k)));
} else if (k.startsWith(KEYS.selectedPrefix)) {
const count = k.slice(KEYS.selectedPrefix.length);
put(arrays.selected, count, JSON.parse(localStorage.getItem(k)));
}
} catch {
// ignore malformed entries
}
}
const data = {
app: "bicial",
version: 1,
savedAt: new Date().toISOString(),
settings,
arrays,
};
const blob = new Blob([JSON.stringify(data, null, 2)], {
type: "application/json",
});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "bicial-settings.json";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
// ---- Copy/Paste FAT helpers ----
function getNonCIEar() {
const ciSide = localStorage.getItem(KEYS.ciSide) || "R";
return ciSide === "R" ? "L" : "R";
}
function getCIEar() {
const ciSide = localStorage.getItem(KEYS.ciSide) || "R";
return ciSide === "R" ? "R" : "L";
}
async function doCopyFAT() {
try {
const container = document.getElementById("fatContainer");
if (!container) return;
const count = Number(localStorage.getItem(KEYS.electrodeCount) || "12");
const ear = getNonCIEar();
const values = [];
for (let i = 0; i < count; i++) {
values.push(String(getDisplayedFreq(container, ear, i)));
}
const text = values.join("\n");
await navigator.clipboard.writeText(text);
showToast('Copied new FAT (from non‑CI ear)');
} catch (err) {
alert("Copy failed. Your browser may block clipboard access.");
}
}
function normalizePasteText(raw) {
if (!raw) return [];
let s = String(raw)
.replace(/[;\t\r ]+/g, "\n")
.replace(/\u00A0/g, "\n");
const lines = s
.split(/\n+/)
.map((x) => x.replace(/,/g, ".").trim())
.filter((x) => x.length > 0);
return lines;
}
async function doPasteFAT() {
try {
const container = document.getElementById("fatContainer");
if (!container) return;
const count = Number(localStorage.getItem(KEYS.electrodeCount) || "12");
const ear = getCIEar();
const text = await navigator.clipboard.readText();
const parts = normalizePasteText(text);
if (parts.length !== count) {
alert(`Paste failed: expected ${count} values, got ${parts.length}.`);
return;
}
const nums = parts.map((p) => {
const v = Math.round(Number(p));
return Number.isFinite(v) && v >= 0 ? v : 0;
});
const c = count;
const left = getF(c, "L");
const right = getF(c, "R");
for (let i = 0; i < c; i++) {
if (ear === "L") left[i] = nums[i];
else right[i] = nums[i];
}
setF(c, "L", left);
setF(c, "R", right);
for (let i = 0; i < c; i++) {
const inp = container.querySelector(
`.ear-input[data-ear="${ear}"][data-i="${i}"]`
);
if (inp) inp.value = String(nums[i]);
}
const ciIsLeft = ear === "L";
const ctx = getAudioCtx();
const now = ctx.currentTime;
for (const [rowIndex, obj] of bothPlayers) {
const v = nums[rowIndex];
if (!Number.isFinite(v)) continue;
try {
if (ciIsLeft && obj.oscL) obj.oscL.frequency.setValueAtTime(v, now);
if (!ciIsLeft && obj.oscR) obj.oscR.frequency.setValueAtTime(v, now);
} catch {}
}
showToast('Pasted old FAT (to CI ear)');
} catch (err) {
alert(
"Paste failed. Your browser may block clipboard access or the data was invalid."
);
}
}
function doImport(e) {
const file = e.target.files && e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = () => {
try {
const data = JSON.parse(reader.result);
const s = data.settings || {};
if (s.ciSide) localStorage.setItem(KEYS.ciSide, s.ciSide);
if (s.electrodeCount)
localStorage.setItem(KEYS.electrodeCount, String(s.electrodeCount));
if (s.volumeL != null)
localStorage.setItem(KEYS.volumeL, String(s.volumeL));
if (s.volumeR != null)
localStorage.setItem(KEYS.volumeR, String(s.volumeR));
if (s.beepDuration != null)
localStorage.setItem(KEYS.beepDuration, String(s.beepDuration));
if (s.beepReps != null)
localStorage.setItem(KEYS.beepReps, String(s.beepReps));
const a = data.arrays || {};
const writeBucket = (bucket, prefix) => {
if (!bucket) return;
Object.keys(bucket).forEach((count) => {
try {
localStorage.setItem(
prefix + count,
JSON.stringify(bucket[count])
);
} catch {}
});
};
writeBucket(a.fL, KEYS.fLPrefix);
writeBucket(a.fR, KEYS.fRPrefix);
writeBucket(a.adjL, KEYS.adjLPrefix);
writeBucket(a.adjR, KEYS.adjRPrefix);
writeBucket(a.selected, KEYS.selectedPrefix);
// reflect imported settings in UI
const sideRadios = document.querySelectorAll('input[name="ciSide"]');
sideRadios.forEach(
(r) =>
(r.checked = r.value === (localStorage.getItem(KEYS.ciSide) || "R"))
);
const countRadios = document.querySelectorAll(
'input[name="electrodeCount"]'
);
countRadios.forEach(
(r) =>
(r.checked =
r.value === (localStorage.getItem(KEYS.electrodeCount) || "12"))
);
const volL = document.getElementById("volumeL");
if (volL) volL.value = localStorage.getItem(KEYS.volumeL) || "75";
const volR = document.getElementById("volumeR");
if (volR) volR.value = localStorage.getItem(KEYS.volumeR) || "75";
const dur = document.getElementById("beepDuration");
if (dur) dur.value = localStorage.getItem(KEYS.beepDuration) || "500";
const reps = document.getElementById("beepReps");
if (reps) reps.value = localStorage.getItem(KEYS.beepReps) || "3";
renderTable();
} catch (err) {
alert("Import failed: invalid file.");
}
// allow re-importing the same file name
try {
e.target.value = "";
} catch {}
};
reader.readAsText(file);
}
window.addEventListener("DOMContentLoaded", initControls);
// ---- table rendering ----
function renderTable() {
const container = document.getElementById("fatContainer");
if (!container) return;
// stop any active L+R rows before re-render to avoid orphan audio
stopAllBoth();
// cancel any batch play sequences
cancelAllBatches();
const count = Number(localStorage.getItem(KEYS.electrodeCount) || "12");
const ciSide = localStorage.getItem(KEYS.ciSide) || "R";
// reflect CI side in container for CSS-based styling of CI ear inputs
try {
container.setAttribute("data-ci-side", ciSide);
} catch {}
const fL = getF(count, "L");
const fR = getF(count, "R");
const adjL = getAdj(count, "L");
const adjR = getAdj(count, "R");
const selected = getSelected(count);
const isCIRight = ciSide === "R";
const head = [
"#",
"L f",
"R f",
"f ±",
"L",
"R",
"L/R",
"L+R",
"✓",
"L vol ±",
"R vol ±",
];
let html =
'<table class="fat"><thead><tr>' +
head.map((h) => `<th>${h}</th>`).join("") +
"</tr></thead><tbody>";
for (let i = 0; i < count; i++) {
const idx = i + 1;
// numeric inputs: left ear freq, right ear freq
const leftVal = fL[i];
const rightVal = fR[i];
html += "<tr>";
html += `<td>${idx}</td>`;
html += `<td><input type="number" class="ear-input" data-ear="L" data-i="${i}" value="${leftVal}" min="0" step="1"></td>`;
html += `<td><input type="number" class="ear-input" data-ear="R" data-i="${i}" value="${rightVal}" min="0" step="1"></td>`;
// nudge non-CI ear frequency: -10, -1, +1, +10
html +=
`<td class=\"nudge-cell\">` +
`<button class=\"btn-icon nudge\" data-act=\"nudge\" data-i=\"${i}\" data-delta=\"-10\" title=\"Non-CI -10 (A)\">⏬</button>` +
`<button class=\"btn-icon nudge\" data-act=\"nudge\" data-i=\"${i}\" data-delta=\"-1\" title=\"Non-CI -1 (S)\">🔽</button>` +
`<button class=\"btn-icon nudge\" data-act=\"nudge\" data-i=\"${i}\" data-delta=\"1\" title=\"Non-CI +1 (D)\">🔼</button>` +
`<button class=\"btn-icon nudge\" data-act=\"nudge\" data-i=\"${i}\" data-delta=\"10\" title=\"Non-CI +10 (F)\">⏫</button>` +
`</td>`;
// play single left/right
html += `<td><button class=\"btn-icon single\" data-act=\"play\" data-ear=\"L\" data-i=\"${i}\" title=\"Play left (J)\">🔉</button></td>`;
html += `<td><button class=\"btn-icon single\" data-act=\"play\" data-ear=\"R\" data-i=\"${i}\" title=\"Play right (K)\">🔉</button></td>`;
// alternating L/R
html += `<td><button class=\"btn-icon lr\" data-act=\"alt\" data-i=\"${i}\" title=\"Alternate L/R (L)\">🔊</button></td>`;
// simultaneous toggle L+R (title shows actual character for the physical semicolon key)
html += `<td><button class=\"btn-icon lr\" data-act=\"both\" data-i=\"${i}\" title=\"Simultaneous L+R (${formatSemiLabel(
getSemiLabel()
)})\">🔊</button></td>`;
// selection checkbox
const checked = selected.has(i) ? "checked" : "";
html += `<td><input type="checkbox" class="row-check" data-i="${i}" ${checked}></td>`;
// per-row volume adjustments
html += `<td><input type="range" class="adj" min="-50" max="50" step="1" value="${adjL[i]}" data-ear="L" data-i="${i}"></td>`;
html += `<td><input type="range" class="adj" min="-50" max="50" step="1" value="${adjR[i]}" data-ear="R" data-i="${i}"></td>`;
html += "</tr>";
}
// bottom batch row
html +=
"<tr>" +
"<td></td>" +
'<td colspan="2"><button class="btn" id="btnVisualize" type="button" title="Visualize (U+AA5C)">꩜ <span>Visualize</span></button></td>' +
"<td></td>" +
`<td><button class="btn-icon single" data-act="play-all" data-ear="L" title="Play checked left">🔉</button></td>` +
`<td><button class="btn-icon single" data-act="play-all" data-ear="R" title="Play checked right">🔉</button></td>` +
`<td><button class="btn-icon lr" data-act="alt-all" title="Alternate checked">🔊</button></td>` +
'<td colspan="4"></td>' +
"</tr>";
html += "</tbody></table>";
container.innerHTML = html;
// hook visualize button
const btnVisualize = container.querySelector("#btnVisualize");
if (btnVisualize) {
btnVisualize.addEventListener("click", showVisualization);
}
// master checkbox in header
const thead = container.querySelector("thead tr");
if (thead) {
const ths = thead.querySelectorAll("th");
const checkThIndex = head.indexOf("✓");
if (ths[checkThIndex]) {
ths[
checkThIndex
].innerHTML = `<input type="checkbox" id="masterCheck">`;
const master = container.querySelector("#masterCheck");
if (master) {
master.addEventListener("change", () => {
const boxes = container.querySelectorAll(".row-check");
const set = new Set();
boxes.forEach((cb, j) => {
cb.checked = master.checked;
if (master.checked) set.add(Number(cb.dataset.i));
});
setSelected(count, set);
updateBatchButtonsDisabled(container);
});
}
}
}
// input handlers
container.querySelectorAll(".ear-input").forEach((inp) => {
const setActive = () => {
const i = Number(inp.dataset.i);
if (Number.isFinite(i)) lastActiveRow = i;
};
inp.addEventListener("focus", setActive);
inp.addEventListener("input", setActive);
inp.addEventListener("change", () => {
setActive();
const i = Number(inp.dataset.i);
const ear = inp.dataset.ear; // 'L' or 'R'
const val = Math.max(0, Math.round(Number(inp.value) || 0));
inp.value = val;
const otherEar = ear === "L" ? "R" : "L";
const c = Number(localStorage.getItem(KEYS.electrodeCount) || "12");
const left = getF(c, "L");
const right = getF(c, "R");
if (ear === "L") left[i] = val;
else right[i] = val;
const ciSide = localStorage.getItem(KEYS.ciSide) || "R";
const isCiEar = ear === ciSide;
if (isCiEar) {
if (ear === "L") right[i] = val;
else left[i] = val;
const other = container.querySelector(
`.ear-input[data-i="${i}"][data-ear="${otherEar}"]`
);
if (other) other.value = String(val);
}
setF(c, "L", left);
setF(c, "R", right);
});
});
container.querySelectorAll(".adj").forEach((sl) => {
const setActive = () => {
const i = Number(sl.dataset.i);
if (Number.isFinite(i)) lastActiveRow = i;
};
sl.addEventListener("focus", setActive);
sl.addEventListener("input", () => {
setActive();
const i = Number(sl.dataset.i);
const ear = sl.dataset.ear; // L or R as displayed
const v = Math.max(
-50,
Math.min(50, Math.round(Number(sl.value) || 0))
);
sl.value = v;
const c = Number(localStorage.getItem(KEYS.electrodeCount) || "12");
const adjArr = getAdj(c, ear);
adjArr[i] = v;
setAdj(c, ear, adjArr);
updateLiveGainFor(i, ear);
});
});
container.querySelectorAll(".row-check").forEach((cb) => {
cb.addEventListener("change", () => {
const c = Number(localStorage.getItem(KEYS.electrodeCount) || "12");
const set = getSelected(c);
const idx = Number(cb.dataset.i);
if (cb.checked) set.add(idx);
else set.delete(idx);
setSelected(c, set);
updateBatchButtonsDisabled(container);
});
});
// one-time event delegation for button clicks
if (!container.dataset.bound) {
container.addEventListener("click", onTableClick);
container.dataset.bound = "1";
}
// Set initial disabled state for batch buttons
updateBatchButtonsDisabled(container);
}
function updateBatchButtonsDisabled(container) {
const { sel } = getSelectedSorted();
const none = sel.length === 0;
const btnL = container.querySelector(
'button[data-act="play-all"][data-ear="L"]'
);
const btnR = container.querySelector(
'button[data-act="play-all"][data-ear="R"]'
);
const btnAlt = container.querySelector('button[data-act="alt-all"]');
if (btnL) btnL.disabled = none || !!batchTimers.L;
if (btnR) btnR.disabled = none || !!batchTimers.R;
if (btnAlt) btnAlt.disabled = none || !!batchTimers.ALT;
}
// ---- audio: single beep L/R ----
let audioCtx = null;
function getAudioCtx() {
if (!audioCtx)
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
// resume if suspended (browser policy)
if (audioCtx.state === "suspended") audioCtx.resume();
return audioCtx;
}
function getDisplayedFreq(container, ear, i) {
const inp = container.querySelector(
`.ear-input[data-ear="${ear}"][data-i="${i}"]`
);
return Math.max(0, Math.round(Number((inp && inp.value) || 0)));
}
function earGain(ear, i) {
const count = Number(localStorage.getItem(KEYS.electrodeCount) || "12");
const base =
(ear === "L"
? Number(localStorage.getItem(KEYS.volumeL) || "75")
: Number(localStorage.getItem(KEYS.volumeR) || "75")) / 100;
const adjArr = getAdj(count, ear);
const adj = Number(adjArr[i] || 0); // -50..50
const factor = 1 + adj / 50; // 0..2
const g = Math.max(0, Math.min(1, base * factor));
return g;
}
function updateLiveGainFor(rowIndex, ear) {
const obj = bothPlayers.get(rowIndex);
if (!obj) return;
const ctx = getAudioCtx();
const now = ctx.currentTime;
const newGain = earGain(ear, rowIndex);
try {
const env = ear === "L" ? obj.envL : obj.envR;
if (!env) return;
env.gain.cancelScheduledValues(now);
env.gain.setTargetAtTime(newGain, now, 0.03);
} catch {}
}
function updateActiveBothGainsForEar(ear) {
for (const [rowIndex, obj] of bothPlayers) {
updateLiveGainFor(rowIndex, ear);
}
}
function playSingleBeep(ear, i) {
const container = document.getElementById("fatContainer");
if (!container) return;
const ctx = getAudioCtx();
const freq = getDisplayedFreq(container, ear, i);
const durMs = Math.max(
10,
Number(localStorage.getItem(KEYS.beepDuration) || "500")
);
const dur = durMs / 1000;
const gainVal = earGain(ear, i);
const now = ctx.currentTime;
const osc = ctx.createOscillator();
osc.type = "sine";
osc.frequency.setValueAtTime(freq, now);
// Envelope
const env = ctx.createGain();
env.gain.setValueAtTime(0, now);
env.gain.linearRampToValueAtTime(gainVal, now + 0.01);
env.gain.setTargetAtTime(0, now + Math.max(0.02, dur - 0.02), 0.01);
if (ctx.createStereoPanner) {
const panner = ctx.createStereoPanner();
panner.pan.value = ear === "L" ? -1 : 1;
osc.connect(env);
env.connect(panner);
panner.connect(ctx.destination);
} else {
// Fallback: split to channels via ChannelMerger
const gL = ctx.createGain();
const gR = ctx.createGain();
gL.gain.value = ear === "L" ? 1 : 0;
gR.gain.value = ear === "R" ? 1 : 0;
const merger = ctx.createChannelMerger(2);
osc.connect(env);
env.connect(gL);
env.connect(gR);
gL.connect(merger, 0, 0);
gR.connect(merger, 0, 1);
merger.connect(ctx.destination);
}
osc.start(now);
osc.stop(now + dur);
osc.onended = () => {
try {
osc.disconnect();
} catch {}
};
}
// ---- simultaneous L+R toggle ----
const bothPlayers = new Map(); // rowIndex -> { oscL, oscR, envL, envR, panL?, panR?, merger?, btn }
function startBoth(i, btn) {
const container = document.getElementById("fatContainer");
if (!container) return;
const ctx = getAudioCtx();
const freqL = getDisplayedFreq(container, "L", i);
const freqR = getDisplayedFreq(container, "R", i);
const gLVal = earGain("L", i);
const gRVal = earGain("R", i);
const now = ctx.currentTime;
const oscL = ctx.createOscillator();
oscL.type = "sine";
oscL.frequency.setValueAtTime(freqL, now);
const envL = ctx.createGain();
envL.gain.setValueAtTime(0, now);
envL.gain.linearRampToValueAtTime(gLVal, now + 0.02);
const panL = ctx.createStereoPanner ? ctx.createStereoPanner() : null;
if (panL) panL.pan.value = -1;
const oscR = ctx.createOscillator();
oscR.type = "sine";
oscR.frequency.setValueAtTime(freqR, now);
const envR = ctx.createGain();
envR.gain.setValueAtTime(0, now);
envR.gain.linearRampToValueAtTime(gRVal, now + 0.02);
const panR = ctx.createStereoPanner ? ctx.createStereoPanner() : null;
if (panR) panR.pan.value = 1;
let merger = null;
if (panL && panR) {
// modern path: panners to destination
oscL.connect(envL);
envL.connect(panL);
panL.connect(ctx.destination);
oscR.connect(envR);
envR.connect(panR);
panR.connect(ctx.destination);
} else {
// fallback: explicit channel routing
merger = ctx.createChannelMerger(2);
oscL.connect(envL);
envL.connect(merger, 0, 0);
oscR.connect(envR);
envR.connect(merger, 0, 1);
merger.connect(ctx.destination);
}
oscL.start(now);
oscR.start(now);
btn.classList.add("is-on");
bothPlayers.set(i, { oscL, oscR, envL, envR, panL, panR, merger, btn });
}
function stopBoth(i, btnFromClick) {
const obj = bothPlayers.get(i);
if (!obj) return;
const ctx = getAudioCtx();
const now = ctx.currentTime;
try {
obj.envL.gain.cancelScheduledValues(now);
obj.envR.gain.cancelScheduledValues(now);
obj.envL.gain.setTargetAtTime(0, now, 0.02);
obj.envR.gain.setTargetAtTime(0, now, 0.02);
} catch {}
// stop oscillators shortly after ramp down using audio timeline (no JS timers)
try {
obj.oscL.stop(now + 0.06);
} catch {}
try {
obj.oscR.stop(now + 0.06);
} catch {}
const btn = btnFromClick || obj.btn;
let ended = 0;
function cleanup() {
ended++;
if (ended < 2) return;
try {
obj.oscL.disconnect();
} catch {}
try {
obj.oscR.disconnect();
} catch {}
try {
obj.envL.disconnect();
} catch {}
try {
obj.envR.disconnect();
} catch {}
try {
obj.panL && obj.panL.disconnect();
} catch {}
try {
obj.panR && obj.panR.disconnect();
} catch {}
try {
obj.merger && obj.merger.disconnect();
} catch {}
if (btn) btn.classList.remove("is-on");
bothPlayers.delete(i);
}
try {
obj.oscL.onended = cleanup;
} catch {}
try {
obj.oscR.onended = cleanup;
} catch {}
}
function stopAllBoth() {
for (const [i] of bothPlayers) stopBoth(i);
}
// Track last-active row for keyboard shortcuts and handle button actions
let lastActiveRow = null;
function onTableClick(e) {
const btn = e.target.closest("button");
if (!btn) return;
const act = btn.dataset.act;
if (btn.dataset.i != null) {
const idx = Number(btn.dataset.i);
if (Number.isFinite(idx)) lastActiveRow = idx;
}
if (act === "play") {
const ear = btn.dataset.ear; // 'L' or 'R'
const i = Number(btn.dataset.i);
if (Number.isFinite(i) && (ear === "L" || ear === "R"))
playSingleBeep(ear, i);
} else if (act === "alt") {
const i = Number(btn.dataset.i);
if (!Number.isFinite(i)) return;
runAltSequence(btn, i);
} else if (act === "both") {
const i = Number(btn.dataset.i);
if (!Number.isFinite(i)) return;
if (bothPlayers.has(i)) stopBoth(i, btn);
else startBoth(i, btn);
} else if (act === "play-all") {
const ear = btn.dataset.ear;
if (ear !== "L" && ear !== "R") return;
startBatchSingle(ear, btn);
} else if (act === "alt-all") {
startBatchAlt(btn);
} else if (act === "nudge") {
const i = Number(btn.dataset.i);
const delta = Math.round(Number(btn.dataset.delta) || 0);
if (!Number.isFinite(i) || !delta) return;
nudgeNonCi(i, delta);
}
// other actions will be implemented later
}
// Global keyboard shortcuts (ignore when typing or help is open)
function blurIfNudgeFocused() {
const ae = document.activeElement;
if (!ae) return;
// Only act on buttons inside the frequency alignment table
const inTable = typeof ae.closest === "function" && ae.closest(".fat");
if (
inTable &&
ae.tagName === "BUTTON" &&
ae.classList &&
ae.classList.contains("btn-icon")
) {
try {
ae.blur();
} catch {}
}
}
document.addEventListener("keydown", (e) => {
const help = document.getElementById("helpView");
const viz = document.getElementById("vizView");
if (help && !help.classList.contains("hidden")) return;
if (viz && !viz.classList.contains("hidden")) return;
const t = e.target;
const tag = t && t.tagName ? t.tagName.toLowerCase() : "";
const isEditable =
tag === "input" ||
tag === "textarea" ||
tag === "select" ||
(t && t.isContentEditable);
if (isEditable) return;
if (lastActiveRow == null) return;
const key = (e.key || "").toLowerCase();
const code = e.code || "";
// ASDF: nudge non-CI ear
if (key === "a") {
nudgeNonCi(lastActiveRow, -10);
e.preventDefault();
blurIfNudgeFocused();
return;
}
if (key === "s") {
nudgeNonCi(lastActiveRow, -1);
e.preventDefault();
blurIfNudgeFocused();
return;
}
if (key === "d") {
nudgeNonCi(lastActiveRow, +1);
e.preventDefault();
blurIfNudgeFocused();
return;
}
if (key === "f") {
nudgeNonCi(lastActiveRow, +10);
e.preventDefault();
blurIfNudgeFocused();
return;
}
// J/K/L/Semicolon: speakers
if (key === "j") {
playSingleBeep("L", lastActiveRow);
e.preventDefault();
blurIfNudgeFocused();
return;
}
if (key === "k") {
playSingleBeep("R", lastActiveRow);
e.preventDefault();