-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkeys.ts
More file actions
388 lines (366 loc) · 16.3 KB
/
Copy pathkeys.ts
File metadata and controls
388 lines (366 loc) · 16.3 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
import type { PitchClass } from './notes';
import type { Scale, ScaleCategory } from './scales';
export type AccidentalKind =
| 'natural'
| 'sharp'
| 'flat'
| 'doubleSharp'
| 'doubleFlat';
const LETTERS = ['C', 'D', 'E', 'F', 'G', 'A', 'B'] as const;
const LETTER_PC: Record<string, number> = {
C: 0,
D: 2,
E: 4,
F: 5,
G: 7,
A: 9,
B: 11,
};
export type KeySpelling = 'sharp' | 'flat';
export interface Key {
/** Display name with unicode accidental, e.g., "C", "F♯", "B♭". */
name: string;
/** Stable identifier used in settings storage, ASCII-only. */
id: string;
pc: PitchClass;
spelling: KeySpelling;
/**
* Key signature for this key's MAJOR scale: positive = sharps, negative
* = flats. AlphaTex `\ks` accepts integers from -7 to 7. Three "weird"
* sharp keys (G♯, A♯, D♯) have impractical key sigs (8-10 sharps); we
* use 0 for those so AlphaTab renders without a key signature, with
* each accidental displayed explicitly.
*/
majorKeySignature: number;
}
export const KEYS: readonly Key[] = [
{ id: 'C', name: 'C', pc: 0, spelling: 'sharp', majorKeySignature: 0 },
{ id: 'Db', name: 'D♭', pc: 1, spelling: 'flat', majorKeySignature: -5 },
{ id: 'Cs', name: 'C♯', pc: 1, spelling: 'sharp', majorKeySignature: 7 },
{ id: 'D', name: 'D', pc: 2, spelling: 'sharp', majorKeySignature: 2 },
{ id: 'Eb', name: 'E♭', pc: 3, spelling: 'flat', majorKeySignature: -3 },
{ id: 'Ds', name: 'D♯', pc: 3, spelling: 'sharp', majorKeySignature: 0 },
{ id: 'E', name: 'E', pc: 4, spelling: 'sharp', majorKeySignature: 4 },
{ id: 'F', name: 'F', pc: 5, spelling: 'flat', majorKeySignature: -1 },
{ id: 'Gb', name: 'G♭', pc: 6, spelling: 'flat', majorKeySignature: -6 },
{ id: 'Fs', name: 'F♯', pc: 6, spelling: 'sharp', majorKeySignature: 6 },
{ id: 'G', name: 'G', pc: 7, spelling: 'sharp', majorKeySignature: 1 },
{ id: 'Ab', name: 'A♭', pc: 8, spelling: 'flat', majorKeySignature: -4 },
{ id: 'Gs', name: 'G♯', pc: 8, spelling: 'sharp', majorKeySignature: 0 },
{ id: 'A', name: 'A', pc: 9, spelling: 'sharp', majorKeySignature: 3 },
{ id: 'Bb', name: 'B♭', pc: 10, spelling: 'flat', majorKeySignature: -2 },
{ id: 'As', name: 'A♯', pc: 10, spelling: 'sharp', majorKeySignature: 0 },
{ id: 'B', name: 'B', pc: 11, spelling: 'sharp', majorKeySignature: 5 },
] as const;
export const KEYS_BY_ID: Record<string, Key> = Object.fromEntries(
KEYS.map((k) => [k.id, k]),
);
interface ParentOffset {
/** Semitones from the parent tonic up to the mode root. */
semitones: number;
/** Letter-name steps from the parent tonic up to the mode root. */
letters: number;
}
/**
* Modes of the major scale: offset from the parent MAJOR tonic to the mode
* root, in both semitones and letter-name steps. The letter step is the
* mode's diatonic degree minus one (Dorian = 2nd degree = 1 letter up, …,
* Locrian = 7th degree = 6 letters up).
*/
const MODE_PARENT: Record<string, ParentOffset> = {
Dorian: { semitones: 2, letters: 1 },
Phrygian: { semitones: 4, letters: 2 },
Lydian: { semitones: 5, letters: 3 },
Mixolydian: { semitones: 7, letters: 4 },
Locrian: { semitones: 11, letters: 6 },
};
/**
* Modes of harmonic/melodic minor: offset from the parent MINOR tonic.
*
* - Phrygian Dominant: 5th mode of harmonic minor (4 letters up).
* - Lydian Dominant: 4th mode of melodic minor (3 letters up).
* - Altered: 7th mode of melodic minor (6 letters up).
* - Lydian ♯2: 6th mode of harmonic minor (5 letters up).
* - Locrian ♮2: 6th mode of melodic minor (5 letters up).
*/
const MODE_OF_MINOR_PARENT: Record<string, ParentOffset> = {
'Phrygian Dominant': { semitones: 7, letters: 4 },
'Lydian Dominant': { semitones: 5, letters: 3 },
Altered: { semitones: 11, letters: 6 },
'Lydian ♯2': { semitones: 8, letters: 5 },
'Locrian ♮2': { semitones: 9, letters: 5 },
};
/** The KEYS entry rooted on a given pitch class AND letter name, if any. */
function keyByPcLetter(pc: PitchClass, letter: string): Key | undefined {
return KEYS.find((k) => k.pc === pc && k.name[0].toUpperCase() === letter);
}
/**
* A major key is "representable" if AlphaTab can draw its key signature. The
* three weird sharp majors (G♯/A♯/D♯) would need 8–10 sharps and carry
* `majorKeySignature: 0` by convention — distinguished from C major (which is
* genuinely 0) by having a non-zero pitch class.
*/
function representableMajor(k: Key | undefined): k is Key {
return !!k && !(k.majorKeySignature === 0 && k.pc !== 0);
}
/**
* The parent tonic (pitch class + letter name) of a mode, chosen so the
* parent scale spells the mode root with the SAME letter. This is what makes
* C Locrian resolve to D♭ major (whose 7th degree is a C-natural) rather than
* C♯ major (whose 7th degree is B♯). Selecting by letter — not by the root's
* arbitrary sharp/flat `spelling` tag — is the whole point.
*/
function parentTonic(
key: Key,
off: ParentOffset,
): { pc: PitchClass; letter: string } {
const pc = ((key.pc - off.semitones + 12) % 12) as PitchClass;
const rootIdx = LETTERS.indexOf(
key.name[0].toUpperCase() as (typeof LETTERS)[number],
);
const letter = LETTERS[(((rootIdx - off.letters) % 7) + 7) % 7];
return { pc, letter };
}
/**
* Key signature for the natural-minor key rooted at (pc, letter) = the
* signature of its relative major (a minor third / two letters up), or null
* when that relative major needs more than 7 accidentals.
*/
function minorKeySignature(pc: PitchClass, letter: string): number | null {
// A♭ minor's relative major is C♭ (−7). C♭ isn't a KEYS entry, but the
// signature is representable; spell it explicitly.
if (pc === 8 && letter === 'A') return -7;
const relMajPc = ((pc + 3) % 12) as PitchClass;
const relMajLetter =
LETTERS[(LETTERS.indexOf(letter as (typeof LETTERS)[number]) + 2) % 7];
const relMaj = keyByPcLetter(relMajPc, relMajLetter);
return representableMajor(relMaj) ? relMaj.majorKeySignature : null;
}
/**
* The minor pentatonic (1, b3, 4, 5, b7) and blues (minor pentatonic + b5)
* scales are rooted in minor tonality. They read more naturally with the
* parallel natural-minor key signature than the parallel major: D minor
* pentatonic gets F major's 1 flat (so its F and C land as naturals) instead
* of D major's 2 sharps. This helper routes both through `keySignatureFor`
* and `keySignatureLabelFor`'s minor branch.
*/
function isMinorTonality(scale: Scale): boolean {
return scale.name === 'Blues' || scale.name === 'Minor Pentatonic';
}
/**
* Compute the key signature to use for a given key + scale combination.
* Drives AlphaTab's accidental spelling — a flat-spelled key emits a flat
* key signature so notes render as B♭ rather than A♯, etc.
*
* - Major: the key's major key signature.
* - Natural minor: the relative major's key signature (3 semitones up).
* - Modes: the parent major's key signature, parent chosen by LETTER name so
* the mode root is spelled correctly (C Locrian → D♭ major, not C♯).
* - Modes-of-minor: the parent (harmonic/melodic) minor's key signature,
* parent also chosen by letter name.
* - Other scales (pentatonic, blues, octatonic, chromatic): the key's own
* major key signature so accidentals match the user's spelling preference.
* Out-of-key notes render with explicit accidentals.
*/
export function keySignatureFor(key: Key, scale: Scale): number {
if (scale.category === 'major') {
return key.majorKeySignature;
}
if (scale.category === 'minor' || isMinorTonality(scale)) {
// All minor scales (natural, harmonic, melodic) share the natural minor
// key signature = relative major (+3 semitones). Harmonic/melodic minor's
// raised 6th/7th render with explicit accidentals. Resolve through
// minorKeySignature (by letter) so the value agrees with the label — in
// particular A♭ minor → C♭ major (−7), which a pc+spelling lookup can't
// represent and would otherwise fall back to B major (+5).
const letter = key.name[0].toUpperCase();
return minorKeySignature(key.pc, letter) ?? key.majorKeySignature;
}
if (scale.category === 'modes') {
// Parent major chosen by LETTER so it spells the mode root correctly
// (C Locrian → D♭ major, not C♯). See parentTonic.
const off = MODE_PARENT[scale.name];
if (!off) return key.majorKeySignature;
const { pc, letter } = parentTonic(key, off);
const parent = keyByPcLetter(pc, letter);
// An unrepresentable letter-parent (e.g. C♭ major) means the user picked
// the wrong enharmonic; the picker filters it, so any value is harmless.
return representableMajor(parent) ? parent.majorKeySignature : key.majorKeySignature;
}
if (scale.category === 'modes-of-minor') {
// Parent (harmonic/melodic) minor chosen by LETTER; the key signature is
// that minor's = its relative major's.
const off = MODE_OF_MINOR_PARENT[scale.name];
if (!off) return key.majorKeySignature;
const { pc, letter } = parentTonic(key, off);
return minorKeySignature(pc, letter) ?? key.majorKeySignature;
}
// Chromatic and octatonic scales don't conform to any diatonic key
// signature; using one creates a misleading visual context. Render with
// no key signature and rely on explicit accidentals.
if (scale.category === 'chromatic' || scale.category === 'octatonic') {
return 0;
}
// Pentatonic and blues: use the key's major key signature so flat keys
// render as flats and sharp keys as sharps. AlphaTab adds explicit
// accidentals for notes outside the key signature.
return key.majorKeySignature;
}
/**
* Convert a Key to the ASCII identifier AlphaTex's `\ks` directive expects
* (e.g., "B♭" -> "Bb", "F♯" -> "F#").
*/
function keyToAlphaTexName(key: Key): string {
return key.name.replace(/♯/g, '#').replace(/♭/g, 'b');
}
/**
* Build a map from pitch class to the correct accidental spelling for the
* given key + scale. Only defined for 7-note diatonic-style scales (major,
* three minors, modes, modes-of-minor, Hungarian) where each scale degree
* gets a unique letter name. Other scales (pentatonic, blues, chromatic,
* octatonic) return an empty map and fall back to AlphaTab's default
* accidental choice.
*
* Example: C♯ melodic minor → {1:#, 3:#, 4:natural, 6:#, 8:#, 10:#, 0:#}.
* The pitch class 0 entry forces the leading tone to render as B♯ instead
* of C-natural.
*/
export function spellingMap(
key: Key,
scale: Scale,
): Map<PitchClass, AccidentalKind> {
const result = new Map<PitchClass, AccidentalKind>();
if (scale.intervals.length !== 7) return result;
const rootLetter = key.name[0].toUpperCase();
const rootIdx = LETTERS.indexOf(rootLetter as (typeof LETTERS)[number]);
if (rootIdx < 0) return result;
for (let i = 0; i < 7; i++) {
const letter = LETTERS[(rootIdx + i) % 7];
const expectedPc = ((key.pc + scale.intervals[i]) % 12) as PitchClass;
const naturalPc = LETTER_PC[letter];
let semitones = expectedPc - naturalPc;
while (semitones > 6) semitones -= 12;
while (semitones < -6) semitones += 12;
let acc: AccidentalKind | null;
switch (semitones) {
case 0:
acc = 'natural';
break;
case 1:
acc = 'sharp';
break;
case 2:
acc = 'doubleSharp';
break;
case -1:
acc = 'flat';
break;
case -2:
acc = 'doubleFlat';
break;
default:
acc = null;
}
if (acc !== null) result.set(expectedPc, acc);
}
// If our forced letter sequence requires any double accidental, the
// spelling is awkward (e.g., D♭ Locrian ♮2 needs A♭♭, B♭♭). Drop the
// override entirely for these cases — AlphaTab's defaults will use
// simpler enharmonic spellings.
for (const acc of result.values()) {
if (acc === 'doubleSharp' || acc === 'doubleFlat') return new Map();
}
return result;
}
/** The AlphaTex `{acc ...}` keyword for each accidental kind. */
export const ALPHATEX_ACCIDENTAL: Record<AccidentalKind, string> = {
natural: 'forceNatural',
sharp: 'forceSharp',
flat: 'forceFlat',
doubleSharp: 'forceDoubleSharp',
doubleFlat: 'forceDoubleFlat',
};
/**
* True when the user's chosen root spelling is the "wrong" enharmonic for the
* mode — i.e. no representable parent major spells the mode root with the
* matching letter. The letter-correct parent of each enharmonic pair lands on
* a real key for exactly one spelling: F♯ Locrian → G major (kept), while G♭
* Locrian's letter-correct parent is A𝄫 major (no such key → redundant, the
* picker surfaces F♯ Locrian instead). Only applies to the diatonic modes;
* other categories handle their own enharmonics in {@link keySignatureLabelFor}.
*/
export function isEnharmonicallyRedundant(key: Key, scale: Scale): boolean {
if (scale.category !== 'modes') return false;
const off = MODE_PARENT[scale.name];
if (!off) return false;
const { pc, letter } = parentTonic(key, off);
return !representableMajor(keyByPcLetter(pc, letter));
}
/**
* AlphaTex `\ks` identifier for a key + scale combination, or null when no
* key signature should be emitted. Using the minor-qualified identifier
* (e.g., `C#minor`) tells AlphaTab to use minor-mode spelling rules — for
* example, the leading tone in C♯ melodic minor renders as B♯ instead of
* C♮.
*/
export function keySignatureLabelFor(key: Key, scale: Scale): string | null {
if (scale.category === 'chromatic' || scale.category === 'octatonic') {
return null;
}
const ascii = keyToAlphaTexName(key);
if (scale.category === 'minor' || isMinorTonality(scale)) {
// D♭ minor and G♭ minor need 8/9 flats (their relative majors,
// F♭ and B♭♭, are beyond AlphaTab's ±7 range). Skip these so the
// picker doesn't surface them; the user has C♯ minor and F♯ minor
// as enharmonic alternatives.
if (key.id === 'Db' || key.id === 'Gb') return null;
// A♭ minor's relative major is C♭ (7 flats). AlphaTab's `\ks
// Abminor` identifier triggers an intermittent parse error on
// first-render cold-load (`AT219 (9,5)->(9,4)`) — the identifier
// isn't reliably consumed as the argument to `\ks`. The relative
// major's name (`Cb`) parses cleanly and produces the same -7-flat
// signature; we override per-note accidentals with `{acc ...}`
// anyway, so losing the minor-mode spelling hint doesn't affect
// the rendered notes.
if (key.id === 'Ab') return 'Cb';
return `${ascii}minor`;
}
if (scale.category === 'major') {
// Skip the label for "weird" sharp keys whose major scale would need
// 8+ sharps (G♯/A♯/D♯) — AlphaTab can't represent that key signature.
if (key.majorKeySignature === 0 && key.pc !== 0) return null;
return ascii;
}
if (scale.category === 'modes') {
// Parent major chosen by LETTER (C Locrian → "Db"). Enharmonic-redundant
// combos are filtered by the picker via {@link isEnharmonicallyRedundant}
// before this runs; an unrepresentable parent here returns null.
const off = MODE_PARENT[scale.name];
if (!off) return ascii;
const { pc, letter } = parentTonic(key, off);
const parent = keyByPcLetter(pc, letter);
return representableMajor(parent) ? keyToAlphaTexName(parent) : null;
}
if (scale.category === 'modes-of-minor') {
// Parent (harmonic/melodic) minor chosen by LETTER; emit
// "<parentMinor>minor" so AlphaTab uses minor-mode spelling.
const off = MODE_OF_MINOR_PARENT[scale.name];
if (!off) return null;
const { pc, letter } = parentTonic(key, off);
const parentMinor = keyByPcLetter(pc, letter);
if (!parentMinor) return null;
// D♭/G♭ minor need 8/9 flats — the picker surfaces the sharp enharmonic
// (C♯/F♯) of the mode instead.
if (parentMinor.id === 'Db' || parentMinor.id === 'Gb') return null;
// A♭ minor → relative major C♭ (−7). `\ks Abminor` trips the AT219
// first-render parse bug, so emit the relative major's name (same −7);
// per-note accidentals carry the spelling.
if (parentMinor.id === 'Ab') return 'Cb';
return `${keyToAlphaTexName(parentMinor)}minor`;
}
// Remaining pentatonic scales (major pentatonic, hirajoshi, in sen, etc.):
// use the key's major label if it has a usable signature. Minor-tonality
// pentatonic/blues and modes-of-minor are handled by earlier branches.
if (key.majorKeySignature === 0 && key.pc !== 0) return null;
return ascii;
}