@dsebastien/music-notation 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1901,6 +1901,21 @@ function parseTuning(text) {
1901
1901
  }
1902
1902
  return midis;
1903
1903
  }
1904
+ function tuningNames(text) {
1905
+ const trimmed = text.trim();
1906
+ const named = NAMED.get(trimmed.toLowerCase().replace(/\s*\(.*\)$/, ""));
1907
+ if (named)
1908
+ return tuningNames(named);
1909
+ if (!parseTuning(trimmed))
1910
+ return null;
1911
+ const spaced = trimmed.split(/[\s,]+/).filter(Boolean);
1912
+ const names = spaced.length > 1 ? spaced : trimmed.match(/[A-G][#♯b♭]?|[a-g][#♯♭]?/g) ?? [];
1913
+ return names.map((n) => {
1914
+ const letter = n.charAt(0).toUpperCase();
1915
+ const accidental = n.slice(1).replace(/-?\d+$/, "").replace("♯", "#").replace("♭", "b");
1916
+ return letter + accidental;
1917
+ });
1918
+ }
1904
1919
 
1905
1920
  // src/keyboard/piano-chord.ts
1906
1921
  import { Note as Note4 } from "tonal";
@@ -2249,6 +2264,11 @@ function triadFingering(voicing) {
2249
2264
  ][inversion];
2250
2265
  return withBass(fingers);
2251
2266
  }
2267
+ function autoVoicingHand(voicing) {
2268
+ if (voicing.hands || voicing.style !== "rootless" && voicing.style !== "shell")
2269
+ return null;
2270
+ return voicing.pitches[0] < 60 ? "left" : "right";
2271
+ }
2252
2272
  function jazzFingering(voicing) {
2253
2273
  const both = voicing.hands === "left+right";
2254
2274
  const chord = both ? voicing.right : voicing.pitches;
@@ -5461,6 +5481,11 @@ function parseFingerList(text) {
5461
5481
  }
5462
5482
  return fingers;
5463
5483
  }
5484
+ function isBothHandsFingering(text) {
5485
+ return /^(auto)?[\s:(,-]*both(?:[\s-]*hands?)?\)?$/.test(text.trim().toLowerCase());
5486
+ }
5487
+ var AUTO_FINGERING_NEEDS_SCALE = "fingering: auto goes with a major or minor scale (scale: G major): write one finger per note, e.g. fingering: 1 2 3 4 5";
5488
+ var autoFingeringUnknown = (scale) => `fingering: auto knows the major, natural minor, harmonic minor and melodic minor scales: write the fingers for ${scale}, root to root, e.g. fingering: 1 2 3 1 2 3 4 5`;
5464
5489
  function autoFingeringHand(text) {
5465
5490
  const m = /^(auto)?[\s:(,-]*(?:(left|right)(?:[\s-]*hand)?)?\)?$/.exec(text.trim().toLowerCase());
5466
5491
  if (!m || !m[1] && !m[2])
@@ -5653,6 +5678,165 @@ function detectChordFromFrets(frets, tuning = STANDARD) {
5653
5678
  return detectChordFromPitches(pitches);
5654
5679
  }
5655
5680
 
5681
+ // src/chord/fingering-words.ts
5682
+ import { Note as Note5 } from "tonal";
5683
+ var ordinal = (n) => `${n}${n % 100 >= 11 && n % 100 <= 13 ? "th" : ["th", "st", "nd", "rd"][n % 10] ?? "th"}`;
5684
+ var GUITAR_FINGERS = {
5685
+ "1": "Index",
5686
+ "2": "Middle",
5687
+ "3": "Ring",
5688
+ "4": "Pinky",
5689
+ T: "Thumb"
5690
+ };
5691
+ var PIANO_FINGERS = {
5692
+ "1": "thumb",
5693
+ "2": "index finger",
5694
+ "3": "middle finger",
5695
+ "4": "ring finger",
5696
+ "5": "little finger"
5697
+ };
5698
+ var capitalized = (s) => s.charAt(0).toUpperCase() + s.slice(1);
5699
+ var andList = (items) => items.length < 2 ? items[0] ?? "" : `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`;
5700
+ var letter = (midi) => noteOf(midi).replace(/-?\d+$/, "");
5701
+ function stringNames(tuning, count, spelled) {
5702
+ const letters = tuning?.map((p, s) => spelled?.[s] ?? letter(p)) ?? [];
5703
+ const repeated = letters.filter((name, i) => letters.indexOf(name) !== i);
5704
+ const byName = tuning !== null && (repeated.length === 0 || repeated.length === 1 && letters[0] === letters[count - 1] && count > 2);
5705
+ return Array.from({ length: count }, (_, s) => {
5706
+ if (!byName)
5707
+ return numbered(tuning, count, s, spelled);
5708
+ const name = letters[s];
5709
+ if (repeated.length && s === 0)
5710
+ return `the low ${name} string`;
5711
+ if (repeated.length && s === count - 1)
5712
+ return `the high ${name} string`;
5713
+ return `the ${name} string`;
5714
+ });
5715
+ }
5716
+ function numbered(tuning, count, s, spelled) {
5717
+ const name = tuning ? spelled?.[s] ?? letter(tuning[s]) : null;
5718
+ return `the ${ordinal(count - s)} string${name ? ` (${name})` : ""}`;
5719
+ }
5720
+ var range = (from, to) => Array.from({ length: to - from + 1 }, (_, i) => from + i);
5721
+ var together = (names) => names.every((n) => /^the [^(]+ string$/.test(n)) ? `the ${andList(names.map((n) => n.slice(4, -7)))} strings` : andList(names);
5722
+ function guitarWords(input) {
5723
+ const { frets } = input;
5724
+ const count = frets.length;
5725
+ const tuning = input.tuning ?? (count === 6 ? STANDARD_TUNING : null);
5726
+ const spelled = input.tuningNames?.length === count ? input.tuningNames : undefined;
5727
+ const names = stringNames(tuning, count, spelled);
5728
+ const capo = input.capo ?? 0;
5729
+ const fromNut = capo > 0 && input.fretsFrom === "nut";
5730
+ const shape = frets.map((f) => f === null ? null : fromNut ? Math.max(0, f - capo) : f);
5731
+ const fingers = input.fingers?.some((f) => f) ? input.fingers : fingerVoicing(shape) ?? frets.map(() => null);
5732
+ const sentences = [];
5733
+ if (capo) {
5734
+ sentences.push(`Capo on the ${ordinal(capo)} fret${fromNut ? "" : ": frets count from the capo"}.`);
5735
+ }
5736
+ const sounding = frets.flatMap((f, s) => f !== null ? [s] : []);
5737
+ if (!sounding.length)
5738
+ return [...sentences, "Every string is muted: no note sounds."];
5739
+ const low = sounding[0];
5740
+ const high = sounding.at(-1);
5741
+ if (low === 0 && high === count - 1) {
5742
+ sentences.push(count === 6 ? "Strum all six strings." : "Strum every string.");
5743
+ } else if (high === count - 1) {
5744
+ sentences.push(`Strum from ${numbered(tuning, count, low, spelled)}.`);
5745
+ } else {
5746
+ sentences.push(`Strum from ${numbered(tuning, count, low, spelled)} to ${numbered(tuning, count, high, spelled)}.`);
5747
+ }
5748
+ const barred = new Set;
5749
+ const byFinger = new Map;
5750
+ shape.forEach((f, s) => {
5751
+ const finger = fingers[s];
5752
+ if (f !== null && f > 0 && finger)
5753
+ byFinger.set(finger, [...byFinger.get(finger) ?? [], s]);
5754
+ });
5755
+ const said = new Set;
5756
+ const fingerName = (finger) => GUITAR_FINGERS[finger] ?? `Finger ${finger}`;
5757
+ frets.forEach((fret, s) => {
5758
+ if (fret === null || shape[s] === 0)
5759
+ return;
5760
+ const finger = fingers[s];
5761
+ if (!finger) {
5762
+ sentences.push(`Press ${names[s]} at the ${ordinal(fret)} fret.`);
5763
+ return;
5764
+ }
5765
+ if (said.has(finger))
5766
+ return;
5767
+ said.add(finger);
5768
+ const strings = byFinger.get(finger).filter((t) => frets[t] === fret);
5769
+ const between = strings.length > 1 ? range(strings[0], strings.at(-1)) : [];
5770
+ const flat = between.every((t) => shape[t] === null || shape[t] >= shape[s]);
5771
+ if (strings.length > 1 && !flat) {
5772
+ sentences.push(`${fingerName(finger)} on ${together(strings.map((t) => names[t]))}, ${ordinal(fret)} fret.`);
5773
+ } else if (strings.length > 1) {
5774
+ const from = count - strings.at(-1);
5775
+ const to = count - strings[0];
5776
+ for (const t of strings)
5777
+ barred.add(t);
5778
+ sentences.push(`${fingerName(finger)} bars the ${ordinal(fret)} fret, strings ${from} to ${to}.`);
5779
+ } else {
5780
+ sentences.push(`${fingerName(finger)} on ${names[s]}, ${ordinal(fret)} fret.`);
5781
+ }
5782
+ for (const t of byFinger.get(finger)) {
5783
+ if (frets[t] !== fret) {
5784
+ sentences.push(`${fingerName(finger)} also on ${names[t]}, ${ordinal(frets[t])} fret.`);
5785
+ }
5786
+ }
5787
+ });
5788
+ const muted = frets.flatMap((f, s) => f === null && s > low && s < high ? [names[s]] : []);
5789
+ if (muted.length) {
5790
+ sentences.push(`Mute ${andList(muted)}: let a fretting finger touch ${muted.length > 1 ? "them" : "it"} lightly.`);
5791
+ }
5792
+ const open = shape.flatMap((f, s) => f === 0 && !barred.has(s) ? [names[s]] : []);
5793
+ if (open.length) {
5794
+ const where = capo ? " at the capo" : " open";
5795
+ const plural = open.length > 1;
5796
+ sentences.push(open.every((n) => /^the [^(]+ string$/.test(n)) ? `The ${andList(open.map((n) => n.slice(4, -7)))} ${plural ? "strings ring" : "string rings"}${where}.` : `${capitalized(andList(open))} ${plural ? "ring" : "rings"}${where}.`);
5797
+ }
5798
+ return sentences;
5799
+ }
5800
+ function pianoWords(input) {
5801
+ const keys = [...input.keys].sort((a, b) => a - b);
5802
+ if (!keys.length)
5803
+ return [];
5804
+ const plain = (midi) => input.names?.get(midi % 12) ?? letter(midi);
5805
+ const octaves = new Set(keys.map(plain)).size < keys.length;
5806
+ const keyName = (midi) => {
5807
+ const name = plain(midi);
5808
+ if (!octaves)
5809
+ return name;
5810
+ return `${name}${Math.floor((midi - (Note5.get(name).alt || 0)) / 12) - 1}`;
5811
+ };
5812
+ const part = (group) => {
5813
+ const withFinger = group.filter((k) => input.fingers?.has(k));
5814
+ const without = group.filter((k) => !input.fingers?.has(k)).map(keyName);
5815
+ const fingered = withFinger.map((k) => {
5816
+ const finger = input.fingers.get(k);
5817
+ return `${PIANO_FINGERS[finger] ?? `finger ${finger}`} on ${keyName(k)}`;
5818
+ });
5819
+ if (!fingered.length)
5820
+ return andList(without);
5821
+ if (!without.length)
5822
+ return fingered.join(", ");
5823
+ return `${fingered.join(", ")}, and also play ${andList(without)}`;
5824
+ };
5825
+ const hands = input.hands;
5826
+ if (!hands?.size) {
5827
+ return [
5828
+ keys.some((k) => input.fingers?.has(k)) ? `${capitalized(part(keys))}.` : `Play ${part(keys)}.`
5829
+ ];
5830
+ }
5831
+ return ["left", "right"].flatMap((hand) => {
5832
+ const group = keys.filter((k) => (hands.get(k) ?? "right") === hand);
5833
+ return group.length ? [`${capitalized(hand)} hand: ${part(group)}.`] : [];
5834
+ });
5835
+ }
5836
+ function fingeringInWords(chord) {
5837
+ return "frets" in chord ? guitarWords(chord) : pianoWords(chord);
5838
+ }
5839
+
5656
5840
  // src/blocks/block-source.ts
5657
5841
  var FIELD2 = /^([A-Za-z][\w-]*)\s*:\s*(.*)$/;
5658
5842
  function parseBlockSource(source) {
@@ -6060,7 +6244,7 @@ var FINGER_NAMES = {
6060
6244
  "4": "pinky",
6061
6245
  T: "thumb"
6062
6246
  };
6063
- var ordinal = (n) => `${n}${n % 100 >= 11 && n % 100 <= 13 ? "th" : ["th", "st", "nd", "rd"][n % 10] ?? "th"}`;
6247
+ var ordinal2 = (n) => `${n}${n % 100 >= 11 && n % 100 <= 13 ? "th" : ["th", "st", "nd", "rd"][n % 10] ?? "th"}`;
6064
6248
  var MAX_SLIDE = 3;
6065
6249
  function stringName(tuning, s) {
6066
6250
  const name = noteOf(tuning[s]).replace(/-?\d+$/, "");
@@ -6068,7 +6252,7 @@ function stringName(tuning, s) {
6068
6252
  if (same < 2)
6069
6253
  return `the ${name} string`;
6070
6254
  if (same > 2)
6071
- return `the ${ordinal(tuning.length - s)} string (${name})`;
6255
+ return `the ${ordinal2(tuning.length - s)} string (${name})`;
6072
6256
  const lowest = tuning.findIndex((p) => noteOf(p).replace(/-?\d+$/, "") === name);
6073
6257
  return `the ${s === lowest ? "low" : "high"} ${name} string`;
6074
6258
  }
@@ -6109,7 +6293,7 @@ function move(from, fromFingers, to, tuning) {
6109
6293
  if (seen.has(f))
6110
6294
  continue;
6111
6295
  seen.add(f);
6112
- tips.push(`Keep your ${fingerName(f)} on ${stringName(tuning, s)}'s ${ordinal(to.frets[s])} fret.`);
6296
+ tips.push(`Keep your ${fingerName(f)} on ${stringName(tuning, s)}'s ${ordinal2(to.frets[s])} fret.`);
6113
6297
  }
6114
6298
  for (const s of guides) {
6115
6299
  const f = to.fingers[s];
@@ -6441,7 +6625,7 @@ function voiceLeadVoicings(symbols, options) {
6441
6625
  }
6442
6626
 
6443
6627
  // src/theory/numerals.ts
6444
- import { Note as Note5 } from "tonal";
6628
+ import { Note as Note6 } from "tonal";
6445
6629
  var MAJOR2 = ["1P", "2M", "3M", "4P", "5P", "6M", "7M"];
6446
6630
  var NATURAL_MINOR = ["1P", "2M", "3m", "4P", "5P", "6m", "7m"];
6447
6631
  var ROMAN_NUMBERS = { i: 1, ii: 2, iii: 3, iv: 4, v: 5, vi: 6, vii: 7 };
@@ -6449,13 +6633,16 @@ var keyOf = (key) => typeof key === "string" ? readKey(key) : key;
6449
6633
  function noteOn(key, degree, accidental, diminished) {
6450
6634
  const minor = key.mode === "minor" || key.mode === "aeolian";
6451
6635
  let interval = MAJOR2[degree - 1];
6452
- let shift = accidental === "#" ? 1 : accidental === "b" ? -1 : 0;
6636
+ const steps = { "##": 2, "#": 1, b: -1, bb: -2 };
6637
+ let shift = steps[accidental] ?? 0;
6453
6638
  if (minor && [3, 6, 7].includes(degree)) {
6454
6639
  interval = NATURAL_MINOR[degree - 1];
6455
- shift = accidental === "#" || !accidental && degree === 7 && diminished ? 1 : 0;
6640
+ shift = accidental === "bb" ? -1 : accidental === "#" || !accidental && degree === 7 && diminished ? 1 : accidental === "##" ? 2 : 0;
6456
6641
  }
6457
- const note = Note5.transpose(key.tonic, interval);
6458
- return shift === 0 ? note : Note5.transpose(note, shift > 0 ? "1A" : "-1A");
6642
+ let note = Note6.transpose(key.tonic, interval);
6643
+ for (let i = 0;i < Math.abs(shift); i++)
6644
+ note = Note6.transpose(note, shift > 0 ? "1A" : "-1A");
6645
+ return note;
6459
6646
  }
6460
6647
  function suffixOf(mark, lower) {
6461
6648
  let s = mark.replace(/♭/g, "b").replace(/♯/g, "#");
@@ -6486,14 +6673,14 @@ function chordFrom(root, suffix) {
6486
6673
  return parseChord(symbol) && chordNoteSet(symbol) ? symbol : null;
6487
6674
  }
6488
6675
  function bassOf(key, text) {
6489
- const m = /^([b#♭♯]?)([1-7])$/.exec(text);
6676
+ const m = /^(bb|##|[b#♭♯]?)([1-7])$/.exec(text);
6490
6677
  if (!m)
6491
6678
  return null;
6492
6679
  const accidental = m[1].replace("♭", "b").replace("♯", "#");
6493
6680
  return noteOn(key, Number(m[2]), accidental, false);
6494
6681
  }
6495
- var ROMAN2 = /^([b#♭♯]?)(VII|VI|V|IV|III|II|I|vii|vi|v|iv|iii|ii|i)(.*)$/;
6496
- var NASHVILLE = /^([b#♭♯]?)([1-7])(.*)$/;
6682
+ var ROMAN2 = /^(bb|##|[b#♭♯]?)(VII|VI|V|IV|III|II|I|vii|vi|v|iv|iii|ii|i)(.*)$/;
6683
+ var NASHVILLE = /^(bb|##|[b#♭♯]?)([1-7])(.*)$/;
6497
6684
  function readOne(key, text) {
6498
6685
  const roman = ROMAN2.exec(text);
6499
6686
  const nashville = roman ? null : NASHVILLE.exec(text);
@@ -6571,7 +6758,7 @@ function keySpelling(note, key) {
6571
6758
  const chroma = chromaOf(note);
6572
6759
  const notes = keyNotes(key);
6573
6760
  if (isMinorMode(key.mode) && notes.length === 7)
6574
- notes.push(Note5.transpose(notes[6], "1A"));
6761
+ notes.push(Note6.transpose(notes[6], "1A"));
6575
6762
  if (notes.includes(note))
6576
6763
  return note;
6577
6764
  return notes.find((n) => chromaOf(n) === chroma) ?? note;
@@ -6623,13 +6810,13 @@ function secondaryTarget(symbol, key) {
6623
6810
  if (has("3m") && has("5d")) {
6624
6811
  if (has("7M"))
6625
6812
  return null;
6626
- target = Note5.transpose(parts.root, "2m");
6813
+ target = Note6.transpose(parts.root, "2m");
6627
6814
  } else {
6628
6815
  if (!has("3M"))
6629
6816
  return null;
6630
6817
  if (set.members.some((m) => ["5d", "5A", "7M"].includes(m.interval ?? "")))
6631
6818
  return null;
6632
- target = Note5.transpose(parts.root, "-5P");
6819
+ target = Note6.transpose(parts.root, "-5P");
6633
6820
  }
6634
6821
  if (chromaOf(target) === chromaOf(key.tonic))
6635
6822
  return null;
@@ -6844,7 +7031,115 @@ function progressionChord(written, key, options = {}) {
6844
7031
  };
6845
7032
  }
6846
7033
 
7034
+ // src/theory/harmonize.ts
7035
+ import { Interval as Interval6, Key as Key2, Note as Note7, Scale as Scale6 } from "tonal";
7036
+ var HARMONIZE_KINDS = ["triads", "sevenths", "sus", "power"];
7037
+ var MAJOR_FUNCTIONS2 = [
7038
+ "tonic",
7039
+ "subdominant",
7040
+ "tonic",
7041
+ "subdominant",
7042
+ "dominant",
7043
+ "tonic",
7044
+ "dominant"
7045
+ ];
7046
+ var MINOR_FUNCTIONS2 = [
7047
+ "tonic",
7048
+ "subdominant",
7049
+ "tonic",
7050
+ "subdominant",
7051
+ "dominant",
7052
+ "subdominant",
7053
+ "dominant"
7054
+ ];
7055
+ var DIATONIC = ["tonic", "subdominant", "dominant"];
7056
+ var unknown = (text) => `Unknown scale "${text.trim()}": use e.g. key: G major, key: A harmonic minor or key: D dorian`;
7057
+ function readHarmonyScale(text) {
7058
+ const name = scaleName(text);
7059
+ const asKey = readKey(name);
7060
+ if (asKey) {
7061
+ const mode = asKey.mode === "ionian" ? "major" : asKey.mode === "aeolian" ? "minor" : asKey.mode;
7062
+ const key = { tonic: asKey.tonic, mode, name: `${asKey.tonic} ${mode}` };
7063
+ const problem = keyProblem(key);
7064
+ if (problem)
7065
+ return { error: problem };
7066
+ return { name: key.name, notes: Scale6.get(key.name).notes, key };
7067
+ }
7068
+ const scale = Scale6.get(name);
7069
+ if (scale.empty || !scale.tonic)
7070
+ return { error: unknown(text) };
7071
+ if (scale.notes.length !== 7) {
7072
+ return {
7073
+ error: `harmonize needs a scale of 7 notes: ${scale.name} has ${scale.notes.length}`
7074
+ };
7075
+ }
7076
+ const tonic = scale.tonic;
7077
+ const notes = scaleSpelling(scale).notes;
7078
+ const minor = Interval6.distance(tonic, notes[2]) === "3m";
7079
+ const key = {
7080
+ tonic,
7081
+ mode: minor ? "minor" : "major",
7082
+ name: `${tonic} ${minor ? "minor" : "major"}`
7083
+ };
7084
+ const count = minor ? Key2.minorKey(tonic).alteration : Key2.majorKey(tonic).alteration;
7085
+ if (Math.abs(count) > MAX_SIGNATURE) {
7086
+ return {
7087
+ error: `${scale.name} needs ${Math.abs(count)} ${count > 0 ? "sharps" : "flats"}: write ${Note7.enharmonic(tonic)} ${scale.type}`
7088
+ };
7089
+ }
7090
+ return { name: scale.name, notes, key };
7091
+ }
7092
+ function chordOn(notes, i, kind) {
7093
+ const root = notes[i];
7094
+ const above = (step) => Interval6.distance(root, notes[(i + step) % 7]);
7095
+ if (kind === "triads" || kind === "sevenths") {
7096
+ const symbol = stackedChord(notes, i, kind === "sevenths");
7097
+ return symbol ? { symbol } : { reason: "not a named chord" };
7098
+ }
7099
+ if (above(4) !== "5P")
7100
+ return { reason: "no perfect fifth" };
7101
+ if (kind === "power")
7102
+ return { symbol: `${root}5` };
7103
+ if (above(3) === "4P")
7104
+ return { symbol: `${root}sus4` };
7105
+ if (above(1) === "2M")
7106
+ return { symbol: `${root}sus2` };
7107
+ return { reason: "no perfect fourth or major second" };
7108
+ }
7109
+ function harmonize(scale, options = {}) {
7110
+ const kind = options.kind ?? "triads";
7111
+ if (!HARMONIZE_KINDS.includes(kind))
7112
+ return null;
7113
+ const read = readHarmonyScale(scale);
7114
+ if ("error" in read)
7115
+ return null;
7116
+ const { notes, key } = read;
7117
+ const byDegree = isMinorMode(key.mode) ? MINOR_FUNCTIONS2 : MAJOR_FUNCTIONS2;
7118
+ const chords = [];
7119
+ const skipped = [];
7120
+ notes.forEach((note, i) => {
7121
+ const made = chordOn(notes, i, kind);
7122
+ if ("reason" in made) {
7123
+ skipped.push({ degree: i + 1, note, reason: made.reason });
7124
+ return;
7125
+ }
7126
+ const { symbol } = made;
7127
+ const fn = harmonicFunction(symbol, key);
7128
+ const shown = (text) => text.replace(/Mb5$/, "(b5)").replace(/Mb⁵$/, "(b⁵)");
7129
+ chords.push({
7130
+ degree: i + 1,
7131
+ note,
7132
+ symbol: shown(symbol),
7133
+ numeral: shown(numeralOf(symbol, key, "roman", { byDegree: true }) ?? symbol),
7134
+ nashville: shown(numeralOf(symbol, key, "nashville", { byDegree: true }) ?? symbol),
7135
+ function: fn && DIATONIC.includes(fn) ? fn : byDegree[i]
7136
+ });
7137
+ });
7138
+ return { ...read, kind, chords, skipped };
7139
+ }
7140
+
6847
7141
  // src/blocks/progression.ts
7142
+ import { Note as Note8 } from "tonal";
6848
7143
  var MAX_CHORDS = 32;
6849
7144
  var MAX_SHARED_OCTAVES = 3;
6850
7145
  var SHARED = [
@@ -6866,8 +7161,22 @@ var SHARED = [
6866
7161
  "time",
6867
7162
  "tempo",
6868
7163
  "bpm",
6869
- "strum"
7164
+ "strum",
7165
+ "harmonize"
6870
7166
  ];
7167
+ var KIND_WORDS = {
7168
+ triad: "triads",
7169
+ triads: "triads",
7170
+ seventh: "sevenths",
7171
+ sevenths: "sevenths",
7172
+ "7th": "sevenths",
7173
+ "7ths": "sevenths",
7174
+ "7": "sevenths",
7175
+ sus: "sus",
7176
+ power: "power",
7177
+ "5": "power"
7178
+ };
7179
+ var HARMONIZED_CHORDS = 7;
6871
7180
  var yes = (text, key, fallback) => {
6872
7181
  if (text === undefined || text === "")
6873
7182
  return fallback;
@@ -6925,7 +7234,69 @@ function sourceOf(part) {
6925
7234
  return { head: lines.length ? lines.join(" ") : null, fields };
6926
7235
  }
6927
7236
  var chordsText = (block) => block.head ?? field(block, "progression") ?? field(block, "chords");
7237
+ function harmonizedSectionOf(block, kindText) {
7238
+ const kind = KIND_WORDS[kindText.toLowerCase()];
7239
+ if (!kind || !HARMONIZE_KINDS.includes(kind)) {
7240
+ throw new Error(`harmonize: write triads, sevenths, sus or power, got "${kindText}"`);
7241
+ }
7242
+ const written = chordsText(block);
7243
+ if (written) {
7244
+ throw new Error(`harmonize draws the chords of the scale: leave out the chords (${written})`);
7245
+ }
7246
+ const keyText = field(block, "key");
7247
+ if (!keyText)
7248
+ throw new Error("Add the scale: e.g. key: A harmonic minor");
7249
+ const shift = Number(field(block, "transpose") ?? 0);
7250
+ if (!Number.isInteger(shift)) {
7251
+ throw new Error(`transpose must be a whole number of semitones, e.g. transpose: -2`);
7252
+ }
7253
+ let scale = readHarmonyScale(keyText);
7254
+ if ("error" in scale)
7255
+ throw new Error(scale.error);
7256
+ if (shift) {
7257
+ const { tonic, mode } = scale.key;
7258
+ const moved = transposeKey(`${tonic}${isMinorMode(mode) ? "m" : ""}`, shift).replace(/m$/, "");
7259
+ const type = scale.name.slice(tonic.length).trim();
7260
+ const spellings = [...new Set([moved, Note8.enharmonic(moved)])].map((t) => readHarmonyScale(`${t} ${type}`));
7261
+ const valid = spellings.filter((sp) => !("error" in sp));
7262
+ const accidentals = (sp) => sp.notes.join("").replace(/[^#b]/g, "").length;
7263
+ const best = valid.sort((a, b) => accidentals(a) - accidentals(b))[0];
7264
+ if (!best)
7265
+ throw new Error(spellings[0].error);
7266
+ scale = best;
7267
+ }
7268
+ const harmonized = harmonize(scale.name, { kind });
7269
+ const chords = harmonized.chords.map((c) => ({
7270
+ written: c.numeral,
7271
+ symbol: c.symbol,
7272
+ numeral: c.numeral,
7273
+ nashville: c.nashville,
7274
+ function: c.function
7275
+ }));
7276
+ const left = harmonized.skipped.map((s) => `degree ${s.degree} (${s.note}), ${s.reason}`);
7277
+ return {
7278
+ key: harmonized.key,
7279
+ others: [],
7280
+ chords,
7281
+ blues: false,
7282
+ block,
7283
+ name: harmonized.name,
7284
+ ...left.length ? { note: `Left out: ${left.join("; ")}` } : {}
7285
+ };
7286
+ }
7287
+ function harmonizeText(block) {
7288
+ if (!block.fields.has("harmonize"))
7289
+ return;
7290
+ const text = field(block, "harmonize");
7291
+ if (text === undefined) {
7292
+ throw new Error("harmonize: write triads, sevenths, sus or power, got nothing");
7293
+ }
7294
+ return text.toLowerCase() === "none" ? undefined : text;
7295
+ }
6928
7296
  function sectionOf(block) {
7297
+ const kindText = harmonizeText(block);
7298
+ if (kindText)
7299
+ return harmonizedSectionOf(block, kindText);
6929
7300
  const text = chordsText(block);
6930
7301
  if (!text) {
6931
7302
  throw new Error("Add the chords: e.g. I V vi IV with key: G, 1 5 6m 4, or G D Em C");
@@ -7068,7 +7439,9 @@ function renderSection(doc, section, options, renderChord) {
7068
7439
  const el = html(doc, "div", "mn-progression-section");
7069
7440
  const others = section.others.length ? ` (or ${section.others.join(", ")})` : "";
7070
7441
  const blues = section.blues ? " (blues)" : "";
7071
- el.appendChild(html(doc, "div", "mn-progression-key", `Key: ${section.key.name}${blues}${others}`));
7442
+ el.appendChild(html(doc, "div", "mn-progression-key", `Key: ${section.name ?? section.key.name}${blues}${others}`));
7443
+ if (section.note)
7444
+ el.appendChild(html(doc, "div", "mn-progression-note", section.note));
7072
7445
  const instrument = (field(block, "instrument") ?? options.instrument ?? "guitar").toLowerCase();
7073
7446
  if (!["guitar", "piano", "keyboard"].includes(instrument)) {
7074
7447
  throw new Error(`Unknown instrument "${instrument}": use guitar or piano`);
@@ -7188,13 +7561,14 @@ function renderProgression(doc, source, options, renderChord) {
7188
7561
  const parts = splitParts(source) ?? [source];
7189
7562
  const blocks = parts.map(sourceOf);
7190
7563
  const first = blocks[0];
7191
- const sharedOnly = blocks.length > 1 && first !== undefined && first.head === null && !first.fields.has("progression") && !first.fields.has("chords") && [...first.fields.keys()].every((k) => SHARED.includes(k));
7564
+ const harmonizedFirst = first !== undefined && first.fields.has("harmonize") && field(first, "key") !== undefined;
7565
+ const sharedOnly = blocks.length > 1 && first !== undefined && first.head === null && !harmonizedFirst && !first.fields.has("progression") && !first.fields.has("chords") && [...first.fields.keys()].every((k) => SHARED.includes(k));
7192
7566
  const shared = sharedOnly ? first.fields : new Map;
7193
7567
  const own = sharedOnly ? blocks.slice(1) : blocks;
7194
7568
  if (!own.length)
7195
7569
  throw new Error('Add the chords after the shared settings, after a "---" line');
7196
7570
  const merged = own.map((b) => ({ head: b.head, fields: new Map([...shared, ...b.fields]) }));
7197
- const count = merged.reduce((n, b) => n + progressionTokens(chordsText(b) ?? "").length, 0);
7571
+ const count = merged.reduce((n, b) => n + (harmonizeText(b) ? HARMONIZED_CHORDS : progressionTokens(chordsText(b) ?? "").length), 0);
7198
7572
  if (count > MAX_CHORDS)
7199
7573
  throw new Error(`At most ${MAX_CHORDS} chords per block, found ${count}`);
7200
7574
  const sections = merged.map(sectionOf);
@@ -7218,7 +7592,7 @@ function renderProgression(doc, source, options, renderChord) {
7218
7592
  }
7219
7593
 
7220
7594
  // src/circle/circle.ts
7221
- import { Key as Key2 } from "tonal";
7595
+ import { Key as Key3 } from "tonal";
7222
7596
  var MAJORS = ["C", "G", "D", "A", "E", "B", "F#/Gb", "Db", "Ab", "Eb", "Bb", "F"];
7223
7597
  var MINORS = ["Am", "Em", "Bm", "F#m", "C#m", "G#m", "D#m/Ebm", "Bbm", "Fm", "Cm", "Gm", "Dm"];
7224
7598
  var DIMINISHED = ["B°", "F#°", "C#°", "G#°", "D#°", "A#°", "E#°", "C°", "G°", "D°", "A°", "E°"];
@@ -7375,7 +7749,7 @@ function renderCircle(doc, options = {}) {
7375
7749
  }
7376
7750
  for (let position = 0;position < 12; position++) {
7377
7751
  const chord = at("major", position);
7378
- const count = chord ? Key2.majorKey(splitChordSymbol(chord.symbol).root).alteration : 0;
7752
+ const count = chord ? Key3.majorKey(splitChordSymbol(chord.symbol).root).alteration : 0;
7379
7753
  const own = chord !== undefined && Math.abs(count) <= MAX_SIGNATURE;
7380
7754
  const text = own ? signatureText(count).replace("no ♯ or ♭", "0") : SIGNATURES[position];
7381
7755
  const [x, y] = point((R.sig + R.major) / 2, position * 30, top);
@@ -8286,7 +8660,8 @@ var SHARED_KEYS = {
8286
8660
  "inversion",
8287
8661
  "octave",
8288
8662
  "hands",
8289
- "fingering"
8663
+ "fingering",
8664
+ "caption"
8290
8665
  ],
8291
8666
  keyboard: ["orientation", "hand", "labels", "range", "highlight", "compare"],
8292
8667
  fretboard: [
@@ -8382,6 +8757,7 @@ var renderChord = (doc, block, options) => {
8382
8757
  const voicingOptions = pianoOptionsOf((key) => field2(block, key));
8383
8758
  const fingering = field2(block, "fingering", "fingers");
8384
8759
  let auto = null;
8760
+ let captionHands;
8385
8761
  let hands;
8386
8762
  let set;
8387
8763
  if (pitchesText) {
@@ -8439,6 +8815,9 @@ var renderChord = (doc, block, options) => {
8439
8815
  }
8440
8816
  if (fingering?.trim().toLowerCase() === "auto") {
8441
8817
  auto = triadFingering(voiced);
8818
+ if (autoVoicingHand(voiced) === "left") {
8819
+ captionHands = new Map(voiced.pitches.map((p) => [p, "left"]));
8820
+ }
8442
8821
  if (!auto) {
8443
8822
  throw new Error("fingering: auto covers triads and four-note chords (sevenths, sixths) in close position, and rootless and shell voicings one hand can reach: write the fingers, e.g. fingering: 1 2 3 4 5");
8444
8823
  }
@@ -8449,7 +8828,8 @@ var renderChord = (doc, block, options) => {
8449
8828
  const fingers = auto ?? (fingering ? fingersFor(set.pitches, fingering) : new Map);
8450
8829
  const range = field2(block, "range");
8451
8830
  handOf(block, options);
8452
- return named(renderKeyboard(doc, set, {
8831
+ const caption = captionOf(block);
8832
+ const keyboard = named(renderKeyboard(doc, set, {
8453
8833
  playAs: "chord",
8454
8834
  title,
8455
8835
  label: labelField(block, fingers.size ? "fingers" : "notes", fingers.size > 0),
@@ -8458,6 +8838,15 @@ var renderChord = (doc, block, options) => {
8458
8838
  range: keyRange(range ? rangeOf(range) : keyRangeOf(set)),
8459
8839
  orientation: orientationOf(block, options.orientation?.keyboard)
8460
8840
  }), symbol);
8841
+ if (!caption)
8842
+ return keyboard;
8843
+ const names = new Map(set.members.map((m) => [m.chroma, m.name]));
8844
+ return captioned(doc, keyboard, fingeringInWords({
8845
+ keys: set.pitches,
8846
+ fingers,
8847
+ ...hands ? { hands } : captionHands ? { hands: captionHands } : {},
8848
+ names
8849
+ }));
8461
8850
  }
8462
8851
  if (instrument && instrument !== "guitar" && !field2(block, "tuning")) {
8463
8852
  throw new Error(`Unknown instrument "${instrument}": use guitar or piano, or give a tuning`);
@@ -8541,8 +8930,30 @@ var renderChord = (doc, block, options) => {
8541
8930
  }), symbol);
8542
8931
  if (capo && sounding && sounding !== symbol)
8543
8932
  diagram.setAttribute("data-mn-sounds", sounding);
8544
- return diagram;
8933
+ if (!captionOf(block))
8934
+ return diagram;
8935
+ return captioned(doc, diagram, fingeringInWords({
8936
+ frets: voicing.frets,
8937
+ fingers: voicing.fingers,
8938
+ ...strings ? { tuning: strings } : {},
8939
+ ...tuningText && tuning ? { tuningNames: tuningNames(tuningText) ?? [] } : {},
8940
+ ...capo ? { capo, fretsFrom: fromNut ? "nut" : "capo" } : {}
8941
+ }));
8545
8942
  };
8943
+ function captionOf(block) {
8944
+ const written = field2(block, "caption")?.trim();
8945
+ const text = written?.toLowerCase();
8946
+ if (!text || ["none", "no", "off", "false"].includes(text))
8947
+ return null;
8948
+ if (text === "fingering")
8949
+ return "fingering";
8950
+ throw new Error(`caption: use fingering (the fingering in words) or none, got "${written}"`);
8951
+ }
8952
+ function captioned(doc, diagram, sentences) {
8953
+ const figure = html(doc, "figure", "mn-captioned");
8954
+ figure.append(diagram, html(doc, "figcaption", "mn-fingering", sentences.join(" ")));
8955
+ return figure;
8956
+ }
8546
8957
  function soundsField(text, shape, capo) {
8547
8958
  const value = text?.trim();
8548
8959
  if (!value || /^(no|false|off)$/i.test(value))
@@ -8612,8 +9023,11 @@ var renderKeyboardBlock = (doc, block, options) => {
8612
9023
  let fingers;
8613
9024
  let title = field2(block, "title");
8614
9025
  const autoHand = fingering ? autoFingeringHand(fingering) : null;
9026
+ if (fingering && isBothHandsFingering(fingering)) {
9027
+ throw new Error("fingering: auto both draws two keyboards: put it in a block of its own, not in a --- row");
9028
+ }
8615
9029
  if (autoHand && (set.root === null || set.list || set.pitches || !set.scaleType)) {
8616
- throw new Error("fingering: auto goes with a major or minor scale (scale: G major): write one finger per note, e.g. fingering: 1 2 3 4 5");
9030
+ throw new Error(AUTO_FINGERING_NEEDS_SCALE);
8617
9031
  }
8618
9032
  if (fingering && set.scaleType && set.root !== null && !set.list && !set.pitches) {
8619
9033
  const chromas = set.members.map((m) => m.chroma);
@@ -8621,7 +9035,7 @@ var renderKeyboardBlock = (doc, block, options) => {
8621
9035
  if (autoHand) {
8622
9036
  const standard = standardScaleFingering(set.root, set.scaleType, autoHand);
8623
9037
  if (!standard) {
8624
- throw new Error(`fingering: auto knows the major, natural minor, harmonic minor and melodic minor scales: write the fingers for ${set.title}, root to root, e.g. fingering: 1 2 3 1 2 3 4 5`);
9038
+ throw new Error(autoFingeringUnknown(set.title));
8625
9039
  }
8626
9040
  octave = standard;
8627
9041
  title ??= `${set.title}, ${autoHand} hand`;
@@ -9691,6 +10105,8 @@ function barFor(doc, win, diagram, data, options) {
9691
10105
  }
9692
10106
  let other;
9693
10107
  const redraws = diagram.getAttribute("data-mn-redraw") !== "no";
10108
+ const figure = wrap.parentElement;
10109
+ const caption = figure?.classList.contains("mn-captioned") ? [...figure.children].find((c) => c.classList.contains("mn-fingering")) : undefined;
9694
10110
  const drawFor = () => {
9695
10111
  if (!redraws)
9696
10112
  return;
@@ -9701,6 +10117,8 @@ function barFor(doc, win, diagram, data, options) {
9701
10117
  wrap.replaceChild(next, shown);
9702
10118
  shown = next;
9703
10119
  }
10120
+ if (caption)
10121
+ caption.hidden = shown !== diagram;
9704
10122
  };
9705
10123
  sound.addEventListener("change", () => {
9706
10124
  stop();
@@ -9931,7 +10349,7 @@ function blockFromProperties(language, properties, options = {}) {
9931
10349
  }
9932
10350
 
9933
10351
  // src/chord/triads.ts
9934
- import { Key as Key3 } from "tonal";
10352
+ import { Key as Key4 } from "tonal";
9935
10353
  var inversionName = (inversion) => inversion === 0 ? "root position" : inversion === 1 ? "1st inversion" : "2nd inversion";
9936
10354
  function triadVoicings(symbol, options) {
9937
10355
  const tuning = options.tuning ?? STANDARD_TUNING;
@@ -9984,7 +10402,7 @@ function keyTriads(key, options) {
9984
10402
  const parsed = parseKey(key);
9985
10403
  if (!parsed)
9986
10404
  return null;
9987
- const scale = parsed.minor ? Key3.minorKey(parsed.tonic).natural : Key3.majorKey(parsed.tonic);
10405
+ const scale = parsed.minor ? Key4.minorKey(parsed.tonic).natural : Key4.majorKey(parsed.tonic);
9988
10406
  if (!scale.triads.length)
9989
10407
  return null;
9990
10408
  const inversion = options.inversion ?? 0;
@@ -10042,7 +10460,7 @@ function renderBlock(language, source, host, given = {}) {
10042
10460
  try {
10043
10461
  if ((language === "fretboard" || language === "keyboard") && !splitParts(text))
10044
10462
  text = resolveScalesFor(text);
10045
- parts = isDiagramLanguage(language) ? splitParts(text) ?? modeParts(language, text) ?? positionParts(language, text) ?? transitionParts(language, text, options.voicings) ?? triadParts(language, text) ?? voicingParts(language, text) : null;
10463
+ parts = isDiagramLanguage(language) ? splitParts(text) ?? modeParts(language, text) ?? positionParts(language, text) ?? handParts(language, text) ?? transitionParts(language, text, options.voicings) ?? triadParts(language, text) ?? voicingParts(language, text) : null;
10046
10464
  } catch (e) {
10047
10465
  return failed(el, host, language, messageOf(e));
10048
10466
  }
@@ -10217,6 +10635,39 @@ function positionParts(language, source) {
10217
10635
  return [...header.length ? [header.join(`
10218
10636
  `)] : [], ...diagrams];
10219
10637
  }
10638
+ function handParts(language, source) {
10639
+ if (language !== "keyboard")
10640
+ return null;
10641
+ let block;
10642
+ try {
10643
+ block = parseBlockSource(source);
10644
+ } catch {
10645
+ return null;
10646
+ }
10647
+ const fingering = block.fields.get("fingering");
10648
+ if (fingering === undefined || !isBothHandsFingering(fingering))
10649
+ return null;
10650
+ block = scalesForBlock(block);
10651
+ const set = noteSetOf(block);
10652
+ if (set.root === null || set.list || set.pitches || !set.scaleType) {
10653
+ throw new Error(AUTO_FINGERING_NEEDS_SCALE);
10654
+ }
10655
+ if (!standardScaleFingering(set.root, set.scaleType, "right")) {
10656
+ throw new Error(autoFingeringUnknown(set.title));
10657
+ }
10658
+ const title = block.fields.get("title")?.trim();
10659
+ const others = [...block.fields].filter(([key]) => !["fingering", "title", "columns"].includes(key)).map(([key, value]) => `${key}: ${value}`);
10660
+ const head = block.head ? [block.head] : [];
10661
+ const hand = (side) => [
10662
+ ...head,
10663
+ ...others,
10664
+ `fingering: auto ${side}`,
10665
+ ...title ? [`title: ${title}, ${side} hand`] : []
10666
+ ].join(`
10667
+ `);
10668
+ const columns = block.fields.get("columns")?.trim() || "1";
10669
+ return [`columns: ${columns}`, hand("right"), hand("left")];
10670
+ }
10220
10671
  function capoIn(block) {
10221
10672
  const text = block.fields.get("capo");
10222
10673
  if (!text?.trim())
@@ -10859,5 +11310,5 @@ export {
10859
11310
  renderAll
10860
11311
  };
10861
11312
 
10862
- //# debugId=FDD304C0A12A289A64756E2164756E21
11313
+ //# debugId=A62ED8A359C490EB64756E2164756E21
10863
11314
  //# sourceMappingURL=index.js.map