-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.js
More file actions
1696 lines (1564 loc) · 61.8 KB
/
Copy pathapp.js
File metadata and controls
1696 lines (1564 loc) · 61.8 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
// SwayCommand cockpit, one always-live page. The stage renders in the
// center from boot to quit; the timeline, the Sway deck, the rails, the
// drawer, and every overlay work on top of it without ever stopping the
// render loop. Projects are .sway files; the legacy screens are gone.
import { createEngine } from './engine/engine.js';
import { createAudioEngine } from './engine/audio.js';
import { createMidi } from './midi/midi.js';
import { renderMarkdown } from './markdown.js';
import { createSampler } from './audio/sampler.js';
import { createSynth, PRESET_NAMES, TABLE_NAMES, MOD_SOURCES, MOD_DESTS } from './audio/synth.js';
import { RANGES as fxRanges, DECKS as fxDecks } from './engine/fxrack.js';
import { createTransport } from './audio/transport.js';
import { createProjectStore } from './project/projectstore.js';
import { createRouter } from './control/router.js';
import { initFrames } from './ui/frame.js';
import { openPopover, closePopover, popoverOpen, popoverAnchor, wirePopover } from './ui/popover.js';
import { createHostBar } from './ui/hostbar.js';
import { hostState, onHostEvent } from './host/host-channel.js';
import { displayPortName } from './midi/swaymap.js';
import { createWave } from './ui/wave.js';
import { createSurface } from './ui/surface.js';
import { createAssign } from './ui/assign.js';
import { createDrawer } from './ui/drawer.js';
import { createTimeline } from './ui/timeline.js';
import { createLayout } from './ui/layout.js';
import { estimateBpm } from './audio/bpm.js';
import { uid } from '../shared/swayproject.js';
const $ = (sel) => document.querySelector(sel);
const state = {
docs: [],
currentDoc: null,
sampler: null,
synth: null,
synthEnabled: true,
checks: [],
midi: null,
audio: null,
engine: null,
transport: null,
router: null,
projectStore: null,
monitorVisible: false,
entered: false, // door opened
};
const ui = {
surface: null,
assign: null,
drawer: null,
timeline: null,
wave: null,
layout: null,
hostbar: null,
};
const studio = {
sources: [],
selectedSample: null,
systemAudio: { supported: false, detail: '' },
};
// ---------------------------------------------------------------- overlays
const MODALS = ['docs', 'help', 'system'];
function openModal(id) {
$(`#modal-${id}`).hidden = false;
}
function closeModal(id) {
$(`#modal-${id}`).hidden = true;
}
function modalOpen(id) {
return !$(`#modal-${id}`).hidden;
}
function topModal() {
// system sits above the others in z, so it pops first
for (const id of ['system', 'help', 'docs']) {
if (modalOpen(id)) return id;
}
return null;
}
// Esc peels one layer: popover, then drawer, then the topmost modal, then
// timeline selection, then the deck selection. "Back" does not exist.
function escapePop() {
if (popoverOpen()) return closePopover();
if (ui.assign.cancelBind()) return ui.surface.setArmed(false);
if (ui.drawer.isOpen()) return ui.drawer.close();
const modal = topModal();
if (modal) {
if (modal === 'system' && !state.entered) return; // first run gates on ENTER
return closeModal(modal);
}
if (ui.timeline.hasSelection()) return ui.timeline.clearSelection();
if (ui.assign.current()) return selectControl(null);
}
let noticeTimer = null;
function notice(html, ms = 5000) {
const el = $('#notice');
el.innerHTML = html;
el.classList.add('visible');
clearTimeout(noticeTimer);
noticeTimer = setTimeout(() => el.classList.remove('visible'), ms);
}
// ---------------------------------------------------------------- doctor
const STATUS_ICON = { ok: '●', warn: '▲', fail: '✕', info: '○' };
function renderChecks() {
$('#check-list').innerHTML = state.checks
.map(
(c) => `
<li class="check ${c.status}">
<span class="check-icon">${STATUS_ICON[c.status] || '○'}</span>
<div class="check-body">
<div class="check-label">${c.label}</div>
<div class="check-detail">${c.detail}</div>
<div class="check-progress" id="progress-${c.id}"></div>
</div>
${c.fix ? `<button class="btn btn-fix" data-fix="${c.fix.id}" data-check="${c.id}">${c.fix.label}</button>` : ''}
</li>`
)
.join('');
}
async function rendererChecks() {
const checks = [];
try {
// The stage already holds a WebGL2 context; ask it rather than opening a
// second one (a cold-GPU-process stall, and it only ever said "WebKit
// WebGL"). The probe canvas is the fallback before the engine exists.
let info = state.engine ? state.engine.gpuName : null;
let gl = !!state.engine;
if (!state.engine) {
const probe = document.createElement('canvas');
const pgl = probe.getContext('webgl2');
gl = !!pgl;
info = pgl ? pgl.getParameter(pgl.RENDERER) : null;
}
checks.push(
gl
? { id: 'gpu', label: 'Graphics (WebGL2)', status: 'ok', detail: `Ready, ${info || 'WebGL2'}.` }
: { id: 'gpu', label: 'Graphics (WebGL2)', status: 'fail', detail: 'WebGL2 unavailable. Update your GPU drivers.' }
);
} catch (e) {
checks.push({ id: 'gpu', label: 'Graphics (WebGL2)', status: 'fail', detail: e.message });
}
if (state.midi.available) {
const c = state.midi.control;
checks.push({
id: 'midi',
label: 'MIDI',
status: 'ok',
detail: c.isSway
? `Sway online: ${displayPortName(c.portName)}, factory map armed.`
: c.connected
? `No Sway yet, but listening on: ${displayPortName(c.portName)}. Incoming CC and note messages are matched against the Sway factory map.`
: 'No MIDI devices right now. Hot-plug any time, mouse & keyboard are fully mapped meanwhile.',
});
} else {
checks.push({ id: 'midi', label: 'MIDI', status: 'warn', detail: 'WebMIDI unavailable, mouse & keyboard control still work.' });
}
try {
const inputs = await state.audio.listInputs();
checks.push({
id: 'audio',
label: 'Audio input',
status: 'ok',
detail: inputs.length
? `${inputs.length} input(s) found, visuals will follow the music. No input? The internal groove takes over.`
: 'No audio inputs, the internal groove (silent, analysis-only) will drive the visuals.',
});
} catch {
checks.push({ id: 'audio', label: 'Audio input', status: 'info', detail: 'Could not enumerate inputs; the internal groove will drive the visuals.' });
}
return checks;
}
// A check that throws or never settles must not lock the blast door. Measured:
// navigator.requestMIDIAccess() inside rendererChecks() does not settle until
// the user answers Chromium's permission prompt, so awaiting it bare left
// #btn-enter disabled - it ships disabled in index.html - with #boot-status
// frozen on 'Checking your system' and nothing logged. That reads as a dead
// application. doctor.run() has the same exposure on the desktop, where it
// shells out to pnputil / Get-PnpDevice / lsusb.
function settleCheck(promise, fallback, label) {
const guard = new Promise((resolve) => {
setTimeout(() => resolve({ __timedOut: true }), 6000);
});
return Promise.race([
Promise.resolve(promise).catch((err) => {
console.warn(`[doctor] ${label} check failed:`, err);
return fallback;
}),
guard,
]).then((value) => {
if (value && value.__timedOut) {
console.warn(`[doctor] ${label} check timed out after 6s`);
return fallback;
}
return value;
});
}
async function runDoctor() {
$('#boot-status').textContent = 'Checking your system...';
const [main, local] = await Promise.all([
settleCheck(window.swaycommand.doctor.run(), [], 'system'),
settleCheck(rendererChecks(), [], 'renderer'),
]);
state.checks = [...(main || []), ...(local || [])];
try {
renderChecks();
} catch (err) {
console.warn('[doctor] renderChecks failed:', err);
}
const worst = state.checks.some((c) => c.status === 'fail')
? 'fail'
: state.checks.some((c) => c.status === 'warn')
? 'warn'
: 'ok';
$('#boot-status').textContent =
worst === 'ok'
? 'All clear.'
: worst === 'warn'
? 'Playable now, a couple of notes above.'
: 'Something needs attention above, you can still continue.';
const enter = $('#btn-enter');
enter.disabled = false;
enter.focus();
if (worst === 'ok' && !state._autoAdvanced && !state.entered) {
state._autoAdvanced = true;
// The door opens by itself once the checks pass, but not onto a stage
// that is still compiling its visuals. It waits for the warm pipeline,
// six seconds at most; ENTER opens it at once regardless.
const t0 = performance.now();
const tryOpen = () => {
if (state.entered || !modalOpen('system')) return;
const wp = state.engine ? state.engine.warmProgress() : { busy: false };
if (!wp.busy || performance.now() - t0 > 6000) enterCockpit();
else setTimeout(tryOpen, 150);
};
setTimeout(tryOpen, 1400);
}
}
function wireDoctor() {
window.swaycommand.doctor.onFixProgress(({ fixId, phase, pct }) => {
const check = state.checks.find((c) => c.fix && c.fix.id === fixId);
if (!check) return;
const el = $(`#progress-${check.id}`);
if (el) el.textContent = phase === 'download' ? `downloading... ${pct || 0}%` : `${phase}...`;
});
$('#check-list').addEventListener('click', async (e) => {
const btn = e.target.closest('[data-fix]');
if (!btn) return;
btn.disabled = true;
btn.textContent = 'Working...';
const result = await window.swaycommand.doctor.fix(btn.dataset.fix);
const check = state.checks.find((c) => c.id === btn.dataset.check);
if (check) {
check.detail = result.detail;
check.status = result.ok ? 'ok' : 'warn';
if (result.ok) check.fix = null;
}
renderChecks();
if (result.ok) runDoctor();
});
$('#btn-enter').addEventListener('click', enterCockpit);
$('#btn-recheck').addEventListener('click', runDoctor);
$('#btn-system').addEventListener('click', () => {
closeModal('help');
openModal('system');
runDoctor();
});
}
// The blast door opens once the system checks are dismissed; the stage was
// already rendering behind it.
function enterCockpit() {
closeModal('system');
if (state.entered) return;
state.entered = true;
// createAudioEngine() builds its AudioContext at boot, which autoplay policy
// starts suspended (measured: repeated 'AudioContext was not allowed to
// start' warnings). This click is the one user gesture guaranteed to have
// happened, so resume here or the analyser reads silence and every scene
// renders flat.
if (state.audio && typeof state.audio.resume === 'function') {
Promise.resolve(state.audio.resume()).catch(() => {});
}
const door = $('#door');
door.classList.add('open');
setTimeout(() => door.classList.add('gone'), 1000);
notice('<b>H</b>, controls');
}
// ---------------------------------------------------------------- samples / kit
function renderSamples() {
const list = state.sampler ? state.sampler.listSamples() : [];
$('#sample-list').innerHTML = list.length
? list
.map(
(s) =>
`<li><button draggable="true" data-sample="${s.id.replace(/"/g, '"')}"${s.id === studio.selectedSample ? ' class="current"' : ''}>${s.name}<em>${s.duration.toFixed(2)} s · ${s.channels}ch</em></button></li>`
)
.join('')
: '<li class="none">No samples loaded.</li>';
}
async function addSamples() {
const note = $('#kit-note');
let picked;
try {
picked = await window.swaycommand.files.pickAudio();
} catch (err) {
note.textContent = `File dialog failed: ${err.message}`;
return;
}
if (!picked.length) return;
let loaded = 0;
const failures = [];
for (const file of picked) {
note.textContent = `Loading ${file.name}...`;
try {
await state.projectStore.addMedia(file);
loaded++;
} catch (err) {
failures.push(`${file.name}: ${err.message}`);
}
}
note.textContent = failures.length
? `Loaded ${loaded}. Failed: ${failures.join('; ')}`
: `Loaded ${loaded} sample${loaded === 1 ? '' : 's'}.`;
renderSamples();
}
// Re-reads every sample file a legacy saved kit references, then restores the
// pads and mirrors them into pad assignments.
async function restoreKit(saved) {
if (!saved || !saved.samples || !saved.samples.length) return;
const missing = [];
for (const s of saved.samples) {
try {
const bytes = await window.swaycommand.files.readAudio(s.id);
await state.sampler.loadSample(s.id, bytes.slice().buffer, { name: s.name });
} catch {
missing.push(s.name);
}
}
state.sampler.setKit(saved);
const pads = state.router.getAssignments().pads;
(saved.pads || []).forEach((pad, i) => {
if (pad && pad.id && !pads[i]) pads[i] = { type: 'sample', pad: i };
});
refreshDeck();
if (missing.length) console.warn('[kit] missing sample files:', missing.join(', '));
}
function wireKit() {
$('#btn-add-samples').addEventListener('click', addSamples);
$('#sample-list').addEventListener('click', (e) => {
const btn = e.target.closest('[data-sample]');
if (!btn) return;
studio.selectedSample = btn.dataset.sample;
renderSamples();
notice('Click a pad on the deck to place the sample');
});
$('#sample-list').addEventListener('dragstart', (e) => {
const btn = e.target.closest('[data-sample]');
if (!btn) return;
e.dataTransfer.setData('application/x-sway-media', btn.dataset.sample);
e.dataTransfer.effectAllowed = 'copy';
});
}
// ---------------------------------------------------------------- synth panel
const SYNTH_GROUPS = ['OSC1', 'OSC2', 'FILTER1', 'ENV1', 'LFO', 'FX', 'GLOBAL'];
const KEY_ROW = [
['a', 48], ['w', 49], ['s', 50], ['e', 51], ['d', 52], ['f', 53], ['t', 54],
['g', 55], ['y', 56], ['h', 57], ['u', 58], ['j', 59],
['k', 60], ['o', 61], ['l', 62], ['p', 63], [';', 64],
];
const heldKeys = new Set();
function renderSynthPanel() {
const synth = state.synth;
const manifest = synth.controlManifest();
$('#synth-preset').innerHTML = PRESET_NAMES.map(
(n) => `<option value="${n}"${n === synth.patch.name ? ' selected' : ''}>${n}</option>`
).join('');
const html = [];
for (const group of SYNTH_GROUPS) {
const rows = [];
if (group === 'OSC1' || group === 'OSC2') {
const osc = group.toLowerCase();
const cur = synth.getParam(`${osc}.table`);
rows.push(
`<label class="fx-row"><select data-synthsel="${osc}.table">${TABLE_NAMES.map(
(t) => `<option value="${t}"${t === cur ? ' selected' : ''}>${t}</option>`
).join('')}</select><span>table</span></label>`
);
}
for (const c of manifest) {
if (c.group !== group) continue;
const value = synth.getParam(c.key);
if (c.kind === 'toggle') {
rows.push(
`<label class="fx-row"><input type="checkbox" data-synth="${c.key}"${value ? ' checked' : ''}><span>${c.label}</span></label>`
);
} else {
rows.push(
`<label class="fx-row"><input type="range" data-synth="${c.key}" min="${c.min}" max="${c.max}" step="${c.step}" value="${value}"><span>${c.label} <b data-synthval="${c.key}">${Number(value).toFixed(3)}</b></span></label>`
);
}
}
if (rows.length) html.push(`<div class="fx-deck"><div class="kit-label">${group}</div>${rows.join('')}</div>`);
}
$('#synth-decks').innerHTML = html.join('');
$('#synth-keys').innerHTML = KEY_ROW.map(([key, note]) => {
const sharp = [1, 3, 6, 8, 10].includes(note % 12);
return `<button class="skey${sharp ? ' sharp' : ''}" data-note="${note}"><b>${key}</b></button>`;
}).join('');
renderModMatrix();
}
function renderModMatrix() {
const rows = state.synth.getMatrix();
$('#mod-rows').innerHTML = rows
.map(
(r, i) => `<div class="mod-row">
<select data-mod="${i}" data-field="source">${MOD_SOURCES.map((s) => `<option${s === r.source ? ' selected' : ''}>${s}</option>`).join('')}</select>
<span>-></span>
<select data-mod="${i}" data-field="dest">${MOD_DESTS.map((d) => `<option${d === r.dest ? ' selected' : ''}>${d}</option>`).join('')}</select>
<input type="range" data-mod="${i}" data-field="amount" min="-1" max="1" step="0.01" value="${r.amount}">
<b>${r.amount.toFixed(2)}</b>
<button class="btn btn-ghost btn-small" data-mod-del="${i}">✕</button>
</div>`
)
.join('');
}
function wireSynth() {
$('#synth-enable').addEventListener('change', (e) => {
state.synthEnabled = e.target.checked;
state.router.synthEnabled = e.target.checked;
state.projectStore.markDirty();
});
$('#synth-preset').addEventListener('change', (e) => {
state.synth.loadPreset(e.target.value);
state.projectStore.markDirty();
renderSynthPanel();
});
$('#synth-decks').addEventListener('input', (e) => {
const el = e.target.closest('[data-synth], [data-synthsel]');
if (!el) return;
const key = el.dataset.synth || el.dataset.synthsel;
const value =
el.type === 'checkbox' ? el.checked : el.tagName === 'SELECT' ? el.value : Number(el.value);
state.synth.setParam(key, value);
state.projectStore.markDirty();
const readout = document.querySelector(`[data-synthval="${key}"]`);
if (readout) readout.textContent = Number(value).toFixed(3);
});
$('#mod-rows').addEventListener('input', (e) => {
const el = e.target.closest('[data-mod]');
if (!el) return;
const rows = state.synth.getMatrix();
const i = Number(el.dataset.mod);
if (!rows[i]) return;
rows[i][el.dataset.field] = el.dataset.field === 'amount' ? Number(el.value) : el.value;
state.synth.setMatrix(rows);
state.projectStore.markDirty();
renderModMatrix();
});
$('#mod-rows').addEventListener('click', (e) => {
const del = e.target.closest('[data-mod-del]');
if (!del) return;
const rows = state.synth.getMatrix();
rows.splice(Number(del.dataset.modDel), 1);
state.synth.setMatrix(rows);
state.projectStore.markDirty();
renderModMatrix();
});
$('#btn-mod-add').addEventListener('click', () => {
const rows = state.synth.getMatrix();
rows.push({ source: 'lfo1', dest: 'filter1.cutoff', amount: 0.3 });
state.synth.setMatrix(rows);
state.projectStore.markDirty();
renderModMatrix();
});
const keys = $('#synth-keys');
keys.addEventListener('pointerdown', (e) => {
const b = e.target.closest('[data-note]');
if (!b) return;
b.classList.add('down');
state.synth.noteOn(Number(b.dataset.note), 0.85);
});
const releaseAll = () => {
for (const b of keys.querySelectorAll('.down')) {
b.classList.remove('down');
state.synth.noteOff(Number(b.dataset.note));
}
};
keys.addEventListener('pointerup', releaseAll);
keys.addEventListener('pointerleave', releaseAll);
window.addEventListener('blur', releaseAll);
}
// The computer keyboard plays the synth only while the synth drawer is open,
// so it never fights the cockpit shortcuts.
function synthKeyDown(e) {
if (!ui.drawer.isOpen('synth') || e.repeat) return false;
if (/^(input|select|textarea)$/i.test(e.target.tagName)) return false;
const entry = KEY_ROW.find(([k]) => k === e.key.toLowerCase());
if (!entry) return false;
if (heldKeys.has(entry[1])) return true;
heldKeys.add(entry[1]);
state.synth.noteOn(entry[1], 0.85);
const btn = document.querySelector(`[data-note="${entry[1]}"]`);
if (btn) btn.classList.add('down');
return true;
}
function synthKeyUp(e) {
const entry = KEY_ROW.find(([k]) => k === e.key.toLowerCase());
if (!entry || !heldKeys.has(entry[1])) return;
heldKeys.delete(entry[1]);
state.synth.noteOff(entry[1]);
const btn = document.querySelector(`[data-note="${entry[1]}"]`);
if (btn) btn.classList.remove('down');
}
// ---------------------------------------------------------------- effects rack
function renderFxPanel() {
const rack = state.engine.fx;
const ranges = fxRanges;
const html = [];
for (const deck of fxDecks) {
const rows = [];
for (const key of deck.keys) {
const spec = ranges[key];
if (spec === undefined || !(key in rack.params)) continue; // rack owns the truth
const value = rack.params[key];
if (spec === true) {
rows.push(
`<label class="fx-row"><input type="checkbox" data-fx="${key}"${value ? ' checked' : ''}><span>${key}</span></label>`
);
} else if (spec === 'hex') {
rows.push(`<label class="fx-row"><input type="color" data-fx="${key}" value="${value}"><span>${key}</span></label>`);
} else if (Array.isArray(spec)) {
const [min, max] = spec;
const step = Number.isInteger(min) && Number.isInteger(max) && max - min >= 4 ? 1 : (max - min) / 200;
rows.push(
`<label class="fx-row"><input type="range" data-fx="${key}" min="${min}" max="${max}" step="${step}" value="${value}"><span>${key} <b data-fxval="${key}">${(+value).toFixed(2)}</b></span></label>`
);
}
}
if (rows.length) html.push(`<div class="fx-deck"><div class="kit-label">${deck.name}</div>${rows.join('')}</div>`);
}
$('#fx-decks').innerHTML = html.join('');
$('#fx-enable').checked = state.engine.fxEnabled;
}
function wireFx() {
$('#fx-enable').addEventListener('change', (e) => {
state.engine.fxEnabled = e.target.checked;
state.projectStore.markDirty();
});
$('#btn-fx-reset').addEventListener('click', () => {
state.engine.resetFx();
state.projectStore.markDirty();
renderFxPanel();
});
$('#fx-decks').addEventListener('input', (e) => {
const el = e.target.closest('[data-fx]');
if (!el) return;
const key = el.dataset.fx;
const value = el.type === 'checkbox' ? el.checked : el.type === 'color' ? el.value : Number(el.value);
state.engine.setFxParam(key, value);
state.projectStore.markDirty();
const readout = document.querySelector(`[data-fxval="${key}"]`);
if (readout) readout.textContent = Number(value).toFixed(2);
});
}
// ---------------------------------------------------------------- documentation
async function openDocs(docId) {
if (!state.docs.length) {
state.docs = await window.swaycommand.docs.list();
$('#docs-list').innerHTML = state.docs
.map((d) => `<li><button data-doc="${d.id}">${d.title}</button></li>`)
.join('');
}
openModal('docs');
await loadDoc(docId || state.currentDoc || (state.docs[0] && state.docs[0].id));
}
async function loadDoc(docId, anchor) {
if (!docId) return;
const body = $('#docs-body');
let source;
try {
source = await window.swaycommand.docs.read(docId);
} catch (err) {
body.innerHTML = `<h1>Unavailable</h1><p>${docId} could not be read: ${err.message}</p>`;
return;
}
state.currentDoc = docId;
const { html, headings } = renderMarkdown(source);
body.innerHTML = html;
body.scrollTop = 0;
for (const btn of document.querySelectorAll('#docs-list button')) {
btn.classList.toggle('current', btn.dataset.doc === docId);
}
$('#docs-toc').innerHTML = headings
.filter((h) => h.level > 1)
.map((h) => `<li><button data-anchor="${h.id}" class="lvl-${h.level}">${h.text}</button></li>`)
.join('');
if (anchor) scrollToAnchor(anchor);
}
function scrollToAnchor(anchor) {
const target = document.getElementById(anchor);
if (target) target.scrollIntoView({ block: 'start', behavior: 'auto' });
}
let externalNoteTimer = null;
function showExternalNote(text) {
let el = $('.docs-external-note');
if (!el) {
el = document.createElement('div');
el.className = 'docs-external-note';
document.body.appendChild(el);
}
el.textContent = text;
clearTimeout(externalNoteTimer);
externalNoteTimer = setTimeout(() => el.remove(), 6000);
}
async function followDocLink(href) {
if (href.startsWith('#')) {
scrollToAnchor(href.slice(1));
return;
}
if (/^https?:/i.test(href)) {
try {
await window.swaycommand.openExternal(href);
} catch {
showExternalNote(`Link not on the allowlist, open manually: ${href}`);
}
return;
}
const [rel, anchor] = href.split('#');
const from = state.currentDoc || 'README.md';
const baseDir = from.includes('/') ? from.slice(0, from.lastIndexOf('/')) : '';
const segments = (baseDir ? baseDir.split('/') : []).concat(rel.split('/'));
const resolved = [];
for (const seg of segments) {
if (seg === '.' || seg === '') continue;
if (seg === '..') resolved.pop();
else resolved.push(seg);
}
const id = resolved.join('/');
if (state.docs.some((d) => d.id === id)) {
await loadDoc(id, anchor);
} else if (anchor && !rel) {
scrollToAnchor(anchor);
} else {
showExternalNote(`Not part of the bundled documentation: ${href}`);
}
}
function wireDocs() {
$('#btn-docs').addEventListener('click', () => (modalOpen('docs') ? closeModal('docs') : openDocs()));
$('#btn-docs-close').addEventListener('click', () => closeModal('docs'));
$('#docs-list').addEventListener('click', (e) => {
const btn = e.target.closest('[data-doc]');
if (btn) loadDoc(btn.dataset.doc);
});
$('#docs-toc').addEventListener('click', (e) => {
const btn = e.target.closest('[data-anchor]');
if (btn) scrollToAnchor(btn.dataset.anchor);
});
$('#docs-body').addEventListener('click', (e) => {
const link = e.target.closest('[data-href]');
if (!link) return;
e.preventDefault();
followDocLink(link.dataset.href);
});
}
// ---------------------------------------------------------------- topbar
function fmtClock(t) {
const m = Math.floor(t / 60);
const s = t - m * 60;
return `${m < 10 ? '0' : ''}${m}:${s < 10 ? '0' : ''}${s.toFixed(1)}`;
}
function updateProjectButton() {
const btn = $('#project-btn');
btn.textContent = state.projectStore.state.name;
btn.classList.toggle('dirty', state.projectStore.state.dirty);
if (ui.hostbar) ui.hostbar.setScene(state.projectStore.state.name, state.projectStore.state.dirty);
}
// New, Open, Save, Save as, a recent file and a template: one handler for every
// menu that offers them (the project menu, and the scene menu inside theDAW).
async function runProjectChoice(choice, data) {
const store = state.projectStore;
const guard = () => !store.state.dirty || window.confirm('Discard unsaved changes?');
try {
if (choice === 'new' && guard()) await store.openTemplate('first-flight');
else if (choice === 'open' && guard()) await store.openFromDialog();
else if (choice === 'save') await store.save();
else if (choice === 'saveas') await store.saveAs();
else if (choice === 'recent' && guard()) await store.openPath(data.path);
else if (choice === 'template' && guard()) await store.openTemplate(data.id);
} catch (err) {
notice(`Project: ${err.message}`, 7000);
}
postProjectLoad();
}
async function openProjectMenu() {
if (popoverAnchor() === $('#project-btn')) return closePopover();
const store = state.projectStore;
const [recent, templates] = await Promise.all([
window.swaycommand.project.recent().catch(() => []),
window.swaycommand.project.templates().catch(() => []),
]);
const rows = [
'<button class="pop-item" data-choice="new">New</button>',
'<button class="pop-item" data-choice="open">Open...</button>',
'<button class="pop-item" data-choice="save">Save</button>',
'<button class="pop-item" data-choice="saveas">Save as...</button>',
];
const recents = recent.filter((r) => r.path !== store.state.path);
if (recents.length) {
rows.push('<div class="pop-label">RECENT</div>');
for (const r of recents.slice(0, 6)) {
rows.push(`<button class="pop-item" data-choice="recent" data-path="${r.path.replace(/"/g, '"')}">${r.name}<span>${r.path}</span></button>`);
}
}
if (templates.length) {
rows.push('<div class="pop-label">TEMPLATES</div>');
for (const t of templates) {
rows.push(`<button class="pop-item" data-choice="template" data-id="${t.id}">${t.name}<span>${t.vibe}</span></button>`);
}
}
openPopover($('#project-btn'), rows.join(''), runProjectChoice);
}
function wireTopbar() {
$('#project-btn').addEventListener('click', openProjectMenu);
$('#t-play').addEventListener('click', () => {
state.transport.state.playing ? state.transport.pause() : state.transport.play();
});
$('#t-stop').addEventListener('click', () => state.transport.stop());
$('#t-loop').addEventListener('click', () => {
const loop = state.transport.state.loop;
state.transport.setLoop(loop.start, loop.end, !loop.enabled);
ui.timeline.render();
});
$('#deckbar').addEventListener('click', (e) => {
const btn = e.target.closest('[data-drawer]');
if (btn) ui.drawer.toggle(btn.dataset.drawer);
});
$('#btn-help').addEventListener('click', () => (modalOpen('help') ? closeModal('help') : openModal('help')));
}
// ---------------------------------------------------------------- input box
async function openSourceMenu() {
if (popoverAnchor() === $('#input-src')) return closePopover();
let inputs = [];
try {
inputs = await state.audio.listInputs();
} catch {
inputs = [];
}
studio.sources = inputs;
const a = state.audio.state;
const rows = [
`<button class="pop-item${a.source === 'system' ? ' current' : ''}" data-choice="system" ${studio.systemAudio.supported ? '' : 'disabled'}>System audio<span>${
studio.systemAudio.supported ? 'Everything playing on this computer' : studio.systemAudio.detail || 'Windows only'
}</span></button>`,
];
for (const d of inputs) {
rows.push(
`<button class="pop-item${a.source === 'input' && a.deviceId === d.id ? ' current' : ''}" data-choice="input" data-id="${d.id}">${d.label}<span>Input device</span></button>`
);
}
rows.push(`<button class="pop-item${a.source === 'internal' ? ' current' : ''}" data-choice="internal">Internal groove<span>Silent 120 BPM analysis signal</span></button>`);
openPopover($('#input-src'), rows.join(''), async (choice, data) => {
try {
if (choice === 'system') await state.audio.useSystemAudio();
else if (choice === 'input') await state.audio.useInput(data.id);
else {
state.audio.releaseInput();
state.audio.startInternal();
}
} catch (err) {
notice(`Source: ${err.message}`, 6000);
}
updateSourceLabel();
});
}
function updateSourceLabel() {
const a = state.audio.state;
$('#input-src').textContent = a.deviceLabel || (a.source === 'internal' ? 'Internal groove' : a.source) || '-';
}
// ---------------------------------------------------------------- scenes / auto
function renderSceneBank() {
const pool = state.engine.autoVJ.pool;
$('#scene-bank').innerHTML = state.engine.sceneList
.map((s) => {
const poolIdx = pool.indexOf(s.id);
const digit = poolIdx >= 0 && poolIdx < 9 ? poolIdx + 1 : '';
return `<li><button draggable="true" data-scene="${s.id}" class="${poolIdx >= 0 ? 'pooled' : ''}"><b>${digit}</b>${s.name}</button></li>`;
})
.join('');
}
function updateAutoBox() {
const av = state.engine.autoVJ;
$('#auto-toggle').classList.toggle('on', av.enabled);
if (document.activeElement !== $('#auto-min')) $('#auto-min').value = Math.round(av.minHold);
if (document.activeElement !== $('#auto-max')) $('#auto-max').value = Math.round(av.maxHold);
if (document.activeElement !== $('#auto-fade')) $('#auto-fade').value = av.fadeTime;
}
function wireScenes() {
$('#scene-bank').addEventListener('click', (e) => {
const btn = e.target.closest('[data-scene]');
if (!btn) return;
state.engine.autoVJ.enabled = false;
state.engine.setScene(btn.dataset.scene);
updateAutoBox();
});
$('#scene-bank').addEventListener('dragstart', (e) => {
const btn = e.target.closest('[data-scene]');
if (!btn) return;
e.dataTransfer.setData('application/x-sway-scene', btn.dataset.scene);
e.dataTransfer.effectAllowed = 'copy';
});
$('#auto-toggle').addEventListener('click', () => {
state.engine.autoVJ.enabled = !state.engine.autoVJ.enabled;
updateAutoBox();
});
$('#auto-min').addEventListener('change', (e) => {
state.engine.autoVJ.minHold = Math.max(1, Number(e.target.value) || 18);
state.projectStore.markDirty();
});
$('#auto-max').addEventListener('change', (e) => {
state.engine.autoVJ.maxHold = Math.max(state.engine.autoVJ.minHold, Number(e.target.value) || 40);
state.projectStore.markDirty();
});
$('#auto-fade').addEventListener('change', (e) => {
state.engine.autoVJ.fadeTime = Math.max(0, Number(e.target.value) || 4);
state.projectStore.markDirty();
});
}
// ---------------------------------------------------------------- deck / selection
function selectControl(target) {
ui.assign.select(target);
ui.surface.select(target);
}
// Pad labels + button lit states, refreshed on assignment/kit changes.
function refreshDeck() {
const asg = state.router.getAssignments();
const samples = state.sampler.listSamples();
const kit = state.sampler.getKit();
const labels = [];
for (let i = 0; i < 16; i++) {
const a = asg.pads[i];
if (!a) {
labels.push('');
} else if (a.type === 'sample') {
const pad = kit.pads && kit.pads[a.pad ?? i];
const s = pad && samples.find((x) => x.id === pad.id);
labels.push(s ? s.name.replace(/\.[a-z0-9]+$/i, '') : '');
} else if (a.type === 'scene') {
const meta = state.engine.sceneList.find((s) => s.id === a.scene);
labels.push(meta ? meta.name : a.scene);
} else if (a.type === 'sceneAction') {
const meta = state.engine.sceneList.find((s) => s.id === a.scene);
const ctl = meta && meta.controls && meta.controls.actions.find((c) => c.key === a.action);
labels.push(ctl ? ctl.label : a.action);
} else if (a.type === 'stem') {
const p = state.projectStore.project();
const m = p && p.media.find((x) => x.id === a.media);
const st = state.transport.stemState(a.media);
labels.push((st === 'on' ? '▶ ' : st === 'pending' ? '... ' : '') + (m ? m.name.replace(/\.[a-z0-9]+$/i, '') : 'stem'));
} else if (a.type === 'trackFx') {
labels.push(a.fx === 'vst' ? 'vst mix' : a.param);
} else {
labels.push(a.param);
}
}
ui.surface.refresh(labels, buttonLitStates());
}
function buttonLitStates() {
const asg = state.router.getAssignments();
return asg.buttons.map((b) => {
if (!b || !b.action) return false;
const t = b.action.target;
if (t === 'engine:fxEnabled') return state.engine.fxEnabled;
if (t === 'engine:autoVJ') return state.engine.autoVJ.enabled;
if (t === 'synth:enabled') return state.router.synthEnabled;
if (t === 'transport:playPause') return state.transport.state.playing;
if (t.startsWith('fx:')) return !!state.engine.fx.params[t.slice(3)];
if (t.startsWith('track:')) {
const parts = t.split(':');
const tr = state.transport.trackById(parts[1]);
if (!tr) return false;
if (parts.length === 3) return parts[2] === 'mute' ? tr.muted : parts[2] === 'solo' ? tr.solo : false;
return state.transport.getTrackParam(tr.id, parts[2], 'enabled') >= 0.5;
}
return false;
});
}
function onDeckSelect(target) {
// With a sample armed from the kit drawer, clicking a pad places it.
if (studio.selectedSample && target.startsWith('pad:') && ui.drawer.isOpen('kit')) {
const i = Number(target.slice(4));
state.sampler.assignPad(i, studio.selectedSample, { mode: 'oneshot', gain: 1 });
const asg = state.router.getAssignments();
asg.pads[i] = { type: 'sample', pad: i };
state.projectStore.markDirty();
refreshDeck();
}
selectControl(target);
}
// ---------------------------------------------------------------- keyboard
const PAD_KEYS = ['z', 'x', 'c', 'v', 'b', 'n', 'm', ','];
function wireKeyboard() {
window.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
escapePop();
return;
}
if (/^(input|select|textarea)$/i.test(e.target.tagName)) return;
if (synthKeyDown(e)) return;
const k = e.key.toLowerCase();
const sceneIdx = Number(k) - 1;
const pool = state.engine.autoVJ.pool;
if (k >= '1' && k <= '9' && sceneIdx < pool.length) {
state.engine.autoVJ.enabled = false;
state.engine.setScene(pool[sceneIdx]);
updateAutoBox();
} else if (k === ' ') {
e.preventDefault();