-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathpiemenus.js
More file actions
4445 lines (3843 loc) · 161 KB
/
piemenus.js
File metadata and controls
4445 lines (3843 loc) · 161 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
/* eslint-disable max-len */
// Copyright (c) 2014-23 Walter Bender
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the The GNU Affero General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// You should have received a copy of the GNU Affero General Public
// License along with this library; if not, write to the Free Software
// Foundation, 51 Franklin Street, Suite 500 Boston, MA 02110-1335 USA
//
/*
global
_, platformColor, docById, Singer, slicePath, wheelnav,
DEFAULTVOICE, getDrumName, getNote, MUSICALMODES last, SHARP, FLAT,
PREVIEWVOLUME, DEFAULTVOLUME, MODE_PIE_MENUS, HelpWidget,
INTERVALVALUES, INTERVALS, getDrumSynthName, getVoiceSynthName,
getMunsellColor, COLORS40, frequencyToPitch, instruments,
DOUBLESHARP, NATURAL, DOUBLEFLAT, EQUIVALENTACCIDENTALS,
FIXEDSOLFEGE, NOTENAMES, FIXEDSOLFEGE, NOTENAMES, numberToPitch,
nthDegreeToPitch, SOLFEGENAMES, buildScale, _THIS_IS_TURTLE_BLOCKS_,
CHORDNAMES
*/
/*
Globals location
- lib/wheelnav
slicePath, wheelnav
- js/utils/musicutils.js
FLAT, SHARP, DEFAULTVOICE, getDrumName, getNote, MODE_PIE_MENUS, MUSICALMODES, INTERVALVALUES,
INTERVALS, getDrumSynthName, getVoiceSynthName, frequencyToPitch, DOUBLESHARP, NATURAL,
DOUBLEFLAT, EQUIVALENTACCIDENTALS, FIXEDSOLFEGE, NOTENAMES, FIXEDSOLFEGE, NOTENAMES, numberToPitch,
nthDegreeToPitch, SOLFEGENAMES, buildScale
- js/utils/utils.js
_, last, docById
- js/turtle-singer.js
Singer
- js/utils/munsell.js
getMunsellColor, COLORS40
- js/widgets/help.js
HelpWidget
- js/utils/platformstyle.js
platformColorcl
- js/utils/synthutils.js
instruments
- js/logo.js
PREVIEWVOLUME, DEFAULTVOLUME
*/
/*
exported
piemenuModes, piemenuPitches, piemenuCustomNotes, piemenuGrid,
piemenuBlockContext, piemenuIntervals, piemenuVoices, piemenuBoolean,
piemenuBasic, piemenuColor, piemenuNumber, piemenuNthModalPitch,
piemenuNoteValue, piemenuAccidentals, piemenuKey, piemenuChords,
piemenuDissectNumber
*/
const setWheelSize = (i = 400) => {
const wheelDiv = document.getElementById("wheelDiv");
const screenWidth = window.innerWidth;
if (!wheelDiv) return;
wheelDiv.style.position = "absolute";
wheelDiv.style.zIndex = "20000"; // Set z-index higher than floating windows (10000)
if (screenWidth >= 1200) {
wheelDiv.style.width = i + "px";
wheelDiv.style.height = i + "px";
} else if (screenWidth >= 768) {
wheelDiv.style.width = i - 50 + "px";
wheelDiv.style.height = i - 50 + "px";
} else {
wheelDiv.style.width = i - 100 + "px";
wheelDiv.style.height = i - 100 + "px";
}
wheelDiv.style.height = wheelDiv.style.width;
};
const getPieMenuSize = block => {
const canvas = block.blocks.turtles._canvas;
return Math.min(canvas.width, canvas.height);
};
// Debounce resize handler for performance
let wheelResizeTimeout;
const debouncedSetWheelSize = () => {
clearTimeout(wheelResizeTimeout);
wheelResizeTimeout = setTimeout(setWheelSize, 150);
};
// Call the function initially and whenever the window is resized
setWheelSize();
window.addEventListener("resize", debouncedSetWheelSize);
// Helper function to enable scroll-to-rotate for pie menus
const enableWheelScroll = (wheel, itemCount) => {
const wheelDiv = document.getElementById("wheelDiv");
if (!wheelDiv || !wheel) return;
// Remove existing scroll handler if any
if (wheelDiv._scrollHandler) {
wheelDiv.removeEventListener("wheel", wheelDiv._scrollHandler);
}
let isScrolling = false;
let scrollTimeout = null;
const scrollHandler = event => {
event.preventDefault();
event.stopPropagation();
// Throttle the scroll events (only process every 150ms)
if (isScrolling) return;
isScrolling = true;
// Calculate the direction and amount to rotate
const delta = event.deltaY > 0 ? 1 : -1;
// Get current selected index
const currentIndex = wheel.selectedNavItemIndex;
// Calculate next index (with wrapping)
let nextIndex = currentIndex + delta;
if (nextIndex < 0) {
nextIndex = itemCount - 1;
} else if (nextIndex >= itemCount) {
nextIndex = 0;
}
// Temporarily disable all navigate functions to prevent sound previews
const originalFunctions = [];
for (let i = 0; i < wheel.navItems.length; i++) {
originalFunctions[i] = wheel.navItems[i].navigateFunction;
wheel.navItems[i].navigateFunction = null;
}
// Navigate to the next item
wheel.navigateWheel(nextIndex);
// Restore navigate functions after a short delay
setTimeout(() => {
for (let i = 0; i < wheel.navItems.length; i++) {
wheel.navItems[i].navigateFunction = originalFunctions[i];
}
}, 50);
// Reset throttle after 150ms
setTimeout(() => {
isScrolling = false;
}, 150);
};
// Store the handler so we can remove it later
wheelDiv._scrollHandler = scrollHandler;
wheelDiv.addEventListener("wheel", scrollHandler, { passive: false });
};
// Accessibility helpers for pie menus (screen reader announcements)
/**
* this function is to ensure that the pie menu live region is created and returned
*/
const __ensurePieMenuLiveRegion = () => {
let liveRegion = docById("pieMenuLiveRegion");
if (liveRegion) {
return liveRegion;
}
liveRegion = document.createElement("div");
liveRegion.id = "pieMenuLiveRegion";
liveRegion.setAttribute("role", "status");
liveRegion.setAttribute("aria-live", "polite");
liveRegion.setAttribute("aria-atomic", "true");
liveRegion.style.position = "absolute";
liveRegion.style.left = "-9999px";
liveRegion.style.width = "1px";
liveRegion.style.height = "1px";
liveRegion.style.overflow = "hidden";
document.body.appendChild(liveRegion);
return liveRegion;
};
/**
* this function is to get the aria label from the title of the pie menu item
*/
const __pieMenuA11yLabelFromTitle = title => {
if (title === null || title === undefined) {
return "";
}
const text = String(title).trim();
if (text.length === 0) {
return "";
}
if (text === "×") {
return _("Close");
}
if (text === "+") {
return _("Increase");
}
if (text === "-") {
return _("Decrease");
}
if (text === "▶") {
return _("Play");
}
if (text.startsWith("imgsrc:")) {
const raw = text.slice("imgsrc:".length);
const file = raw.split("/").pop() || raw;
const base = file.replace(/\.[^/.]+$/, "");
return base.replace(/[-_]+/g, " ").trim();
}
return text;
};
const __announcePieMenuLabel = label => {
const trimmed = String(label || "").trim();
if (!trimmed) {
return;
}
/**
* this logic is to prevent any duplicate announcements
* i.e if the same label is announced within 400ms, it will not be announced again
*/
const now = Date.now();
if (
window.__wheelnavA11yLastLabel === trimmed &&
window.__wheelnavA11yLastTime &&
now - window.__wheelnavA11yLastTime < 400
) {
return;
}
window.__wheelnavA11yLastLabel = trimmed;
window.__wheelnavA11yLastTime = now;
__ensurePieMenuLiveRegion().textContent = trimmed;
};
/**
* this function is to speak the pie menu label to the screen reader
*/
const __speakPieMenuLabel = label => {
const trimmed = String(label || "").trim();
if (!trimmed) {
return;
}
//If the browser doesn’t support TTS, do nothing.
if (!("speechSynthesis" in window)) {
return;
}
//If the user toggled speech off, do nothing.
if (window.__wheelnavA11ySpeakEnabled === false) {
return;
}
try {
window.speechSynthesis.cancel(); //Stop any current speech so the new label replaces it immediately.
const utterance = new SpeechSynthesisUtterance(trimmed);
utterance.rate = 1;
utterance.pitch = 1;
window.speechSynthesis.speak(utterance);
} catch (e) {
// Ignore speech synthesis errors
}
};
// Expose hooks for the wheelnav library to call
if (window.__wheelnavA11ySpeakEnabled === undefined) {
window.__wheelnavA11ySpeakEnabled = true;
}
window.__wheelnavA11yLabelForItem = navItem =>
__pieMenuA11yLabelFromTitle(navItem && navItem.title);
// When called, it writes the label into the live region so screen readers announce it.
window.__wheelnavA11yAnnounce = navItem => {
const label = __pieMenuA11yLabelFromTitle(navItem && navItem.title);
__announcePieMenuLabel(label);
};
//When called (on click), it speaks the label using speechSynthesis
window.__wheelnavA11ySpeak = navItem => {
const label = __pieMenuA11yLabelFromTitle(navItem && navItem.title);
__speakPieMenuLabel(label);
// Ensure exit wheels behave like stateless buttons (no sticky selection)
const configureExitWheel = exitWheel => {
if (!exitWheel || !exitWheel.navItems) {
return;
}
const clearSelection = () => {
exitWheel.selectedNavItemIndex = null;
for (let i = 0; i < exitWheel.navItems.length; i++) {
exitWheel.navItems[i].selected = false;
exitWheel.navItems[i].hovered = false;
}
if (exitWheel.raphael && exitWheel.raphael.canvas) {
exitWheel.refreshWheel(true);
}
};
clearSelection();
exitWheel.navigateWheel = clicked => {
const item = exitWheel.navItems[clicked];
if (!item || item.enabled === false) {
return;
}
clearSelection();
if (typeof item.navigateFunction === "function") {
item.navigateFunction();
}
};
};
const piemenuPitches = (block, noteLabels, noteValues, accidentals, note, accidental, custom) => {
let prevPitch = null;
// wheelNav pie menu for pitch selection
if (block.blocks.stageClick) {
return;
}
if (custom === undefined) {
custom = false;
}
// Some blocks have both pitch and octave, so we can modify
// both at once.
const hasOctaveWheel =
block.connections[0] !== null &&
["pitch", "setpitchnumberoffset", "invert1", "tofrequency"].includes(
block.blocks.blockList[block.connections[0]].name
);
// If we are attached to a set key block, we want to order
// pitch by fifths.
if (
block.connections[0] !== null &&
["setkey", "setkey2"].includes(block.blocks.blockList[block.connections[0]].name)
) {
noteLabels = ["C", "G", "D", "A", "E", "B", "F"];
noteValues = ["C", "G", "D", "A", "E", "B", "F"];
}
const wheelDiv = docById("wheelDiv");
wheelDiv.style.display = ""; // Show the div but keep it invisible initially
wheelDiv.style.opacity = "0";
// The pitch selector
const wheelSize = getPieMenuSize(block);
block._pitchWheel = new wheelnav("wheelDiv", null, wheelSize, wheelSize);
if (!custom) {
// The accidental selector
block._accidentalsWheel = new wheelnav("_accidentalsWheel", block._pitchWheel.raphael);
}
// The octave selector
if (hasOctaveWheel) {
block._octavesWheel = new wheelnav("_octavesWheel", block._pitchWheel.raphael);
}
// The exit button
block._exitWheel = new wheelnav("_exitWheel", block._pitchWheel.raphael);
wheelnav.cssMode = true;
block._pitchWheel.keynavigateEnabled = false;
block._pitchWheel.colors = platformColor.pitchWheelcolors;
block._pitchWheel.slicePathFunction = slicePath().DonutSlice;
block._pitchWheel.slicePathCustom = slicePath().DonutSliceCustomization();
block._pitchWheel.slicePathCustom.minRadiusPercent = 0.2;
if (!custom) {
block._pitchWheel.slicePathCustom.maxRadiusPercent = 0.5;
} else {
block._pitchWheel.slicePathCustom.maxRadiusPercent = 0.75;
}
block._pitchWheel.sliceSelectedPathCustom = block._pitchWheel.slicePathCustom;
block._pitchWheel.sliceInitPathCustom = block._pitchWheel.slicePathCustom;
block._pitchWheel.animatetime = 0; // 300;
block._pitchWheel.createWheel(noteLabels);
block._exitWheel.colors = platformColor.exitWheelcolors;
block._exitWheel.slicePathFunction = slicePath().DonutSlice;
block._exitWheel.slicePathCustom = slicePath().DonutSliceCustomization();
block._exitWheel.slicePathCustom.minRadiusPercent = 0.0;
block._exitWheel.slicePathCustom.maxRadiusPercent = 0.2;
block._exitWheel.sliceSelectedPathCustom = block._exitWheel.slicePathCustom;
block._exitWheel.sliceInitPathCustom = block._exitWheel.slicePathCustom;
block._exitWheel.clickModeRotate = false;
block._exitWheel.initWheel(["×", " "]);
block._exitWheel.navItems[1].enabled = false;
block._exitWheel.navItems[0].sliceSelectedAttr.cursor = "pointer";
block._exitWheel.navItems[0].sliceHoverAttr.cursor = "pointer";
block._exitWheel.navItems[0].titleSelectedAttr.cursor = "pointer";
block._exitWheel.navItems[0].titleHoverAttr.cursor = "pointer";
block._exitWheel.createWheel();
configureExitWheel(block._exitWheel);
if (!custom) {
block._accidentalsWheel.colors = platformColor.accidentalsWheelcolors;
block._accidentalsWheel.slicePathFunction = slicePath().DonutSlice;
block._accidentalsWheel.slicePathCustom = slicePath().DonutSliceCustomization();
block._accidentalsWheel.slicePathCustom.minRadiusPercent = 0.5;
block._accidentalsWheel.slicePathCustom.maxRadiusPercent = 0.75;
block._accidentalsWheel.sliceSelectedPathCustom = block._accidentalsWheel.slicePathCustom;
block._accidentalsWheel.sliceInitPathCustom = block._accidentalsWheel.slicePathCustom;
const accidentalLabels = [];
for (let i = 0; i < accidentals.length; i++) {
accidentalLabels.push(accidentals[i]);
}
for (let i = 0; i < 9; i++) {
accidentalLabels.push(null);
block._accidentalsWheel.colors.push(platformColor.accidentalsWheelcolorspush);
}
block._accidentalsWheel.animatetime = 0; // 300;
block._accidentalsWheel.createWheel(accidentalLabels);
block._accidentalsWheel.setTooltips([
_("double sharp"),
_("sharp"),
_("natural"),
_("flat"),
_("double flat")
]);
}
if (hasOctaveWheel) {
block._octavesWheel.colors = platformColor.octavesWheelcolors;
block._octavesWheel.slicePathFunction = slicePath().DonutSlice;
block._octavesWheel.slicePathCustom = slicePath().DonutSliceCustomization();
block._octavesWheel.slicePathCustom.minRadiusPercent = 0.75;
block._octavesWheel.slicePathCustom.maxRadiusPercent = 0.95;
block._octavesWheel.sliceSelectedPathCustom = block._octavesWheel.slicePathCustom;
block._octavesWheel.sliceInitPathCustom = block._octavesWheel.slicePathCustom;
const octaveLabels = [
"8",
"7",
"6",
"5",
"4",
"3",
"2",
"1",
null,
null,
null,
null,
null,
null
];
block._octavesWheel.animatetime = 0; // 300;
block._octavesWheel.createWheel(octaveLabels);
}
// Position the widget over the note block.
const x = block.container.x;
const y = block.container.y;
const canvasLeft = block.activity.canvas.offsetLeft + 28 * block.blocks.blockScale;
const canvasTop = block.activity.canvas.offsetTop + 6 * block.blocks.blockScale;
docById("wheelDiv").style.position = "absolute";
const displaySize = 400;
setWheelSize(displaySize);
const halfWheelSize = displaySize / 2;
docById("wheelDiv").style.left =
Math.min(
block.blocks.turtles._canvas.width - displaySize,
Math.max(
0,
Math.round(
(x + block.activity.blocksContainer.x) * block.activity.getStageScale() +
canvasLeft
) - halfWheelSize
)
) + "px";
docById("wheelDiv").style.top =
Math.min(
block.blocks.turtles._canvas.height - displaySize,
Math.max(
0,
Math.round(
(y + block.activity.blocksContainer.y) * block.activity.getStageScale() +
canvasTop
) - halfWheelSize
)
) + "px";
// Navigate to a the current note value.
let i = noteValues.indexOf(note);
if (i === -1) {
if (custom) {
i = 0;
} else {
i = 4;
}
}
prevPitch = i;
block._pitchWheel.navigateWheel(i);
const OFFSET = {
major: 1,
dorian: 2,
phrygian: 3,
lydian: 4,
mixolydian: 5,
minor: 6,
locrian: 7
};
const ROTATION = { A: 2, B: 1, C: 0, D: 6, E: 5, F: 4, G: 3 };
const k = OFFSET[block.activity.KeySignatureEnv[1]];
let key;
const attrList = ["", SHARP, FLAT];
for (const j in attrList) {
for (const i in NOTENAMES) {
const tempScale = buildScale(NOTENAMES[i] + attrList[j] + " major")[0];
if (tempScale[k - 1] === block.activity.KeySignatureEnv[0]) {
key = NOTENAMES[i] + attrList[j];
break;
}
}
if (key !== undefined) {
break;
}
}
let scale = buildScale(key + " major")[0];
scale = scale.splice(0, scale.length - 1);
for (let j = 0; j < ROTATION[key[0]]; j++) {
scale.push(scale.shift());
}
// Auto-selection of sharps and flats in fixed solfege handles the
// case of opening the pie-menu, not whilst in the pie-menu.
// Skip auto-selection if user already has a non-natural accidental (Issue #4886).
const pitchHasAccidental = accidental !== "" && accidental !== NATURAL;
if (
!pitchHasAccidental &&
((!block.activity.KeySignatureEnv[2] && block.name === "solfege") ||
(block.name === "notename" &&
(block.connections[0] != undefined
? !["setkey", "setkey2"].includes(
block.blocks.blockList[block.connections[0]].name
)
: true)))
) {
if (scale[6 - i][0] === FIXEDSOLFEGE[note] || scale[6 - i][0] === note) {
accidental = scale[6 - i].substr(1);
} else {
accidental = EQUIVALENTACCIDENTALS[scale[6 - i]].substr(1);
}
block.value = block.value
.replace(SHARP, "")
.replace(FLAT, "")
.replace(DOUBLESHARP, "")
.replace(DOUBLEFLAT, "");
block.value += accidental;
block.text.text = block.value;
}
if (!custom) {
// Navigate to the current accidental value.
// Use the accidental parameter directly - it's already correctly parsed from block value.
let accidentalIndex = 2; // Default to "natural"
if (accidental === DOUBLESHARP) {
accidentalIndex = 0;
} else if (accidental === SHARP) {
accidentalIndex = 1;
} else if (accidental === NATURAL || accidental === "") {
accidentalIndex = 2;
} else if (accidental === FLAT) {
accidentalIndex = 3;
} else if (accidental === DOUBLEFLAT) {
accidentalIndex = 4;
}
block._accidentalsWheel.navigateWheel(accidentalIndex);
}
if (hasOctaveWheel) {
// Use the octave associated with block block, if available.
const pitchOctave = block.blocks.findPitchOctave(block.connections[0]);
// Navigate to current octave.
block._octavesWheel.navigateWheel(8 - pitchOctave);
// const prevOctave = 8 - pitchOctave;
}
// Now that everything is set up, make the wheel visible with a smooth transition
wheelDiv.style.transition = "opacity 0.15s ease-in";
setTimeout(() => {
wheelDiv.style.opacity = "1";
}, 50);
// Set up event handlers.
const that = block;
const selection = {
note: note,
attr: accidental
};
/*
* Preview the selected pitch using the synth
* @return{void}
* @private
*/
const __pitchPreview = async () => {
try {
// Ensure audio context is initialized first
await setupAudioContext();
// Ensure synth is initialized before proceeding
if (!that.activity.logo.synth) {
that.activity.logo.synth = new Synth();
}
// Always ensure tone is initialized
if (!that.activity.logo.synth.tone) {
that.activity.logo.synth.newTone();
}
const label = that._pitchWheel.navItems[that._pitchWheel.selectedNavItemIndex].title;
const i = noteLabels.indexOf(label);
// Are we wrapping across C? We need to compare with the previous pitch
if (prevPitch === null) {
prevPitch = i;
}
const deltaPitch = i - prevPitch;
let delta;
if (deltaPitch > 3) {
delta = deltaPitch - 7;
} else if (deltaPitch < -3) {
delta = deltaPitch + 7;
} else {
delta = deltaPitch;
}
// If we wrapped across C, we need to adjust the octave.
let deltaOctave = 0;
if (prevPitch + delta > 6) {
deltaOctave = -1;
} else if (prevPitch + delta < 0) {
deltaOctave = 1;
}
let attr;
prevPitch = i;
let note = noteValues[i];
if (!custom) {
attr =
that._accidentalsWheel.navItems[that._accidentalsWheel.selectedNavItemIndex]
.title;
if (label === " ") {
return;
} else if (attr !== "♮") {
note += attr;
}
}
let octave;
if (hasOctaveWheel) {
// Always use the current octave from the wheel
octave = Number(
that._octavesWheel.navItems[that._octavesWheel.selectedNavItemIndex].title
);
} else {
octave = 4;
}
octave += deltaOctave;
if (octave < 1) {
octave = 1;
} else if (octave > 8) {
octave = 8;
}
// Store the final octave back in selection
selection["octave"] = octave;
if (hasOctaveWheel && deltaOctave !== 0) {
that._octavesWheel.navigateWheel(8 - octave);
that.blocks.setPitchOctave(that.connections[0], octave);
}
const keySignature =
block.activity.KeySignatureEnv[0] + " " + block.activity.KeySignatureEnv[1];
let obj;
if (that.name == "scaledegree2") {
note = note.replace(attr, "");
note = SOLFEGENAMES[note - 1];
note += attr;
obj = getNote(
note,
octave,
0,
keySignature,
true,
null,
that.activity.errorMsg,
that.activity.logo.synth.inTemperament
);
} else {
obj = getNote(
note,
octave,
0,
keySignature,
block.activity.KeySignatureEnv[2],
null,
that.activity.errorMsg,
that.activity.logo.synth.inTemperament
);
}
if (!custom) {
obj[0] = obj[0].replace(SHARP, "#").replace(FLAT, "b");
}
// Create and load synth if needed
if (!instruments[0] || !instruments[0][DEFAULTVOICE]) {
try {
that.activity.logo.synth.createDefaultSynth(0);
await that.activity.logo.synth.loadSynth(0, DEFAULTVOICE);
} catch (e) {
return;
}
}
// Ensure synth is properly initialized
if (!that.activity.logo.synth.tone) {
that.activity.logo.synth.newTone();
}
// Set volume
try {
that.activity.logo.synth.setMasterVolume(PREVIEWVOLUME);
that.activity.logo.synth.setVolume(0, DEFAULTVOICE, PREVIEWVOLUME);
} catch (e) {
return;
}
// Trigger note with proper error handling
if (!that._triggerLock) {
that._triggerLock = true;
try {
await that.activity.logo.synth.trigger(
0,
[obj[0] + obj[1]],
1 / 8,
DEFAULTVOICE,
null,
null,
false
);
} catch (e) {
// Ensure trigger lock is released after a delay
setTimeout(() => {
that._triggerLock = false;
}, 125); // 1/8 second in milliseconds
}
}
} catch (e) {
console.error("Error in pitch preview:", e);
}
};
const __selectionChangedSolfege = () => {
selection["note"] = that._pitchWheel.navItems[that._pitchWheel.selectedNavItemIndex].title;
const i = noteLabels.indexOf(selection["note"]);
that.value = noteValues[i];
// Auto-selection of sharps and flats in fixed solfege handles
// the case of opening the pie-menu, not whilst in the
// pie-menu. FIXEDSOLFEGE converts solfege to alphabet, needed
// for solfege pie-menu In. case of alphabet, direct comparison
// is performed.
if (
(!block.activity.KeySignatureEnv[2] && that.name === "solfege") ||
(that.name === "notename" &&
(that.connections[0] != undefined
? !["setkey", "setkey2"].includes(
that.blocks.blockList[that.connections[0]].name
)
: true))
) {
let i = scale.indexOf(selection["note"]);
if (i === -1) {
i = scale.indexOf(that.value);
}
if (i === -1) {
i = NOTENAMES.indexOf(FIXEDSOLFEGE[selection["note"]]);
}
if (i === -1) {
i = NOTENAMES.indexOf(FIXEDSOLFEGE[that.value]);
}
if (
NOTENAMES.includes(selection["note"]) ||
scale[i][0] === FIXEDSOLFEGE[selection["note"]] ||
scale[i][0] === FIXEDSOLFEGE[that.value] ||
scale[i][0] === selection["note"]
) {
selection["attr"] = scale[i].substr(1);
} else {
selection["attr"] = EQUIVALENTACCIDENTALS[scale[i]].substr(1);
}
switch (selection["attr"]) {
case DOUBLEFLAT:
that._accidentalsWheel.navigateWheel(4);
break;
case FLAT:
that._accidentalsWheel.navigateWheel(3);
break;
case NATURAL:
that._accidentalsWheel.navigateWheel(2);
break;
case SHARP:
that._accidentalsWheel.navigateWheel(1);
break;
case DOUBLESHARP:
that._accidentalsWheel.navigateWheel(0);
break;
default:
that._accidentalsWheel.navigateWheel(2);
break;
}
}
that.text.text = selection["note"];
if (selection["attr"] !== "♮") {
that.text.text += selection["attr"];
}
// Make sure text is on top.
that.container.setChildIndex(that.text, that.container.children.length - 1);
that.updateCache();
if (hasOctaveWheel) {
// Set the octave of the pitch block, if available.
const octave = Number(
that._octavesWheel.navItems[that._octavesWheel.selectedNavItemIndex].title
);
that.blocks.setPitchOctave(that.connections[0], octave);
// Update the state with the current octave
selection["octave"] = octave;
}
if (
that.connections[0] !== null &&
["setkey", "setkey2"].includes(that.blocks.blockList[that.connections[0]].name)
) {
// We may need to update the mode widget.
that.activity.logo.modeBlock = that.blocks.blockList.indexOf(that);
}
};
const __selectionChangedOctave = () => {
const octave = Number(
that._octavesWheel.navItems[that._octavesWheel.selectedNavItemIndex].title
);
that.blocks.setPitchOctave(that.connections[0], octave);
// Update the state before preview
selection["octave"] = octave;
};
const __selectionChangedAccidental = () => {
const i = that._pitchWheel.selectedNavItemIndex;
selection["note"] = noteLabels[i];
const selectedNoteValue = noteValues[i];
selection["attr"] =
that._accidentalsWheel.navItems[that._accidentalsWheel.selectedNavItemIndex].title;
if (selection["attr"] === "♮") {
that.text.text = selection["note"];
that.value = selectedNoteValue;
} else {
that.value = selectedNoteValue + selection["attr"];
that.text.text = selection["note"] + selection["attr"];
}
that.container.setChildIndex(that.text, that.container.children.length - 1);
that.updateCache();
// Ensure we have the current octave
if (hasOctaveWheel) {
selection["octave"] = Number(
that._octavesWheel.navItems[that._octavesWheel.selectedNavItemIndex].title
);
}
};
// Set up handlers for pitch preview.
const setupAudioContext = async () => {
try {
await Tone.start();
} catch (e) {
// Tone.start() may fail if the user has not interacted with the page yet
// or if the audio context is already running. We can safely ignore this.
console.debug("Tone.start() skipped or failed", e);
}
};
const __selectionChangedSolfegeWithAudio = async () => {
__selectionChangedSolfege();
};
const __selectionChangedOctaveWithAudio = async () => {
__selectionChangedOctave();
};
const __selectionChangedAccidentalWithAudio = async () => {
__selectionChangedAccidental();
};
// Set up handlers for pitch preview.
const __previewWrapper = async () => {
await setupAudioContext();
if (!that.activity.logo.synth.tone) {
that.activity.logo.synth.newTone();
}
await __pitchPreview();
};
for (let i = 0; i < noteValues.length; i++) {
block._pitchWheel.navItems[i].navigateFunction = async () => {
__selectionChangedSolfege();
await __previewWrapper();
};
}
if (!custom) {
for (let i = 0; i < accidentals.length; i++) {
block._accidentalsWheel.navItems[i].navigateFunction = async () => {
__selectionChangedAccidental();
await __previewWrapper();
};
}
}
if (hasOctaveWheel) {
for (let i = 0; i < 8; i++) {
block._octavesWheel.navItems[i].navigateFunction = async () => {
__selectionChangedOctave();
await __previewWrapper();
};
}
}
enableWheelScroll(block._pitchWheel, noteLabels.length);
// Hide the widget when the exit button is clicked.
block._exitWheel.navItems[0].navigateFunction = () => {
that._piemenuExitTime = new Date().getTime();
const selectedNote = that._pitchWheel.navItems[that._pitchWheel.selectedNavItemIndex].title;
const selectedAccidental =
!custom && that._accidentalsWheel
? that._accidentalsWheel.navItems[that._accidentalsWheel.selectedNavItemIndex].title
: "";
// Update the block's displayed text with the note and accidental
const i = that._pitchWheel.selectedNavItemIndex;
const selectedNoteValue = noteValues[i];
if (selectedAccidental === "♮" || selectedAccidental === "") {
// Natural or no accidental: display only the note
that.text.text = selectedNote;
that.value = selectedNoteValue;
} else {
// Combine note and accidental for display
that.text.text = selectedNote + selectedAccidental;
that.value = selectedNoteValue + selectedAccidental;
}
// Ensure proper layering of the text element
that.container.setChildIndex(that.text, that.container.children.length - 1);
// Refresh the block's cache
that.updateCache();
// Hide the pie menu and remove the wheels
docById("wheelDiv").style.display = "none";
that._pitchWheel.removeWheel();