-
Notifications
You must be signed in to change notification settings - Fork 190
/
Copy pathSongEditor.ts
2080 lines (1943 loc) · 96.8 KB
/
SongEditor.ts
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
// Copyright (c) John Nesky and contributing authors, distributed under the MIT license, see accompanying the LICENSE.md file.
import {InstrumentType, EffectType, Config, getPulseWidthRatio, effectsIncludeTransition, effectsIncludeChord, effectsIncludePitchShift, effectsIncludeDetune, effectsIncludeVibrato, effectsIncludeNoteFilter, effectsIncludeDistortion, effectsIncludeBitcrusher, effectsIncludePanning, effectsIncludeChorus, effectsIncludeEcho, effectsIncludeReverb} from "../synth/SynthConfig.js";
import {Preset, PresetCategory, EditorConfig, isMobile, prettyNumber} from "./EditorConfig.js";
import {ColorConfig, ChannelColors} from "./ColorConfig.js";
import "./Layout.js"; // Imported here for the sake of ensuring this code is transpiled early.
import {Instrument, Channel, Synth} from "../synth/synth.js";
import {HTML} from "imperative-html/dist/esm/elements-strict.js";
import {EasyPointers, getElementDimensions} from "./EasyPointers.js";
import {Preferences} from "./Preferences.js";
import {SongDocument} from "./SongDocument.js";
import {Prompt} from "./Prompt.js";
import {TipPrompt} from "./TipPrompt.js";
import {PatternEditor} from "./PatternEditor.js";
import {EnvelopeEditor} from "./EnvelopeEditor.js";
import {FadeInOutEditor} from "./FadeInOutEditor.js";
import {FilterEditor} from "./FilterEditor.js";
import {MuteEditor} from "./MuteEditor.js";
import {TrackEditor} from "./TrackEditor.js";
import {ChannelRow} from "./ChannelRow.js";
import {LayoutPrompt} from "./LayoutPrompt.js";
import {LoopEditor} from "./LoopEditor.js";
import {SpectrumEditor} from "./SpectrumEditor.js";
import {HarmonicsEditor} from "./HarmonicsEditor.js";
import {BarScrollBar} from "./BarScrollBar.js";
import {OctaveScrollBar} from "./OctaveScrollBar.js";
import {MidiInputHandler} from "./MidiInput.js";
import {KeyboardLayout} from "./KeyboardLayout.js";
import {Piano} from "./Piano.js";
import {BeatsPerBarPrompt} from "./BeatsPerBarPrompt.js";
import {MoveNotesSidewaysPrompt} from "./MoveNotesSidewaysPrompt.js";
import {SongDurationPrompt} from "./SongDurationPrompt.js";
import {SustainPrompt} from "./SustainPrompt.js";
import {ChannelSettingsPrompt} from "./ChannelSettingsPrompt.js";
import {ExportPrompt} from "./ExportPrompt.js";
import {ImportPrompt} from "./ImportPrompt.js";
import {SongRecoveryPrompt} from "./SongRecoveryPrompt.js";
import {RecordingSetupPrompt} from "./RecordingSetupPrompt.js";
import {Change} from "./Change.js";
import {ChangeTempo, ChangeChorus, ChangeEchoDelay, ChangeEchoSustain, ChangeReverb, ChangeVolume, ChangePan, ChangePatternSelection, ChangeSupersawDynamism, ChangeSupersawSpread, ChangeSupersawShape, ChangePulseWidth, ChangeFeedbackAmplitude, ChangeOperatorAmplitude, ChangeOperatorFrequency, ChangeDrumsetEnvelope, ChangePasteInstrument, ChangePreset, pickRandomPresetValue, ChangeRandomGeneratedInstrument, ChangeScale, ChangeDetectKey, ChangeKey, ChangeRhythm, ChangeFeedbackType, ChangeAlgorithm, ChangeCustomizeInstrument, ChangeChipWave, ChangeNoiseWave, ChangeTransition, ChangeToggleEffects, ChangeVibrato, ChangeUnison, ChangeChord, ChangeSong, ChangePitchShift, ChangeDetune, ChangeDistortion, ChangeStringSustain, ChangeBitcrusherFreq, ChangeBitcrusherQuantization, ChangeAddEnvelope, ChangeAddChannelInstrument, ChangeRemoveChannelInstrument} from "./changes.js";
const {a, button, div, input, select, span, optgroup, option} = HTML;
function buildOptions(menu: HTMLSelectElement, items: ReadonlyArray<string | number>): HTMLSelectElement {
for (let index: number = 0; index < items.length; index++) {
menu.appendChild(option({value: index}, items[index]));
}
return menu;
}
function buildPresetOptions(isNoise: boolean): HTMLSelectElement {
const menu: HTMLSelectElement = select();
menu.appendChild(optgroup({label: "Edit"},
option({value: "copyInstrument"}, "Copy Instrument (⇧C)"),
option({value: "pasteInstrument"}, "Paste Instrument (⇧V)"),
option({value: "randomPreset"}, "Random Preset (R)"),
option({value: "randomGenerated"}, "Random Generated (⇧R)"),
));
// Show the "spectrum" custom type in both pitched and noise channels.
const customTypeGroup: HTMLElement = optgroup({label: EditorConfig.presetCategories[0].name});
if (isNoise) {
customTypeGroup.appendChild(option({value: InstrumentType.noise}, EditorConfig.valueToPreset(InstrumentType.noise)!.name));
customTypeGroup.appendChild(option({value: InstrumentType.spectrum}, EditorConfig.valueToPreset(InstrumentType.spectrum)!.name));
customTypeGroup.appendChild(option({value: InstrumentType.drumset}, EditorConfig.valueToPreset(InstrumentType.drumset)!.name));
} else {
customTypeGroup.appendChild(option({value: InstrumentType.chip}, EditorConfig.valueToPreset(InstrumentType.chip)!.name));
customTypeGroup.appendChild(option({value: InstrumentType.pwm}, EditorConfig.valueToPreset(InstrumentType.pwm)!.name));
customTypeGroup.appendChild(option({value: InstrumentType.supersaw}, EditorConfig.valueToPreset(InstrumentType.supersaw)!.name));
customTypeGroup.appendChild(option({value: InstrumentType.harmonics}, EditorConfig.valueToPreset(InstrumentType.harmonics)!.name));
customTypeGroup.appendChild(option({value: InstrumentType.pickedString}, EditorConfig.valueToPreset(InstrumentType.pickedString)!.name));
customTypeGroup.appendChild(option({value: InstrumentType.spectrum}, EditorConfig.valueToPreset(InstrumentType.spectrum)!.name));
customTypeGroup.appendChild(option({value: InstrumentType.fm}, EditorConfig.valueToPreset(InstrumentType.fm)!.name));
}
menu.appendChild(customTypeGroup);
for (let categoryIndex: number = 1; categoryIndex < EditorConfig.presetCategories.length; categoryIndex++) {
const category: PresetCategory = EditorConfig.presetCategories[categoryIndex];
const group: HTMLElement = optgroup({label: category.name});
let foundAny: boolean = false;
for (let presetIndex: number = 0; presetIndex < category.presets.length; presetIndex++) {
const preset: Preset = category.presets[presetIndex];
if ((preset.isNoise == true) == isNoise) {
group.appendChild(option({value: (categoryIndex << 6) + presetIndex}, preset.name));
foundAny = true;
}
}
if (foundAny) menu.appendChild(group);
}
return menu;
}
function setSelectedValue(menu: HTMLSelectElement, value: number): void {
const stringValue = value.toString();
if (menu.value != stringValue) menu.value = stringValue;
}
class Slider {
public container: HTMLSpanElement;
private _change: Change | null = null;
private _value: number = 0;
private _oldValue: number = 0;
constructor(public readonly input: HTMLInputElement, private readonly _doc: SongDocument, private readonly _getChange: (oldValue: number, newValue: number) => Change | null) {
input.addEventListener("input", this._onInput);
input.addEventListener("change", this._onChange);
// Touch screens update the slider value as soon as you touch the slider,
// but also allow scrolling by vertically dragging from the slider, which
// can result in both the slider changing and the screen scrolling from
// the same gesture, which feels bad. Unfortunately, calling
// preventDefault() in the pointerdown listener does not prevent changing
// the slider value on touchscreens, so we need to completely bypass
// touching the slider. This code prevents the initial slider change and
// reimplements it if the pointer will not scroll.
input.style.pointerEvents = "none";
this.container = span(input, {style: "touch-action: pan-y; display: flex;"});
new EasyPointers(this.container);
this.container.addEventListener("pointerdown", this._onPointerDown);
this.container.addEventListener("pointermove", this._onPointerMove);
this.container.addEventListener("pointerup", this._onPointerUp);
}
private _setFromPointer(event: PointerEvent): void {
const x = event.pointer!.getPointIn(this.input, "contentBox").x;
const dimensions = getElementDimensions(this.input, "contentBox");
const thumbWidth: number = 6; // BeepBox slider thumbs are styled with a width of 6 pixels.
const ratio = (x - (thumbWidth / 2)) / (dimensions.width - thumbWidth);
const step = parseFloat(this.input.step) || 1;
let min = parseFloat(this.input.min);
let max = parseFloat(this.input.max);
if (!isFinite(min)) min = 0;
if (!isFinite(max)) max = 100;
const value = Math.max(min, Math.min(max, Math.round(((max - min) * ratio) / step) * step + min));
this.input.value = String(value);
}
private _onPointerDown = (event: PointerEvent): void => {
this._setFromPointer(event);
this.input.dispatchEvent(new InputEvent("input", {bubbles: true, cancelable: false, composed: true}));
}
private _onPointerMove = (event: PointerEvent): void => {
if (event.pointer!.isDown) {
this._setFromPointer(event);
this.input.dispatchEvent(new InputEvent("input", {bubbles: true, cancelable: false, composed: true}));
}
}
private _onPointerUp = (event: PointerEvent): void => {
this._setFromPointer(event);
this.input.dispatchEvent(new InputEvent("input", {bubbles: true, cancelable: false, composed: true}));
this.input.dispatchEvent(new Event("change", {bubbles: true, cancelable: false, composed: true}));
}
public updateValue(value: number): void {
this._value = value;
this.input.value = String(value);
}
private _onInput = (): void => {
const continuingProspectiveChange: boolean = this._doc.lastChangeWas(this._change);
if (!continuingProspectiveChange) this._oldValue = this._value;
this._change = this._getChange(this._oldValue, parseInt(this.input.value));
if (this._change) this._doc.setProspectiveChange(this._change);
};
private _onChange = (): void => {
if (this._change) this._doc.record(this._change);
this._change = null;
};
}
export class SongEditor {
public readonly doc: SongDocument = new SongDocument();
public prompt: Prompt | null = null;
private readonly _keyboardLayout: KeyboardLayout = new KeyboardLayout(this.doc);
private readonly _patternEditorPrev: PatternEditor = new PatternEditor(this.doc, false, -1);
private readonly _patternEditor: PatternEditor = new PatternEditor(this.doc, true, 0);
private readonly _patternEditorNext: PatternEditor = new PatternEditor(this.doc, false, 1);
private readonly _muteEditor: MuteEditor = new MuteEditor(this.doc);
private readonly _trackEditor: TrackEditor = new TrackEditor(this.doc);
private readonly _loopEditor: LoopEditor = new LoopEditor(this.doc);
private readonly _octaveScrollBar: OctaveScrollBar = new OctaveScrollBar(this.doc);
private readonly _piano: Piano = new Piano(this.doc);
private readonly _playButton: HTMLButtonElement = button({class: "playButton", type: "button", title: "Play (Space)"}, span("Play"));
private readonly _pauseButton: HTMLButtonElement = button({class: "pauseButton", style: "display: none;", type: "button", title: "Pause (Space)"}, "Pause");
private readonly _recordButton: HTMLButtonElement = button({class: "recordButton", style: "display: none;", type: "button", title: "Record (Ctrl+Space)"}, span("Record"));
private readonly _stopButton: HTMLButtonElement = button({class: "stopButton", style: "display: none;", type: "button", title: "Stop Recording (Space)"}, "Stop Recording");
private readonly _prevBarButton: HTMLButtonElement = button({class: "prevBarButton", type: "button", title: "Previous Bar (left bracket)"});
private readonly _nextBarButton: HTMLButtonElement = button({class: "nextBarButton", type: "button", title: "Next Bar (right bracket)"});
private readonly _volumeSlider: Slider = new Slider(input({title: "main volume", style: "flex-grow: 1; margin: 0;", type: "range", min: "0", max: "75", value: "50", step: "1"}), this.doc, (oldValue: number, newValue: number) => { this._setVolumeSlider(); return null; });
private readonly _fileMenu: HTMLSelectElement = select({style: "width: 100%;"},
option({selected: true, disabled: true, hidden: false}, "File"), // todo: "hidden" should be true but looks wrong on mac chrome, adds checkmark next to first visible option even though it's not selected. :(
option({value: "new"}, "+ New Blank Song"),
option({value: "import"}, "↑ Import Song... (" + EditorConfig.ctrlSymbol + "O)"),
option({value: "export"}, "↓ Export Song... (" + EditorConfig.ctrlSymbol + "S)"),
option({value: "copyUrl"}, "⎘ Copy Song URL"),
option({value: "shareUrl"}, "⤳ Share Song URL"),
option({value: "shortenUrl"}, "… Shorten Song URL"),
option({value: "viewPlayer"}, "▶ View in Song Player"),
option({value: "copyEmbed"}, "⎘ Copy HTML Embed Code"),
option({value: "songRecovery"}, "⚠ Recover Recent Song..."),
);
private readonly _editMenu: HTMLSelectElement = select({style: "width: 100%;"},
option({selected: true, disabled: true, hidden: false}, "Edit"), // todo: "hidden" should be true but looks wrong on mac chrome, adds checkmark next to first visible option even though it's not selected. :(
option({value: "undo"}, "Undo (Z)"),
option({value: "redo"}, "Redo (Y)"),
option({value: "copy"}, "Copy Pattern (C)"),
option({value: "pasteNotes"}, "Paste Pattern Notes (V)"),
option({value: "pasteNumbers"}, "Paste Pattern Numbers (" + EditorConfig.ctrlSymbol + "⇧V)"),
option({value: "insertBars"}, "Insert Bar (⏎)"),
option({value: "deleteBars"}, "Delete Selected Bars (⌫)"),
option({value: "insertChannel"}, "Insert Channel (" + EditorConfig.ctrlSymbol + "⏎)"),
option({value: "deleteChannel"}, "Delete Selected Channels (" + EditorConfig.ctrlSymbol + "⌫)"),
option({value: "selectAll"}, "Select All (A)"),
option({value: "selectChannel"}, "Select Channel (⇧A)"),
option({value: "duplicatePatterns"}, "Duplicate Reused Patterns (D)"),
option({value: "transposeUp"}, "Move Notes Up (+ or ⇧+)"),
option({value: "transposeDown"}, "Move Notes Down (- or ⇧-)"),
option({value: "moveNotesSideways"}, "Move All Notes Sideways..."),
option({value: "beatsPerBar"}, "Change Beats Per Bar..."),
option({value: "barCount"}, "Change Song Length..."),
option({value: "channelSettings"}, "Channel Settings... (Q)"),
);
private readonly _optionsMenu: HTMLSelectElement = select({style: "width: 100%;"},
option({selected: true, disabled: true, hidden: false}, "Preferences"), // todo: "hidden" should be true but looks wrong on mac chrome, adds checkmark next to first visible option even though it's not selected. :(
option({value: "autoPlay"}, "Auto Play on Load"),
option({value: "autoFollow"}, "Show And Play The Same Bar"),
option({value: "enableNotePreview"}, "Hear Preview of Added Notes"),
option({value: "showLetters"}, "Show Piano Keys"),
option({value: "showFifth"}, 'Highlight "Fifth" of Song Key'),
option({value: "notesOutsideScale"}, "Allow Adding Notes Not in Scale"),
option({value: "setDefaultScale"}, "Use Current Scale as Default"),
option({value: "showChannels"}, "Show Notes From All Channels"),
option({value: "showScrollBar"}, "Show Octave Scroll Bar"),
option({value: "alwaysShowSettings"}, "Customize All Instruments"),
option({value: "instrumentCopyPaste"}, "Instrument Copy/Paste Buttons"),
option({value: "enableChannelMuting"}, "Enable Channel Muting"),
option({value: "displayBrowserUrl"}, "Display Song Data in URL"),
option({value: "layout"}, "Choose Layout..."),
option({value: "colorTheme"}, "Light Theme"),
option({value: "recordingSetup"}, "Set Up Note Recording..."),
);
private readonly _scaleSelect: HTMLSelectElement = buildOptions(select(), Config.scales.map(scale=>scale.name));
private readonly _keySelect: HTMLSelectElement = buildOptions(select(), Config.keys.map(key=>key.name).reverse());
private readonly _tempoSlider: Slider = new Slider(input({style: "margin: 0; width: 4em; flex-grow: 1; vertical-align: middle;", type: "range", min: "0", max: "14", value: "7", step: "1"}), this.doc, (oldValue: number, newValue: number) => new ChangeTempo(this.doc, oldValue, Math.round(120.0 * Math.pow(2.0, (-4.0 + newValue) / 9.0))));
private readonly _tempoStepper: HTMLInputElement = input({style: "width: 3em; margin-left: 0.4em; vertical-align: middle;", type: "number", step: "1"});
private readonly _chorusSlider: Slider = new Slider(input({style: "margin: 0;", type: "range", min: "0", max: Config.chorusRange - 1, value: "0", step: "1"}), this.doc, (oldValue: number, newValue: number) => new ChangeChorus(this.doc, oldValue, newValue));
private readonly _chorusRow: HTMLDivElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("chorus")}, "Chorus:"), this._chorusSlider.container);
private readonly _reverbSlider: Slider = new Slider(input({style: "margin: 0;", type: "range", min: "0", max: Config.reverbRange - 1, value: "0", step: "1"}), this.doc, (oldValue: number, newValue: number) => new ChangeReverb(this.doc, oldValue, newValue));
private readonly _reverbRow: HTMLDivElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("reverb")}, "Reverb:"), this._reverbSlider.container);
private readonly _echoSustainSlider: Slider = new Slider(input({style: "margin: 0;", type: "range", min: "0", max: Config.echoSustainRange - 1, value: "0", step: "1"}), this.doc, (oldValue: number, newValue: number) => new ChangeEchoSustain(this.doc, oldValue, newValue));
private readonly _echoSustainRow: HTMLDivElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("echoSustain")}, "Echo:"), this._echoSustainSlider.container);
private readonly _echoDelaySlider: Slider = new Slider(input({style: "margin: 0;", type: "range", min: "0", max: Config.echoDelayRange - 1, value: "0", step: "1"}), this.doc, (oldValue: number, newValue: number) => new ChangeEchoDelay(this.doc, oldValue, newValue));
private readonly _echoDelayRow: HTMLDivElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("echoDelay")}, "Echo Delay:"), this._echoDelaySlider.container);
private readonly _rhythmSelect: HTMLSelectElement = buildOptions(select(), Config.rhythms.map(rhythm=>rhythm.name));
private readonly _pitchedPresetSelect: HTMLSelectElement = buildPresetOptions(false);
private readonly _drumPresetSelect: HTMLSelectElement = buildPresetOptions(true);
private readonly _algorithmSelect: HTMLSelectElement = buildOptions(select(), Config.algorithms.map(algorithm=>algorithm.name));
private readonly _algorithmSelectRow: HTMLDivElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("algorithm")}, "Algorithm:"), div({class: "selectContainer"}, this._algorithmSelect));
private readonly _instrumentButtons: HTMLButtonElement[] = [];
private readonly _instrumentAddButton: HTMLButtonElement = button({type: "button", class: "add-instrument last-button"});
private readonly _instrumentRemoveButton: HTMLButtonElement = button({type: "button", class: "remove-instrument"});
private readonly _instrumentsButtonBar: HTMLDivElement = div({class: "instrument-bar"}, this._instrumentRemoveButton, this._instrumentAddButton);
private readonly _instrumentsButtonRow: HTMLDivElement = div({class: "selectRow", style: "display: none;"}, span({class: "tip", onclick: ()=>this._openPrompt("instrumentIndex")}, "Instrument:"), this._instrumentsButtonBar);
private readonly _instrumentCopyButton: HTMLButtonElement = button({type: "button", class: "copy-instrument", title: "Copy Instrument (⇧C)"}, "Copy");
private readonly _instrumentPasteButton: HTMLButtonElement = button({type: "button", class: "paste-instrument", title: "Paste Instrument (⇧V)"}, "Paste");
private readonly _instrumentCopyPasteRow: HTMLDivElement = div({class: "instrumentCopyPasteRow", style: "display: none;"}, this._instrumentCopyButton, this._instrumentPasteButton);
private readonly _instrumentVolumeSlider: Slider = new Slider(input({style: "margin: 0;", type: "range", min: -(Config.volumeRange - 1), max: "0", value: "0", step: "1"}), this.doc, (oldValue: number, newValue: number) => new ChangeVolume(this.doc, oldValue, -newValue));
private readonly _instrumentVolumeSliderRow: HTMLDivElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("instrumentVolume")}, "Volume:"), this._instrumentVolumeSlider.container);
private readonly _panSlider: Slider = new Slider(input({style: "margin: 0;", type: "range", min: "0", max: Config.panMax, value: Config.panCenter, step: "1"}), this.doc, (oldValue: number, newValue: number) => new ChangePan(this.doc, oldValue, newValue));
private readonly _panSliderRow: HTMLDivElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("pan")}, "Panning:"), this._panSlider.container);
private readonly _chipWaveSelect: HTMLSelectElement = buildOptions(select(), Config.chipWaves.map(wave=>wave.name));
private readonly _chipNoiseSelect: HTMLSelectElement = buildOptions(select(), Config.chipNoises.map(wave=>wave.name));
private readonly _chipWaveSelectRow: HTMLDivElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("chipWave")}, "Wave:"), div({class: "selectContainer"}, this._chipWaveSelect));
private readonly _chipNoiseSelectRow: HTMLDivElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("chipNoise")}, "Noise:"), div({class: "selectContainer"}, this._chipNoiseSelect));
private readonly _fadeInOutEditor: FadeInOutEditor = new FadeInOutEditor(this.doc);
private readonly _fadeInOutRow: HTMLElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("fadeInOut")}, "Fade In/Out:"), this._fadeInOutEditor.container);
private readonly _transitionSelect: HTMLSelectElement = buildOptions(select(), Config.transitions.map(transition=>transition.name));
private readonly _transitionRow: HTMLDivElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("transition")}, "Transition:"), div({class: "selectContainer"}, this._transitionSelect));
private readonly _effectsSelect: HTMLSelectElement = select(option({selected: true, disabled: true, hidden: false})); // todo: "hidden" should be true but looks wrong on mac chrome, adds checkmark next to first visible option even though it's not selected. :(
private readonly _eqFilterEditor: FilterEditor = new FilterEditor(this.doc);
private readonly _eqFilterRow: HTMLElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("eqFilter")}, "EQ Filter:"), this._eqFilterEditor.container);
private readonly _noteFilterEditor: FilterEditor = new FilterEditor(this.doc, true);
private readonly _noteFilterRow: HTMLElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("noteFilter")}, "Note Filter:"), this._noteFilterEditor.container);
private readonly _supersawDynamismSlider: Slider = new Slider(input({style: "margin: 0;", type: "range", min: "0", max: Config.supersawDynamismMax, value: "0", step: "1"}), this.doc, (oldValue: number, newValue: number) => new ChangeSupersawDynamism(this.doc, oldValue, newValue));
private readonly _supersawDynamismRow: HTMLDivElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("supersawDynamism")}, "Dynamism:"), this._supersawDynamismSlider.container);
private readonly _supersawSpreadSlider: Slider = new Slider(input({style: "margin: 0;", type: "range", min: "0", max: Config.supersawSpreadMax, value: "0", step: "1"}), this.doc, (oldValue: number, newValue: number) => new ChangeSupersawSpread(this.doc, oldValue, newValue));
private readonly _supersawSpreadRow: HTMLDivElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("supersawSpread")}, "Spread:"), this._supersawSpreadSlider.container);
private readonly _supersawShapeSlider: Slider = new Slider(input({style: "margin: 0;", type: "range", min: "0", max: Config.supersawShapeMax, value: "0", step: "1"}), this.doc, (oldValue: number, newValue: number) => new ChangeSupersawShape(this.doc, oldValue, newValue));
private readonly _supersawShapeRow: HTMLDivElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("supersawShape")}, "Saw↔Pulse:"), this._supersawShapeSlider.container);
private readonly _pulseWidthSlider: Slider = new Slider(input({style: "margin: 0;", type: "range", min: "0", max: Config.pulseWidthRange - 1, value: "0", step: "1"}), this.doc, (oldValue: number, newValue: number) => new ChangePulseWidth(this.doc, oldValue, newValue));
private readonly _pulseWidthRow: HTMLDivElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("pulseWidth")}, "Pulse Width:"), this._pulseWidthSlider.container);
private readonly _pitchShiftSlider: Slider = new Slider(input({style: "margin: 0;", type: "range", min: "0", max: Config.pitchShiftRange - 1, value: "0", step: "1"}), this.doc, (oldValue: number, newValue: number) => new ChangePitchShift(this.doc, oldValue, newValue));
private readonly _pitchShiftTonicMarkers: HTMLDivElement[] = [div({class: "pitchShiftMarker", style: {color: ColorConfig.tonic}}), div({class: "pitchShiftMarker", style: {color: ColorConfig.tonic, left: "50%"}}), div({class: "pitchShiftMarker", style: {color: ColorConfig.tonic, left: "100%"}})];
private readonly _pitchShiftFifthMarkers: HTMLDivElement[] = [div({class: "pitchShiftMarker", style: {color: ColorConfig.fifthNote, left: (100*7/24)+"%"}}), div({class: "pitchShiftMarker", style: {color: ColorConfig.fifthNote, left: (100*19/24)+"%"}})];
private readonly _pitchShiftMarkerContainer: HTMLDivElement = div({style: "display: flex; position: relative;"}, this._pitchShiftSlider.container, div({class: "pitchShiftMarkerContainer"}, this._pitchShiftTonicMarkers, this._pitchShiftFifthMarkers));
private readonly _pitchShiftRow: HTMLDivElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("pitchShift")}, "Pitch Shift:"), this._pitchShiftMarkerContainer);
private readonly _detuneSlider: Slider = new Slider(input({style: "margin: 0;", type: "range", min: "0", max: Config.detuneMax, value: "0", step: "1"}), this.doc, (oldValue: number, newValue: number) => new ChangeDetune(this.doc, oldValue, newValue));
private readonly _detuneRow: HTMLDivElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("detune")}, "Detune:"), this._detuneSlider.container);
private readonly _distortionSlider: Slider = new Slider(input({style: "margin: 0;", type: "range", min: "0", max: Config.distortionRange - 1, value: "0", step: "1"}), this.doc, (oldValue: number, newValue: number) => new ChangeDistortion(this.doc, oldValue, newValue));
private readonly _distortionRow: HTMLDivElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("distortion")}, "Distortion:"), this._distortionSlider.container);
private readonly _bitcrusherQuantizationSlider: Slider = new Slider(input({style: "margin: 0;", type: "range", min: "0", max: Config.bitcrusherQuantizationRange - 1, value: "0", step: "1"}), this.doc, (oldValue: number, newValue: number) => new ChangeBitcrusherQuantization(this.doc, oldValue, newValue));
private readonly _bitcrusherQuantizationRow: HTMLDivElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("bitcrusherQuantization")}, "Bit Crush:"), this._bitcrusherQuantizationSlider.container);
private readonly _bitcrusherFreqSlider: Slider = new Slider(input({style: "margin: 0;", type: "range", min: "0", max: Config.bitcrusherFreqRange - 1, value: "0", step: "1"}), this.doc, (oldValue: number, newValue: number) => new ChangeBitcrusherFreq(this.doc, oldValue, newValue));
private readonly _bitcrusherFreqRow: HTMLDivElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("bitcrusherFreq")}, "Freq Crush:"), this._bitcrusherFreqSlider.container);
private readonly _stringSustainSlider: Slider = new Slider(input({style: "margin: 0;", type: "range", min: "0", max: Config.stringSustainRange - 1, value: "0", step: "1"}), this.doc, (oldValue: number, newValue: number) => new ChangeStringSustain(this.doc, oldValue, newValue));
private readonly _stringSustainLabel: HTMLSpanElement = span({class: "tip", onclick: ()=>this._openPrompt("stringSustain")}, "Sustain:");
private readonly _stringSustainRow: HTMLDivElement = div({class: "selectRow"}, this._stringSustainLabel, this._stringSustainSlider.container);
private readonly _unisonSelect: HTMLSelectElement = buildOptions(select(), Config.unisons.map(unison=>unison.name));
private readonly _unisonSelectRow: HTMLElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("unison")}, "Unison:"), div({class: "selectContainer"}, this._unisonSelect));
private readonly _chordSelect: HTMLSelectElement = buildOptions(select(), Config.chords.map(chord=>chord.name));
private readonly _chordSelectRow: HTMLElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("chords")}, "Chords:"), div({class: "selectContainer"}, this._chordSelect));
private readonly _vibratoSelect: HTMLSelectElement = buildOptions(select(), Config.vibratos.map(vibrato=>vibrato.name));
private readonly _vibratoSelectRow: HTMLElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("vibrato")}, "Vibrato:"), div({class: "selectContainer"}, this._vibratoSelect));
private readonly _phaseModGroup: HTMLElement = div({class: "editor-controls"});
private readonly _feedbackTypeSelect: HTMLSelectElement = buildOptions(select(), Config.feedbacks.map(feedback=>feedback.name));
private readonly _feedbackRow1: HTMLDivElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("feedbackType")}, "Feedback:"), div({class: "selectContainer"}, this._feedbackTypeSelect));
private readonly _spectrumEditor: SpectrumEditor = new SpectrumEditor(this.doc, null);
private readonly _spectrumRow: HTMLElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("spectrum")}, "Spectrum:"), this._spectrumEditor.container);
private readonly _harmonicsEditor: HarmonicsEditor = new HarmonicsEditor(this.doc);
private readonly _harmonicsRow: HTMLElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("harmonics")}, "Harmonics:"), this._harmonicsEditor.container);
private readonly _envelopeEditor: EnvelopeEditor = new EnvelopeEditor(this.doc);
private readonly _drumsetGroup: HTMLElement = div({class: "editor-controls"});
private readonly _feedbackAmplitudeSlider: Slider = new Slider(input({type: "range", min: "0", max: Config.operatorAmplitudeMax, value: "0", step: "1", title: "Feedback Amplitude"}), this.doc, (oldValue: number, newValue: number) => new ChangeFeedbackAmplitude(this.doc, oldValue, newValue));
private readonly _feedbackRow2: HTMLDivElement = div({class: "selectRow"}, span({class: "tip", onclick: ()=>this._openPrompt("feedbackVolume")}, "Fdback Vol:"), this._feedbackAmplitudeSlider.container);
private readonly _customizeInstrumentButton: HTMLButtonElement = button({type: "button", class: "customize-instrument"},
"Customize Instrument",
);
private readonly _addEnvelopeButton: HTMLButtonElement = button({type: "button", class: "add-envelope"});
private readonly _customInstrumentSettingsGroup: HTMLDivElement = div({class: "editor-controls"},
this._eqFilterRow,
this._fadeInOutRow,
this._chipWaveSelectRow,
this._chipNoiseSelectRow,
this._algorithmSelectRow,
this._phaseModGroup,
this._feedbackRow1,
this._feedbackRow2,
this._spectrumRow,
this._harmonicsRow,
this._drumsetGroup,
this._supersawDynamismRow,
this._supersawSpreadRow,
this._supersawShapeRow,
this._pulseWidthRow,
this._stringSustainRow,
this._unisonSelectRow,
div({style: `margin: 2px 0; margin-left: 2em; display: flex; align-items: center;`},
span({style: `flex-grow: 1; text-align: center;`}, span({class: "tip", onclick: ()=>this._openPrompt("effects")}, "Effects")),
div({class: "effects-menu"}, this._effectsSelect),
),
this._transitionRow,
this._chordSelectRow,
this._pitchShiftRow,
this._detuneRow,
this._vibratoSelectRow,
this._noteFilterRow,
this._distortionRow,
this._bitcrusherQuantizationRow,
this._bitcrusherFreqRow,
this._panSliderRow,
this._chorusRow,
this._echoSustainRow,
this._echoDelayRow,
this._reverbRow,
div({style: `margin: 2px 0; margin-left: 2em; display: flex; align-items: center;`},
span({style: `flex-grow: 1; text-align: center;`}, span({class: "tip", onclick: ()=>this._openPrompt("envelopes")}, "Envelopes")),
this._addEnvelopeButton,
),
this._envelopeEditor.container,
);
private readonly _instrumentSettingsGroup: HTMLDivElement = div({class: "editor-controls"},
div({style: `margin: 3px 0; text-align: center; color: ${ColorConfig.secondaryText};`},
"Instrument Settings"
),
this._instrumentsButtonRow,
this._instrumentCopyPasteRow,
this._instrumentVolumeSliderRow,
div({class: "selectRow"},
span({class: "tip", onclick: ()=>this._openPrompt("instrumentType")}, "Type:"),
div({class: "selectContainer"}, this._pitchedPresetSelect, this._drumPresetSelect),
),
this._customizeInstrumentButton,
this._customInstrumentSettingsGroup,
);
private readonly _promptContainer: HTMLDivElement = div({class: "promptContainer", style: "display: none;"});
private readonly _zoomInButton: HTMLButtonElement = button({class: "zoomInButton", type: "button", title: "Zoom In"});
private readonly _zoomOutButton: HTMLButtonElement = button({class: "zoomOutButton", type: "button", title: "Zoom Out"});
private readonly _patternEditorRow: HTMLDivElement = div({style: "flex: 1; height: 100%; display: flex; overflow: hidden; justify-content: center;"},
this._patternEditorPrev.container,
this._patternEditor.container,
this._patternEditorNext.container,
);
private readonly _patternArea: HTMLDivElement = div({class: "pattern-area"},
this._piano.container,
this._patternEditorRow,
this._octaveScrollBar.container,
this._zoomInButton,
this._zoomOutButton,
);
private readonly _trackContainer: HTMLDivElement = div({class: "trackContainer noSelection"},
this._trackEditor.container,
this._loopEditor.container,
);
private readonly _trackVisibleArea: HTMLDivElement = div({style: "position: absolute; width: 100%; height: 100%; pointer-events: none;"});
private readonly _trackAndMuteContainer: HTMLDivElement = div({class: "trackAndMuteContainer prefers-big-scrollbars"},
this._muteEditor.container,
this._trackContainer,
this._trackVisibleArea,
);
private readonly _barScrollBar: BarScrollBar = new BarScrollBar(this.doc);
private readonly _trackArea: HTMLDivElement = div({class: "track-area"},
this._trackAndMuteContainer,
this._barScrollBar.container,
);
private readonly _menuArea: HTMLDivElement = div({class: "menu-area"},
div({class: "selectContainer menu file"},
this._fileMenu,
),
div({class: "selectContainer menu edit"},
this._editMenu,
),
div({class: "selectContainer menu preferences"},
this._optionsMenu,
),
);
private readonly _songSettingsArea: HTMLDivElement = div({class: "song-settings-area"},
div({class: "editor-controls"},
div({style: `margin: 3px 0; text-align: center; color: ${ColorConfig.secondaryText};`},
"Song Settings",
),
div({class: "selectRow"},
span({class: "tip", onclick: ()=>this._openPrompt("scale")}, "Scale:"),
div({class: "selectContainer"}, this._scaleSelect),
),
div({class: "selectRow"},
span({class: "tip", onclick: ()=>this._openPrompt("key")}, "Key:"),
div({class: "selectContainer"}, this._keySelect),
),
div({class: "selectRow"},
span({class: "tip", onclick: ()=>this._openPrompt("tempo")}, "Tempo:"),
span({style: "display: flex;"},
this._tempoSlider.container,
this._tempoStepper,
),
),
div({class: "selectRow"},
span({class: "tip", onclick: ()=>this._openPrompt("rhythm")}, "Rhythm:"),
div({class: "selectContainer"}, this._rhythmSelect),
),
),
);
private readonly _instrumentSettingsArea: HTMLDivElement = div({class: "instrument-settings-area"}, this._instrumentSettingsGroup);
private readonly _settingsArea: HTMLDivElement = div({class: "settings-area noSelection"},
div({class: "version-area"},
div({style: `text-align: center; margin: 3px 0; color: ${ColorConfig.secondaryText};`},
EditorConfig.versionDisplayName,
" ",
a({class: "tip", target: "_blank", href: EditorConfig.releaseNotesURL},
EditorConfig.version,
),
),
),
div({class: "play-pause-area"},
div({class: "playback-bar-controls"},
this._playButton,
this._pauseButton,
this._recordButton,
this._stopButton,
this._prevBarButton,
this._nextBarButton,
),
div({class: "playback-volume-controls"},
span({class: "volume-speaker"}),
this._volumeSlider.container,
),
),
this._menuArea,
this._songSettingsArea,
this._instrumentSettingsArea,
);
public readonly mainLayer: HTMLDivElement = div({class: "beepboxEditor", tabIndex: "0"},
this._patternArea,
this._trackArea,
this._settingsArea,
this._promptContainer,
);
private _wasPlaying: boolean = false;
private _currentPromptName: string | null = null;
private _highlightedInstrumentIndex: number = -1;
private _renderedInstrumentCount: number = 0;
private _renderedIsPlaying: boolean = false;
private _renderedIsRecording: boolean = false;
private _renderedShowRecordButton: boolean = false;
private _renderedCtrlHeld: boolean = false;
private _ctrlHeld: boolean = false;
private _deactivatedInstruments: boolean = false;
private readonly _operatorRows: HTMLDivElement[] = []
private readonly _operatorAmplitudeSliders: Slider[] = []
private readonly _operatorFrequencySelects: HTMLSelectElement[] = []
private readonly _drumsetSpectrumEditors: SpectrumEditor[] = [];
private readonly _drumsetEnvelopeSelects: HTMLSelectElement[] = [];
constructor(beepboxEditorContainer: HTMLElement) {
this.doc.notifier.watch(this.whenUpdated);
new MidiInputHandler(this.doc);
window.addEventListener("resize", this.whenUpdated);
window.requestAnimationFrame(this.updatePlayButton);
if (!("share" in navigator)) {
this._fileMenu.removeChild(this._fileMenu.querySelector("[value='shareUrl']")!);
}
this._scaleSelect.appendChild(optgroup({label: "Edit"},
option({value: "forceScale"}, "Snap Notes To Scale"),
));
this._keySelect.appendChild(optgroup({label: "Edit"},
option({value: "detectKey"}, "Detect Key"),
));
this._rhythmSelect.appendChild(optgroup({label: "Edit"},
option({value: "forceRhythm"}, "Snap Notes To Rhythm"),
));
this._phaseModGroup.appendChild(div({class: "selectRow", style: `color: ${ColorConfig.secondaryText}; height: 1em; margin-top: 0.5em;`},
div({style: "margin-right: .1em; visibility: hidden;"}, 1 + "."),
div({style: "width: 3em; margin-right: .3em;", class: "tip", onclick: ()=>this._openPrompt("operatorFrequency")}, "Freq:"),
div({class: "tip", onclick: ()=>this._openPrompt("operatorVolume")}, "Volume:"),
));
for (let i: number = 0; i < Config.operatorCount; i++) {
const operatorIndex: number = i;
const operatorNumber: HTMLDivElement = div({style: `margin-right: .1em; color: ${ColorConfig.secondaryText};`}, i + 1 + ".");
const frequencySelect: HTMLSelectElement = buildOptions(select({style: "width: 100%;", title: "Frequency"}), Config.operatorFrequencies.map(freq=>freq.name));
const amplitudeSlider: Slider = new Slider(input({type: "range", min: "0", max: Config.operatorAmplitudeMax, value: "0", step: "1", title: "Volume"}), this.doc, (oldValue: number, newValue: number) => new ChangeOperatorAmplitude(this.doc, operatorIndex, oldValue, newValue));
const row: HTMLDivElement = div({class: "selectRow"},
operatorNumber,
div({class: "selectContainer", style: "width: 3em; margin-right: .3em;"}, frequencySelect),
amplitudeSlider.container,
);
this._phaseModGroup.appendChild(row);
this._operatorRows[i] = row;
this._operatorAmplitudeSliders[i] = amplitudeSlider;
this._operatorFrequencySelects[i] = frequencySelect;
frequencySelect.addEventListener("change", () => {
this.doc.record(new ChangeOperatorFrequency(this.doc, operatorIndex, frequencySelect.selectedIndex));
});
}
this._drumsetGroup.appendChild(
div({class: "selectRow"},
span({class: "tip", onclick: ()=>this._openPrompt("drumsetEnvelope")}, "Envelope:"),
span({class: "tip", onclick: ()=>this._openPrompt("drumsetSpectrum")}, "Spectrum:"),
),
);
for (let i: number = Config.drumCount - 1; i >= 0; i--) {
const drumIndex: number = i;
const spectrumEditor: SpectrumEditor = new SpectrumEditor(this.doc, drumIndex);
spectrumEditor.container.addEventListener("pointerdown", this._refocusStage);
this._drumsetSpectrumEditors[i] = spectrumEditor;
const envelopeSelect: HTMLSelectElement = buildOptions(select({style: "width: 100%;", title: "Filter Envelope"}), Config.envelopes.map(envelope=>envelope.name));
this._drumsetEnvelopeSelects[i] = envelopeSelect;
envelopeSelect.addEventListener("change", () => {
this.doc.record(new ChangeDrumsetEnvelope(this.doc, drumIndex, envelopeSelect.selectedIndex));
});
const row: HTMLDivElement = div({class: "selectRow"},
div({class: "selectContainer", style: "width: 5em; margin-right: .3em;"}, envelopeSelect),
this._drumsetSpectrumEditors[i].container,
);
this._drumsetGroup.appendChild(row);
}
this._fileMenu.addEventListener("change", this._fileMenuHandler);
this._editMenu.addEventListener("change", this._editMenuHandler);
this._optionsMenu.addEventListener("change", this._optionsMenuHandler);
this._tempoStepper.addEventListener("change", this._whenSetTempo);
this._scaleSelect.addEventListener("change", this._whenSetScale);
this._keySelect.addEventListener("change", this._whenSetKey);
this._rhythmSelect.addEventListener("change", this._whenSetRhythm);
this._pitchedPresetSelect.addEventListener("change", this._whenSetPitchedPreset);
this._drumPresetSelect.addEventListener("change", this._whenSetDrumPreset);
this._algorithmSelect.addEventListener("change", this._whenSetAlgorithm);
this._instrumentsButtonBar.addEventListener("click", this._whenSelectInstrument);
this._instrumentCopyButton.addEventListener("click", this._copyInstrument);
this._instrumentPasteButton.addEventListener("click", this._pasteInstrument);
this._customizeInstrumentButton.addEventListener("click", this._whenCustomizePressed);
this._feedbackTypeSelect.addEventListener("change", this._whenSetFeedbackType);
this._chipWaveSelect.addEventListener("change", this._whenSetChipWave);
this._chipNoiseSelect.addEventListener("change", this._whenSetNoiseWave);
this._transitionSelect.addEventListener("change", this._whenSetTransition);
this._effectsSelect.addEventListener("change", this._whenSetEffects);
this._unisonSelect.addEventListener("change", this._whenSetUnison);
this._chordSelect.addEventListener("change", this._whenSetChord);
this._vibratoSelect.addEventListener("change", this._whenSetVibrato);
this._playButton.addEventListener("click", this._togglePlay);
this._pauseButton.addEventListener("click", this._togglePlay);
this._recordButton.addEventListener("click", this._toggleRecord);
this._stopButton.addEventListener("click", this._toggleRecord);
// Start recording instead of opening context menu when control-clicking the record button on a Mac.
this._recordButton.addEventListener("contextmenu", (event: MouseEvent) => {
if (event.ctrlKey) {
event.preventDefault();
this._toggleRecord();
}
});
this._stopButton.addEventListener("contextmenu", (event: MouseEvent) => {
if (event.ctrlKey) {
event.preventDefault();
this._toggleRecord();
}
});
this._prevBarButton.addEventListener("click", this._whenPrevBarPressed);
this._nextBarButton.addEventListener("click", this._whenNextBarPressed);
this._volumeSlider.input.addEventListener("input", this._setVolumeSlider);
this._zoomInButton.addEventListener("click", this._zoomIn);
this._zoomOutButton.addEventListener("click", this._zoomOut);
this._patternArea.addEventListener("pointerdown", this._refocusStage);
this._trackArea.addEventListener("pointerdown", this._refocusStage);
this._fadeInOutEditor.container.addEventListener("pointerdown", this._refocusStage);
this._spectrumEditor.container.addEventListener("pointerdown", this._refocusStage);
this._eqFilterEditor.container.addEventListener("pointerdown", this._refocusStage);
this._noteFilterEditor.container.addEventListener("pointerdown", this._refocusStage);
this._harmonicsEditor.container.addEventListener("pointerdown", this._refocusStage);
this._tempoStepper.addEventListener("keydown", this._tempoStepperCaptureNumberKeys, false);
this._addEnvelopeButton.addEventListener("click", this._addNewEnvelope);
this._patternArea.addEventListener("contextmenu", this._disableCtrlContextMenu);
this._trackArea.addEventListener("contextmenu", this._disableCtrlContextMenu);
this.mainLayer.addEventListener("keydown", this._whenKeyPressed);
this.mainLayer.addEventListener("keyup", this._whenKeyReleased);
this.mainLayer.addEventListener("focusin", this._onFocusIn);
this._promptContainer.addEventListener("click", (event) => {
if (event.target == this._promptContainer) {
this.doc.undo();
}
});
// Sorry, bypassing typescript type safety on this function because I want to use the new "passive" option.
//this._trackAndMuteContainer.addEventListener("scroll", this._onTrackAreaScroll, {capture: false, passive: true});
(<Function>this._trackAndMuteContainer.addEventListener)("scroll", this._onTrackAreaScroll, {capture: false, passive: true});
if (isMobile) {
const autoPlayOption: HTMLOptionElement = <HTMLOptionElement> this._optionsMenu.querySelector("[value=autoPlay]");
autoPlayOption.disabled = true;
autoPlayOption.setAttribute("hidden", "");
}
if (window.screen.availWidth < 710 || window.screen.availHeight < 710) {
const layoutOption: HTMLOptionElement = <HTMLOptionElement> this._optionsMenu.querySelector("[value=layout]");
layoutOption.disabled = true;
layoutOption.setAttribute("hidden", "");
}
beepboxEditorContainer.appendChild(this.mainLayer);
this.whenUpdated();
this.mainLayer.focus();
// don't autoplay on mobile devices, wait for input.
if (!isMobile && this.doc.prefs.autoPlay) {
if (document.hidden) {
const autoplay = (event: Event): void => {
if (!document.hidden) {
this.doc.synth.play();
this.updatePlayButton();
window.removeEventListener("visibilitychange", autoplay);
}
}
// Wait until the tab is visible to autoplay:
window.addEventListener("visibilitychange", autoplay);
} else {
this.doc.synth.play();
}
}
this.updatePlayButton();
// BeepBox uses browser history state as its own undo history. Browsers typically
// remember scroll position for each history state, but BeepBox users would prefer not
// auto scrolling when undoing. Sadly this tweak doesn't work on Edge or IE.
if ("scrollRestoration" in history) history.scrollRestoration = "manual";
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/service_worker.js", {updateViaCache: "all", scope: "/"}).catch(() => {});
}
}
private _openPrompt(promptName: string): void {
this.doc.openPrompt(promptName);
this._setPrompt(promptName);
}
private _setPrompt(promptName: string | null): void {
if (this._currentPromptName == promptName) return;
this._currentPromptName = promptName;
if (this.prompt) {
if (this._wasPlaying && !(this.prompt instanceof TipPrompt || this.prompt instanceof SustainPrompt)) {
this.doc.performance.play();
}
this._wasPlaying = false;
this._promptContainer.style.display = "none";
this._promptContainer.removeChild(this.prompt.container);
this.prompt.cleanUp();
this.prompt = null;
this._refocusStage();
}
if (promptName) {
switch (promptName) {
case "export":
this.prompt = new ExportPrompt(this.doc);
break;
case "import":
this.prompt = new ImportPrompt(this.doc);
break;
case "songRecovery":
this.prompt = new SongRecoveryPrompt(this.doc);
break;
case "barCount":
this.prompt = new SongDurationPrompt(this.doc);
break;
case "beatsPerBar":
this.prompt = new BeatsPerBarPrompt(this.doc);
break;
case "moveNotesSideways":
this.prompt = new MoveNotesSidewaysPrompt(this.doc);
break;
case "channelSettings":
this.prompt = new ChannelSettingsPrompt(this.doc);
break;
case "layout":
this.prompt = new LayoutPrompt(this.doc);
break;
case "recordingSetup":
this.prompt = new RecordingSetupPrompt(this.doc);
break;
case "stringSustain":
this.prompt = new SustainPrompt(this.doc);
break;
default:
this.prompt = new TipPrompt(this.doc, promptName);
break;
}
if (this.prompt) {
if (!(this.prompt instanceof TipPrompt || this.prompt instanceof SustainPrompt)) {
this._wasPlaying = this.doc.synth.playing;
this.doc.performance.pause();
}
this._promptContainer.style.display = "";
this._promptContainer.appendChild(this.prompt.container);
}
}
}
private _refocusStage = (): void => {
this.mainLayer.focus({preventScroll: true});
}
private _onFocusIn = (event: Event): void => {
if (this.doc.synth.recording && event.target != this.mainLayer && event.target != this._stopButton && event.target != this._volumeSlider.input) {
// Don't allow using tab to focus on the song settings while recording,
// since interacting with them while recording would mess up the recording.
this._refocusStage();
}
}
public whenUpdated = (): void => {
const prefs: Preferences = this.doc.prefs;
this._muteEditor.container.style.display = prefs.enableChannelMuting ? "" : "none";
this.doc.trackVisibleBars = Math.floor((this._trackVisibleArea.clientWidth - (prefs.enableChannelMuting ? 32 : 0)) / this.doc.getBarWidth());
this.doc.trackVisibleChannels = Math.floor((this._trackVisibleArea.clientHeight - 30) / ChannelRow.patternHeight);
this._barScrollBar.render();
this._muteEditor.render();
this._trackEditor.render();
this._trackAndMuteContainer.scrollLeft = this.doc.barScrollPos * this.doc.getBarWidth();
this._trackAndMuteContainer.scrollTop = this.doc.channelScrollPos * ChannelRow.patternHeight;
this._piano.container.style.display = prefs.showLetters ? "" : "none";
this._octaveScrollBar.container.style.display = prefs.showScrollBar ? "" : "none";
this._barScrollBar.container.style.display = this.doc.song.barCount > this.doc.trackVisibleBars ? "" : "none";
if (this.doc.getFullScreen()) {
const semitoneHeight: number = this._patternEditorRow.clientHeight / this.doc.getVisiblePitchCount();
const targetBeatWidth: number = semitoneHeight * 5;
const minBeatWidth: number = this._patternEditorRow.clientWidth / (this.doc.song.beatsPerBar * 3);
const maxBeatWidth: number = this._patternEditorRow.clientWidth / (this.doc.song.beatsPerBar + 2);
const beatWidth: number = Math.max(minBeatWidth, Math.min(maxBeatWidth, targetBeatWidth));
const patternEditorWidth: number = beatWidth * this.doc.song.beatsPerBar;
this._patternEditorPrev.container.style.width = patternEditorWidth + "px";
this._patternEditor.container.style.width = patternEditorWidth + "px";
this._patternEditorNext.container.style.width = patternEditorWidth + "px";
this._patternEditorPrev.container.style.flexShrink = "0";
this._patternEditor.container.style.flexShrink = "0";
this._patternEditorNext.container.style.flexShrink = "0";
this._patternEditorPrev.container.style.display = "";
this._patternEditorNext.container.style.display = "";
this._patternEditorPrev.render();
this._patternEditorNext.render();
this._zoomInButton.style.display = "";
this._zoomOutButton.style.display = "";
this._zoomInButton.style.right = prefs.showScrollBar ? "24px" : "4px";
this._zoomOutButton.style.right = prefs.showScrollBar ? "24px" : "4px";
} else {
this._patternEditor.container.style.width = "";
this._patternEditor.container.style.flexShrink = "";
this._patternEditorPrev.container.style.display = "none";
this._patternEditorNext.container.style.display = "none";
this._zoomInButton.style.display = "none";
this._zoomOutButton.style.display = "none";
}
this._patternEditor.render();
const optionCommands: ReadonlyArray<string> = [
(prefs.autoPlay ? "✓ " : " ") + "Auto Play on Load",
(prefs.autoFollow ? "✓ " : " ") + "Show And Play The Same Bar",
(prefs.enableNotePreview ? "✓ " : " ") + "Hear Preview of Added Notes",
(prefs.showLetters ? "✓ " : " ") + "Show Piano Keys",
(prefs.showFifth ? "✓ " : " ") + 'Highlight "Fifth" of Song Key',
(prefs.notesOutsideScale ? "✓ " : " ") + "Allow Adding Notes Not in Scale",
(prefs.defaultScale == this.doc.song.scale ? "✓ " : " ") + "Use Current Scale as Default",
(prefs.showChannels ? "✓ " : " ") + "Show Notes From All Channels",
(prefs.showScrollBar ? "✓ " : " ") + "Show Octave Scroll Bar",
(prefs.alwaysShowSettings ? "✓ " : " ") + "Customize All Instruments",
(prefs.instrumentCopyPaste ? "✓ " : " ") + "Instrument Copy/Paste Buttons",
(prefs.enableChannelMuting ? "✓ " : " ") + "Enable Channel Muting",
(prefs.displayBrowserUrl ? "✓ " : " ") + "Display Song Data in URL",
" Choose Layout...",
(prefs.colorTheme == "light classic" ? "✓ " : " ") + "Light Theme",
" Set Up Note Recording...",
];
for (let i: number = 0; i < optionCommands.length; i++) {
const option: HTMLOptionElement = <HTMLOptionElement> this._optionsMenu.children[i + 1];
if (option.textContent != optionCommands[i]) option.textContent = optionCommands[i];
}
const channel: Channel = this.doc.song.channels[this.doc.channel];
const instrumentIndex: number = this.doc.getCurrentInstrument();
const instrument: Instrument = channel.instruments[instrumentIndex];
const wasActive: boolean = this.mainLayer.contains(document.activeElement);
const activeElement: Element | null = document.activeElement;
const colors: ChannelColors = ColorConfig.getChannelColor(this.doc.song, this.doc.channel);
for (let i: number = this._effectsSelect.childElementCount - 1; i < Config.effectOrder.length; i++) {
this._effectsSelect.appendChild(option({value: i}));
}
this._effectsSelect.selectedIndex = 0;
for (let i: number = 0; i < Config.effectOrder.length; i++) {
let effectFlag: number = Config.effectOrder[i];
const selected: boolean = ((instrument.effects & (1 << effectFlag)) != 0);
const label: string = (selected ? "✓ " : " ") + Config.effectNames[effectFlag];
const option: HTMLOptionElement = <HTMLOptionElement> this._effectsSelect.children[i + 1];
if (option.textContent != label) option.textContent = label;
}
setSelectedValue(this._scaleSelect, this.doc.song.scale);
this._scaleSelect.title = Config.scales[this.doc.song.scale].realName;
setSelectedValue(this._keySelect, Config.keys.length - 1 - this.doc.song.key);
this._tempoSlider.updateValue(Math.max(0, Math.min(28, Math.round(4.0 + 9.0 * Math.log2(this.doc.song.tempo / 120.0)))));
this._tempoStepper.value = this.doc.song.tempo.toString();
setSelectedValue(this._rhythmSelect, this.doc.song.rhythm);
if (this.doc.song.getChannelIsNoise(this.doc.channel)) {
this._pitchedPresetSelect.style.display = "none";
this._drumPresetSelect.style.display = "";
setSelectedValue(this._drumPresetSelect, instrument.preset);
} else {
this._pitchedPresetSelect.style.display = "";
this._drumPresetSelect.style.display = "none";
setSelectedValue(this._pitchedPresetSelect, instrument.preset);
}
if (prefs.instrumentCopyPaste) {
this._instrumentCopyPasteRow.style.display = "";
} else {
this._instrumentCopyPasteRow.style.display = "none";
}
if (!prefs.alwaysShowSettings && instrument.preset != instrument.type) {
this._customizeInstrumentButton.style.display = "";
this._customInstrumentSettingsGroup.style.display = "none";
} else {
this._customizeInstrumentButton.style.display = "none";
this._customInstrumentSettingsGroup.style.display = "";
if (instrument.type == InstrumentType.noise) {
this._chipNoiseSelectRow.style.display = "";
setSelectedValue(this._chipNoiseSelect, instrument.chipNoise);
} else {
this._chipNoiseSelectRow.style.display = "none";
}
if (instrument.type == InstrumentType.spectrum) {
this._spectrumRow.style.display = "";
this._spectrumEditor.render();
} else {
this._spectrumRow.style.display = "none";
}
if (instrument.type == InstrumentType.harmonics || instrument.type == InstrumentType.pickedString) {
this._harmonicsRow.style.display = "";
this._harmonicsEditor.render();
} else {
this._harmonicsRow.style.display = "none";
}
if (instrument.type == InstrumentType.pickedString) {
this._stringSustainRow.style.display = "";
this._stringSustainSlider.updateValue(instrument.stringSustain);
this._stringSustainLabel.textContent = Config.enableAcousticSustain ? "Sustain (" + Config.sustainTypeNames[instrument.stringSustainType].substring(0,1).toUpperCase() + "):" : "Sustain:";
} else {
this._stringSustainRow.style.display = "none";
}
if (instrument.type == InstrumentType.drumset) {
this._drumsetGroup.style.display = "";
this._fadeInOutRow.style.display = "none";
for (let i: number = 0; i < Config.drumCount; i++) {
setSelectedValue(this._drumsetEnvelopeSelects[i], instrument.drumsetEnvelopes[i]);
this._drumsetSpectrumEditors[i].render();
}
} else {
this._drumsetGroup.style.display = "none";
this._fadeInOutRow.style.display = "";
this._fadeInOutEditor.render();
}
if (instrument.type == InstrumentType.chip) {
this._chipWaveSelectRow.style.display = "";
setSelectedValue(this._chipWaveSelect, instrument.chipWave);
} else {
this._chipWaveSelectRow.style.display = "none";
}
if (instrument.type == InstrumentType.fm) {
this._algorithmSelectRow.style.display = "";
this._phaseModGroup.style.display = "";
this._feedbackRow1.style.display = "";
this._feedbackRow2.style.display = "";
setSelectedValue(this._algorithmSelect, instrument.algorithm);
setSelectedValue(this._feedbackTypeSelect, instrument.feedbackType);
this._feedbackAmplitudeSlider.updateValue(instrument.feedbackAmplitude);
for (let i: number = 0; i < Config.operatorCount; i++) {
const isCarrier: boolean = (i < Config.algorithms[instrument.algorithm].carrierCount);
this._operatorRows[i].style.color = isCarrier ? ColorConfig.primaryText : "";
setSelectedValue(this._operatorFrequencySelects[i], instrument.operators[i].frequency);
this._operatorAmplitudeSliders[i].updateValue(instrument.operators[i].amplitude);
const operatorName: string = (isCarrier ? "Voice " : "Modulator ") + (i + 1);
this._operatorFrequencySelects[i].title = operatorName + " Frequency";
this._operatorAmplitudeSliders[i].input.title = operatorName + (isCarrier ? " Volume" : " Amplitude");
}
} else {
this._algorithmSelectRow.style.display = "none";
this._phaseModGroup.style.display = "none";
this._feedbackRow1.style.display = "none";
this._feedbackRow2.style.display = "none";
}
if (instrument.type == InstrumentType.supersaw) {
this._supersawDynamismRow.style.display = "";
this._supersawSpreadRow.style.display = "";
this._supersawShapeRow.style.display = "";
this._supersawDynamismSlider.updateValue(instrument.supersawDynamism);
this._supersawSpreadSlider.updateValue(instrument.supersawSpread);
this._supersawShapeSlider.updateValue(instrument.supersawShape);
} else {
this._supersawDynamismRow.style.display = "none";
this._supersawSpreadRow.style.display = "none";
this._supersawShapeRow.style.display = "none";
}
if (instrument.type == InstrumentType.pwm || instrument.type == InstrumentType.supersaw) {
this._pulseWidthRow.style.display = "";
this._pulseWidthSlider.input.title = prettyNumber(getPulseWidthRatio(instrument.pulseWidth) * 100) + "%";
this._pulseWidthSlider.updateValue(instrument.pulseWidth);
} else {
this._pulseWidthRow.style.display = "none";
}
if (effectsIncludeTransition(instrument.effects)) {
this._transitionRow.style.display = "";
setSelectedValue(this._transitionSelect, instrument.transition);
} else {
this._transitionRow.style.display = "none";
}
if (effectsIncludeChord(instrument.effects)) {
this._chordSelectRow.style.display = "";
setSelectedValue(this._chordSelect, instrument.chord);
} else {
this._chordSelectRow.style.display = "none";
}
if (effectsIncludePitchShift(instrument.effects)) {
this._pitchShiftRow.style.display = "";
this._pitchShiftSlider.updateValue(instrument.pitchShift);