-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
4563 lines (3917 loc) · 145 KB
/
app.js
File metadata and controls
4563 lines (3917 loc) · 145 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
(function buildChipRollApp() {
const root = document.getElementById("piano-roll-root");
const patternRackRoot = document.getElementById("pattern-rack");
const songLaneRoot = document.getElementById("song-lane");
const SONG_DRAG_RACK_MIME = "application/x-chiproll-rack-pattern";
const SONG_DRAG_REORDER_MIME = "application/x-chiproll-song-index";
const chipSelect = document.getElementById("chip-select");
const heroTitle = document.getElementById("hero-title");
const heroCopy = document.getElementById("hero-copy");
const heroChip = document.getElementById("hero-chip");
const panelTitle = document.getElementById("panel-title");
const playButton = document.getElementById("play-button");
const stopButton = document.getElementById("stop-button");
const loopButton = document.getElementById("loop-button");
const countdownButton = document.getElementById("countdown-button");
const clearButton = document.getElementById("clear-button");
const bpmInput = document.getElementById("bpm-input");
const stepCountSelect = document.getElementById("step-count-select");
const modePatternButton = document.getElementById("mode-pattern-button");
const modeSongButton = document.getElementById("mode-song-button");
const saveButton = document.getElementById("save-button");
const loadButton = document.getElementById("load-button");
const loadFileInput = document.getElementById("load-file-input");
const importButton = document.getElementById("import-button");
const midiDeviceWrap = document.getElementById("midi-device-wrap");
const midiDeviceSelect = document.getElementById("midi-device-select");
const SESSION_FILE_VERSION = 1;
const importOverlay = document.getElementById("import-overlay");
const importClose = document.getElementById("import-close");
const importDropZone = document.getElementById("import-drop-zone");
const importFileInput = document.getElementById("import-file-input");
const importStatus = document.getElementById("import-status");
const importControls = document.getElementById("import-controls");
const voiceStrategySelect = document.getElementById("voice-strategy-select");
const importPatternLengthSelect = document.getElementById("import-pattern-length-select");
const importSummary = document.getElementById("import-summary");
const importTracksList = document.getElementById("import-tracks");
const importUnassignedList = document.getElementById("import-unassigned");
const importCancel = document.getElementById("import-cancel");
const importConfirm = document.getElementById("import-confirm");
const {
TIA_TIMBRE_OPTIONS,
POKEY_TIMBRE_OPTIONS,
getNearestNote,
getNearestPokeyNote,
getTiaFrequencyTable,
} = window.FrequencyEngine;
const { parseMidi } = window.MidiParser;
const { quantizeTrack } = window.Quantizer;
const { reduceTrack } = window.VoiceReducer;
const { splitNotesIntoChunks } = window.NoteSplitter;
const { computeImportTimingAdjustment } = window.ImportTiming;
const { PERSONALITIES, getGmFamily } = window.GmMapping;
const { assignTracks } = window.TrackAssigner;
const VOICE_STRATEGIES = ["highest", "lowest", "last"];
const NES_CHANNEL_LABELS = {
pulse1: "Pulse 1",
pulse2: "Pulse 2",
triangle: "Triangle",
noise: "Noise",
};
const TIA_CHANNEL_LABELS = {
tia1: "TIA Ch.1",
tia2: "TIA Ch.2",
};
const POKEY_CHANNEL_LABELS = {
pokey1: "POKEY Ch.1",
pokey2: "POKEY Ch.2",
pokey3: "POKEY Ch.3",
pokey4: "POKEY Ch.4",
};
const STEP_COUNT_OPTIONS = [8, 16, 32];
const BPM_MIN = 40;
const BPM_MAX = 300;
const PREVIEW_DURATION_SECONDS = 0.15;
const ATTACK_SECONDS = 0.005;
const RELEASE_SECONDS = 0.05;
const CHIP_OPTIONS = {
NES: {
heroTitle: "ChipRoll - NES / Famicom",
heroCopy:
"Four separate NES channels, 16 steps and instant playback. Pulse 1 / Pulse 2 / Triangle are pitched; Noise is percussive.",
heroChip: "NES / Famicom",
panelTitle: "Pulse 1 / Pulse 2 / Triangle / Noise",
},
TIA: {
heroTitle: "ChipRoll - Atari TIA",
heroCopy:
"Two TIA channels with per-lane selectable timbre. Each timbre shows only the pitches physically available on the chip.",
heroChip: "Atari TIA",
panelTitle: "TIA Ch.1 / TIA Ch.2",
},
POKEY: {
heroTitle: "ChipRoll - Atari POKEY",
heroCopy:
"Four POKEY channels across 5 octaves (B2-B7). Each channel has a per-pattern timbre (Pure tone / Buzz / Noise) — to switch timbre on the same channel mid-song, use a separate pattern.",
heroChip: "Atari POKEY",
panelTitle: "POKEY Ch.1 / Ch.2 / Ch.3 / Ch.4",
},
};
const NES_CHANNEL_DEFS = [
{
id: "pulse1",
name: "Pulse 1",
chip: "NES_PULSE",
profile: "NES",
kind: "pitched",
waveform: "square",
laneClass: "pulse",
rowLabel: "Note / Step",
supportsIntonation: true,
rows: buildNoteRange("C2", "C7"),
},
{
id: "pulse2",
name: "Pulse 2",
chip: "NES_PULSE",
profile: "NES",
kind: "pitched",
waveform: "square",
laneClass: "pulse",
rowLabel: "Note / Step",
supportsIntonation: true,
rows: buildNoteRange("C2", "C7"),
},
{
id: "triangle",
name: "Triangle",
chip: "NES_TRIANGLE",
profile: "NES",
kind: "pitched",
waveform: "triangle",
laneClass: "triangle",
rowLabel: "Note / Step",
supportsIntonation: true,
rows: buildNoteRange("C1", "C6"),
},
{
id: "noise",
name: "Noise",
chip: "NES_NOISE",
profile: "NES",
kind: "noise",
waveform: "noise",
laneClass: "noise",
rowLabel: "Level / Step",
supportsIntonation: false,
rows: buildNoiseRows(),
},
];
const TIA_CHANNEL_DEFS = [
{ id: "tia1", name: "TIA Ch.1", profile: "TIA" },
{ id: "tia2", name: "TIA Ch.2", profile: "TIA" },
];
// POKEY: 4 canali con stesso range musicale (clock fisso 64 kHz su tutti).
// rows e' pre-calcolato qui (note continue, NES-style) — il timbre cambia
// solo come l'audio synth e il chip interpretano AUDC, non i pitch.
const POKEY_CHANNEL_DEFS = [
{ id: "pokey1", name: "POKEY Ch.1", profile: "POKEY", rows: buildNoteRange("C2", "C7") },
{ id: "pokey2", name: "POKEY Ch.2", profile: "POKEY", rows: buildNoteRange("C2", "C7") },
{ id: "pokey3", name: "POKEY Ch.3", profile: "POKEY", rows: buildNoteRange("C2", "C7") },
{ id: "pokey4", name: "POKEY Ch.4", profile: "POKEY", rows: buildNoteRange("C2", "C7") },
];
// Pattern-aware state (Step 1 del refactor patterns/song).
// - patterns: dict { [id]: Pattern }, dove Pattern = { id, label, stepCount, channels: { [id]: { notes: Map, audc? } } }
// - channelGlobals: mixer state (muted/solo/collapsed) trasversale a tutti i pattern.
// - patternOrder: ordine dei pattern nel rack (puo' divergere da song).
// - song: sequenza di patternId per Song mode.
// - currentPatternId / transportMode: stato di edit/playback, salvati nel JSON.
const appState = {
activeChip: "NES",
tiaRowsByAudc: {},
bpm: 120,
loop: false,
countdown: false,
patterns: {},
patternOrder: [],
song: [],
currentPatternId: null,
transportMode: "pattern",
channelGlobals: {},
};
// MIDI input state. Single-target model: at most one channel has any MIDI
// role active. play/rec possono essere entrambi su quel canale ma cliccare
// un ruolo su un altro canale azzera lo stato del canale precedente.
const MIDI_DEVICE_KEY = "chiproll.midi.deviceId";
const midi = {
supported: typeof navigator !== "undefined" && typeof navigator.requestMIDIAccess === "function",
access: null,
inputs: [],
selectedInputId: null,
selectedInput: null,
playChannelId: null,
recChannelId: null,
activePlayVoices: new Map(),
activeRecHolds: new Map(),
};
// Counter per la generazione di ID pattern (P1, P2, ...). Non si decrementa mai
// alla delete per evitare collisioni con pattern referenziati nella song.
let patternIdCounter = 0;
function nextPatternId() {
patternIdCounter += 1;
return `P${patternIdCounter}`;
}
function currentPattern() {
return appState.patterns[appState.currentPatternId];
}
function currentStepCount() {
const pattern = currentPattern();
return pattern ? pattern.stepCount : 16;
}
function channelData(channelId, patternId = appState.currentPatternId) {
const pattern = appState.patterns[patternId];
return pattern ? pattern.channels[channelId] : undefined;
}
function channelMixer(channelId) {
return appState.channelGlobals[channelId];
}
function getChannelIds() {
return Object.keys(appState.channelGlobals);
}
// Pattern in edit-label inline. null = nessun pattern in editing.
// Quando settato, renderPatternRack() disegna un <input> al posto della pill.
let editingPatternLabelId = null;
function renderPatternRack() {
patternRackRoot.innerHTML = "";
const onlyOnePattern = appState.patternOrder.length === 1;
for (const patternId of appState.patternOrder) {
const pattern = appState.patterns[patternId];
const isActive = patternId === appState.currentPatternId;
const isEditing = patternId === editingPatternLabelId;
if (isEditing) {
patternRackRoot.appendChild(renderPatternLabelInput(pattern));
continue;
}
const pill = document.createElement("button");
pill.type = "button";
pill.className = `pattern-pill ${isActive ? "active" : ""}`.trim();
pill.setAttribute("role", "tab");
pill.setAttribute("aria-selected", String(isActive));
pill.dataset.patternId = patternId;
pill.draggable = true;
pill.addEventListener("dragstart", (event) => {
event.dataTransfer.effectAllowed = "copy";
event.dataTransfer.setData(SONG_DRAG_RACK_MIME, patternId);
pill.classList.add("dragging");
});
pill.addEventListener("dragend", () => {
pill.classList.remove("dragging");
});
const idSpan = document.createElement("span");
idSpan.className = "pattern-pill-id";
idSpan.textContent = patternId;
pill.appendChild(idSpan);
if (pattern.label) {
const labelSpan = document.createElement("span");
labelSpan.className = "pattern-pill-label";
labelSpan.textContent = pattern.label;
pill.appendChild(labelSpan);
}
const deleteButton = document.createElement("button");
deleteButton.type = "button";
deleteButton.className = "pattern-pill-delete";
deleteButton.setAttribute("aria-label", `Delete pattern ${patternId}`);
deleteButton.textContent = "×";
if (onlyOnePattern) {
deleteButton.disabled = true;
}
deleteButton.addEventListener("click", (event) => {
// Stop propagation: il click sulla X non deve switchare al pattern.
event.stopPropagation();
deletePattern(patternId);
});
pill.appendChild(deleteButton);
pill.addEventListener("click", () => switchPattern(patternId));
pill.addEventListener("dblclick", (event) => {
event.preventDefault();
editingPatternLabelId = patternId;
renderPatternRack();
});
patternRackRoot.appendChild(pill);
}
const addButton = document.createElement("button");
addButton.type = "button";
addButton.className = "pattern-rack-add";
addButton.setAttribute("aria-label", "Add pattern");
addButton.textContent = "+";
addButton.addEventListener("click", createPattern);
patternRackRoot.appendChild(addButton);
}
function renderPatternLabelInput(pattern) {
const input = document.createElement("input");
input.type = "text";
input.className = "pattern-pill-label-input";
input.value = pattern.label || "";
input.placeholder = pattern.id;
input.setAttribute("aria-label", `Rename ${pattern.id}`);
input.maxLength = 32;
const commit = () => {
const value = input.value.trim();
pattern.label = value === "" ? null : value;
editingPatternLabelId = null;
renderPatternRack();
};
const cancel = () => {
editingPatternLabelId = null;
renderPatternRack();
};
input.addEventListener("keydown", (event) => {
if (event.key === "Enter") {
event.preventDefault();
commit();
} else if (event.key === "Escape") {
event.preventDefault();
cancel();
}
});
input.addEventListener("blur", commit);
// Focus + select dopo il mount nel DOM (microtask).
queueMicrotask(() => {
input.focus();
input.select();
});
return input;
}
function renderSongLane() {
songLaneRoot.innerHTML = "";
const label = document.createElement("span");
label.className = "song-lane-label";
label.textContent = "Song";
songLaneRoot.appendChild(label);
if (appState.song.length === 0) {
const empty = document.createElement("span");
empty.className = "song-lane-empty";
empty.textContent = "Drag patterns here to build the song";
songLaneRoot.appendChild(empty);
}
for (let i = 0; i < appState.song.length; i += 1) {
songLaneRoot.appendChild(renderSongSlot(i));
}
songLaneRoot.appendChild(renderSongTail());
}
function renderSongSlot(index) {
const patternId = appState.song[index];
const pattern = appState.patterns[patternId];
const slot = document.createElement("span");
slot.className = "song-lane-slot";
slot.dataset.songIndex = String(index);
const indicator = document.createElement("span");
indicator.className = "song-drop-indicator";
slot.appendChild(indicator);
const pill = document.createElement("span");
const isPlayingHere = index === activeSongIndex;
pill.className = `song-pill ${isPlayingHere ? "playing" : ""}`.trim();
pill.setAttribute("role", "listitem");
pill.draggable = true;
pill.dataset.songIndex = String(index);
const idSpan = document.createElement("span");
idSpan.className = "song-pill-id";
idSpan.textContent = patternId;
pill.appendChild(idSpan);
if (pattern && pattern.label) {
const labelSpan = document.createElement("span");
labelSpan.className = "pattern-pill-label";
labelSpan.textContent = pattern.label;
pill.appendChild(labelSpan);
}
const deleteButton = document.createElement("button");
deleteButton.type = "button";
deleteButton.className = "song-pill-delete";
deleteButton.setAttribute("aria-label", `Remove ${patternId} at position ${index + 1}`);
deleteButton.textContent = "×";
deleteButton.addEventListener("click", (event) => {
event.stopPropagation();
removeSongEntryAt(index);
});
deleteButton.addEventListener("mousedown", (event) => {
// Evita che il mousedown sulla X faccia partire il drag del pill.
event.stopPropagation();
});
pill.appendChild(deleteButton);
pill.addEventListener("dragstart", (event) => {
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.setData(SONG_DRAG_REORDER_MIME, String(index));
pill.classList.add("dragging");
});
pill.addEventListener("dragend", () => {
pill.classList.remove("dragging");
});
slot.appendChild(pill);
slot.addEventListener("dragover", (event) => {
if (!hasSongPayload(event)) {
return;
}
event.preventDefault();
event.dataTransfer.dropEffect = isRackPayload(event) ? "copy" : "move";
clearSongDropIndicators();
slot.classList.add("drop-before");
});
slot.addEventListener("dragleave", (event) => {
if (event.currentTarget.contains(event.relatedTarget)) {
return;
}
slot.classList.remove("drop-before");
});
slot.addEventListener("drop", (event) => {
if (!hasSongPayload(event)) {
return;
}
event.preventDefault();
slot.classList.remove("drop-before");
handleSongDrop(event, index);
});
return slot;
}
function renderSongTail() {
const tail = document.createElement("span");
tail.className = "song-lane-tail";
const indicator = document.createElement("span");
indicator.className = "song-drop-indicator";
tail.appendChild(indicator);
tail.addEventListener("dragover", (event) => {
if (!hasSongPayload(event)) {
return;
}
event.preventDefault();
event.dataTransfer.dropEffect = isRackPayload(event) ? "copy" : "move";
clearSongDropIndicators();
tail.classList.add("drop-active");
});
tail.addEventListener("dragleave", (event) => {
if (event.currentTarget.contains(event.relatedTarget)) {
return;
}
tail.classList.remove("drop-active");
});
tail.addEventListener("drop", (event) => {
if (!hasSongPayload(event)) {
return;
}
event.preventDefault();
tail.classList.remove("drop-active");
handleSongDrop(event, appState.song.length);
});
return tail;
}
function hasSongPayload(event) {
const types = Array.from(event.dataTransfer.types || []);
return types.includes(SONG_DRAG_RACK_MIME) || types.includes(SONG_DRAG_REORDER_MIME);
}
function isRackPayload(event) {
// I browser bloccano getData() in dragover; types resta accessibile, quindi
// discriminiamo source via MIME distinta (rack vs song-reorder).
return Array.from(event.dataTransfer.types || []).includes(SONG_DRAG_RACK_MIME);
}
function clearSongDropIndicators() {
const slots = songLaneRoot.querySelectorAll(".song-lane-slot.drop-before");
slots.forEach((s) => s.classList.remove("drop-before"));
const tails = songLaneRoot.querySelectorAll(".song-lane-tail.drop-active");
tails.forEach((t) => t.classList.remove("drop-active"));
}
function handleSongDrop(event, targetIndex) {
const rackPatternId = event.dataTransfer.getData(SONG_DRAG_RACK_MIME);
if (rackPatternId) {
if (!appState.patterns[rackPatternId]) {
return;
}
appState.song.splice(targetIndex, 0, rackPatternId);
render();
return;
}
const reorderRaw = event.dataTransfer.getData(SONG_DRAG_REORDER_MIME);
if (reorderRaw === "") {
return;
}
const fromIndex = Number(reorderRaw);
if (!Number.isInteger(fromIndex) || fromIndex < 0 || fromIndex >= appState.song.length) {
return;
}
// Drop su se stesso o subito dopo se stesso: no-op.
if (targetIndex === fromIndex || targetIndex === fromIndex + 1) {
return;
}
const [moved] = appState.song.splice(fromIndex, 1);
const adjustedTarget = targetIndex > fromIndex ? targetIndex - 1 : targetIndex;
appState.song.splice(adjustedTarget, 0, moved);
render();
}
function removeSongEntryAt(index) {
if (index < 0 || index >= appState.song.length) {
return;
}
appState.song.splice(index, 1);
render();
}
function switchPattern(id) {
if (id === appState.currentPatternId) {
return;
}
if (!appState.patterns[id]) {
return;
}
stopPlayback();
appState.currentPatternId = id;
render();
}
function createPattern() {
// Eredita stepCount del pattern corrente (decisione D1.opt1).
// Note vuote, AUDC TIA al default (12).
const inheritedStepCount = currentStepCount();
const newId = nextPatternId();
appState.patterns[newId] = createEmptyPattern(newId, appState.activeChip, inheritedStepCount);
appState.patternOrder.push(newId);
appState.song.push(newId);
stopPlayback();
appState.currentPatternId = newId;
render();
}
function duplicatePattern(sourceId) {
const source = appState.patterns[sourceId];
if (!source) {
return;
}
const newId = nextPatternId();
// Deep clone canali + note. Le note sono oggetti plain; spread basta.
const channels = {};
for (const [chId, chData] of Object.entries(source.channels)) {
const notesMap = new Map();
for (const [key, entry] of chData.notes.entries()) {
notesMap.set(key, { ...entry });
}
const out = { notes: notesMap };
if (chData.audc !== undefined) {
out.audc = chData.audc;
}
channels[chId] = out;
}
appState.patterns[newId] = {
id: newId,
label: null,
stepCount: source.stepCount,
channels,
};
// Inserisce subito dopo il source nel rack; appende alla song
// (coerente con createPattern).
const orderIdx = appState.patternOrder.indexOf(sourceId);
if (orderIdx === -1) {
appState.patternOrder.push(newId);
} else {
appState.patternOrder.splice(orderIdx + 1, 0, newId);
}
appState.song.push(newId);
stopPlayback();
appState.currentPatternId = newId;
render();
}
function goToAdjacentPattern(direction) {
const order = appState.patternOrder;
if (order.length <= 1) {
return;
}
const idx = order.indexOf(appState.currentPatternId);
if (idx === -1) {
return;
}
const nextIdx = (idx + direction + order.length) % order.length;
switchPattern(order[nextIdx]);
}
function deletePattern(id) {
if (appState.patternOrder.length <= 1) {
return;
}
if (!appState.patterns[id]) {
return;
}
const songRefs = appState.song.filter((pid) => pid === id).length;
if (songRefs > 0) {
const confirmed = window.confirm(
`Pattern ${id} is used ${songRefs} time${songRefs === 1 ? "" : "s"} in the song. Delete and remove from song?`,
);
if (!confirmed) {
return;
}
}
appState.song = appState.song.filter((pid) => pid !== id);
appState.patternOrder = appState.patternOrder.filter((pid) => pid !== id);
delete appState.patterns[id];
if (appState.currentPatternId === id) {
appState.currentPatternId = appState.patternOrder[0];
stopPlayback();
}
render();
}
const DEFAULT_IMPORT_PATTERN_LENGTH = 32;
const VALID_IMPORT_PATTERN_LENGTHS = new Set([8, 16, 32]);
const importSession = {
parsedSong: null,
result: null,
overrides: new Map(),
voiceStrategy: "highest",
patternLength: DEFAULT_IMPORT_PATTERN_LENGTH,
};
let audioContext = null;
let cachedNoiseBuffer = null;
let isPlaying = false;
let playbackCleanupTimerId = null;
let playheadTimerIds = [];
let activeStep = null;
let activeSongIndex = null;
let copiedExportId = null;
let copiedExportTimerId = null;
let dragState = null;
let suppressNextClick = false;
const DRAG_THRESHOLD_PX = 4;
const dragPreviewCells = new Set();
const activeVoices = new Set();
resetChannelsForChip("NES");
playButton.addEventListener("click", () => {
void startPlayback();
});
stopButton.addEventListener("click", () => {
stopPlayback();
});
loopButton.addEventListener("click", () => {
appState.loop = !appState.loop;
updateLoopButtonVisual();
});
countdownButton.addEventListener("click", () => {
appState.countdown = !appState.countdown;
updateCountdownButtonVisual();
});
clearButton.addEventListener("click", () => {
clearAllNotes();
});
bpmInput.addEventListener("change", (event) => {
handleBpmChange(event);
});
stepCountSelect.addEventListener("change", (event) => {
handleStepCountChange(event);
});
modePatternButton.addEventListener("click", () => setTransportMode("pattern"));
modeSongButton.addEventListener("click", () => setTransportMode("song"));
saveButton.addEventListener("click", handleSaveSession);
loadButton.addEventListener("click", () => loadFileInput.click());
loadFileInput.addEventListener("change", (event) => {
void handleLoadFileSelected(event);
});
importButton.addEventListener("click", openImportPanel);
importClose.addEventListener("click", closeImportPanel);
importCancel.addEventListener("click", closeImportPanel);
importConfirm.addEventListener("click", handleConfirmImport);
importFileInput.addEventListener("change", (event) => {
void handleImportFileSelected(event);
});
importDropZone.addEventListener("click", () => importFileInput.click());
importDropZone.addEventListener("dragover", handleDragOver);
importDropZone.addEventListener("dragleave", handleDragLeave);
importDropZone.addEventListener("drop", (event) => {
void handleFileDrop(event);
});
voiceStrategySelect.addEventListener("change", (event) => {
handleVoiceStrategyChange(event.target.value);
});
importPatternLengthSelect.addEventListener("change", (event) => {
handleImportPatternLengthChange(event.target.value);
});
chipSelect.addEventListener("change", (event) => {
void handleChipChange(event.target.value);
});
document.addEventListener("keydown", (event) => {
void handleGlobalKeydown(event);
});
document.addEventListener("mousemove", handleDocumentMouseMove);
document.addEventListener("mouseup", (event) => {
if (event.button !== 0 || !dragState) {
return;
}
const mode = dragState.mode;
if (mode === "pending") {
// Sotto soglia: trattato come click puro, lascio fare al click handler.
cleanupDragPreviewVisuals();
dragState = null;
return;
}
if (mode === "create") {
const moved = dragState.startStep !== dragState.currentStep;
if (moved) {
suppressClickBriefly();
void finalizeDragCreate();
} else {
// Threshold attraversata ma cella invariata (wobble): cleanup e lascio
// che il click handler faccia il toggleCell come per un single-click.
cleanupDragPreviewVisuals();
dragState = null;
}
return;
}
if (mode === "move-block") {
suppressClickBriefly();
finalizeMoveBlock();
return;
}
if (mode === "move-pitch") {
suppressClickBriefly();
finalizeMovePitch();
return;
}
});
function suppressClickBriefly() {
suppressNextClick = true;
setTimeout(() => {
suppressNextClick = false;
}, 0);
}
chipSelect.value = appState.activeChip;
bpmInput.value = String(appState.bpm);
stepCountSelect.value = String(currentStepCount());
updateTransportState();
updateLoopButtonVisual();
updateCountdownButtonVisual();
updateTransportModeVisual();
render();
void initMidi();
window.ChipRoll = window.ChipRoll || {};
window.ChipRoll.parseMidi = parseMidi;
window.ChipRoll.runImportPipeline = runImportPipeline;
window.ChipRoll.applyImportToPianoRoll = applyImportToPianoRoll;
window.ChipRoll.readFileAsArrayBuffer = readFileAsArrayBuffer;
window.ChipRoll.openImportPanel = openImportPanel;
window.ChipRoll.getImportSession = () => ({
parsedSong: importSession.parsedSong,
result: importSession.result,
overrides: Object.fromEntries(importSession.overrides),
voiceStrategy: importSession.voiceStrategy,
patternLength: importSession.patternLength,
});
function render() {
// stepCount e' per-pattern: switchando pattern, il select del transport
// riflette il valore del nuovo pattern attivo.
stepCountSelect.value = String(currentStepCount());
renderPatternRack();
renderSongLane();
root.innerHTML = "";
updateHeaderCopy();
const channelsStack = document.createElement("div");
channelsStack.className = "channels-stack";
for (const channel of getCurrentChannels()) {
channelsStack.appendChild(renderChannel(channel));
}
root.appendChild(channelsStack);
root.appendChild(renderExportSection());
}
function updateHeaderCopy() {
const copy = CHIP_OPTIONS[appState.activeChip];
heroTitle.textContent = copy.heroTitle;
heroCopy.textContent = copy.heroCopy;
heroChip.textContent = copy.heroChip;
panelTitle.textContent = copy.panelTitle;
}
function renderChannel(channel) {
const data = channelData(channel.id);
const mixer = channelMixer(channel.id);
const lane = document.createElement("section");
lane.className = `channel-lane lane-${channel.laneClass} ${mixer.collapsed ? "collapsed" : ""}`.trim();
const laneHeader = document.createElement("div");
laneHeader.className = "channel-header";
const laneTitle = document.createElement("div");
laneTitle.className = "channel-title";
const laneEyebrow = document.createElement("p");
laneEyebrow.className = "channel-label";
laneEyebrow.textContent = channel.kind === "noise" ? "Percussion" : "Pitched";
const laneName = document.createElement("h3");
laneName.textContent = (channel.profile === "TIA" || channel.profile === "POKEY")
? `${channel.name} - ${channel.timbreLabel}`
: channel.name;
laneTitle.appendChild(laneEyebrow);
laneTitle.appendChild(laneName);
const laneControls = document.createElement("div");
laneControls.className = "channel-controls";
const collapseButton = document.createElement("button");
collapseButton.type = "button";
collapseButton.className = "lane-button collapse-button";
collapseButton.textContent = mixer.collapsed ? "^" : "v";
collapseButton.setAttribute(
"aria-label",
mixer.collapsed ? `Expand ${channel.name}` : `Collapse ${channel.name}`,
);
collapseButton.addEventListener("click", () => toggleCollapsed(channel.id));
laneControls.appendChild(collapseButton);
if (channel.profile === "TIA" || channel.profile === "POKEY") {
laneControls.appendChild(renderTimbreSelect(channel, data));
}
const muteButton = document.createElement("button");
muteButton.type = "button";
muteButton.className = `lane-button ${mixer.muted ? "active" : ""}`.trim();
muteButton.textContent = "Mute";
muteButton.addEventListener("click", () => toggleMute(channel.id));
const soloButton = document.createElement("button");
soloButton.type = "button";
soloButton.className = `lane-button ${mixer.solo ? "active" : ""}`.trim();
soloButton.textContent = "Solo";
soloButton.addEventListener("click", () => toggleSolo(channel.id));
laneControls.appendChild(muteButton);
laneControls.appendChild(soloButton);
if (channel.kind !== "noise") {
const midiAvailable = !!midi.selectedInputId;
const isMidiPlay = midi.playChannelId === channel.id;
const isMidiRec = midi.recChannelId === channel.id;
const midiPlayButton = document.createElement("button");
midiPlayButton.type = "button";
midiPlayButton.className = `lane-button midi-button midi-play ${isMidiPlay ? "active" : ""}`.trim();
midiPlayButton.textContent = "MIDI▶";
midiPlayButton.title = midiAvailable
? `Route MIDI input to ${channel.name} (live monitor)`
: "Connect a MIDI controller and pick a device to enable";
midiPlayButton.disabled = !midiAvailable;
midiPlayButton.addEventListener("click", () => setMidiPlay(channel.id));
const midiRecButton = document.createElement("button");
midiRecButton.type = "button";
midiRecButton.className = `lane-button midi-button midi-rec ${isMidiRec ? "active" : ""}`.trim();
midiRecButton.textContent = "MIDI●";
midiRecButton.title = midiAvailable
? `Arm ${channel.name} for MIDI punch-in recording (during transport Play)`
: "Connect a MIDI controller and pick a device to enable";
midiRecButton.disabled = !midiAvailable;
midiRecButton.addEventListener("click", () => setMidiRec(channel.id));
laneControls.appendChild(midiPlayButton);
laneControls.appendChild(midiRecButton);
}
if (channel.kind !== "noise") {
const octDownButton = document.createElement("button");
octDownButton.type = "button";
octDownButton.className = "lane-button shift-button";
octDownButton.textContent = "Oct↓";
octDownButton.title = `Octave down (${channel.name})`;
octDownButton.addEventListener("click", () => shiftChannelNotes(channel.id, "octave", -1));
const octUpButton = document.createElement("button");
octUpButton.type = "button";
octUpButton.className = "lane-button shift-button";
octUpButton.textContent = "Oct↑";
octUpButton.title = `Octave up (${channel.name})`;
octUpButton.addEventListener("click", () => shiftChannelNotes(channel.id, "octave", +1));
const trDownButton = document.createElement("button");
trDownButton.type = "button";
trDownButton.className = "lane-button shift-button";
trDownButton.textContent = "Tr↓";
trDownButton.title = channel.profile === "TIA"
? `Shift 1 row down (${channel.name})`
: `Transpose 1 semitone down (${channel.name})`;
trDownButton.addEventListener("click", () => shiftChannelNotes(channel.id, "semitone", -1));
const trUpButton = document.createElement("button");
trUpButton.type = "button";
trUpButton.className = "lane-button shift-button";
trUpButton.textContent = "Tr↑";
trUpButton.title = channel.profile === "TIA"
? `Shift 1 row up (${channel.name})`
: `Transpose 1 semitone up (${channel.name})`;
trUpButton.addEventListener("click", () => shiftChannelNotes(channel.id, "semitone", +1));
laneControls.appendChild(octDownButton);
laneControls.appendChild(octUpButton);
laneControls.appendChild(trDownButton);
laneControls.appendChild(trUpButton);
}
laneHeader.appendChild(laneTitle);
laneHeader.appendChild(laneControls);
lane.appendChild(laneHeader);
if (mixer.collapsed) {
lane.appendChild(renderCollapsedSummary(channel.id));
} else {
lane.appendChild(renderGrid(channel, data));
}
return lane;
}
function renderCollapsedSummary(channelId) {
const summary = document.createElement("div");
summary.className = "collapsed-summary";
const noteCount = channelData(channelId).notes.size;
summary.textContent = noteCount === 0
? "Lane collapsed. No notes."
: `Lane collapsed. ${noteCount} note${noteCount === 1 ? "" : "s"}.`;
return summary;
}