-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2931 lines (2585 loc) · 103 KB
/
Copy pathapp.js
File metadata and controls
2931 lines (2585 loc) · 103 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';
// ═══════════════════════════════════════════════════════════
// CONSTANTS
// ═══════════════════════════════════════════════════════════
const CHROMATIC = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B'];
const NUM_ROWS = 13; // one octave inclusive (e.g. C4 → C5)
const STEPS = 16;
const NODE_STACK_SPACING = 52; // px between node centres in a chord stack
// ─── Drum Sequencer Constants ───────────────────────────────
const DRUM_BASE = 'audio/';
const DRUM_INSTRUMENTS = [
{ label: 'Perc', abbr: 'Pe', url: DRUM_BASE + 'trbotperc.mp3' },
{ label: 'HH2', abbr: 'H2', url: DRUM_BASE + 'trbothh2.mp3' },
{ label: 'HH1', abbr: 'H1', url: DRUM_BASE + 'trbothh1.mp3' },
{ label: 'Snare', abbr: 'Sn', url: DRUM_BASE + 'trbotsnare.mp3' },
{ label: 'Clap', abbr: 'Cl', url: DRUM_BASE + 'trbotclap.mp3' },
{ label: 'Kick', abbr: 'Kk', url: DRUM_BASE + 'trbotkick.mp3' },
];
const NUM_DRUM_ROWS = 6;
// ═══════════════════════════════════════════════════════════
// PITCH STATE — drives NOTES / NOTE_LABELS dynamically
// ═══════════════════════════════════════════════════════════
let octaveOffset = 0; // -2 … +2 (shifts the displayed octave)
let rootSemitone = 0; // 0=C … 11=B (starting note of the scale)
/** 13 note names, highest (row 0) to lowest (row 12). */
function getCurrentNotes() {
const baseOctave = 4 + octaveOffset;
const notes = [];
for (let i = NUM_ROWS - 1; i >= 0; i--) {
const semitone = (rootSemitone + i) % 12;
const octave = baseOctave + Math.floor((rootSemitone + i) / 12);
notes.push(`${CHROMATIC[semitone]}${octave}`);
}
return notes;
}
/** Display labels: top and bottom rows show octave number, middle rows omit it. */
function getCurrentNoteLabels() {
return getCurrentNotes().map((note, i) =>
(i === 0 || i === NUM_ROWS - 1) ? note : note.replace(/\d+$/, '')
);
}
let NOTES = getCurrentNotes();
let NOTE_LABELS = getCurrentNoteLabels();
// ═══════════════════════════════════════════════════════════
// AUTOMATION PARAMS CONFIG
// ═══════════════════════════════════════════════════════════
const AUTO_PARAMS = [
{
id: 'flt-freq', label: 'Freq', color: '#4da6ff',
min: 0, max: 100, step: 1, default: 75,
format: v => formatFreq(freqFromSlider(v)),
apply: v => { if (filter) filter.frequency.value = freqFromSlider(v); },
},
{
id: 'flt-q', label: 'Res', color: '#a78bfa',
min: 0.1, max: 12, step: 0.1, default: 1,
format: v => v.toFixed(1),
apply: v => { if (filter) filter.Q.value = v; },
},
{
id: 'rvb-send', label: 'Send', color: '#34d399',
min: 0, max: 0.8, step: 0.01, default: 0,
format: v => v.toFixed(2),
apply: v => { if (reverbSend) reverbSend.gain.value = v; },
},
{
id: 'rvb-decay', label: 'Len', color: '#22d3ee',
min: 0.1, max: 10, step: 0.1, default: 2,
format: v => v.toFixed(1) + 's',
apply: v => {
if (!reverb) return;
reverb.decay = v;
clearTimeout(reverbDecayAutoTimer);
reverbDecayAutoTimer = setTimeout(() => reverb.generate(), 500);
},
},
{
id: 'adsr-a', label: 'Atk', color: '#fbbf24',
min: 0.001, max: 2, step: 0.005, default: 0.01,
format: v => v.toFixed(2) + 's',
apply: v => setEnvelope('attack', v),
},
{
id: 'adsr-d', label: 'Dec', color: '#f97316',
min: 0.001, max: 2, step: 0.005, default: 0.1,
format: v => v.toFixed(2) + 's',
apply: v => setEnvelope('decay', v),
},
{
id: 'adsr-s', label: 'Sus', color: '#fb923c',
min: 0, max: 1, step: 0.01, default: 0.5,
format: v => v.toFixed(2),
apply: v => setEnvelope('sustain', v),
},
{
id: 'adsr-r', label: 'Rel', color: '#e879f9',
min: 0.001, max: 5, step: 0.01, default: 0.4,
format: v => v.toFixed(2) + 's',
apply: v => setEnvelope('release', v),
},
];
// ═══════════════════════════════════════════════════════════
// STATE
// ═══════════════════════════════════════════════════════════
// grid[row][step] = true/false (row 0 = highest note, row 12 = lowest)
const grid = {};
for (let r = 0; r < NUM_ROWS; r++) { grid[r] = new Array(STEPS).fill(false); }
// Drum state
const drumGrid = {};
const drumMuted = {};
const drumPlayers = {}; // Tone.Buffer instances — used only for URL loading
const drumBuffers = {}; // raw AudioBuffer per row — used for direct sample-accurate triggering
const drumOffsets = {}; // per-row leading-silence offset (seconds) to skip MP3 encoder delay
const drumTrackGain = {}; // raw GainNode per row — per-track volume control
const drumTrackVolume = {}; // 0..1 per row (mirrors drumTrackGain gain value for UI)
let drumBus = null; // Tone.Gain — routes all drum tracks through masterVol
// Whole-sequencer mutes
let notesMuted = false;
let drumSeqMuted = false;
for (let r = 0; r < NUM_DRUM_ROWS; r++) {
drumGrid[r] = new Array(STEPS).fill(false);
drumMuted[r] = false;
}
let drumPlaybackMode = 'forward';
let drumSeqPosition = 0;
let drumChordGroups = new Map();
let drumStepSequence = [];
let prevDrumPlayingNodes = [];
// chordGroups: Map<step, { notes, nodeIds, anchor, anchorId }>
let chordGroups = new Map();
// stepSequence: [{ step, notes, anchor, … }] in step order
let stepSequence = [];
let synth = null;
let filter = null;
let reverbSend = null;
let reverb = null;
let masterVol = null;
let loop = null;
let cy = null;
let isPlaying = false;
// Metronome
let metronomeEnabled = false;
let metronomeLoop = null;
let metronomeSynth = null;
let prevPlayingNodes = [];
// Automation sequencing state
const autoSeqs = {}; // paramId → Float64Array(16)
const autoActive = new Set(); // paramIds currently in seq mode
let activeTab = 'notes'; // 'notes' | paramId
const prevAutoPlayingNode = {}; // paramId → cy node | null
let reverbDecayAutoTimer = null;
let cellDragState = null; // { type: 'notes'|'drums', activating: bool } — drag-to-paint state
let playbackMode = 'forward'; // 'forward' | 'reverse' | 'pingpong'
let pendingPlaybackMode = null;
let activeStepArray = [];
let seqPosition = 0;
let prevStep = -1; // for ping-pong: detect duplicate turnaround steps
// ─── Pattern Bank State ──────────────────────────────────────
const notesPatterns = []; // Array of saved notes pattern objects
const drumPatterns = []; // Array of saved drum pattern objects
let activeNotesPatternId = null; // ID of currently active notes pattern (null = unsaved live)
let activeDrumPatternId = null;
let pendingNotesSwitch = null; // queued pattern ID, applied at loop boundary
let pendingDrumSwitch = null;
let notesNameCounter = 0; // for auto-naming: A, B, C, ...
let drumNameCounter = 0;
const MAX_NOTES_PATTERNS = 6;
const MAX_DRUM_PATTERNS = 6;
let deleteConfirmId = null; // pattern ID awaiting delete confirmation
let deleteConfirmTimer = null; // 2s timeout for delete confirm
// ═══════════════════════════════════════════════════════════
// PATTERN BANK — snapshot / restore / thumbnail
// ═══════════════════════════════════════════════════════════
function deepCopyGrid(src, rows) {
const copy = {};
for (let r = 0; r < rows; r++) copy[r] = src[r].slice();
return copy;
}
/** Capture the full notes synth scene into a pattern object. */
function snapshotNotesPattern() {
// Deep copy automation sequences
const seqsCopy = {};
for (const paramId in autoSeqs) {
seqsCopy[paramId] = new Float64Array(autoSeqs[paramId]);
}
// Read current slider / button states from DOM
const fltFreqEl = document.getElementById('flt-freq');
const fltQEl = document.getElementById('flt-q');
const rvbSendEl = document.getElementById('rvb-send');
const rvbDecEl = document.getElementById('rvb-decay');
const adsrAEl = document.getElementById('adsr-a');
const adsrDEl = document.getElementById('adsr-d');
const adsrSEl = document.getElementById('adsr-s');
const adsrREl = document.getElementById('adsr-r');
const selFilter = document.querySelector('.filter-type-btn.selected');
return {
grid: deepCopyGrid(grid, NUM_ROWS, STEPS),
autoSeqs: seqsCopy,
autoActive: new Set(autoActive),
octaveOffset,
rootSemitone,
sliderValues: {
filterFreq: parseFloat(fltFreqEl.value),
filterQ: parseFloat(fltQEl.value),
filterType: selFilter ? selFilter.dataset.type : 'lowpass',
reverbSend: parseFloat(rvbSendEl.value),
reverbDecay: parseFloat(rvbDecEl.value),
attack: parseFloat(adsrAEl.value),
decay: parseFloat(adsrDEl.value),
sustain: parseFloat(adsrSEl.value),
release: parseFloat(adsrREl.value),
},
waveform: document.querySelector('.waveform-btn.selected').dataset.wave,
playbackMode: playbackMode,
};
}
/** Capture drum state into a pattern object. */
function snapshotDrumPattern() {
const mutedCopy = {};
const volCopy = {};
for (let r = 0; r < NUM_DRUM_ROWS; r++) {
mutedCopy[r] = drumMuted[r];
volCopy[r] = drumTrackVolume[r];
}
return {
drumGrid: deepCopyGrid(drumGrid, NUM_DRUM_ROWS, STEPS),
drumMuted: mutedCopy,
drumTrackVolume: volCopy,
drumPlaybackMode: drumPlaybackMode,
};
}
/** Restore a notes pattern into live state. Fast — JS writes only; DOM deferred. */
function restoreNotesPattern(pattern) {
// Grid
for (let r = 0; r < NUM_ROWS; r++) {
for (let s = 0; s < STEPS; s++) grid[r][s] = pattern.grid[r][s];
}
// Automation: exit params not in this pattern, enter ones that are
const targetActive = pattern.autoActive;
const toExit = [...autoActive].filter(p => !targetActive.has(p));
const toEnter = [...targetActive].filter(p => !autoActive.has(p));
toExit.forEach(p => exitSeqMode(p));
toEnter.forEach(p => {
// Pre-fill autoSeqs so enterSeqMode doesn't overwrite with slider default
if (pattern.autoSeqs[p]) autoSeqs[p] = new Float64Array(pattern.autoSeqs[p]);
enterSeqMode(p);
});
// Update seq data for params already active
for (const paramId of autoActive) {
if (pattern.autoSeqs[paramId]) {
autoSeqs[paramId] = new Float64Array(pattern.autoSeqs[paramId]);
refreshAutoSeqPanel(paramId);
for (let s = 0; s < 16; s++) updateAutoGraphNode(paramId, s);
}
}
// Octave / root
octaveOffset = pattern.octaveOffset;
rootSemitone = pattern.rootSemitone;
NOTES = getCurrentNotes();
NOTE_LABELS = getCurrentNoteLabels();
// Slider values + audio params
const sv = pattern.sliderValues;
setSliderAndAudio('flt-freq', sv.filterFreq, v => { if (filter) filter.frequency.value = freqFromSlider(v); });
setSliderAndAudio('flt-q', sv.filterQ, v => { if (filter) filter.Q.value = v; });
setSliderAndAudio('rvb-send', sv.reverbSend, v => { if (reverbSend) reverbSend.gain.value = v; });
setSliderAndAudio('rvb-decay', sv.reverbDecay, v => { if (reverb) { reverb.decay = v; clearTimeout(reverbDecayAutoTimer); reverbDecayAutoTimer = setTimeout(() => reverb.generate(), 500); } });
setSliderAndAudio('adsr-a', sv.attack, v => setEnvelope('attack', v));
setSliderAndAudio('adsr-d', sv.decay, v => setEnvelope('decay', v));
setSliderAndAudio('adsr-s', sv.sustain, v => setEnvelope('sustain', v));
setSliderAndAudio('adsr-r', sv.release, v => setEnvelope('release', v));
// Filter type button
document.querySelectorAll('.filter-type-btn').forEach(b => {
b.classList.toggle('selected', b.dataset.type === sv.filterType);
});
if (filter) filter.type = sv.filterType;
// Waveform
document.querySelectorAll('.waveform-btn').forEach(b =>
b.classList.toggle('selected', b.dataset.wave === pattern.waveform));
setWaveform(pattern.waveform);
// Playback mode (apply immediately — pattern switches already happen at loop boundary)
document.querySelectorAll('.playmode-btn').forEach(b =>
b.classList.toggle('selected', b.dataset.mode === pattern.playbackMode));
pendingPlaybackMode = null;
playbackMode = pattern.playbackMode;
activeStepArray = getStepArray(playbackMode);
seqPosition = 0;
prevStep = -1;
}
/** Helper: set a slider element value, update its display, and apply audio change. */
function setSliderAndAudio(sliderId, value, applyFn) {
const slider = document.getElementById(sliderId);
if (!slider) return;
slider.value = value;
slider.dispatchEvent(new Event('input', { bubbles: true }));
applyFn(value);
}
/** Restore a drum pattern into live state. */
function restoreDrumPattern(pattern) {
for (let r = 0; r < NUM_DRUM_ROWS; r++) {
for (let s = 0; s < STEPS; s++) drumGrid[r][s] = pattern.drumGrid[r][s];
drumMuted[r] = pattern.drumMuted[r];
drumTrackVolume[r] = pattern.drumTrackVolume[r];
if (drumTrackGain[r]) {
drumTrackGain[r].gain.value = pattern.drumTrackVolume[r];
}
}
// Drum playback mode
document.querySelectorAll('.drum-playmode-btn').forEach(b =>
b.classList.toggle('selected', b.dataset.drumMode === pattern.drumPlaybackMode));
drumPlaybackMode = pattern.drumPlaybackMode;
}
/** Refresh all drum UI elements to match current drumGrid/drumMuted/drumTrackVolume state. */
function refreshDrumUI() {
// Grid cells
document.querySelectorAll('.drum-cell').forEach(cell => {
const r = parseInt(cell.dataset.row), s = parseInt(cell.dataset.step);
cell.classList.toggle('active', drumGrid[r][s]);
cell.classList.toggle('muted', drumMuted[r]);
});
// Mute buttons
document.querySelectorAll('.drum-mute-btn').forEach(btn => {
const r = parseInt(btn.dataset.row);
btn.classList.toggle('muted', drumMuted[r]);
});
// Volume slider fills
document.querySelectorAll('.dr-vol-slider').forEach((slider, idx) => {
const fill = slider.querySelector('.dr-vol-fill');
if (fill) fill.style.width = (drumTrackVolume[idx] * 100) + '%';
});
}
/** Refresh notes grid UI to match current grid state. */
function refreshNotesUI() {
document.querySelectorAll('.step-cell').forEach(cell => {
const r = parseInt(cell.dataset.row), s = parseInt(cell.dataset.step);
if (!isNaN(r) && !isNaN(s)) cell.classList.toggle('active', grid[r][s]);
});
rebuildPianoRollLabels();
document.getElementById('oct-display').textContent = 4 + octaveOffset;
document.querySelectorAll('.root-btn').forEach(b => {
b.classList.toggle('selected', parseInt(b.dataset.semitone) === rootSemitone);
});
}
/** Generate a radial dot-plot thumbnail for a pattern. Returns a data URL. */
function generateThumbnail(type, pattern) {
const size = 80;
const canvas = document.createElement('canvas');
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext('2d');
const cx = size / 2;
const cy_t = size / 2;
const radius = size * 0.35;
const color = type === 'notes' ? '#00d4aa' : '#ff6b6b';
const gridData = type === 'notes' ? pattern.grid : pattern.drumGrid;
const numRows = type === 'notes' ? NUM_ROWS : NUM_DRUM_ROWS;
ctx.fillStyle = '#0d0d1a';
ctx.fillRect(0, 0, size, size);
// Draw faint circle guide
ctx.beginPath();
ctx.arc(cx, cy_t, radius, 0, Math.PI * 2);
ctx.strokeStyle = type === 'notes' ? 'rgba(0,212,170,0.15)' : 'rgba(255,107,107,0.15)';
ctx.lineWidth = 1;
ctx.stroke();
for (let s = 0; s < STEPS; s++) {
let count = 0;
for (let r = 0; r < numRows; r++) {
if (gridData[r] && gridData[r][s]) count++;
}
if (count === 0) continue;
const angle = -Math.PI / 2 + (s / STEPS) * 2 * Math.PI;
const x = cx + radius * Math.cos(angle);
const y = cy_t + radius * Math.sin(angle);
const dotR = 2 + Math.min(count, 6) * 1.2;
ctx.beginPath();
ctx.arc(x, y, dotR, 0, Math.PI * 2);
ctx.fillStyle = color;
ctx.globalAlpha = 0.7 + 0.3 * Math.min(count / numRows, 1);
ctx.fill();
ctx.globalAlpha = 1;
}
return canvas.toDataURL('image/png');
}
/** Auto-name generator: "Notes A", "Notes B", ..., "Notes AA", etc. */
function autoNotesName() {
const idx = notesNameCounter++;
let name = '';
let n = idx;
do {
name = String.fromCharCode(65 + (n % 26)) + name;
n = Math.floor(n / 26) - 1;
} while (n >= 0);
return 'Notes ' + name;
}
function autoDrumName() {
return 'Beat ' + (++drumNameCounter);
}
/** Save: update active pattern in place, or create first if none. */
function saveNotesPattern() {
const snapshot = snapshotNotesPattern();
if (activeNotesPatternId !== null) {
const existing = notesPatterns.find(p => p.id === activeNotesPatternId);
if (existing) {
Object.assign(existing, snapshot);
existing.thumbnail = generateThumbnail('notes', existing);
rebuildPatternThumbnails();
scheduleHashSync();
return;
}
}
// No active pattern — create the first one
saveNewNotesPattern();
}
/** "+" button: always create a new pattern slot (subject to limit). */
function saveNewNotesPattern() {
if (notesPatterns.length >= MAX_NOTES_PATTERNS) return;
const snapshot = snapshotNotesPattern();
const id = crypto.randomUUID ? crypto.randomUUID() : 'np-' + Date.now() + '-' + Math.random().toString(36).slice(2);
const pattern = {
id,
name: autoNotesName(),
type: 'notes',
...snapshot,
thumbnail: '',
};
pattern.thumbnail = generateThumbnail('notes', pattern);
notesPatterns.push(pattern);
activeNotesPatternId = id;
rebuildPatternThumbnails();
updateNotesCenterLabel();
scheduleHashSync();
}
/** Save: update active drum pattern in place, or create first if none. */
function saveDrumPattern() {
const snapshot = snapshotDrumPattern();
if (activeDrumPatternId !== null) {
const existing = drumPatterns.find(p => p.id === activeDrumPatternId);
if (existing) {
Object.assign(existing, snapshot);
existing.thumbnail = generateThumbnail('drums', existing);
rebuildPatternThumbnails();
scheduleHashSync();
return;
}
}
// No active pattern — create the first one
saveNewDrumPattern();
}
/** "+" button: always create a new drum pattern slot (subject to limit). */
function saveNewDrumPattern() {
if (drumPatterns.length >= MAX_DRUM_PATTERNS) return;
const snapshot = snapshotDrumPattern();
const id = crypto.randomUUID ? crypto.randomUUID() : 'dp-' + Date.now() + '-' + Math.random().toString(36).slice(2);
const pattern = {
id,
name: autoDrumName(),
type: 'drums',
...snapshot,
thumbnail: '',
};
pattern.thumbnail = generateThumbnail('drums', pattern);
drumPatterns.push(pattern);
activeDrumPatternId = id;
rebuildPatternThumbnails();
updateDrumsCenterLabel();
scheduleHashSync();
}
/** Update pattern in-place without changing thumbnail or name. */
function updatePatternInPlace(patternId) {
let pat = notesPatterns.find(p => p.id === patternId);
if (pat) {
Object.assign(pat, snapshotNotesPattern());
pat.thumbnail = generateThumbnail('notes', pat);
return;
}
pat = drumPatterns.find(p => p.id === patternId);
if (pat) {
Object.assign(pat, snapshotDrumPattern());
pat.thumbnail = generateThumbnail('drums', pat);
}
}
/** Queue a notes pattern switch at the next loop boundary. */
function queueNotesSwitch(patternId) {
if (patternId === activeNotesPatternId) return;
if (!isPlaying) {
// Immediate switch when not playing
const target = notesPatterns.find(p => p.id === patternId);
if (target) {
restoreNotesPattern(target);
refreshNotesUI();
activeNotesPatternId = patternId;
updateGraph();
updateNotesCenterLabel();
rebuildPatternThumbnails();
scheduleHashSync();
}
return;
}
pendingNotesSwitch = patternId;
rebuildPatternThumbnails();
scheduleHashSync();
}
/** Queue a drum pattern switch at the next loop boundary. */
function queueDrumSwitch(patternId) {
if (patternId === activeDrumPatternId) return;
if (!isPlaying) {
const target = drumPatterns.find(p => p.id === patternId);
if (target) {
restoreDrumPattern(target);
refreshDrumUI();
activeDrumPatternId = patternId;
updateDrumGraph();
updateDrumsCenterLabel();
rebuildPatternThumbnails();
scheduleHashSync();
}
return;
}
pendingDrumSwitch = patternId;
rebuildPatternThumbnails();
scheduleHashSync();
}
function updateNotesCenterLabel() { /* no-op: center labels are static */ }
function updateDrumsCenterLabel() { /* no-op: center labels are static */ }
/** Delete a pattern by ID. */
function deletePattern(patternId, patternType) {
if (patternType === 'notes') {
const idx = notesPatterns.findIndex(p => p.id === patternId);
if (idx === -1) return;
notesPatterns.splice(idx, 1);
if (activeNotesPatternId === patternId) {
activeNotesPatternId = null;
updateNotesCenterLabel();
}
if (pendingNotesSwitch === patternId) pendingNotesSwitch = null;
} else {
const idx = drumPatterns.findIndex(p => p.id === patternId);
if (idx === -1) return;
drumPatterns.splice(idx, 1);
if (activeDrumPatternId === patternId) {
activeDrumPatternId = null;
updateDrumsCenterLabel();
}
if (pendingDrumSwitch === patternId) pendingDrumSwitch = null;
}
rebuildPatternThumbnails();
scheduleHashSync();
}
/** Clear delete-confirm state. */
function clearDeleteConfirm() {
if (deleteConfirmId && cy) {
const node = cy.getElementById(`__pat-${deleteConfirmId}__`);
if (node.length) node.removeClass('pattern-delete-confirm');
}
deleteConfirmId = null;
clearTimeout(deleteConfirmTimer);
deleteConfirmTimer = null;
}
// ═══════════════════════════════════════════════════════════
// URL HASH SESSION — serialize / deserialize / sync
// ═══════════════════════════════════════════════════════════
const WAVE_TO_CODE = { sine: 's', square: 'q', sawtooth: 'w' };
const CODE_TO_WAVE = { s: 'sine', q: 'square', w: 'sawtooth' };
const MODE_TO_CODE = { forward: 'f', reverse: 'r', pingpong: 'p' };
const CODE_TO_MODE = { f: 'forward', r: 'reverse', p: 'pingpong' };
const FTYPE_TO_CODE = { lowpass: 'l', highpass: 'h' };
const CODE_TO_FTYPE = { l: 'lowpass', h: 'highpass' };
const DMODE_TO_CODE = { forward: 'f', link: 'k' };
const CODE_TO_DMODE = { f: 'forward', k: 'link' };
function encodeGrid(gridObj, rows) {
let bits = '';
for (let r = 0; r < rows; r++)
for (let s = 0; s < STEPS; s++)
bits += gridObj[r][s] ? '1' : '0';
// Convert bitstring to hex (4 bits per char)
let hex = '';
for (let i = 0; i < bits.length; i += 4)
hex += parseInt(bits.slice(i, i + 4), 2).toString(16);
return hex;
}
function decodeGrid(hex, rows) {
let bits = '';
for (let i = 0; i < hex.length; i++)
bits += parseInt(hex[i], 16).toString(2).padStart(4, '0');
const g = {};
for (let r = 0; r < rows; r++) {
g[r] = new Array(STEPS).fill(false);
for (let s = 0; s < STEPS; s++)
g[r][s] = bits[r * STEPS + s] === '1';
}
return g;
}
function rd(v) { return Math.round(v * 100) / 100; }
function encodeAutoSeqs(seqs, active) {
const out = {};
for (const pid of active) {
if (!seqs[pid]) continue;
out[pid] = Array.from(seqs[pid]).map(v => rd(v));
}
return out;
}
function encodeNotesPattern(pat) {
const c = {
g: encodeGrid(pat.grid, NUM_ROWS),
w: WAVE_TO_CODE[pat.waveform] || 's',
m: MODE_TO_CODE[pat.playbackMode] || 'f',
o: pat.octaveOffset,
r: pat.rootSemitone,
};
const sv = pat.sliderValues;
c.sv = {
ff: rd(sv.filterFreq), fq: rd(sv.filterQ), ft: FTYPE_TO_CODE[sv.filterType] || 'l',
rs: rd(sv.reverbSend), rd: rd(sv.reverbDecay),
a: rd(sv.attack), d: rd(sv.decay), s: rd(sv.sustain), re: rd(sv.release),
};
if (pat.autoActive && pat.autoActive.size > 0) {
c.aa = [...pat.autoActive];
c.as = encodeAutoSeqs(pat.autoSeqs, pat.autoActive);
}
return c;
}
function decodeNotesPattern(c) {
const sv = c.sv || {};
return {
grid: decodeGrid(c.g, NUM_ROWS),
waveform: CODE_TO_WAVE[c.w] || 'sine',
playbackMode: CODE_TO_MODE[c.m] || 'forward',
octaveOffset: c.o || 0,
rootSemitone: c.r || 0,
sliderValues: {
filterFreq: sv.ff != null ? sv.ff : 75,
filterQ: sv.fq != null ? sv.fq : 1,
filterType: CODE_TO_FTYPE[sv.ft] || 'lowpass',
reverbSend: sv.rs != null ? sv.rs : 0,
reverbDecay: sv.rd != null ? sv.rd : 2,
attack: sv.a != null ? sv.a : 0.01,
decay: sv.d != null ? sv.d : 0.1,
sustain: sv.s != null ? sv.s : 0.5,
release: sv.re != null ? sv.re : 0.4,
},
autoActive: new Set(c.aa || []),
autoSeqs: Object.fromEntries(
Object.entries(c.as || {}).map(([k, v]) => [k, new Float64Array(v)])
),
};
}
function encodeDrumPattern(pat) {
const c = {
g: encodeGrid(pat.drumGrid, NUM_DRUM_ROWS),
dm: DMODE_TO_CODE[pat.drumPlaybackMode] || 'f',
};
// Mutes — only include if any are true
const mArr = [];
let anyMute = false;
for (let r = 0; r < NUM_DRUM_ROWS; r++) {
mArr.push(pat.drumMuted[r] ? 1 : 0);
if (pat.drumMuted[r]) anyMute = true;
}
if (anyMute) c.mu = mArr;
// Volumes — only include if any differ from 1
const vArr = [];
let anyVol = false;
for (let r = 0; r < NUM_DRUM_ROWS; r++) {
vArr.push(rd(pat.drumTrackVolume[r]));
if (pat.drumTrackVolume[r] !== 1) anyVol = true;
}
if (anyVol) c.tv = vArr;
return c;
}
function decodeDrumPattern(c) {
const pat = {
drumGrid: decodeGrid(c.g, NUM_DRUM_ROWS),
drumPlaybackMode: CODE_TO_DMODE[c.dm] || 'forward',
drumMuted: {},
drumTrackVolume: {},
};
for (let r = 0; r < NUM_DRUM_ROWS; r++) {
pat.drumMuted[r] = c.mu ? !!c.mu[r] : false;
pat.drumTrackVolume[r] = c.tv ? c.tv[r] : 1;
}
return pat;
}
function serializeSession() {
const data = { v: 1 };
// Live state
data.n = encodeNotesPattern(snapshotNotesPattern());
data.d = encodeDrumPattern(snapshotDrumPattern());
// Global controls
data.bpm = parseInt(document.getElementById('bpm').value, 10) || 120;
const volDb = parseInt(document.getElementById('vol').value, 10);
if (volDb !== 0) data.vol = volDb;
if (notesMuted) data.nm = 1;
if (drumSeqMuted) data.dsm = 1;
if (metronomeEnabled) data.met = 1;
// Saved patterns
if (notesPatterns.length > 0) {
data.np = notesPatterns.map(p => encodeNotesPattern(p));
if (activeNotesPatternId) {
const idx = notesPatterns.findIndex(p => p.id === activeNotesPatternId);
if (idx >= 0) data.ani = idx;
}
}
if (drumPatterns.length > 0) {
data.dp = drumPatterns.map(p => encodeDrumPattern(p));
if (activeDrumPatternId) {
const idx = drumPatterns.findIndex(p => p.id === activeDrumPatternId);
if (idx >= 0) data.adi = idx;
}
}
return data;
}
function deserializeSession(data) {
// Live notes state
const notesPat = decodeNotesPattern(data.n);
restoreNotesPattern(notesPat);
refreshNotesUI();
// Live drum state
const drumPat = decodeDrumPattern(data.d);
restoreDrumPattern(drumPat);
refreshDrumUI();
// Globals
const bpmEl = document.getElementById('bpm');
bpmEl.value = data.bpm || 120;
setBPM(bpmEl.value);
if (data.vol != null) {
const volEl = document.getElementById('vol');
volEl.value = data.vol;
setMasterVolume(data.vol);
document.getElementById('vol-val').textContent = `${data.vol}dB`;
}
notesMuted = !!data.nm;
document.getElementById('notes-mute-btn').classList.toggle('active', notesMuted);
drumSeqMuted = !!data.dsm;
document.getElementById('drum-seq-mute-btn').classList.toggle('active', drumSeqMuted);
if (data.met) {
metronomeEnabled = true;
document.getElementById('metro-btn').classList.add('active');
}
// Restore saved patterns
notesPatterns.length = 0;
drumPatterns.length = 0;
activeNotesPatternId = null;
activeDrumPatternId = null;
notesNameCounter = 0;
drumNameCounter = 0;
if (data.np) {
data.np.forEach(c => {
const decoded = decodeNotesPattern(c);
const id = crypto.randomUUID ? crypto.randomUUID() : 'np-' + Date.now() + '-' + Math.random().toString(36).slice(2);
notesPatterns.push({
id,
name: autoNotesName(),
type: 'notes',
...decoded,
thumbnail: '',
});
notesPatterns[notesPatterns.length - 1].thumbnail = generateThumbnail('notes', notesPatterns[notesPatterns.length - 1]);
});
if (data.ani != null && data.ani < notesPatterns.length)
activeNotesPatternId = notesPatterns[data.ani].id;
}
if (data.dp) {
data.dp.forEach(c => {
const decoded = decodeDrumPattern(c);
const id = crypto.randomUUID ? crypto.randomUUID() : 'dp-' + Date.now() + '-' + Math.random().toString(36).slice(2);
drumPatterns.push({
id,
name: autoDrumName(),
type: 'drums',
...decoded,
thumbnail: '',
});
drumPatterns[drumPatterns.length - 1].thumbnail = generateThumbnail('drums', drumPatterns[drumPatterns.length - 1]);
});
if (data.adi != null && data.adi < drumPatterns.length)
activeDrumPatternId = drumPatterns[data.adi].id;
}
rebuildPatternThumbnails();
updateGraph();
updateDrumGraph();
}
// ─── Debounced Hash Sync ──────────────────────────────────────
let hashSyncTimer = null;
function scheduleHashSync() {
clearTimeout(hashSyncTimer);
hashSyncTimer = setTimeout(syncHash, 500);
}
function syncHash() {
try {
const data = serializeSession();
const compressed = LZString.compressToEncodedURIComponent(JSON.stringify(data));
history.replaceState(null, '', '#' + compressed);
} catch (e) {
console.warn('Hash sync failed:', e);
}
}
function restoreFromHash() {
const hash = location.hash.slice(1);
if (!hash) return false;
try {
const json = LZString.decompressFromEncodedURIComponent(hash);
if (!json) throw new Error('Decompression returned null');
const data = JSON.parse(json);
if (data.v !== 1) throw new Error('Unknown session version: ' + data.v);
deserializeSession(data);
return true;
} catch (e) {
console.warn('Could not restore session from URL hash:', e);
return false;
}
}
/** Enable/disable "+" buttons based on pattern count. */
function updateSaveNewButtonState() {
const notesPlusBtn = document.getElementById('notes-save-new-btn');
if (notesPlusBtn) {
notesPlusBtn.disabled = notesPatterns.length >= MAX_NOTES_PATTERNS;
}
const drumPlusBtn = document.getElementById('drum-save-new-btn');
if (drumPlusBtn) {
drumPlusBtn.disabled = drumPatterns.length >= MAX_DRUM_PATTERNS;
}
}
/** Add/remove/update pattern thumbnail nodes in the graph. */
function rebuildPatternThumbnails() {
if (!cy) return;
const allPatterns = [...notesPatterns, ...drumPatterns];
const activeThumbIds = new Set(allPatterns.map(p => `__pat-${p.id}__`));
// Remove stale thumbnail nodes
cy.nodes('.pattern-thumb').forEach(node => {
if (!activeThumbIds.has(node.id())) node.remove();
});
// Add or update thumbnail nodes
allPatterns.forEach((pat, idx) => {
const nodeId = `__pat-${pat.id}__`;
const isActive = pat.id === activeNotesPatternId || pat.id === activeDrumPatternId;
const isPending = pat.id === pendingNotesSwitch || pat.id === pendingDrumSwitch;
const color = pat.type === 'notes' ? '#00d4aa' : '#ff6b6b';
let node = cy.getElementById(nodeId);
if (node.length) {
node.data('thumbnail', pat.thumbnail);
node.data('color', color);
node.data('order', idx);
node.toggleClass('pattern-active', isActive);
node.toggleClass('pattern-pending', isPending);
} else {
cy.add({
data: {
id: nodeId,
thumbnail: pat.thumbnail,
color,
order: idx,
patternId: pat.id,
patternType: pat.type,
},
classes: 'pattern-thumb' + (isActive ? ' pattern-active' : '') + (isPending ? ' pattern-pending' : ''),
position: { x: 0, y: 0 },
});
}
});
positionAllRings();
updateSaveNewButtonState();
}
// ═══════════════════════════════════════════════════════════
// A. PIANO ROLL
// ═══════════════════════════════════════════════════════════
function buildPianoRoll() {
const container = document.getElementById('piano-roll');
// Header: blank label + step numbers
const blankLabel = document.createElement('div');
blankLabel.className = 'pr-label';
container.appendChild(blankLabel);
for (let s = 0; s < STEPS; s++) {
const num = document.createElement('div');
num.className = 'pr-step-num';
num.textContent = s + 1;
container.appendChild(num);
}
// Note rows — row 0 at top (highest pitch)
const labels = getCurrentNoteLabels();
for (let r = 0; r < NUM_ROWS; r++) {
const lbl = document.createElement('div');
lbl.className = 'pr-label';
lbl.dataset.row = r;
lbl.textContent = labels[r];
container.appendChild(lbl);
for (let s = 0; s < STEPS; s++) {
const cell = document.createElement('div');
cell.className = 'step-cell';
cell.dataset.row = r;
cell.dataset.step = s;
cell.addEventListener('pointerdown', (e) => startCellDrag('notes', r, s, cell, e));
container.appendChild(cell);
}