Repository navigation
Expand file tree
/
Copy pathscreen.js
More file actions
4974 lines (4667 loc) · 233 KB
/
Copy pathscreen.js
File metadata and controls
4974 lines (4667 loc) · 233 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
/*
* Live Tab — a tablature you can actually read while it moves.
*
* The plugin sits between the views that already exist. Tab View draws real
* tab, but as static pages with a cursor that jumps. Jumping Tab is fully
* game-like: gems fly at a hit line and there is no tab left to read. Live Tab
* keeps the tab legible while it moves, hosts any note board above it, and
* shows the same hit/miss verdicts the board shows — so the feedback lands
* where the player is already looking.
*
* How the file is arranged:
*
* 1. Settings schema one list drives defaults, clamping and the panel
* 2. Presets named starting points, plus advanced options
* 3. Palette colour, borrowed from the app's string colours
* 4. Pure helpers no canvas, no host, unit-testable
* 5. Tempo map time <-> beat position, from a cleaned beat grid
* 6. Reading modes which staves to draw, and what each one covers
* 7. Host access everything read from `window.highway`
* 8. Drawing the staff, its notes and its marks
* 9. Composite viz the borrowed board above, the tab below
* 10. Settings panel built from the schema
* 11. Player control the two or three choices taken mid-song
* 12. Public API window.livetab
*/
/*
* ── THE SHARED KIT ──────────────────────────────────────────────────────
*
* Vendored under `src/kit/`, copied and never imported from anywhere shared:
* there are no import maps in this host and no load-order guarantee between
* plugins, and any plugin can be disabled — so a plugin that reached into
* another one for its design system would be a plugin that stops rendering
* when the reader turns something else off.
*
* The imports live out here because a module's do, and the IIFE below closes
* over this scope, so everything inside it can see them. The IIFE is now
* redundant — a module has its own scope — and is kept because removing it
* would reindent three thousand lines for no behaviour.
*
* `plugin.json` gained `scriptType: "module"` for this. The file was already
* `'use strict'` and already one closed IIFE, so nothing else about it had to
* change.
*/
import * as kit from './src/kit/index.js';
import * as c from './src/kit/controls.js';
(function () {
'use strict';
const ID = 'livetab';
const LS_KEY = 'livetab.settings';
// ── Running twice ────────────────────────────────────────────────────
//
// The host re-evaluates a plugin's script on update, rollback and
// reinstall. Everything below is built fresh when it does, so without
// this a second run would leave the first run's panel orphaned in the
// DOM, its theme listener still firing, and its mount-retry timer still
// ticking — three of the things plugin-runtime-idempotent.v1 names.
//
// So each run publishes how to dismantle itself on a stable window key,
// and calls its predecessor's before building anything. The shape is the
// one docs/capability-domains.md prescribes for shared plugin state.
const HOOKS_KEY = '__feedBackLiveTabHooks';
try {
const prev = window[HOOKS_KEY];
if (prev && typeof prev.teardown === 'function') prev.teardown();
} catch (err) {
console.warn('[' + ID + '] the previous instance did not come down '
+ 'cleanly; carrying on:', err);
}
/** Everything this run has to undo, newest last. */
const disposers = [];
/**
* Tell the capability graph how the renderer got on.
*
* The host records who is providing the visualization and why one failed;
* a provider that never says is a blank row in the inspector when someone
* is trying to work out why the screen is empty.
*/
function emitViz(event, payload) {
const caps = window.feedBack && window.feedBack.capabilities;
if (!caps || caps.version !== 1 || typeof caps.emitEvent !== 'function') return;
try {
caps.emitEvent('visualization', event, Object.assign({ providerId: ID }, payload || {}));
} catch (_) { /* the graph is a nicety, never a dependency */ }
}
function onTeardown(fn) { disposers.push(fn); }
// The host cache-busts plugin scripts with `?v=<manifest version>`, so the
// running version can be read off our own <script> tag rather than kept in
// a constant here that would drift from plugin.json the first time someone
// forgot to change both.
const VERSION = (function () {
try {
/*
* `import.meta.url` FIRST, because this file is a module now.
*
* `document.currentScript` is null inside a module — always, by
* spec — so the conversion to `scriptType: "module"` would have
* dropped this to 'dev' silently, and 'dev' is what the kit
* stylesheet's cache key would then have been for every release.
* The `currentScript` read stays as the fallback for a host that
* ever serves this as a classic script again.
*/
const src = (typeof import.meta !== 'undefined' && import.meta.url)
|| (document.currentScript && document.currentScript.src)
|| '';
const m = /[?&]v=([^&]+)/.exec(src);
return m ? decodeURIComponent(m[1]) : 'dev';
} catch (_) {
return 'dev';
}
})();
/*
* THE KIT'S STYLESHEET, injected by the kit itself.
*
* `install` prepends the link so the kit loses every specificity tie to
* this plugin's own rules, and stamps `?v=` from the version above — which
* is why that read had to keep working.
*/
kit.install({ id: ID, version: VERSION });
// ─────────────────────────────────────────────────────────────────────
// 1. Settings schema — the single source of truth.
//
// Every option is declared once, with its type, its range and how the
// panel should present it. `DEFAULTS`, `normalise()` and the whole
// settings UI are derived from this list, so adding an option is one entry
// here rather than four edits that can drift apart. Unknown keys in
// storage are dropped on load, which is also how options retired between
// versions clean themselves up.
// ─────────────────────────────────────────────────────────────────────
const GROUPS = [
{ id: 'basics', label: 'Basics', advanced: false },
{ id: 'reading', label: 'Reading', advanced: true },
{ id: 'look', label: 'Notes & colour', advanced: true },
{ id: 'marks', label: 'What is written', advanced: true },
{ id: 'frame', label: 'Board & backdrop', advanced: true },
];
const isPaged = (s) => s.readMode === 'page';
const isScroll = (s) => s.readMode === 'scroll';
const SCHEMA = [
{
key: 'enabled', type: 'bool', def: true, group: 'basics',
label: 'Show the tab',
when: (s) => s.readMode === 'scroll' && s.board !== 'none',
hint: 'Turning it off gives the whole player to the board above and '
+ 'leaves Live Tab hosting it. It only means anything when there '
+ 'is a board to give the room to: with none, and while the tab '
+ 'turns pages, the tab is all there is.',
},
{
key: 'readMode', type: 'enum', def: 'scroll', group: 'basics',
label: 'How the tab moves',
options: [
['scroll', 'Scrolling — the tab slides under a fixed cursor'],
['page', 'Page turns — the cursor walks, the page turns'],
],
hint: 'Scrolling is one continuous staff: nothing to lose your place '
+ 'in, and it pairs with a board above. Page turns is how sheet '
+ 'music reads — each staff holds a fixed range of bars, the '
+ 'cursor crosses it, and at the end the stack slides up one '
+ 'staff. Nothing moves mid-bar, so the numbers hold still while '
+ 'you play them.',
},
{
key: 'board', type: 'enum', def: 'highway_3d', dynamic: true,
group: 'basics', label: 'Board above the tab', when: isScroll,
hint: 'Live Tab hosts this board in the upper part of the player and '
+ 'keeps the lower part for the tab, so neither covers the other. '
+ 'The list is read from the app, so any view you install appears '
+ 'here. Scrolling only: page turns give the whole player to the '
+ 'staves, because sharing it with a board leaves them closer '
+ 'together than a note head is wide.',
},
{
key: 'heightPct', type: 'num', def: 30, min: 14, max: 60, step: 1,
group: 'basics', label: 'Tab height', unit: '% of the player',
when: isScroll,
hint: 'How the player is split between the board and the tab. '
+ 'Ignored when there is no board above.',
},
// ── Reading ──────────────────────────────────────────────────
{
key: 'rows', type: 'int', def: 3, min: 2, max: 4, group: 'reading',
label: 'Staves', when: isPaged,
hint: 'Page turns only. The staves below the cursor already hold the '
+ 'bars to come, so the eye can read ahead the way it does off '
+ 'paper. Scrolling always uses one staff: two staves both sliding '
+ 'at once give the eye no way to tell which line is now.',
},
{
key: 'pageBars', type: 'int', def: 3, min: 1, max: 8, group: 'reading',
label: 'Bars per staff', when: isPaged,
hint: 'Three bars of 4/4 lasts long enough to read at any tempo in '
+ 'reach — five and a half seconds at 130, three and a half at '
+ 'the fastest thing you are likely to play — and holds twelve '
+ 'beats, which stays legible at any width. Fewer turns the page '
+ 'more often; more packs the notes tighter. Past eight the fret '
+ 'numbers have under 30 pixels each and stop being separable.',
},
{
key: 'aheadBeats', type: 'num', def: 5, min: 2, max: 24, step: 0.5,
group: 'reading', label: 'Ahead', unit: 'beats', when: isScroll,
hint: 'How much of what is coming is on screen, in beats — so note '
+ 'spacing is proportional to note value and a quarter really is '
+ 'twice an eighth. Above a moderate tempo the window widens to '
+ 'keep the reading speed steady, and the panel shows both '
+ 'numbers: what you asked for, and what is on screen.',
},
{
key: 'behindBeats', type: 'num', def: 1.25, min: 0.5, max: 8, step: 0.25,
group: 'reading', label: 'Behind', unit: 'beats', when: isScroll,
hint: 'How much of what you have just played stays visible.',
},
// ── Notes & colour ───────────────────────────────────────────
{
key: 'highStringOnTop', type: 'bool', def: true, group: 'look',
label: 'Thinnest string on top',
hint: 'On by default: that is how tablature is written on paper. '
+ 'Turn it off to put the thin E at the bottom and mirror the '
+ 'note board’s order instead.',
},
{
key: 'useHostColors', type: 'bool', def: true, group: 'look',
label: 'Use the app’s string colours',
hint: 'Per-string colours and their presets live in the app’s own '
+ 'Graphics settings, and the tab follows them, so one palette '
+ 'serves every view. Turn this off to keep Live Tab on its own '
+ 'default palette instead.',
},
{
key: 'noteLabel', type: 'enum', def: 'fret', group: 'look',
label: 'What the note head says', options: [
['fret', 'The fret number'],
['name', 'The note name \u2014 E, F#, A#'],
['both', 'The fret, with the note name beside it'],
['nameFret', 'The note name, with the fret beside it'],
],
hint: 'Learning where the notes are, rather than only which fret to '
+ 'press, is most of what reading music buys you. Names are '
+ 'worked out from the song\u2019s own tuning, so a drop or a flat '
+ 'tuning names its notes correctly. The head is the legible '
+ 'slot, so put in it whichever of the two you are working on: '
+ 'the fret to find the note, the name to learn it. Whatever '
+ 'goes beside is dropped wherever a run is too tight to fit '
+ 'it, the same way the technique marks are.',
},
{
/*
* ACCESO di default, e prima era spento.
*
* Ha effetto in un caso solo — `staffLines()`: il tuo strumento ha
* PIU' corde del chart e della stessa famiglia. Fuori da quel caso
* accenderlo e spegnerlo e' identico, e su una chitarra a sei corde
* con un chart a sei corde e' ogni caso.
*
* Quando invece serve, acceso e' la risposta: una riga sullo
* schermo e' una corda sul manico, che e' tutto il valore di una
* tablatura. Spento, la riga piu' in basso non e' la corda piu'
* grave che tieni in mano, e la traslazione la fa il lettore.
*
* Il prezzo esiste e non lo diceva nessuno: una riga in piu' e'
* spazio verticale in meno, quindi `headR = min(headWanted, gap *
* 0.46)` porta giu' le teste con se'. E' un compromesso di
* densita', non di corrispondenza — chi ha un basso a cinque corde
* e vuole le teste grandi lo spegne, e ora l'hint glielo dice.
*/
key: 'matchInstrument', type: 'bool', def: true, group: 'look',
label: 'Match my instrument\u2019s strings',
hint: 'A four-string chart on a five-string bass draws the extra low '
+ 'string as an empty line, so the staff matches the neck in front '
+ 'of you and a string is one line in both places. Read from the '
+ 'instrument set in the app\u2019s tuning settings. The extra '
+ 'line costs vertical space, so the heads sit a little smaller — '
+ 'turn it off if you would rather have the size.',
},
{
key: 'noteInk', type: 'enum', def: 'string', group: 'look',
label: 'Fret numbers', options: [
['string', 'In the string’s colour'],
['mono', 'One ink, like printed tab'],
],
hint: 'Colour tells you which string at a glance. One ink is how tab '
+ 'is printed, and some eyes hold a shape better without hue.',
},
{
key: 'lineInk', type: 'enum', def: 'string', group: 'look',
label: 'String lines', options: [
['string', 'Coloured per string'],
['mono', 'Grey'],
],
},
{
key: 'noteFill', type: 'enum', def: 'dark', group: 'look',
label: 'Note heads', options: [
['dark', 'Dark head, coloured digit — printed tab'],
['solid', 'Filled head, dark digit — like the board’s gems'],
],
hint: 'A filled head is the fastest thing to spot at speed. A dark '
+ 'head puts the digit forward, which reads better slowly.',
},
{
key: 'noteScale', type: 'num', def: 1, min: 0.7, max: 1.6, step: 0.05,
group: 'look', label: 'Note size',
hint: 'Heads and digits together. Dense passages still shrink on their '
+ 'own so the numbers never collide; this sets the ceiling.',
},
{
key: 'stringAlpha', type: 'num', def: 0.42, min: 0.15, max: 1, step: 0.02,
group: 'look', label: 'String contrast',
},
// ── What is written ──────────────────────────────────────────
{
key: 'rhythmGrid', type: 'enum', def: 'auto', group: 'marks',
label: 'Rhythm ruler',
options: [
['auto', 'Subdivided as finely as it fits'],
['beats', 'Whole beats only'],
['off', 'Nothing'],
],
hint: 'Note spacing is already proportional to note value, so where '
+ 'a note sits between two beats IS its rhythm. The ruler gives '
+ 'the eye something to count against: whole beats through the '
+ 'staff, and halves and quarters of a beat hanging below it '
+ 'when there is room for them to be told apart.',
},
{
key: 'showLoop', type: 'bool', def: true, group: 'marks',
label: 'The loop',
hint: 'When a loop is armed, shade the stretch that repeats and '
+ 'mark where it turns. Learning a passage is playing it round '
+ 'and round, and the thing that gets lost is where round '
+ 'begins.',
},
{ key: 'showBars', type: 'bool', def: true, group: 'marks', label: 'Bar numbers' },
{ key: 'showSections', type: 'bool', def: true, group: 'marks', label: 'Section names' },
{ key: 'showChords', type: 'bool', def: true, group: 'marks', label: 'Chord names' },
{
key: 'showTech', type: 'bool', def: true, group: 'marks',
label: 'Technique marks (h, p, t, ◇)',
},
{ key: 'showPM', type: 'bool', def: true, group: 'marks', label: 'Palm-mute brackets' },
{
key: 'showStrings', type: 'bool', def: true, group: 'marks',
label: 'String names in the margin',
hint: 'The open note of each line, down the left edge, read from the '
+ 'song\u2019s own tuning \u2014 so a drop or a flat tuning shows what it '
+ 'really is. Worth more here than on paper: the order can be '
+ 'flipped and the staff can have four, five or six lines.',
},
{
key: 'showTempo', type: 'bool', def: true, group: 'marks',
label: 'Tempo mark',
hint: 'The beats per minute where the cursor is, so a change of tempo '
+ 'shows as a change of number.',
},
{
key: 'showLyrics', type: 'bool', def: false, group: 'marks',
label: 'Lyrics under the staff',
hint: 'Syllables under the notes they fall on. The app already shows '
+ 'the line you are on across the top; this is the other thing '
+ 'lyrics are good for \u2014 knowing exactly which note the word '
+ 'lands on.',
},
// ── Board & backdrop ─────────────────────────────────────────
{
key: 'boardAspect', type: 'num', def: 1.78, min: 0, max: 4, step: 0.02,
group: 'frame', label: 'Board proportions', when: isScroll,
hint: 'Width ÷ height the board is held to. A short full-width box '
+ 'distorts a 3D board into a wide funnel, so it is narrowed and '
+ 'centred instead. Below 1 it fills the width.',
},
{
key: 'panelOpacity', type: 'num', def: 0.9, min: 0.3, max: 1, step: 0.02,
group: 'frame', label: 'Backdrop', when: isScroll,
hint: 'How solid the tab’s own background is behind a board. With no '
+ 'board it is always solid.',
},
];
const FIELD = {};
for (const f of SCHEMA) FIELD[f.key] = f;
function optionValues(f) {
return (f.options || []).map((o) => o[0]);
}
/** Coerce any object into a valid settings object. Drops unknown keys. */
function normalise(raw) {
const s = raw || {};
const out = {};
for (const f of SCHEMA) {
const v = s[f.key];
if (f.type === 'bool') {
out[f.key] = (v === undefined || v === null) ? f.def : !!v;
} else if (f.type === 'num' || f.type === 'int') {
let n = Number(v);
if (!isFinite(n)) n = f.def;
n = Math.max(f.min, Math.min(f.max, n));
out[f.key] = (f.type === 'int') ? Math.round(n) : n;
} else if (f.type === 'enum') {
const ok = f.dynamic
? (typeof v === 'string' && !!v)
: optionValues(f).indexOf(v) >= 0;
out[f.key] = ok ? v : f.def;
} else {
out[f.key] = (v === undefined) ? f.def : v;
}
}
return out;
}
const DEFAULTS = normalise({});
function loadSettings() {
let stored = null;
try {
const raw = window.localStorage.getItem(LS_KEY);
if (raw) stored = JSON.parse(raw);
} catch (_) { /* private mode or bad JSON */ }
return normalise(Object.assign({}, DEFAULTS, stored || {}));
}
let S = loadSettings();
function saveSettings() {
try { window.localStorage.setItem(LS_KEY, JSON.stringify(S)); } catch (_) {}
}
/** True when a field is meaningful given the rest of the settings. */
function fieldLive(f) {
return (typeof f.when !== 'function') || !!f.when(S);
}
// ─────────────────────────────────────────────────────────────────────
// 2. Presets — a starting point, not a straitjacket.
//
// Almost nobody wants to set fifteen sliders, and the ones who do want
// them all. So: a row of presets that each make internal sense, and the
// advanced options folded away underneath. A preset is plain data, and it
// only claims to be active while every value it names still holds.
// ─────────────────────────────────────────────────────────────────────
const PRESETS = [
{
id: 'live', label: 'Live',
hint: 'Play along and read the tab while you do: a board above, a '
+ 'full staff below with the bars, the sections and the marks on it.',
values: {
readMode: 'scroll', board: 'highway_3d', heightPct: 32,
aheadBeats: 5, behindBeats: 1.25, noteFill: 'dark', noteScale: 1,
noteInk: 'string', lineInk: 'string', stringAlpha: 0.42,
noteLabel: 'fret',
showBars: true, showSections: true, showChords: true,
showTech: true, showPM: true, showLoop: true, rhythmGrid: 'auto',
showStrings: true, showTempo: true, showLyrics: false,
},
},
{
id: 'study', label: 'Study',
hint: 'Learn the part away from the board: page turns, three staves, '
+ 'and every note named beside its fret.',
values: {
readMode: 'page', rows: 3, pageBars: 3, board: 'none',
noteFill: 'dark', noteScale: 1.05, noteInk: 'string',
lineInk: 'string', stringAlpha: 0.42, noteLabel: 'both',
showBars: true, showSections: true, showChords: true,
showTech: true, showPM: true, showLoop: true, rhythmGrid: 'auto',
showStrings: true, showTempo: true, showLyrics: true,
},
},
{
id: 'sightread', label: 'Sight-reading',
hint: 'Read it like paper: the same page turns in a single ink, with '
+ 'no colour to lean on.',
values: {
readMode: 'page', rows: 3, pageBars: 3, board: 'none',
noteInk: 'mono', lineInk: 'mono', noteFill: 'dark',
noteScale: 1.05, stringAlpha: 0.5, noteLabel: 'both',
showBars: true, showSections: true, showChords: true,
showTech: true, showPM: true, showLoop: true, rhythmGrid: 'auto',
showStrings: true, showTempo: true, showLyrics: true,
},
},
{
id: 'arcade', label: 'Arcade',
hint: 'Play, do not read: the board is the game and the tab shrinks '
+ 'to a ribbon of filled heads beneath it, nothing written on it '
+ 'at all — there to show what you hit, not to be read.',
values: {
readMode: 'scroll', board: 'highway_3d', heightPct: 16,
aheadBeats: 3.5, behindBeats: 1, noteFill: 'solid', noteScale: 1.15,
noteInk: 'string', lineInk: 'string', stringAlpha: 0.42,
noteLabel: 'fret',
showBars: false, showSections: false, showChords: false,
showTech: false, showPM: false, showLoop: false, rhythmGrid: 'off',
showStrings: false, showTempo: false, showLyrics: false,
},
},
{
id: 'minimal', label: 'Minimal',
hint: 'One big scrolling staff and nothing else — no board, no '
+ 'names, nothing written but the bar numbers.',
values: {
readMode: 'scroll', board: 'none', heightPct: 45,
aheadBeats: 6, behindBeats: 1.5, noteFill: 'dark', noteScale: 0.95,
noteInk: 'string', lineInk: 'mono', stringAlpha: 0.3,
noteLabel: 'fret',
showBars: true, showSections: false, showChords: false,
showTech: false, showPM: false, showLoop: true, rhythmGrid: 'beats',
showStrings: true, showTempo: false, showLyrics: false,
},
},
];
function presetMatches(preset) {
for (const key of Object.keys(preset.values)) {
if (S[key] !== preset.values[key]) return false;
}
return true;
}
function activePresetId() {
for (const p of PRESETS) if (presetMatches(p)) return p.id;
return null;
}
// ─────────────────────────────────────────────────────────────────────
// 3. Palette
// ─────────────────────────────────────────────────────────────────────
const GUITAR_COLORS = ['#ff5552', '#fff352', '#31caff', '#ffae31', '#84ff42', '#e639ff'];
const BASS_COLORS = ['#ff5552', '#fff352', '#31caff', '#ffae31', '#84ff42', '#e639ff'];
/*
* ── THE DRAWING READS THE KIT'S TOKENS ──────────────────────────────
*
* These were hex: `#e8eef7`, `#9aa7b8`, `#4ade80`, `#f87171`. Every one of
* them is a role the kit already publishes, and three were the WRONG shade
* of the right idea — the kit's `good` is #3DDC84, not #4ade80, so a green
* head and a green rail in the panel beside it were two different greens.
*
* Read at CALL TIME, not captured once: the kit writes `--fbk-*` on the
* root and rewrites them when a theme changes, so a constant would be
* whatever was true when the module loaded. That is the same mistake as
* the panel's `repaintControls`, one layer down — except a canvas cannot
* inherit a custom property, so it has to ask.
*
* A cache keyed on the root's own `data-fbk-theme`-less reality would be
* premature: `getComputedStyle` on the root is a few microseconds and this
* runs once per frame per colour, not per note.
*/
const KIT_FALLBACK = {
text: '232 238 252', dim: '138 160 200', accent: '41 168 255',
good: '61 220 132', bad: '229 72 77', bg: '5 7 12',
};
/*
* UNA LETTURA PER FRAME PER COLORE — e stavolta davvero.
*
* Il commento qui sopra lo prometteva gia', ma le chiamate stanno dentro i
* cicli PER NOTA: il carattere delle cifre a ogni testa, il colore del
* verdetto a ogni giudizio, `dim` a ogni arco, a ogni badge, a ogni
* legatura. Con tre staffe e quaranta note visibili sono centinaia di
* risoluzioni di stile al frame, ognuna delle quali puo' costringere il
* motore a ricalcolare lo stile del documento.
*
* La cache si svuota all'inizio di ogni `paintTab` e al cambio di tema, che
* sono i due soli momenti in cui quei valori possono essere diversi.
*/
const inkCache = new Map();
let inkAt = 0;
function forgetInk() {
inkCache.clear();
inkAt = (typeof performance !== 'undefined') ? performance.now() : Date.now();
}
/*
* Chi legge fuori dal ciclo di disegno — il pannello, quando si costruisce —
* non passa da `paintTab`, quindi senza questo si porterebbe dietro i valori
* dell'ultimo frame disegnato, che con la vista spenta puo' voler dire
* quelli di ieri. Un quarto di secondo e' piu' corto di qualunque gesto
* umano e piu' lungo di qualunque frame.
*/
function inkFresh() {
const now = (typeof performance !== 'undefined') ? performance.now() : Date.now();
if (now - inkAt > 250) forgetInk();
}
function readVar(name) {
try {
const v = getComputedStyle(document.documentElement)
.getPropertyValue(name).trim();
return v || null;
} catch (_) { return null; } /* no document yet */
}
function kitInk(role, alpha) {
inkFresh();
const key = 'i:' + role;
let triplet = inkCache.get(key);
if (triplet === undefined) {
triplet = readVar('--fbk-' + role) || KIT_FALLBACK[role] || KIT_FALLBACK.text;
inkCache.set(key, triplet);
}
return (alpha === undefined)
? 'rgb(' + triplet + ')'
: 'rgb(' + triplet + ' / ' + alpha + ')';
}
/*
* The kit's own type stacks, so a fret number on the tab and one in the
* panel are the same face. Numbers were already Mono; the TEXT was `Inter`,
* which is nothing this design system uses.
*/
function kitFont(role) {
inkFresh();
const key = 'f:' + role;
let face = inkCache.get(key);
if (face === undefined) {
const fallback = (role === 'num')
? '"JetBrains Mono", ui-monospace, monospace'
: 'Rubik, system-ui, sans-serif';
face = readVar(role === 'num' ? '--fbk-font-num' : '--fbk-font') || fallback;
inkCache.set(key, face);
}
return face;
}
const MONO_NOTE = () => kitInk('text');
const MONO_LINE = () => kitInk('dim');
const COL_HIT = () => kitInk('good');
const COL_MISS = () => kitInk('bad');
const COL_BAR = 'rgba(255,255,255,0.34)';
const COL_BEAT = 'rgba(255,255,255,0.11)';
const COL_HALF = 'rgba(255,255,255,0.075)';
const COL_QUARTER = 'rgba(255,255,255,0.042)';
// The app's own loop buttons are green; the tab says the same thing in the
// same colour rather than inventing a second vocabulary for it.
const COL_LOOP = 'rgba(74,222,128,0.85)';
const COL_LOOP_FILL = 'rgba(74,222,128,0.10)';
/*
* IL VERDE E' DELLA PARTE DA SUONARE, E DI NESSUN'ALTRA.
*
* Prima la rincorsa del drill — i cinque secondi che il loop apre prima
* delle battute scelte, perche' tu non ci entri di corsa — aveva lo stesso
* verde della parte giudicata, solo piu' pallido: un velo al 10% contro due
* al 10%. Due verdi vicini non sono due categorie, sono lo stesso colore
* con due luci: a schermo si confondevano, e la rincorsa continuava a dire
* "questa e' roba tua".
*
* Adesso la rincorsa non e' verde affatto. Fondo neutro piu' una tratteggia-
* tura diagonale, che e' la convenzione con cui si dice "zona, ma non
* agibile" da prima dei monitor. Il verde resta uno solo, piu' deciso di
* com'era, e vuol dire una cosa sola: qui si suona.
*
* La tratteggiatura, e non un semplice grigio piu' scuro: sul nero di
* sfondo un velo neutro leggero e' quasi invisibile, e uno pesante spegne
* le note che ci stanno sopra — e quelle note vanno lette lo stesso, sono
* il contesto da cui il pezzo esce. Le righe si vedono senza coprire.
*/
const COL_JUDGED_FILL = 'rgba(74,222,128,0.20)';
const COL_RUNIN_FILL = () => kitInk('dim', 0.10);
const COL_RUNIN_HATCH = () => kitInk('dim', 0.22);
/*
* Le note che in questo passaggio non tocca suonare: grigie, non colorate.
*
* `dim` e non un grigio inventato, cosi' seguono il tema come tutto il
* resto. Al 55% restano leggibili — devono restare leggibili, sono il
* contesto da cui il pezzo esce — ma smettono di competere con la zona.
*/
const COL_OUT = () => kitInk('dim', 0.55);
/*
* THE CURSOR IS THE ACCENT, not white.
*
* White made it one more bright thing among the note heads and the bar
* lines; the accent is the only colour in this system that means "here,
* now", and it is what the panel's own live rung uses. Reported as part of
* the tab's own design pass.
*/
const COL_PLAYHEAD = () => kitInk('accent');
const NOW_WINDOW = 0.09;
const ROW_GAP_MAX = 26;
// Seven- and eight-string guitars add their extra strings below the low E,
// which is the order the app's own colour slots use too (low7, low8).
const LOW_EXTRA = ['#7c8cff', '#f472b6'];
function paletteFor(stringCount, isBass) {
const bass = (isBass === undefined) ? (stringCount <= 5) : !!isBass;
const base = bass ? BASS_COLORS : GUITAR_COLORS;
if (stringCount <= base.length) return base;
return LOW_EXTRA.slice(0, stringCount - base.length).reverse().concat(base);
}
// ─────────────────────────────────────────────────────────────────────
// 4. Pure helpers — no canvas, no host.
// ─────────────────────────────────────────────────────────────────────
/**
* Which visual row a string index sits on.
*
* Chart index 0 is the lowest string. Tab is written with the thinnest on
* top, so by default the order is reversed; the board draws it the other
* way round, and some players would rather the two agree.
*/
function rowFor(stringIndex, stringCount, highOnTop) {
return highOnTop ? (stringCount - 1 - stringIndex) : stringIndex;
}
function techniqueMark(n) {
if (!n) return '';
if (n.ho) return 'h';
if (n.po) return 'p';
if (n.tp) return 't';
if (n.hm || n.hp) return '◇';
return '';
}
function slideTarget(n) {
if (!n) return null;
const sl = (typeof n.sl === 'number' && n.sl >= 0) ? n.sl : null;
if (sl != null) return sl;
return (typeof n.slu === 'number' && n.slu >= 0) ? n.slu : null;
}
/*
* IL VERDETTO SI RICORDA, perche' il provider lo dice per poco.
*
* `noteStateFor` nel rilevatore restituisce `miss` solo finche'
* `age < NOTE_MISS_GEM_TTL`, cioe' 0,6 secondi, e poi `null`; il verde di
* una nota colpita svanisce con `hitGlowDuration`. E' giusto per una gemma
* che scorre e sparisce, ma una tablatura tiene la nota sullo schermo
* finche' non esce dalla finestra: passati quei sei decimi la nota tornava
* grigia al 30%, cioe' "non e' successo niente" al posto di "questa
* l'hai sbagliata". Segnalato come riscontro che non arriva.
*
* Quindi il primo verdetto che arriva viene tenuto, e il provider vince
* sempre quando ha qualcosa da dire: la memoria riempie i buchi, non
* inventa giudizi. Non anticipa nulla — decidere da soli che una nota e'
* mancata vorrebbe dire duplicare la finestra di timing del rilevatore e
* poter contraddire il suo verdetto su una nota presa in ritardo.
*
* Una `WeakMap` sulla nota stessa, non una mappa con una chiave: le note
* arrivano dagli array del chart, che il caricamento di un altro brano
* sostituisce — quindi la memoria si invalida da se' e non c'e' niente da
* ripulire. E niente viene scritto sugli oggetti dell'app, che il suo
* contratto chiede di trattare come di sola lettura.
*/
let verdictSeen = new WeakMap();
let verdictSince = -1;
/*
* UN SALTO INDIETRO AZZERA LA MEMORIA.
*
* Le note sono gli stessi oggetti a ogni giro, quindi in un loop di Riff
* Repeater il rosso del passaggio precedente si sarebbe ripresentato prima
* che tu suonassi la nota: un giudizio dato sul giro sbagliato, che e' peggio
* di nessun giudizio. Vale anche per un seek a mano e per il cambio di
* brano.
*
* Il tempo che torna indietro e' il segnale, e non serve un evento
* dell'app: un quarto di secondo di tolleranza perche' il tempo del player
* puo' oscillare di un frame senza che sia un salto.
*/
function verdictClock(now) {
if (now < verdictSince - 0.25) verdictSeen = new WeakMap();
verdictSince = now;
}
/**
* Se una nota puo' portare un verdetto: solo quando il cursore l'ha
* raggiunta.
*
* SEMBRA OVVIO E NON LO E'. Un verdetto e' un'affermazione su qualcosa che
* hai suonato, quindi su una nota che deve ancora arrivare non ne esiste
* uno — e invece dopo il riavvio di un loop le prime note tornavano
* colorate col giudizio del giro precedente, verdi e rosse davanti al
* cursore. Segnalato esattamente cosi'.
*
* Le due sorgenti erano diverse e questa regola le chiude entrambe.
*
* IL VERDE veniva dal rilevatore. `noteStateFor` calcola
* `age = songT - dispAnchor` e fa `if (age < 0) return { state: 'hit',
* alpha: 1 }`, con il commento "struck a hair early": su un'autostrada di
* gemme quel ramo vale una nota presa qualche millesimo prima del tempo.
* Ma un avvolgimento di loop riporta l'orologio indietro di undici secondi,
* e allora OGNI nota giudicata nel giro prima cade in quel ramo e torna
* come colpita a piena forza. Per il suo renderer non e' un difetto —
* un'autostrada non mostra mai le note dietro il salto — mentre una
* tablatura disegna una finestra di note DAVANTI al cursore, e si ritrova
* consegnato tutto il giro precedente.
*
* IL ROSSO era mio: la memoria dei verdetti (vedi sotto) riempiva il buco
* che il rilevatore lascia sui miss dopo il salto, e azzerarla quando il
* tempo torna indietro non bastava.
*
* Quindi la regola non e' "accorgiti del salto", che e' una gara con
* l'orologio: e' "il futuro non ha verdetti", che e' vero per costruzione
* e non dipende dall'accorgersi di niente. `NOW_WINDOW` di tolleranza,
* perche' la nota sotto il cursore la stai suonando adesso.
*/
function verdictApplies(live, noteT, now) {
if (!live) return true;
return !(Number(noteT) > Number(now) + NOW_WINDOW);
}
/** Normalise a provider verdict: bare string or { state } -> 'hit'|'miss'|null. */
function verdictOf(raw) {
if (!raw) return null;
const st = (typeof raw === 'object') ? raw.state : raw;
if (st === 'hit' || st === 'active') return 'hit';
if (st === 'miss') return 'miss';
return null;
}
/*
* Le note di un accordo, appiattite — e SEMPRE GLI STESSI OGGETTI.
*
* La memoria dei verdetti e' una `WeakMap` sulla nota: se la nota e' un
* oggetto nuovo a ogni frame la memoria non trova mai niente, e l'accordo
* sbagliato tornava grigio dopo i 0,6 secondi di vita del verdetto invece
* di restare rosso finche' esce dalla finestra — cioe' esattamente il
* difetto che quella memoria era stata scritta per togliere. Le note
* singole non ne soffrivano perche' arrivano dall'ospite e la loro identita'
* regge tutto il brano.
*
* La cache e' sull'accordo (`WeakMap`, quindi se ne va con lui) e porta con
* se' il template da cui e' nata: cambiare difficolta' rimappa le forme, e
* una versione appiattita vecchia disegnerebbe la diteggiatura sbagliata.
*/
const chordNoteCache = new WeakMap();
/** Flatten a chord into note-shaped entries sharing the chord's time. */
function chordNotes(chord, templates) {
if (!chord) return [];
const tplNow = (Array.isArray(templates) && chord.id != null) ? templates[chord.id] : null;
const hit = chordNoteCache.get(chord);
if (hit && hit.tpl === tplNow) return hit.out;
const out = build(chord, templates, tplNow);
chordNoteCache.set(chord, { tpl: tplNow, out });
return out;
}
function build(chord, templates, tplNow) {
if (Array.isArray(chord.notes) && chord.notes.length) {
return chord.notes.map((cn) => Object.assign({}, cn, { t: chord.t }));
}
const frets = tplNow && Array.isArray(tplNow.frets) ? tplNow.frets : null;
if (!frets) return [];
const out = [];
for (let s = 0; s < frets.length; s++) {
if (frets[s] >= 0) out.push({ s: s, f: frets[s], t: chord.t });
}
return out;
}
/**
* Smallest pixel gap between consecutive notes on the same string.
*
* A fast passage packs notes closer than a fret number is wide and the
* digits start colliding. Measuring the tightest spacing actually on
* screen lets the type shrink exactly as much as that passage needs,
* instead of picking one size that is either too big for a solo or too
* small for everything else.
*/
function tightestGap(items, xOf, stringCount) {
const lastX = new Array(stringCount).fill(null);
const ordered = items.slice().sort((a, b) => a.t - b.t);
let min = Infinity;
for (const it of ordered) {
const s = it.n.s | 0;
if (s < 0 || s >= stringCount) continue;
const x = xOf(it.t);
const prev = lastX[s];
if (prev != null) {
const d = Math.abs(x - prev);
if (d > 0.5 && d < min) min = d;
}
lastX[s] = x;
}
return min;
}
// ── Pitch ────────────────────────────────────────────────────────
// Only pitch classes, never octaves: a name is what was asked for, and
// there is no octave numbering to get wrong. Fret numbers in these charts
// are absolute positions on the neck, so a capo does not enter into it —
// fret 5 is fret 5 whether or not something is clamped at fret 2.
const NOTE_NAMES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
const OPEN_GUITAR = [4, 9, 2, 7, 11, 4]; // E A D G B E
const OPEN_BASS4 = [4, 9, 2, 7]; // E A D G
const OPEN_BASS5 = [11, 4, 9, 2, 7]; // B E A D G
/**
* Open-string pitch classes, lowest string first, for any string count.
*
* Extended rather than enumerated: a seven-string adds a B a fourth below
* the low E, an eight-string an F# below that, and a five-string bass adds
* the same low B while a six adds a high C. Charts with more strings than
* we have ever seen therefore name their notes correctly instead of being
* truncated to six and silently losing the bottom of the instrument.
*/
function openPitchClasses(stringCount, isBass) {
const n = Math.max(4, stringCount | 0);
let out;
if (isBass) {
out = OPEN_BASS4.slice(); // E A D G
if (n >= 5) out = OPEN_BASS5.slice(); // B E A D G
if (n >= 6) out.push(0); // high C
} else {
out = OPEN_GUITAR.slice(); // E A D G B E
while (out.length < n) out.unshift((((out[0] - 5) % 12) + 12) % 12);
}
return out.slice(0, n);
}
/**
* Name of the note a fret sounds, given the song's tuning.
*
* `tuning.offsets` are per-string semitone offsets from standard, which is
* how the charts carry a drop D or an Eb tuning, so a transposed song names
* its notes correctly rather than a semitone out.
*/
function noteNameFor(stringIndex, fret, tuning, stringCount) {
if (fret == null || fret < 0) return '';
const open = openPitchClasses(stringCount, !!(tuning && tuning.bass));
const base = open[stringIndex];
if (base == null) return '';
const offsets = (tuning && Array.isArray(tuning.offsets)) ? tuning.offsets : [];
const off = Number(offsets[stringIndex]) || 0;
return NOTE_NAMES[(((base + off + fret) % 12) + 12) % 12];
}
/**
* How many lines the staff draws, and how far the chart's strings shift up.
*
* Extra strings on a real instrument are always the low ones — a five-string
* bass adds a B below the E — so a four-string chart on that bass keeps its
* strings and gains an empty line underneath. Only within the same family:
* a bass chart read by someone holding a six-string guitar must not sprout
* two bass strings, which is exactly what the naive version did.
*/
/**
* How finely to rule the beat, given how much room a beat has.
*
* Halves and quarters of a beat, and no further: a thirty-second is not
* something anyone counts off a moving ruler, and drawing one only fills
* the space between the notes with lines. A subdivision is only worth
* drawing if its ticks are far enough apart to be told from each other —
* below that they read as a smear, which is the opposite of counting.
*/
const SUB_MIN_PX = 18;
/**
* Draw text centred on the INK, not on the em box.
*
* `textBaseline = 'middle'` centres the font's em box, and a digit's ink is
* not in the middle of that box: `5` has no descender, so the em box
* reserves room below it that the glyph never uses and the digit rides
* high. Inside a circle that is immediately visible — reported as the
* number not being in the centre of the circumference — and the old answer
* was a hand-tuned `y + 0.5`, which is a fudge for one font at one size
* that goes wrong at every other.
*
* `actualBoundingBoxAscent/Descent` measure the glyph that will actually be
* painted, so the correction is exact for whatever is inside: a digit, two
* digits, `A#`, a bracketed `(7)`, an `H`. Which is the requirement —
* whatever is in there is in the true centre.
*
* Falls back to `middle` where the metrics are missing, because a slightly
* high digit is better than a digit at the baseline.
*/
function fillInkCentred(ctx, text, cx, cy, align) {
ctx.textAlign = align || 'center';
/*
* CENTRE WHAT YOU READ, not the decorations around it.
*
* A held note is written `(7)`, and centring the whole ink box centres
* the BRACKETS — which hang lower than the digit does, so the digit
* itself ends up high. Measured at 40px: the group lands on centre and
* the digit sits 2.5px above it, which is exactly the offset that kept
* being reported after the first fix "worked". A plain `7` was already
* within half a pixel, which is why the fault only showed on the tied