@dsebastien/music-notation 0.12.0 → 0.14.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.
@@ -44,6 +44,7 @@ function html(doc, tag, cls, text) {
44
44
  }
45
45
  var NAME_PREFIX = `mn-name-${Math.random().toString(36).slice(2, 8)}-`;
46
46
  var names = 0;
47
+ var uniqueId = () => `${NAME_PREFIX}${++names}`;
47
48
  function svgRoot(doc, width, height, cls, label) {
48
49
  const id = `${NAME_PREFIX}${++names}`;
49
50
  const title = svg(doc, "title", { class: "mn-name", id });
@@ -1901,6 +1902,21 @@ function parseTuning(text) {
1901
1902
  }
1902
1903
  return midis;
1903
1904
  }
1905
+ function tuningNames(text) {
1906
+ const trimmed = text.trim();
1907
+ const named = NAMED.get(trimmed.toLowerCase().replace(/\s*\(.*\)$/, ""));
1908
+ if (named)
1909
+ return tuningNames(named);
1910
+ if (!parseTuning(trimmed))
1911
+ return null;
1912
+ const spaced = trimmed.split(/[\s,]+/).filter(Boolean);
1913
+ const names = spaced.length > 1 ? spaced : trimmed.match(/[A-G][#♯b♭]?|[a-g][#♯♭]?/g) ?? [];
1914
+ return names.map((n) => {
1915
+ const letter = n.charAt(0).toUpperCase();
1916
+ const accidental = n.slice(1).replace(/-?\d+$/, "").replace("♯", "#").replace("♭", "b");
1917
+ return letter + accidental;
1918
+ });
1919
+ }
1904
1920
 
1905
1921
  // src/keyboard/piano-chord.ts
1906
1922
  import { Note as Note4 } from "tonal";
@@ -2249,6 +2265,11 @@ function triadFingering(voicing) {
2249
2265
  ][inversion];
2250
2266
  return withBass(fingers);
2251
2267
  }
2268
+ function autoVoicingHand(voicing) {
2269
+ if (voicing.hands || voicing.style !== "rootless" && voicing.style !== "shell")
2270
+ return null;
2271
+ return voicing.pitches[0] < 60 ? "left" : "right";
2272
+ }
2252
2273
  function jazzFingering(voicing) {
2253
2274
  const both = voicing.hands === "left+right";
2254
2275
  const chord = both ? voicing.right : voicing.pitches;
@@ -5461,6 +5482,11 @@ function parseFingerList(text) {
5461
5482
  }
5462
5483
  return fingers;
5463
5484
  }
5485
+ function isBothHandsFingering(text) {
5486
+ return /^(auto)?[\s:(,-]*both(?:[\s-]*hands?)?\)?$/.test(text.trim().toLowerCase());
5487
+ }
5488
+ 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";
5489
+ 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
5490
  function autoFingeringHand(text) {
5465
5491
  const m = /^(auto)?[\s:(,-]*(?:(left|right)(?:[\s-]*hand)?)?\)?$/.exec(text.trim().toLowerCase());
5466
5492
  if (!m || !m[1] && !m[2])
@@ -5653,6 +5679,165 @@ function detectChordFromFrets(frets, tuning = STANDARD) {
5653
5679
  return detectChordFromPitches(pitches);
5654
5680
  }
5655
5681
 
5682
+ // src/chord/fingering-words.ts
5683
+ import { Note as Note5 } from "tonal";
5684
+ var ordinal = (n) => `${n}${n % 100 >= 11 && n % 100 <= 13 ? "th" : ["th", "st", "nd", "rd"][n % 10] ?? "th"}`;
5685
+ var GUITAR_FINGERS = {
5686
+ "1": "Index",
5687
+ "2": "Middle",
5688
+ "3": "Ring",
5689
+ "4": "Pinky",
5690
+ T: "Thumb"
5691
+ };
5692
+ var PIANO_FINGERS = {
5693
+ "1": "thumb",
5694
+ "2": "index finger",
5695
+ "3": "middle finger",
5696
+ "4": "ring finger",
5697
+ "5": "little finger"
5698
+ };
5699
+ var capitalized = (s) => s.charAt(0).toUpperCase() + s.slice(1);
5700
+ var andList = (items) => items.length < 2 ? items[0] ?? "" : `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`;
5701
+ var letter = (midi) => noteOf(midi).replace(/-?\d+$/, "");
5702
+ function stringNames(tuning, count, spelled) {
5703
+ const letters = tuning?.map((p, s) => spelled?.[s] ?? letter(p)) ?? [];
5704
+ const repeated = letters.filter((name, i) => letters.indexOf(name) !== i);
5705
+ const byName = tuning !== null && (repeated.length === 0 || repeated.length === 1 && letters[0] === letters[count - 1] && count > 2);
5706
+ return Array.from({ length: count }, (_, s) => {
5707
+ if (!byName)
5708
+ return numbered(tuning, count, s, spelled);
5709
+ const name = letters[s];
5710
+ if (repeated.length && s === 0)
5711
+ return `the low ${name} string`;
5712
+ if (repeated.length && s === count - 1)
5713
+ return `the high ${name} string`;
5714
+ return `the ${name} string`;
5715
+ });
5716
+ }
5717
+ function numbered(tuning, count, s, spelled) {
5718
+ const name = tuning ? spelled?.[s] ?? letter(tuning[s]) : null;
5719
+ return `the ${ordinal(count - s)} string${name ? ` (${name})` : ""}`;
5720
+ }
5721
+ var range = (from, to) => Array.from({ length: to - from + 1 }, (_, i) => from + i);
5722
+ var together = (names) => names.every((n) => /^the [^(]+ string$/.test(n)) ? `the ${andList(names.map((n) => n.slice(4, -7)))} strings` : andList(names);
5723
+ function guitarWords(input) {
5724
+ const { frets } = input;
5725
+ const count = frets.length;
5726
+ const tuning = input.tuning ?? (count === 6 ? STANDARD_TUNING : null);
5727
+ const spelled = input.tuningNames?.length === count ? input.tuningNames : undefined;
5728
+ const names = stringNames(tuning, count, spelled);
5729
+ const capo = input.capo ?? 0;
5730
+ const fromNut = capo > 0 && input.fretsFrom === "nut";
5731
+ const shape = frets.map((f) => f === null ? null : fromNut ? Math.max(0, f - capo) : f);
5732
+ const fingers = input.fingers?.some((f) => f) ? input.fingers : fingerVoicing(shape) ?? frets.map(() => null);
5733
+ const sentences = [];
5734
+ if (capo) {
5735
+ sentences.push(`Capo on the ${ordinal(capo)} fret${fromNut ? "" : ": frets count from the capo"}.`);
5736
+ }
5737
+ const sounding = frets.flatMap((f, s) => f !== null ? [s] : []);
5738
+ if (!sounding.length)
5739
+ return [...sentences, "Every string is muted: no note sounds."];
5740
+ const low = sounding[0];
5741
+ const high = sounding.at(-1);
5742
+ if (low === 0 && high === count - 1) {
5743
+ sentences.push(count === 6 ? "Strum all six strings." : "Strum every string.");
5744
+ } else if (high === count - 1) {
5745
+ sentences.push(`Strum from ${numbered(tuning, count, low, spelled)}.`);
5746
+ } else {
5747
+ sentences.push(`Strum from ${numbered(tuning, count, low, spelled)} to ${numbered(tuning, count, high, spelled)}.`);
5748
+ }
5749
+ const barred = new Set;
5750
+ const byFinger = new Map;
5751
+ shape.forEach((f, s) => {
5752
+ const finger = fingers[s];
5753
+ if (f !== null && f > 0 && finger)
5754
+ byFinger.set(finger, [...byFinger.get(finger) ?? [], s]);
5755
+ });
5756
+ const said = new Set;
5757
+ const fingerName = (finger) => GUITAR_FINGERS[finger] ?? `Finger ${finger}`;
5758
+ frets.forEach((fret, s) => {
5759
+ if (fret === null || shape[s] === 0)
5760
+ return;
5761
+ const finger = fingers[s];
5762
+ if (!finger) {
5763
+ sentences.push(`Press ${names[s]} at the ${ordinal(fret)} fret.`);
5764
+ return;
5765
+ }
5766
+ if (said.has(finger))
5767
+ return;
5768
+ said.add(finger);
5769
+ const strings = byFinger.get(finger).filter((t) => frets[t] === fret);
5770
+ const between = strings.length > 1 ? range(strings[0], strings.at(-1)) : [];
5771
+ const flat = between.every((t) => shape[t] === null || shape[t] >= shape[s]);
5772
+ if (strings.length > 1 && !flat) {
5773
+ sentences.push(`${fingerName(finger)} on ${together(strings.map((t) => names[t]))}, ${ordinal(fret)} fret.`);
5774
+ } else if (strings.length > 1) {
5775
+ const from = count - strings.at(-1);
5776
+ const to = count - strings[0];
5777
+ for (const t of strings)
5778
+ barred.add(t);
5779
+ sentences.push(`${fingerName(finger)} bars the ${ordinal(fret)} fret, strings ${from} to ${to}.`);
5780
+ } else {
5781
+ sentences.push(`${fingerName(finger)} on ${names[s]}, ${ordinal(fret)} fret.`);
5782
+ }
5783
+ for (const t of byFinger.get(finger)) {
5784
+ if (frets[t] !== fret) {
5785
+ sentences.push(`${fingerName(finger)} also on ${names[t]}, ${ordinal(frets[t])} fret.`);
5786
+ }
5787
+ }
5788
+ });
5789
+ const muted = frets.flatMap((f, s) => f === null && s > low && s < high ? [names[s]] : []);
5790
+ if (muted.length) {
5791
+ sentences.push(`Mute ${andList(muted)}: let a fretting finger touch ${muted.length > 1 ? "them" : "it"} lightly.`);
5792
+ }
5793
+ const open = shape.flatMap((f, s) => f === 0 && !barred.has(s) ? [names[s]] : []);
5794
+ if (open.length) {
5795
+ const where = capo ? " at the capo" : " open";
5796
+ const plural = open.length > 1;
5797
+ 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}.`);
5798
+ }
5799
+ return sentences;
5800
+ }
5801
+ function pianoWords(input) {
5802
+ const keys = [...input.keys].sort((a, b) => a - b);
5803
+ if (!keys.length)
5804
+ return [];
5805
+ const plain = (midi) => input.names?.get(midi % 12) ?? letter(midi);
5806
+ const octaves = new Set(keys.map(plain)).size < keys.length;
5807
+ const keyName = (midi) => {
5808
+ const name = plain(midi);
5809
+ if (!octaves)
5810
+ return name;
5811
+ return `${name}${Math.floor((midi - (Note5.get(name).alt || 0)) / 12) - 1}`;
5812
+ };
5813
+ const part = (group) => {
5814
+ const withFinger = group.filter((k) => input.fingers?.has(k));
5815
+ const without = group.filter((k) => !input.fingers?.has(k)).map(keyName);
5816
+ const fingered = withFinger.map((k) => {
5817
+ const finger = input.fingers.get(k);
5818
+ return `${PIANO_FINGERS[finger] ?? `finger ${finger}`} on ${keyName(k)}`;
5819
+ });
5820
+ if (!fingered.length)
5821
+ return andList(without);
5822
+ if (!without.length)
5823
+ return fingered.join(", ");
5824
+ return `${fingered.join(", ")}, and also play ${andList(without)}`;
5825
+ };
5826
+ const hands = input.hands;
5827
+ if (!hands?.size) {
5828
+ return [
5829
+ keys.some((k) => input.fingers?.has(k)) ? `${capitalized(part(keys))}.` : `Play ${part(keys)}.`
5830
+ ];
5831
+ }
5832
+ return ["left", "right"].flatMap((hand) => {
5833
+ const group = keys.filter((k) => (hands.get(k) ?? "right") === hand);
5834
+ return group.length ? [`${capitalized(hand)} hand: ${part(group)}.`] : [];
5835
+ });
5836
+ }
5837
+ function fingeringInWords(chord) {
5838
+ return "frets" in chord ? guitarWords(chord) : pianoWords(chord);
5839
+ }
5840
+
5656
5841
  // src/blocks/block-source.ts
5657
5842
  var FIELD2 = /^([A-Za-z][\w-]*)\s*:\s*(.*)$/;
5658
5843
  function parseBlockSource(source) {
@@ -6060,7 +6245,7 @@ var FINGER_NAMES = {
6060
6245
  "4": "pinky",
6061
6246
  T: "thumb"
6062
6247
  };
6063
- var ordinal = (n) => `${n}${n % 100 >= 11 && n % 100 <= 13 ? "th" : ["th", "st", "nd", "rd"][n % 10] ?? "th"}`;
6248
+ var ordinal2 = (n) => `${n}${n % 100 >= 11 && n % 100 <= 13 ? "th" : ["th", "st", "nd", "rd"][n % 10] ?? "th"}`;
6064
6249
  var MAX_SLIDE = 3;
6065
6250
  function stringName(tuning, s) {
6066
6251
  const name = noteOf(tuning[s]).replace(/-?\d+$/, "");
@@ -6068,7 +6253,7 @@ function stringName(tuning, s) {
6068
6253
  if (same < 2)
6069
6254
  return `the ${name} string`;
6070
6255
  if (same > 2)
6071
- return `the ${ordinal(tuning.length - s)} string (${name})`;
6256
+ return `the ${ordinal2(tuning.length - s)} string (${name})`;
6072
6257
  const lowest = tuning.findIndex((p) => noteOf(p).replace(/-?\d+$/, "") === name);
6073
6258
  return `the ${s === lowest ? "low" : "high"} ${name} string`;
6074
6259
  }
@@ -6109,7 +6294,7 @@ function move(from, fromFingers, to, tuning) {
6109
6294
  if (seen.has(f))
6110
6295
  continue;
6111
6296
  seen.add(f);
6112
- tips.push(`Keep your ${fingerName(f)} on ${stringName(tuning, s)}'s ${ordinal(to.frets[s])} fret.`);
6297
+ tips.push(`Keep your ${fingerName(f)} on ${stringName(tuning, s)}'s ${ordinal2(to.frets[s])} fret.`);
6113
6298
  }
6114
6299
  for (const s of guides) {
6115
6300
  const f = to.fingers[s];
@@ -6441,7 +6626,7 @@ function voiceLeadVoicings(symbols, options) {
6441
6626
  }
6442
6627
 
6443
6628
  // src/theory/numerals.ts
6444
- import { Note as Note5 } from "tonal";
6629
+ import { Note as Note6 } from "tonal";
6445
6630
  var MAJOR2 = ["1P", "2M", "3M", "4P", "5P", "6M", "7M"];
6446
6631
  var NATURAL_MINOR = ["1P", "2M", "3m", "4P", "5P", "6m", "7m"];
6447
6632
  var ROMAN_NUMBERS = { i: 1, ii: 2, iii: 3, iv: 4, v: 5, vi: 6, vii: 7 };
@@ -6449,13 +6634,16 @@ var keyOf = (key) => typeof key === "string" ? readKey(key) : key;
6449
6634
  function noteOn(key, degree, accidental, diminished) {
6450
6635
  const minor = key.mode === "minor" || key.mode === "aeolian";
6451
6636
  let interval = MAJOR2[degree - 1];
6452
- let shift = accidental === "#" ? 1 : accidental === "b" ? -1 : 0;
6637
+ const steps = { "##": 2, "#": 1, b: -1, bb: -2 };
6638
+ let shift = steps[accidental] ?? 0;
6453
6639
  if (minor && [3, 6, 7].includes(degree)) {
6454
6640
  interval = NATURAL_MINOR[degree - 1];
6455
- shift = accidental === "#" || !accidental && degree === 7 && diminished ? 1 : 0;
6641
+ shift = accidental === "bb" ? -1 : accidental === "#" || !accidental && degree === 7 && diminished ? 1 : accidental === "##" ? 2 : 0;
6456
6642
  }
6457
- const note = Note5.transpose(key.tonic, interval);
6458
- return shift === 0 ? note : Note5.transpose(note, shift > 0 ? "1A" : "-1A");
6643
+ let note = Note6.transpose(key.tonic, interval);
6644
+ for (let i = 0;i < Math.abs(shift); i++)
6645
+ note = Note6.transpose(note, shift > 0 ? "1A" : "-1A");
6646
+ return note;
6459
6647
  }
6460
6648
  function suffixOf(mark, lower) {
6461
6649
  let s = mark.replace(/♭/g, "b").replace(/♯/g, "#");
@@ -6486,14 +6674,14 @@ function chordFrom(root, suffix) {
6486
6674
  return parseChord(symbol) && chordNoteSet(symbol) ? symbol : null;
6487
6675
  }
6488
6676
  function bassOf(key, text) {
6489
- const m = /^([b#♭♯]?)([1-7])$/.exec(text);
6677
+ const m = /^(bb|##|[b#♭♯]?)([1-7])$/.exec(text);
6490
6678
  if (!m)
6491
6679
  return null;
6492
6680
  const accidental = m[1].replace("♭", "b").replace("♯", "#");
6493
6681
  return noteOn(key, Number(m[2]), accidental, false);
6494
6682
  }
6495
- var ROMAN2 = /^([b#♭♯]?)(VII|VI|V|IV|III|II|I|vii|vi|v|iv|iii|ii|i)(.*)$/;
6496
- var NASHVILLE = /^([b#♭♯]?)([1-7])(.*)$/;
6683
+ var ROMAN2 = /^(bb|##|[b#♭♯]?)(VII|VI|V|IV|III|II|I|vii|vi|v|iv|iii|ii|i)(.*)$/;
6684
+ var NASHVILLE = /^(bb|##|[b#♭♯]?)([1-7])(.*)$/;
6497
6685
  function readOne(key, text) {
6498
6686
  const roman = ROMAN2.exec(text);
6499
6687
  const nashville = roman ? null : NASHVILLE.exec(text);
@@ -6571,7 +6759,7 @@ function keySpelling(note, key) {
6571
6759
  const chroma = chromaOf(note);
6572
6760
  const notes = keyNotes(key);
6573
6761
  if (isMinorMode(key.mode) && notes.length === 7)
6574
- notes.push(Note5.transpose(notes[6], "1A"));
6762
+ notes.push(Note6.transpose(notes[6], "1A"));
6575
6763
  if (notes.includes(note))
6576
6764
  return note;
6577
6765
  return notes.find((n) => chromaOf(n) === chroma) ?? note;
@@ -6623,13 +6811,13 @@ function secondaryTarget(symbol, key) {
6623
6811
  if (has("3m") && has("5d")) {
6624
6812
  if (has("7M"))
6625
6813
  return null;
6626
- target = Note5.transpose(parts.root, "2m");
6814
+ target = Note6.transpose(parts.root, "2m");
6627
6815
  } else {
6628
6816
  if (!has("3M"))
6629
6817
  return null;
6630
6818
  if (set.members.some((m) => ["5d", "5A", "7M"].includes(m.interval ?? "")))
6631
6819
  return null;
6632
- target = Note5.transpose(parts.root, "-5P");
6820
+ target = Note6.transpose(parts.root, "-5P");
6633
6821
  }
6634
6822
  if (chromaOf(target) === chromaOf(key.tonic))
6635
6823
  return null;
@@ -6844,7 +7032,115 @@ function progressionChord(written, key, options = {}) {
6844
7032
  };
6845
7033
  }
6846
7034
 
7035
+ // src/theory/harmonize.ts
7036
+ import { Interval as Interval6, Key as Key2, Note as Note7, Scale as Scale6 } from "tonal";
7037
+ var HARMONIZE_KINDS = ["triads", "sevenths", "sus", "power"];
7038
+ var MAJOR_FUNCTIONS2 = [
7039
+ "tonic",
7040
+ "subdominant",
7041
+ "tonic",
7042
+ "subdominant",
7043
+ "dominant",
7044
+ "tonic",
7045
+ "dominant"
7046
+ ];
7047
+ var MINOR_FUNCTIONS2 = [
7048
+ "tonic",
7049
+ "subdominant",
7050
+ "tonic",
7051
+ "subdominant",
7052
+ "dominant",
7053
+ "subdominant",
7054
+ "dominant"
7055
+ ];
7056
+ var DIATONIC = ["tonic", "subdominant", "dominant"];
7057
+ var unknown = (text) => `Unknown scale "${text.trim()}": use e.g. key: G major, key: A harmonic minor or key: D dorian`;
7058
+ function readHarmonyScale(text) {
7059
+ const name = scaleName(text);
7060
+ const asKey = readKey(name);
7061
+ if (asKey) {
7062
+ const mode = asKey.mode === "ionian" ? "major" : asKey.mode === "aeolian" ? "minor" : asKey.mode;
7063
+ const key = { tonic: asKey.tonic, mode, name: `${asKey.tonic} ${mode}` };
7064
+ const problem = keyProblem(key);
7065
+ if (problem)
7066
+ return { error: problem };
7067
+ return { name: key.name, notes: Scale6.get(key.name).notes, key };
7068
+ }
7069
+ const scale = Scale6.get(name);
7070
+ if (scale.empty || !scale.tonic)
7071
+ return { error: unknown(text) };
7072
+ if (scale.notes.length !== 7) {
7073
+ return {
7074
+ error: `harmonize needs a scale of 7 notes: ${scale.name} has ${scale.notes.length}`
7075
+ };
7076
+ }
7077
+ const tonic = scale.tonic;
7078
+ const notes = scaleSpelling(scale).notes;
7079
+ const minor = Interval6.distance(tonic, notes[2]) === "3m";
7080
+ const key = {
7081
+ tonic,
7082
+ mode: minor ? "minor" : "major",
7083
+ name: `${tonic} ${minor ? "minor" : "major"}`
7084
+ };
7085
+ const count = minor ? Key2.minorKey(tonic).alteration : Key2.majorKey(tonic).alteration;
7086
+ if (Math.abs(count) > MAX_SIGNATURE) {
7087
+ return {
7088
+ error: `${scale.name} needs ${Math.abs(count)} ${count > 0 ? "sharps" : "flats"}: write ${Note7.enharmonic(tonic)} ${scale.type}`
7089
+ };
7090
+ }
7091
+ return { name: scale.name, notes, key };
7092
+ }
7093
+ function chordOn(notes, i, kind) {
7094
+ const root = notes[i];
7095
+ const above = (step) => Interval6.distance(root, notes[(i + step) % 7]);
7096
+ if (kind === "triads" || kind === "sevenths") {
7097
+ const symbol = stackedChord(notes, i, kind === "sevenths");
7098
+ return symbol ? { symbol } : { reason: "not a named chord" };
7099
+ }
7100
+ if (above(4) !== "5P")
7101
+ return { reason: "no perfect fifth" };
7102
+ if (kind === "power")
7103
+ return { symbol: `${root}5` };
7104
+ if (above(3) === "4P")
7105
+ return { symbol: `${root}sus4` };
7106
+ if (above(1) === "2M")
7107
+ return { symbol: `${root}sus2` };
7108
+ return { reason: "no perfect fourth or major second" };
7109
+ }
7110
+ function harmonize(scale, options = {}) {
7111
+ const kind = options.kind ?? "triads";
7112
+ if (!HARMONIZE_KINDS.includes(kind))
7113
+ return null;
7114
+ const read = readHarmonyScale(scale);
7115
+ if ("error" in read)
7116
+ return null;
7117
+ const { notes, key } = read;
7118
+ const byDegree = isMinorMode(key.mode) ? MINOR_FUNCTIONS2 : MAJOR_FUNCTIONS2;
7119
+ const chords = [];
7120
+ const skipped = [];
7121
+ notes.forEach((note, i) => {
7122
+ const made = chordOn(notes, i, kind);
7123
+ if ("reason" in made) {
7124
+ skipped.push({ degree: i + 1, note, reason: made.reason });
7125
+ return;
7126
+ }
7127
+ const { symbol } = made;
7128
+ const fn = harmonicFunction(symbol, key);
7129
+ const shown = (text) => text.replace(/Mb5$/, "(b5)").replace(/Mb⁵$/, "(b⁵)");
7130
+ chords.push({
7131
+ degree: i + 1,
7132
+ note,
7133
+ symbol: shown(symbol),
7134
+ numeral: shown(numeralOf(symbol, key, "roman", { byDegree: true }) ?? symbol),
7135
+ nashville: shown(numeralOf(symbol, key, "nashville", { byDegree: true }) ?? symbol),
7136
+ function: fn && DIATONIC.includes(fn) ? fn : byDegree[i]
7137
+ });
7138
+ });
7139
+ return { ...read, kind, chords, skipped };
7140
+ }
7141
+
6847
7142
  // src/blocks/progression.ts
7143
+ import { Note as Note8 } from "tonal";
6848
7144
  var MAX_CHORDS = 32;
6849
7145
  var MAX_SHARED_OCTAVES = 3;
6850
7146
  var SHARED = [
@@ -6866,8 +7162,22 @@ var SHARED = [
6866
7162
  "time",
6867
7163
  "tempo",
6868
7164
  "bpm",
6869
- "strum"
7165
+ "strum",
7166
+ "harmonize"
6870
7167
  ];
7168
+ var KIND_WORDS = {
7169
+ triad: "triads",
7170
+ triads: "triads",
7171
+ seventh: "sevenths",
7172
+ sevenths: "sevenths",
7173
+ "7th": "sevenths",
7174
+ "7ths": "sevenths",
7175
+ "7": "sevenths",
7176
+ sus: "sus",
7177
+ power: "power",
7178
+ "5": "power"
7179
+ };
7180
+ var HARMONIZED_CHORDS = 7;
6871
7181
  var yes = (text, key, fallback) => {
6872
7182
  if (text === undefined || text === "")
6873
7183
  return fallback;
@@ -6925,7 +7235,69 @@ function sourceOf(part) {
6925
7235
  return { head: lines.length ? lines.join(" ") : null, fields };
6926
7236
  }
6927
7237
  var chordsText = (block) => block.head ?? field(block, "progression") ?? field(block, "chords");
7238
+ function harmonizedSectionOf(block, kindText) {
7239
+ const kind = KIND_WORDS[kindText.toLowerCase()];
7240
+ if (!kind || !HARMONIZE_KINDS.includes(kind)) {
7241
+ throw new Error(`harmonize: write triads, sevenths, sus or power, got "${kindText}"`);
7242
+ }
7243
+ const written = chordsText(block);
7244
+ if (written) {
7245
+ throw new Error(`harmonize draws the chords of the scale: leave out the chords (${written})`);
7246
+ }
7247
+ const keyText = field(block, "key");
7248
+ if (!keyText)
7249
+ throw new Error("Add the scale: e.g. key: A harmonic minor");
7250
+ const shift = Number(field(block, "transpose") ?? 0);
7251
+ if (!Number.isInteger(shift)) {
7252
+ throw new Error(`transpose must be a whole number of semitones, e.g. transpose: -2`);
7253
+ }
7254
+ let scale = readHarmonyScale(keyText);
7255
+ if ("error" in scale)
7256
+ throw new Error(scale.error);
7257
+ if (shift) {
7258
+ const { tonic, mode } = scale.key;
7259
+ const moved = transposeKey(`${tonic}${isMinorMode(mode) ? "m" : ""}`, shift).replace(/m$/, "");
7260
+ const type = scale.name.slice(tonic.length).trim();
7261
+ const spellings = [...new Set([moved, Note8.enharmonic(moved)])].map((t) => readHarmonyScale(`${t} ${type}`));
7262
+ const valid = spellings.filter((sp) => !("error" in sp));
7263
+ const accidentals = (sp) => sp.notes.join("").replace(/[^#b]/g, "").length;
7264
+ const best = valid.sort((a, b) => accidentals(a) - accidentals(b))[0];
7265
+ if (!best)
7266
+ throw new Error(spellings[0].error);
7267
+ scale = best;
7268
+ }
7269
+ const harmonized = harmonize(scale.name, { kind });
7270
+ const chords = harmonized.chords.map((c) => ({
7271
+ written: c.numeral,
7272
+ symbol: c.symbol,
7273
+ numeral: c.numeral,
7274
+ nashville: c.nashville,
7275
+ function: c.function
7276
+ }));
7277
+ const left = harmonized.skipped.map((s) => `degree ${s.degree} (${s.note}), ${s.reason}`);
7278
+ return {
7279
+ key: harmonized.key,
7280
+ others: [],
7281
+ chords,
7282
+ blues: false,
7283
+ block,
7284
+ name: harmonized.name,
7285
+ ...left.length ? { note: `Left out: ${left.join("; ")}` } : {}
7286
+ };
7287
+ }
7288
+ function harmonizeText(block) {
7289
+ if (!block.fields.has("harmonize"))
7290
+ return;
7291
+ const text = field(block, "harmonize");
7292
+ if (text === undefined) {
7293
+ throw new Error("harmonize: write triads, sevenths, sus or power, got nothing");
7294
+ }
7295
+ return text.toLowerCase() === "none" ? undefined : text;
7296
+ }
6928
7297
  function sectionOf(block) {
7298
+ const kindText = harmonizeText(block);
7299
+ if (kindText)
7300
+ return harmonizedSectionOf(block, kindText);
6929
7301
  const text = chordsText(block);
6930
7302
  if (!text) {
6931
7303
  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 +7440,9 @@ function renderSection(doc, section, options, renderChord) {
7068
7440
  const el = html(doc, "div", "mn-progression-section");
7069
7441
  const others = section.others.length ? ` (or ${section.others.join(", ")})` : "";
7070
7442
  const blues = section.blues ? " (blues)" : "";
7071
- el.appendChild(html(doc, "div", "mn-progression-key", `Key: ${section.key.name}${blues}${others}`));
7443
+ el.appendChild(html(doc, "div", "mn-progression-key", `Key: ${section.name ?? section.key.name}${blues}${others}`));
7444
+ if (section.note)
7445
+ el.appendChild(html(doc, "div", "mn-progression-note", section.note));
7072
7446
  const instrument = (field(block, "instrument") ?? options.instrument ?? "guitar").toLowerCase();
7073
7447
  if (!["guitar", "piano", "keyboard"].includes(instrument)) {
7074
7448
  throw new Error(`Unknown instrument "${instrument}": use guitar or piano`);
@@ -7188,13 +7562,14 @@ function renderProgression(doc, source, options, renderChord) {
7188
7562
  const parts = splitParts(source) ?? [source];
7189
7563
  const blocks = parts.map(sourceOf);
7190
7564
  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));
7565
+ const harmonizedFirst = first !== undefined && first.fields.has("harmonize") && field(first, "key") !== undefined;
7566
+ 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
7567
  const shared = sharedOnly ? first.fields : new Map;
7193
7568
  const own = sharedOnly ? blocks.slice(1) : blocks;
7194
7569
  if (!own.length)
7195
7570
  throw new Error('Add the chords after the shared settings, after a "---" line');
7196
7571
  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);
7572
+ const count = merged.reduce((n, b) => n + (harmonizeText(b) ? HARMONIZED_CHORDS : progressionTokens(chordsText(b) ?? "").length), 0);
7198
7573
  if (count > MAX_CHORDS)
7199
7574
  throw new Error(`At most ${MAX_CHORDS} chords per block, found ${count}`);
7200
7575
  const sections = merged.map(sectionOf);
@@ -7218,7 +7593,7 @@ function renderProgression(doc, source, options, renderChord) {
7218
7593
  }
7219
7594
 
7220
7595
  // src/circle/circle.ts
7221
- import { Key as Key2 } from "tonal";
7596
+ import { Key as Key3 } from "tonal";
7222
7597
  var MAJORS = ["C", "G", "D", "A", "E", "B", "F#/Gb", "Db", "Ab", "Eb", "Bb", "F"];
7223
7598
  var MINORS = ["Am", "Em", "Bm", "F#m", "C#m", "G#m", "D#m/Ebm", "Bbm", "Fm", "Cm", "Gm", "Dm"];
7224
7599
  var DIMINISHED = ["B°", "F#°", "C#°", "G#°", "D#°", "A#°", "E#°", "C°", "G°", "D°", "A°", "E°"];
@@ -7375,7 +7750,7 @@ function renderCircle(doc, options = {}) {
7375
7750
  }
7376
7751
  for (let position = 0;position < 12; position++) {
7377
7752
  const chord = at("major", position);
7378
- const count = chord ? Key2.majorKey(splitChordSymbol(chord.symbol).root).alteration : 0;
7753
+ const count = chord ? Key3.majorKey(splitChordSymbol(chord.symbol).root).alteration : 0;
7379
7754
  const own = chord !== undefined && Math.abs(count) <= MAX_SIGNATURE;
7380
7755
  const text = own ? signatureText(count).replace("no ♯ or ♭", "0") : SIGNATURES[position];
7381
7756
  const [x, y] = point((R.sig + R.major) / 2, position * 30, top);
@@ -8286,7 +8661,8 @@ var SHARED_KEYS = {
8286
8661
  "inversion",
8287
8662
  "octave",
8288
8663
  "hands",
8289
- "fingering"
8664
+ "fingering",
8665
+ "caption"
8290
8666
  ],
8291
8667
  keyboard: ["orientation", "hand", "labels", "range", "highlight", "compare"],
8292
8668
  fretboard: [
@@ -8382,6 +8758,7 @@ var renderChord = (doc, block, options) => {
8382
8758
  const voicingOptions = pianoOptionsOf((key) => field2(block, key));
8383
8759
  const fingering = field2(block, "fingering", "fingers");
8384
8760
  let auto = null;
8761
+ let captionHands;
8385
8762
  let hands;
8386
8763
  let set;
8387
8764
  if (pitchesText) {
@@ -8439,6 +8816,9 @@ var renderChord = (doc, block, options) => {
8439
8816
  }
8440
8817
  if (fingering?.trim().toLowerCase() === "auto") {
8441
8818
  auto = triadFingering(voiced);
8819
+ if (autoVoicingHand(voiced) === "left") {
8820
+ captionHands = new Map(voiced.pitches.map((p) => [p, "left"]));
8821
+ }
8442
8822
  if (!auto) {
8443
8823
  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
8824
  }
@@ -8449,7 +8829,8 @@ var renderChord = (doc, block, options) => {
8449
8829
  const fingers = auto ?? (fingering ? fingersFor(set.pitches, fingering) : new Map);
8450
8830
  const range = field2(block, "range");
8451
8831
  handOf(block, options);
8452
- return named(renderKeyboard(doc, set, {
8832
+ const caption = captionOf(block);
8833
+ const keyboard = named(renderKeyboard(doc, set, {
8453
8834
  playAs: "chord",
8454
8835
  title,
8455
8836
  label: labelField(block, fingers.size ? "fingers" : "notes", fingers.size > 0),
@@ -8458,6 +8839,15 @@ var renderChord = (doc, block, options) => {
8458
8839
  range: keyRange(range ? rangeOf(range) : keyRangeOf(set)),
8459
8840
  orientation: orientationOf(block, options.orientation?.keyboard)
8460
8841
  }), symbol);
8842
+ if (!caption)
8843
+ return keyboard;
8844
+ const names = new Map(set.members.map((m) => [m.chroma, m.name]));
8845
+ return captioned(doc, keyboard, fingeringInWords({
8846
+ keys: set.pitches,
8847
+ fingers,
8848
+ ...hands ? { hands } : captionHands ? { hands: captionHands } : {},
8849
+ names
8850
+ }));
8461
8851
  }
8462
8852
  if (instrument && instrument !== "guitar" && !field2(block, "tuning")) {
8463
8853
  throw new Error(`Unknown instrument "${instrument}": use guitar or piano, or give a tuning`);
@@ -8541,8 +8931,30 @@ var renderChord = (doc, block, options) => {
8541
8931
  }), symbol);
8542
8932
  if (capo && sounding && sounding !== symbol)
8543
8933
  diagram.setAttribute("data-mn-sounds", sounding);
8544
- return diagram;
8934
+ if (!captionOf(block))
8935
+ return diagram;
8936
+ return captioned(doc, diagram, fingeringInWords({
8937
+ frets: voicing.frets,
8938
+ fingers: voicing.fingers,
8939
+ ...strings ? { tuning: strings } : {},
8940
+ ...tuningText && tuning ? { tuningNames: tuningNames(tuningText) ?? [] } : {},
8941
+ ...capo ? { capo, fretsFrom: fromNut ? "nut" : "capo" } : {}
8942
+ }));
8545
8943
  };
8944
+ function captionOf(block) {
8945
+ const written = field2(block, "caption")?.trim();
8946
+ const text = written?.toLowerCase();
8947
+ if (!text || ["none", "no", "off", "false"].includes(text))
8948
+ return null;
8949
+ if (text === "fingering")
8950
+ return "fingering";
8951
+ throw new Error(`caption: use fingering (the fingering in words) or none, got "${written}"`);
8952
+ }
8953
+ function captioned(doc, diagram, sentences) {
8954
+ const figure = html(doc, "figure", "mn-captioned");
8955
+ figure.append(diagram, html(doc, "figcaption", "mn-fingering", sentences.join(" ")));
8956
+ return figure;
8957
+ }
8546
8958
  function soundsField(text, shape, capo) {
8547
8959
  const value = text?.trim();
8548
8960
  if (!value || /^(no|false|off)$/i.test(value))
@@ -8612,8 +9024,11 @@ var renderKeyboardBlock = (doc, block, options) => {
8612
9024
  let fingers;
8613
9025
  let title = field2(block, "title");
8614
9026
  const autoHand = fingering ? autoFingeringHand(fingering) : null;
9027
+ if (fingering && isBothHandsFingering(fingering)) {
9028
+ throw new Error("fingering: auto both draws two keyboards: put it in a block of its own, not in a --- row");
9029
+ }
8615
9030
  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");
9031
+ throw new Error(AUTO_FINGERING_NEEDS_SCALE);
8617
9032
  }
8618
9033
  if (fingering && set.scaleType && set.root !== null && !set.list && !set.pitches) {
8619
9034
  const chromas = set.members.map((m) => m.chroma);
@@ -8621,7 +9036,7 @@ var renderKeyboardBlock = (doc, block, options) => {
8621
9036
  if (autoHand) {
8622
9037
  const standard = standardScaleFingering(set.root, set.scaleType, autoHand);
8623
9038
  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`);
9039
+ throw new Error(autoFingeringUnknown(set.title));
8625
9040
  }
8626
9041
  octave = standard;
8627
9042
  title ??= `${set.title}, ${autoHand} hand`;
@@ -8839,6 +9254,109 @@ var RENDERERS = {
8839
9254
  circle: renderCircleBlock
8840
9255
  };
8841
9256
 
9257
+ // src/playback/bar-parts.ts
9258
+ var ICONS = {
9259
+ play: "M4 2.5v11l9-5.5z",
9260
+ stop: "M4 4h8v8H4z",
9261
+ all: "M1.5 2.5v11l6.5-5.5zM8 2.5v11l6.5-5.5z",
9262
+ loop: "M3 8a5 5 0 0 1 8.5-3.5L13 6V2.5M13 8a5 5 0 0 1-8.5 3.5L3 10v3.5",
9263
+ count: "M5.5 14h5L9 2.5H7zM8 11.5l4.5-7",
9264
+ click: "M3 5v6M8 5v6M13 5v6"
9265
+ };
9266
+ var STROKED = new Set(["loop", "count", "click"]);
9267
+ function icon(doc, name) {
9268
+ const root = svg(doc, "svg", {
9269
+ class: `mn-play-icon mn-play-icon-${name}${STROKED.has(name) ? " mn-play-icon-line" : ""}`,
9270
+ viewBox: "0 0 16 16",
9271
+ width: 12,
9272
+ height: 12,
9273
+ "aria-hidden": "true"
9274
+ });
9275
+ root.appendChild(svg(doc, "path", { d: ICONS[name] }));
9276
+ return root;
9277
+ }
9278
+ function playBar(doc, cls, label) {
9279
+ const bar = html(doc, "div", `mn-play mn-play-static ${cls}`);
9280
+ bar.addEventListener("mousedown", (event) => event.stopPropagation());
9281
+ bar.setAttribute("role", "group");
9282
+ bar.setAttribute("aria-label", label);
9283
+ return bar;
9284
+ }
9285
+ function iconButton(doc, cls, label, name) {
9286
+ const button = html(doc, "button", cls);
9287
+ button.type = "button";
9288
+ button.appendChild(icon(doc, name));
9289
+ button.title = label;
9290
+ button.setAttribute("aria-label", label);
9291
+ return button;
9292
+ }
9293
+ function pressedButton(doc, cls, label, name, on, set) {
9294
+ const button = iconButton(doc, cls, label, name);
9295
+ const show = () => {
9296
+ button.setAttribute("aria-pressed", String(on));
9297
+ button.classList.toggle("mn-on", on);
9298
+ };
9299
+ button.addEventListener("click", () => {
9300
+ on = !on;
9301
+ set(on);
9302
+ show();
9303
+ });
9304
+ show();
9305
+ return button;
9306
+ }
9307
+ function valueSlider(doc, label, unit, min, max, value, set, hint) {
9308
+ const field = html(doc, "label", "mn-play-field");
9309
+ const input = html(doc, "input");
9310
+ input.type = "range";
9311
+ input.min = String(min);
9312
+ input.max = String(max);
9313
+ input.setAttribute("aria-label", label);
9314
+ if (hint)
9315
+ input.setAttribute("aria-description", hint);
9316
+ const text = html(doc, "span", "mn-play-value");
9317
+ text.setAttribute("aria-hidden", "true");
9318
+ const show = (n) => {
9319
+ input.value = String(n);
9320
+ const written = `${n} ${unit}`;
9321
+ text.textContent = written;
9322
+ input.setAttribute("aria-valuetext", written);
9323
+ field.title = `${label}: ${written}${hint ? ` (${hint})` : ""}`;
9324
+ };
9325
+ input.addEventListener("input", () => {
9326
+ const n = Number(input.value);
9327
+ set(n);
9328
+ show(n);
9329
+ });
9330
+ show(value);
9331
+ field.append(input, text);
9332
+ return { field, input, show };
9333
+ }
9334
+ function choice(doc, cls, label, values, chosen, names, set) {
9335
+ const el = html(doc, "select", cls);
9336
+ el.setAttribute("aria-label", label);
9337
+ el.title = label;
9338
+ for (const value of values) {
9339
+ const option = html(doc, "option", undefined, names[value]);
9340
+ option.value = value;
9341
+ option.selected = value === chosen;
9342
+ el.appendChild(option);
9343
+ }
9344
+ el.addEventListener("change", () => set(el.value));
9345
+ return el;
9346
+ }
9347
+ var DEFAULT_VOLUME = 0.8;
9348
+ function volumeOf(volume) {
9349
+ let value = volume;
9350
+ if (typeof volume === "function") {
9351
+ try {
9352
+ value = volume();
9353
+ } catch {
9354
+ value = undefined;
9355
+ }
9356
+ }
9357
+ return typeof value === "number" && Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : DEFAULT_VOLUME;
9358
+ }
9359
+
8842
9360
  // src/playback/app-bar.ts
8843
9361
  var NONE = { tempoChanged() {}, free() {} };
8844
9362
  function handToApp(options, bar, info) {
@@ -8949,7 +9467,6 @@ function barPlayer(wrap, win, options) {
8949
9467
  }
8950
9468
  };
8951
9469
  }
8952
- var COUNT_IN = "M5.5 14h5L9 2.5H7zM8 11.5l4.5-7";
8953
9470
  function strumBarFor(doc, win, drawing, options) {
8954
9471
  const score = scoreFromDrawing(drawing);
8955
9472
  if (!score)
@@ -8968,13 +9485,10 @@ function strumBarFor(doc, win, drawing, options) {
8968
9485
  });
8969
9486
  }
8970
9487
  function timedBarFor(doc, win, drawing, options, piece) {
8971
- const wrap = html(doc, "div", `mn-playable ${piece.cls}`);
9488
+ const wrap = html(doc, "div", `mn-timed ${piece.cls}`);
8972
9489
  drawing.parentNode?.insertBefore(wrap, drawing);
8973
9490
  wrap.appendChild(drawing);
8974
- const bar = html(doc, "div", "mn-play");
8975
- bar.addEventListener("mousedown", (event) => event.stopPropagation());
8976
- bar.setAttribute("role", "group");
8977
- bar.setAttribute("aria-label", piece.label);
9491
+ const bar = playBar(doc, "mn-timed-bar", piece.label);
8978
9492
  wrap.appendChild(bar);
8979
9493
  const tempo = Number(drawing.getAttribute("data-mn-tempo"));
8980
9494
  const compound = piece.compound;
@@ -8984,7 +9498,7 @@ function timedBarFor(doc, win, drawing, options, piece) {
8984
9498
  loop: false,
8985
9499
  click: piece.click ?? false,
8986
9500
  sound: options.sound ?? "guitar",
8987
- volume: clamp(options.volume, 0, 1, 0.8)
9501
+ volume: volumeOf(options.volume)
8988
9502
  };
8989
9503
  let playing = null;
8990
9504
  const toggle = html(doc, "button", "mn-play-toggle");
@@ -9005,7 +9519,11 @@ function timedBarFor(doc, win, drawing, options, piece) {
9005
9519
  if (!wrap.isConnected)
9006
9520
  return;
9007
9521
  const here = wrap.ownerDocument.defaultView ?? win;
9008
- playing = runPasses(piece.make, player, () => ({ ...settings, loop: settings.loop && wrap.isConnected }), here, () => {
9522
+ playing = runPasses(piece.make, player, () => ({
9523
+ ...settings,
9524
+ volume: volumeOf(options.volume),
9525
+ loop: settings.loop && wrap.isConnected
9526
+ }), here, () => {
9009
9527
  playing = null;
9010
9528
  show();
9011
9529
  }, (strums, current) => {
@@ -9023,85 +9541,18 @@ function timedBarFor(doc, win, drawing, options, piece) {
9023
9541
  toggle.addEventListener("click", () => playing ? stop() : start());
9024
9542
  show();
9025
9543
  bar.appendChild(toggle);
9026
- const pressed = (cls, label, mark, set, start = false) => {
9027
- const button = html(doc, "button", cls);
9028
- button.type = "button";
9029
- button.appendChild(mark);
9030
- button.title = label;
9031
- button.setAttribute("aria-label", label);
9032
- button.setAttribute("aria-pressed", String(start));
9033
- button.classList.toggle("mn-on", start);
9034
- let on = start;
9035
- button.addEventListener("click", () => {
9036
- on = !on;
9037
- set(on);
9038
- button.setAttribute("aria-pressed", String(on));
9039
- button.classList.toggle("mn-on", on);
9040
- });
9041
- bar.appendChild(button);
9042
- };
9043
- pressed("mn-play-loop", "Loop", icon(doc, "loop"), (on) => settings.loop = on);
9044
- const metronome = svg(doc, "svg", {
9045
- class: "mn-play-icon mn-play-icon-loop",
9046
- viewBox: "0 0 16 16",
9047
- width: 12,
9048
- height: 12,
9049
- "aria-hidden": "true"
9050
- });
9051
- metronome.appendChild(svg(doc, "path", { d: COUNT_IN }));
9052
- pressed("mn-play-count", "Count-in", metronome, (on) => settings.countIn = on);
9053
- if (piece.click !== undefined) {
9054
- const beats = svg(doc, "svg", {
9055
- class: "mn-play-icon mn-play-icon-loop",
9056
- viewBox: "0 0 16 16",
9057
- width: 12,
9058
- height: 12,
9059
- "aria-hidden": "true"
9060
- });
9061
- beats.appendChild(svg(doc, "path", { d: "M3 5v6M8 5v6M13 5v6" }));
9062
- pressed("mn-play-click", "Click", beats, (on) => settings.click = on, piece.click);
9063
- }
9064
- const slider = (label, min, max, value, set, mark) => {
9065
- const field = html(doc, "label", "mn-play-field");
9066
- field.title = `${label}: ${value}`;
9067
- const tag = html(doc, "span", "mn-play-label");
9068
- tag.setAttribute("aria-hidden", "true");
9069
- tag.append(mark);
9070
- const input = html(doc, "input");
9071
- input.type = "range";
9072
- input.min = String(min);
9073
- input.max = String(max);
9074
- input.value = String(value);
9075
- input.setAttribute("aria-label", label);
9076
- input.addEventListener("input", () => {
9077
- set(Number(input.value));
9078
- field.title = `${label}: ${input.value}`;
9079
- });
9080
- field.append(tag, input);
9081
- bar.appendChild(field);
9082
- };
9083
- slider("Tempo (BPM)", 20, 240, settings.bpm, (n) => {
9544
+ bar.append(pressedButton(doc, "mn-play-loop", "Loop", "loop", false, (on) => settings.loop = on), pressedButton(doc, "mn-play-count", "Count-in", "count", false, (on) => {
9545
+ settings.countIn = on;
9546
+ }));
9547
+ if (piece.click !== undefined)
9548
+ bar.appendChild(pressedButton(doc, "mn-play-click", "Click", "click", piece.click, (on) => {
9549
+ settings.click = on;
9550
+ }));
9551
+ bar.appendChild(valueSlider(doc, "Tempo (BPM)", "BPM", 20, 240, settings.bpm, (n) => {
9084
9552
  settings.bpm = tempoOf(n);
9085
9553
  app.tempoChanged(settings.bpm);
9086
- }, compound ? "♩." : "♩");
9087
- slider("Volume", 0, 100, Math.round(settings.volume * 100), (n) => settings.volume = n / 100, icon(doc, "volume"));
9088
- const sound = html(doc, "select", "mn-play-sound");
9089
- sound.setAttribute("aria-label", "Sound");
9090
- for (const value of ["guitar", "piano"]) {
9091
- const option = html(doc, "option", undefined, value === "guitar" ? "Guitar" : "Piano");
9092
- option.value = value;
9093
- option.selected = value === settings.sound;
9094
- sound.appendChild(option);
9095
- }
9096
- sound.addEventListener("change", () => {
9097
- settings.sound = sound.value === "piano" ? "piano" : "guitar";
9098
- });
9099
- bar.appendChild(sound);
9100
- wrap.addEventListener("pointerdown", (event) => {
9101
- if (event.pointerType !== "touch" || bar.contains(event.target))
9102
- return;
9103
- wrap.classList.toggle("mn-play-open");
9104
- });
9554
+ }, compound ? "counts dotted quarters" : undefined).field);
9555
+ bar.appendChild(choice(doc, "mn-play-sound", "Sound", ["guitar", "piano"], settings.sound, { guitar: "Guitar", piano: "Piano" }, (value) => settings.sound = value === "piano" ? "piano" : "guitar"));
9105
9556
  const app = handToApp(options, bar, {
9106
9557
  kind: piece.kind,
9107
9558
  drawing,
@@ -9115,8 +9566,6 @@ function timedBarFor(doc, win, drawing, options, piece) {
9115
9566
  }
9116
9567
 
9117
9568
  // src/playback/progression-bar.ts
9118
- var COUNT_IN2 = "M5.5 14h5L9 2.5H7zM8 11.5l4.5-7";
9119
- var CLICK4 = "M3 5v6M8 5v6M13 5v6";
9120
9569
  var pitchesOf2 = (text) => (text ?? "").split(" ").filter(Boolean).map(Number).filter((n) => Number.isFinite(n));
9121
9570
  function barsFromDrawing(drawing) {
9122
9571
  const byBar = new Map;
@@ -9167,7 +9616,7 @@ var STRUM_LABELS = {
9167
9616
  arpeggio: "Arpeggio",
9168
9617
  pattern: "Pattern"
9169
9618
  };
9170
- function progressionBarFor(doc, win, drawing, options) {
9619
+ function progressionBarFor(doc, win, drawing, options, diagrams = null) {
9171
9620
  const { bars, marks } = barsFromDrawing(drawing);
9172
9621
  if (!bars.length)
9173
9622
  return () => {};
@@ -9190,15 +9639,12 @@ function progressionBarFor(doc, win, drawing, options) {
9190
9639
  loop: false,
9191
9640
  click: true,
9192
9641
  sound: options.sound ?? (piano ? "piano" : "guitar"),
9193
- volume: clamp(options.volume, 0, 1, 0.8)
9642
+ volume: volumeOf(options.volume)
9194
9643
  };
9195
9644
  let strum = pattern ? "pattern" : written.strum;
9196
9645
  let playing = null;
9197
- const bar = html(doc, "div", "mn-play mn-play-static mn-progression-play");
9198
- bar.addEventListener("mousedown", (event) => event.stopPropagation());
9199
- bar.setAttribute("role", "group");
9200
- bar.setAttribute("aria-label", "Play the chords in time");
9201
- drawing.insertBefore(bar, drawing.firstChild);
9646
+ const bar = playBar(doc, "mn-progression-play", "Play the chords in time");
9647
+ drawing.appendChild(bar);
9202
9648
  const toggle = html(doc, "button", "mn-play-toggle");
9203
9649
  toggle.type = "button";
9204
9650
  const show = () => {
@@ -9211,17 +9657,30 @@ function progressionBarFor(doc, win, drawing, options) {
9211
9657
  playing = null;
9212
9658
  show();
9213
9659
  };
9660
+ if (diagrams) {
9661
+ diagrams.onPlay = stop;
9662
+ diagrams.stopOthers = () => {
9663
+ const was = playing !== null;
9664
+ stop();
9665
+ return was;
9666
+ };
9667
+ }
9214
9668
  const start = () => {
9215
9669
  stop();
9216
9670
  if (!drawing.isConnected)
9217
9671
  return;
9672
+ diagrams?.stop();
9218
9673
  const here = drawing.ownerDocument.defaultView ?? win;
9219
9674
  playing = runProgression(bars, {
9220
9675
  beatsPerBar,
9221
9676
  beatUnit,
9222
9677
  strum: strum === "pattern" ? "beats" : strum,
9223
9678
  pattern: strum === "pattern" ? pattern : null
9224
- }, () => barPlayer(drawing, win, options), () => ({ ...settings, loop: settings.loop && drawing.isConnected }), here, () => {
9679
+ }, () => barPlayer(drawing, win, options), () => ({
9680
+ ...settings,
9681
+ volume: volumeOf(options.volume),
9682
+ loop: settings.loop && drawing.isConnected
9683
+ }), here, () => {
9225
9684
  playing = null;
9226
9685
  show();
9227
9686
  }, (timings, current) => followNotes(here, drawing, timings.map((t) => marks[t.slot] ?? []), timings.map((t) => ({ midi: 0, time: t.time, duration: t.duration })), current.reportsStart === true ? Infinity : START_WAIT));
@@ -9230,85 +9689,26 @@ function progressionBarFor(doc, win, drawing, options) {
9230
9689
  toggle.addEventListener("click", () => playing ? stop() : start());
9231
9690
  show();
9232
9691
  bar.appendChild(toggle);
9233
- const mark = (path) => {
9234
- const el = svg(doc, "svg", {
9235
- class: "mn-play-icon mn-play-icon-loop",
9236
- viewBox: "0 0 16 16",
9237
- width: 12,
9238
- height: 12,
9239
- "aria-hidden": "true"
9240
- });
9241
- el.appendChild(svg(doc, "path", { d: path }));
9242
- return el;
9243
- };
9244
- const pressed = (cls, label, glyph, on, set) => {
9245
- const button = html(doc, "button", cls);
9246
- button.type = "button";
9247
- button.appendChild(glyph);
9248
- button.title = label;
9249
- button.setAttribute("aria-label", label);
9250
- const show = () => {
9251
- button.setAttribute("aria-pressed", String(on));
9252
- button.classList.toggle("mn-on", on);
9253
- };
9254
- button.addEventListener("click", () => {
9255
- on = !on;
9256
- set(on);
9257
- show();
9258
- });
9259
- show();
9260
- bar.appendChild(button);
9261
- };
9262
- pressed("mn-play-loop", "Loop", icon(doc, "loop"), false, (on) => settings.loop = on);
9263
- pressed("mn-play-count", "Count-in", mark(COUNT_IN2), false, (on) => settings.countIn = on);
9264
- pressed("mn-play-click", "Click", mark(CLICK4), true, (on) => settings.click = on);
9265
- const slider = (label, min, max, value, set, glyph) => {
9266
- const field = html(doc, "label", "mn-play-field");
9267
- field.title = `${label}: ${value}`;
9268
- const tag = html(doc, "span", "mn-play-label");
9269
- tag.setAttribute("aria-hidden", "true");
9270
- tag.append(glyph);
9271
- const input = html(doc, "input");
9272
- input.type = "range";
9273
- input.min = String(min);
9274
- input.max = String(max);
9275
- input.value = String(value);
9276
- input.setAttribute("aria-label", label);
9277
- input.addEventListener("input", () => {
9278
- set(Number(input.value));
9279
- field.title = `${label}: ${input.value}`;
9280
- });
9281
- field.append(tag, input);
9282
- bar.appendChild(field);
9283
- };
9284
- slider("Tempo (BPM)", 20, 240, settings.bpm, (n) => {
9692
+ bar.append(pressedButton(doc, "mn-play-loop", "Loop", "loop", false, (on) => settings.loop = on), pressedButton(doc, "mn-play-count", "Count-in", "count", false, (on) => {
9693
+ settings.countIn = on;
9694
+ }), pressedButton(doc, "mn-play-click", "Click", "click", true, (on) => settings.click = on));
9695
+ bar.appendChild(valueSlider(doc, "Tempo (BPM)", "BPM", 20, 240, settings.bpm, (n) => {
9285
9696
  settings.bpm = tempoOf(n);
9286
9697
  app.tempoChanged(settings.bpm);
9287
- }, compound ? "♩." : "♩");
9288
- slider("Volume", 0, 100, Math.round(settings.volume * 100), (n) => settings.volume = n / 100, icon(doc, "volume"));
9289
- const select = (cls, label, values, chosen, names, set) => {
9290
- const el = html(doc, "select", cls);
9291
- el.setAttribute("aria-label", label);
9292
- el.title = label;
9293
- for (const value of values) {
9294
- const option = html(doc, "option", undefined, names[value]);
9295
- option.value = value;
9296
- option.selected = value === chosen;
9297
- el.appendChild(option);
9298
- }
9299
- el.addEventListener("change", () => set(el.value));
9300
- bar.appendChild(el);
9301
- };
9698
+ }, compound ? "counts dotted quarters" : undefined).field);
9302
9699
  const strums = [
9303
9700
  ...pattern ? ["pattern"] : [],
9304
9701
  ...PROGRESSION_STRUMS
9305
9702
  ];
9306
- select("mn-play-strum", "Strum", strums, strum, STRUM_LABELS, (value) => {
9703
+ bar.appendChild(choice(doc, "mn-play-strum", "Strum", strums, strum, STRUM_LABELS, (value) => {
9307
9704
  strum = value;
9308
9705
  if (playing)
9309
9706
  start();
9310
- });
9311
- select("mn-play-sound", "Sound", ["guitar", "piano"], settings.sound, { guitar: "Guitar", piano: "Piano" }, (value) => settings.sound = value === "piano" ? "piano" : "guitar");
9707
+ }));
9708
+ bar.appendChild(choice(doc, "mn-play-sound", "Sound", ["guitar", "piano"], settings.sound, { guitar: "Guitar", piano: "Piano" }, (value) => {
9709
+ settings.sound = value === "piano" ? "piano" : "guitar";
9710
+ diagrams?.setSound(settings.sound);
9711
+ }));
9312
9712
  const app = handToApp(options, bar, {
9313
9713
  kind: drawing.classList.contains("mn-chart") ? "chart" : "progression",
9314
9714
  drawing,
@@ -9317,6 +9717,10 @@ function progressionBarFor(doc, win, drawing, options) {
9317
9717
  });
9318
9718
  return () => {
9319
9719
  stop();
9720
+ if (diagrams?.onPlay === stop) {
9721
+ diagrams.onPlay = null;
9722
+ diagrams.stopOthers = null;
9723
+ }
9320
9724
  app.free();
9321
9725
  };
9322
9726
  }
@@ -9379,6 +9783,396 @@ function pickingBarFor(doc, win, drawing, options) {
9379
9783
  });
9380
9784
  }
9381
9785
 
9786
+ // src/playback/block-bar.ts
9787
+ function nameOf2(diagram) {
9788
+ const title = diagram.querySelector(".mn-title")?.textContent?.trim();
9789
+ return title || accessibleName(diagram) || "Diagram";
9790
+ }
9791
+ function noteAt(node) {
9792
+ const el = node;
9793
+ if (typeof el?.closest !== "function")
9794
+ return null;
9795
+ return el.closest("[data-midi]") ?? el.closest(".mn-mark")?.querySelector("[data-midi]") ?? null;
9796
+ }
9797
+ function diagramGroup(doc, win, diagrams, options, how) {
9798
+ const items = diagrams.map(({ diagram, data }) => {
9799
+ const wrap = html(doc, "div", "mn-playable");
9800
+ diagram.parentNode?.insertBefore(wrap, diagram);
9801
+ wrap.appendChild(diagram);
9802
+ const figure = wrap.parentElement;
9803
+ const caption = figure?.classList.contains("mn-captioned") ? [...figure.children].find((c) => c.classList.contains("mn-fingering")) : undefined;
9804
+ return {
9805
+ diagram,
9806
+ data,
9807
+ wrap,
9808
+ shown: diagram,
9809
+ other: undefined,
9810
+ caption,
9811
+ name: nameOf2(diagram),
9812
+ spoken: accessibleName(diagram) ?? nameOf2(diagram)
9813
+ };
9814
+ });
9815
+ const counts = new Map;
9816
+ for (const item of items)
9817
+ counts.set(item.name, (counts.get(item.name) ?? 0) + 1);
9818
+ items.forEach((item, i) => {
9819
+ if ((counts.get(item.name) ?? 0) <= 1)
9820
+ return;
9821
+ const place = ` (${i + 1} of ${items.length})`;
9822
+ item.name += place;
9823
+ item.spoken += place;
9824
+ });
9825
+ const strums = strumsOf(options.strum);
9826
+ const settings = {
9827
+ chosen: options.sound ?? null,
9828
+ bpm: clamp(options.bpm, 20, 240, DEFAULT_SEQUENCE.bpm),
9829
+ loop: false
9830
+ };
9831
+ let selected = items[0];
9832
+ let playing = null;
9833
+ let playingItem = null;
9834
+ let lights = null;
9835
+ let inTurn = false;
9836
+ let pause = null;
9837
+ let ui = null;
9838
+ let alive = true;
9839
+ let run = 0;
9840
+ const self = {
9841
+ stop: () => stop(),
9842
+ setSound: (sound) => setSound(sound),
9843
+ onPlay: null,
9844
+ stopOthers: null,
9845
+ destroy() {
9846
+ stop();
9847
+ alive = false;
9848
+ }
9849
+ };
9850
+ const soundOf = (item) => settings.chosen ?? item.data.sound;
9851
+ const connected = () => items.some((item) => item.wrap.isConnected);
9852
+ const changed = () => ui?.changed();
9853
+ const clearPause = () => {
9854
+ if (pause)
9855
+ pause.win.clearTimeout(pause.id);
9856
+ pause = null;
9857
+ };
9858
+ const later = (item, ms, then) => {
9859
+ clearPause();
9860
+ const here = item.wrap.ownerDocument.defaultView ?? win;
9861
+ pause = {
9862
+ win: here,
9863
+ id: here.setTimeout(() => {
9864
+ pause = null;
9865
+ then();
9866
+ }, ms)
9867
+ };
9868
+ };
9869
+ const ended = (mine, then) => () => queueMicrotask(() => {
9870
+ if (mine === run)
9871
+ then();
9872
+ });
9873
+ const stop = () => {
9874
+ clearPause();
9875
+ inTurn = false;
9876
+ run++;
9877
+ playing?.stop();
9878
+ playing = null;
9879
+ playingItem = null;
9880
+ lights?.stop();
9881
+ lights = null;
9882
+ changed();
9883
+ };
9884
+ const play = (item, events, onEnd, targets) => {
9885
+ const here = item.wrap.ownerDocument.defaultView ?? win;
9886
+ const run = (player) => {
9887
+ lights?.stop();
9888
+ const follower = followNotes(here, item.shown, targets, events, startsReported(player) ? Infinity : START_WAIT);
9889
+ lights = follower;
9890
+ const onStart = () => {
9891
+ sawStart(player);
9892
+ follower.heard();
9893
+ };
9894
+ try {
9895
+ return player.play(events, {
9896
+ sound: soundOf(item),
9897
+ volume: volumeOf(options.volume),
9898
+ onEnd,
9899
+ onStart
9900
+ });
9901
+ } catch (error) {
9902
+ follower.stop();
9903
+ throw error;
9904
+ }
9905
+ };
9906
+ try {
9907
+ return run(playerFor(here, options));
9908
+ } catch {
9909
+ return run(lightFor(here));
9910
+ }
9911
+ };
9912
+ const select = (item) => {
9913
+ selected = item;
9914
+ if (how.bar && items.length > 1)
9915
+ for (const each of items) {
9916
+ each.wrap.classList.toggle("mn-selected", each === item);
9917
+ if (each === item)
9918
+ each.wrap.setAttribute("aria-current", "true");
9919
+ else
9920
+ each.wrap.removeAttribute("aria-current");
9921
+ }
9922
+ changed();
9923
+ };
9924
+ const start = (item, turn) => {
9925
+ clearPause();
9926
+ run++;
9927
+ playing?.stop();
9928
+ playing = null;
9929
+ lights?.stop();
9930
+ lights = null;
9931
+ inTurn = turn !== null;
9932
+ if (!alive || !item.wrap.isConnected)
9933
+ return stop();
9934
+ self.onPlay?.();
9935
+ const shown = item.shown;
9936
+ const pitches = shown === item.diagram ? item.data.pitches : dataOf(shown)?.pitches ?? item.data.pitches;
9937
+ const tones = tonesOf(shown);
9938
+ const sound = soundOf(item);
9939
+ const events = sequenceOf(item.data.kind, pitches, {
9940
+ sound,
9941
+ bpm: settings.bpm,
9942
+ strum: strums[sound],
9943
+ root: shown === item.diagram ? item.data.root : rootOf2(shown),
9944
+ ...tones ? { tones } : {},
9945
+ ...shown.getAttribute("data-mn-order") === "written" ? { ordered: true } : {}
9946
+ });
9947
+ playingItem = item;
9948
+ const mine = ++run;
9949
+ playing = play(item, events, ended(mine, () => {
9950
+ playing = null;
9951
+ playingItem = null;
9952
+ if (inTurn && turn !== null)
9953
+ later(item, 60000 / settings.bpm, () => next(turn + 1));
9954
+ else if (settings.loop && item.wrap.isConnected && alive)
9955
+ later(item, 0, () => start(item, null));
9956
+ else
9957
+ changed();
9958
+ }), noteTargets(shown, events, item.data.kind));
9959
+ changed();
9960
+ };
9961
+ const next = (index) => {
9962
+ if (!inTurn || !alive)
9963
+ return;
9964
+ if (!connected())
9965
+ return stop();
9966
+ if (index >= items.length) {
9967
+ if (!settings.loop)
9968
+ return stop();
9969
+ index = 0;
9970
+ }
9971
+ const item = items[index];
9972
+ select(item);
9973
+ start(item, index);
9974
+ };
9975
+ const playAll = () => {
9976
+ stop();
9977
+ inTurn = true;
9978
+ next(0);
9979
+ };
9980
+ const playNote = (item, target) => {
9981
+ const midi = Number(target.getAttribute("data-midi"));
9982
+ if (!alive || !Number.isFinite(midi))
9983
+ return;
9984
+ stop();
9985
+ select(item);
9986
+ self.onPlay?.();
9987
+ const strum = (target.getAttribute("data-mn-strum") ?? "").split(" ").filter(Boolean).map(Number).filter((n) => Number.isFinite(n));
9988
+ const sound = soundOf(item);
9989
+ const events = strum.length ? sequenceOf("chord", strum, { sound, bpm: settings.bpm, strum: strums[sound] }) : [{ midi, time: 0, duration: 1.5 }];
9990
+ const mine = ++run;
9991
+ playing = play(item, events, ended(mine, () => {
9992
+ playing = null;
9993
+ changed();
9994
+ }), events.map(() => [target]));
9995
+ changed();
9996
+ };
9997
+ const press = (item) => {
9998
+ if (!alive)
9999
+ return;
10000
+ if (playingItem === item || inTurn && selected === item)
10001
+ return stop();
10002
+ select(item);
10003
+ start(item, null);
10004
+ };
10005
+ const drawFor = (item) => {
10006
+ if (!how.bar)
10007
+ return;
10008
+ if (item.diagram.getAttribute("data-mn-redraw") === "no")
10009
+ return;
10010
+ const sound = soundOf(item);
10011
+ if (sound !== item.data.sound)
10012
+ item.other ??= redrawFor(doc, item.diagram, item.data, options.hand);
10013
+ const next = sound === item.data.sound ? item.diagram : item.other ?? item.diagram;
10014
+ if (next !== item.shown && item.shown.parentNode === item.wrap) {
10015
+ item.wrap.replaceChild(next, item.shown);
10016
+ item.shown = next;
10017
+ }
10018
+ if (item.caption)
10019
+ item.caption.hidden = item.shown !== item.diagram;
10020
+ };
10021
+ const setSound = (sound) => {
10022
+ stop();
10023
+ settings.chosen = sound;
10024
+ for (const item of items)
10025
+ drawFor(item);
10026
+ changed();
10027
+ };
10028
+ for (const item of items) {
10029
+ const { wrap } = item;
10030
+ wrap.tabIndex = 0;
10031
+ wrap.setAttribute("role", "button");
10032
+ const label = html(doc, "span", "mn-playable-name", `Play ${item.spoken}`);
10033
+ label.id = uniqueId();
10034
+ label.hidden = true;
10035
+ wrap.prepend(label);
10036
+ wrap.setAttribute("aria-labelledby", label.id);
10037
+ wrap.addEventListener("mousedown", (event) => event.stopPropagation());
10038
+ wrap.addEventListener("click", (event) => {
10039
+ const note = noteAt(event.target);
10040
+ if (note && item.shown.contains(note))
10041
+ playNote(item, note);
10042
+ else
10043
+ press(item);
10044
+ });
10045
+ wrap.addEventListener("keydown", (event) => {
10046
+ if (event.target !== wrap)
10047
+ return;
10048
+ if (event.key === " " || event.key === "Enter") {
10049
+ event.preventDefault();
10050
+ press(item);
10051
+ } else if (event.key === "Escape") {
10052
+ const here = playing !== null || inTurn;
10053
+ const others = self.stopOthers?.() ?? false;
10054
+ if (here)
10055
+ stop();
10056
+ if (here || others)
10057
+ event.preventDefault();
10058
+ }
10059
+ });
10060
+ }
10061
+ for (const item of items)
10062
+ drawFor(item);
10063
+ select(selected);
10064
+ const api = {
10065
+ get selected() {
10066
+ return selected;
10067
+ },
10068
+ get busy() {
10069
+ return playing !== null || inTurn || pause !== null;
10070
+ },
10071
+ get inTurn() {
10072
+ return inTurn;
10073
+ },
10074
+ get sound() {
10075
+ return soundOf(selected);
10076
+ },
10077
+ get bpm() {
10078
+ return settings.bpm;
10079
+ },
10080
+ set bpm(n) {
10081
+ settings.bpm = n;
10082
+ },
10083
+ strumOf: (sound) => strums[sound],
10084
+ setStrum(sound, n) {
10085
+ strums[sound] = n;
10086
+ },
10087
+ get loop() {
10088
+ return settings.loop;
10089
+ },
10090
+ set loop(on) {
10091
+ settings.loop = on;
10092
+ },
10093
+ playSelected: () => start(selected, null),
10094
+ playAll,
10095
+ stop
10096
+ };
10097
+ return {
10098
+ group: self,
10099
+ items,
10100
+ api,
10101
+ bind: (given) => {
10102
+ ui = given;
10103
+ changed();
10104
+ }
10105
+ };
10106
+ }
10107
+ function placeBar(block, last, bar) {
10108
+ if (last.parentElement?.classList.contains("mn-exercise-block")) {
10109
+ last.after(bar);
10110
+ return;
10111
+ }
10112
+ let node = last;
10113
+ while (node.parentElement && node.parentElement !== block)
10114
+ node = node.parentElement;
10115
+ if (node.parentElement === block)
10116
+ node.after(bar);
10117
+ else
10118
+ block.appendChild(bar);
10119
+ }
10120
+ function blockBarFor(doc, win, block, diagrams, options) {
10121
+ const {
10122
+ group,
10123
+ items,
10124
+ api: made,
10125
+ bind
10126
+ } = diagramGroup(doc, win, diagrams, options, {
10127
+ bar: true
10128
+ });
10129
+ const several = items.length > 1;
10130
+ const bar = playBar(doc, "mn-block-bar", "Playback");
10131
+ placeBar(block, items[items.length - 1].wrap, bar);
10132
+ const toggle = html(doc, "button", "mn-play-toggle");
10133
+ toggle.type = "button";
10134
+ toggle.addEventListener("click", () => made.busy ? made.stop() : made.playSelected());
10135
+ bar.appendChild(toggle);
10136
+ if (several) {
10137
+ const all = iconButton(doc, "mn-play-all", "Play all in turn", "all");
10138
+ all.addEventListener("click", () => made.inTurn ? made.stop() : made.playAll());
10139
+ bar.appendChild(all);
10140
+ }
10141
+ const name = several ? html(doc, "span", "mn-play-name") : null;
10142
+ if (name)
10143
+ bar.appendChild(name);
10144
+ bar.appendChild(pressedButton(doc, "mn-play-loop", "Loop", "loop", false, (on) => made.loop = on));
10145
+ const tempo = items.some((i) => i.data.kind === "scale" && i.data.pitches.length > 1) ? valueSlider(doc, "Tempo (BPM)", "BPM", 20, 240, made.bpm, (n) => made.bpm = n) : null;
10146
+ const strum = items.some((i) => i.data.kind === "chord" && i.data.pitches.length > 1) ? valueSlider(doc, "Strum (ms between strings)", "ms", 0, 200, made.strumOf(made.sound), (n) => made.setStrum(made.sound, n)) : null;
10147
+ if (tempo)
10148
+ bar.appendChild(tempo.field);
10149
+ if (strum)
10150
+ bar.appendChild(strum.field);
10151
+ const sound = choice(doc, "mn-play-sound", "Sound", ["guitar", "piano"], made.sound, { guitar: "Guitar", piano: "Piano" }, (value) => group.setSound(value === "piano" ? "piano" : "guitar"));
10152
+ bar.appendChild(sound);
10153
+ bind({
10154
+ changed() {
10155
+ const busy = made.busy;
10156
+ toggle.replaceChildren(icon(doc, busy ? "stop" : "play"));
10157
+ toggle.setAttribute("aria-label", busy ? "Stop" : "Play");
10158
+ toggle.title = busy ? "Stop" : "Play";
10159
+ const item = made.selected;
10160
+ if (name)
10161
+ name.textContent = item.name;
10162
+ bar.setAttribute("aria-label", `Play ${item.spoken}`);
10163
+ const several = item.data.pitches.length > 1;
10164
+ if (tempo)
10165
+ tempo.field.hidden = !(several && item.data.kind === "scale");
10166
+ if (strum) {
10167
+ strum.field.hidden = !(several && item.data.kind === "chord");
10168
+ strum.show(made.strumOf(made.sound));
10169
+ }
10170
+ sound.value = made.sound;
10171
+ }
10172
+ });
10173
+ return () => group.destroy();
10174
+ }
10175
+
9382
10176
  // src/playback/controls.ts
9383
10177
  var clamp = (n, lo, hi, fallback) => n === undefined || !Number.isFinite(n) ? fallback : Math.min(hi, Math.max(lo, n));
9384
10178
  function strumsOf(strum) {
@@ -9388,23 +10182,6 @@ function strumsOf(strum) {
9388
10182
  piano: clamp(given.piano, 0, 200, DEFAULT_STRUM.piano)
9389
10183
  };
9390
10184
  }
9391
- var ICONS = {
9392
- play: "M4 2.5v11l9-5.5z",
9393
- stop: "M4 4h8v8H4z",
9394
- loop: "M3 8a5 5 0 0 1 8.5-3.5L13 6V2.5M13 8a5 5 0 0 1-8.5 3.5L3 10v3.5",
9395
- volume: "M2 6h3l4-3v10l-4-3H2zM11 5.5a3.5 3.5 0 0 1 0 5"
9396
- };
9397
- function icon(doc, name) {
9398
- const root = svg(doc, "svg", {
9399
- class: `mn-play-icon mn-play-icon-${name}`,
9400
- viewBox: "0 0 16 16",
9401
- width: 12,
9402
- height: 12,
9403
- "aria-hidden": "true"
9404
- });
9405
- root.appendChild(svg(doc, "path", { d: ICONS[name] }));
9406
- return root;
9407
- }
9408
10185
  var players = new WeakMap;
9409
10186
  function lightFor(win) {
9410
10187
  let player = players.get(win);
@@ -9532,206 +10309,34 @@ function attachPlayback(el, options = {}) {
9532
10309
  if (!win)
9533
10310
  return () => {};
9534
10311
  const stops = [];
9535
- for (const diagram of [...el.querySelectorAll("svg[data-mn-pitches]")]) {
9536
- const data = dataOf(diagram);
9537
- if (!data)
9538
- continue;
9539
- stops.push(barFor(doc, win, diagram, data, options));
9540
- }
9541
10312
  for (const pattern of [...el.querySelectorAll("svg[data-mn-strum]")])
9542
10313
  stops.push(strumBarFor(doc, win, pattern, options));
9543
10314
  for (const pattern of [...el.querySelectorAll("svg[data-mn-picking]")])
9544
10315
  stops.push(pickingBarFor(doc, win, pattern, options));
9545
- for (const drawing of [...el.querySelectorAll("[data-mn-progression-play]")])
9546
- stops.push(progressionBarFor(doc, win, drawing, options));
9547
- return () => stops.forEach((stop) => stop());
9548
- }
9549
- function barFor(doc, win, diagram, data, options) {
9550
- const wrap = html(doc, "div", "mn-playable");
9551
- diagram.parentNode?.insertBefore(wrap, diagram);
9552
- wrap.appendChild(diagram);
9553
- const bar = html(doc, "div", "mn-play");
9554
- bar.addEventListener("mousedown", (event) => event.stopPropagation());
9555
- bar.setAttribute("role", "group");
9556
- const name = accessibleName(diagram);
9557
- bar.setAttribute("aria-label", name ? `Play ${name}` : "Playback");
9558
- wrap.appendChild(bar);
9559
- const firstSound = options.sound ?? data.sound;
9560
- const strums = strumsOf(options.strum);
9561
- const settings = {
9562
- sound: firstSound,
9563
- volume: clamp(options.volume, 0, 1, 0.8),
9564
- bpm: clamp(options.bpm, 20, 240, DEFAULT_SEQUENCE.bpm),
9565
- strum: strums[firstSound],
9566
- loop: false
9567
- };
9568
- let playing = null;
9569
- let lights = null;
9570
- let shown = diagram;
9571
- const pitchesShown = () => shown === diagram ? data.pitches : dataOf(shown)?.pitches ?? data.pitches;
9572
- const rootShown = () => shown === diagram ? data.root : rootOf2(shown);
9573
- const toggle = html(doc, "button", "mn-play-toggle");
9574
- toggle.type = "button";
9575
- const show = () => {
9576
- toggle.replaceChildren(icon(doc, playing ? "stop" : "play"));
9577
- toggle.setAttribute("aria-label", playing ? "Stop" : "Play");
9578
- toggle.title = playing ? "Stop" : "Play";
9579
- };
9580
- const stop = () => {
9581
- playing?.stop();
9582
- playing = null;
9583
- lights?.stop();
9584
- lights = null;
9585
- show();
9586
- };
9587
- const play = (events, onEnd, targets) => {
9588
- const here = wrap.ownerDocument.defaultView ?? win;
9589
- const run = (player) => {
9590
- lights?.stop();
9591
- const follower = followNotes(here, shown, targets, events, startsReported(player) ? Infinity : START_WAIT);
9592
- lights = follower;
9593
- const onStart = () => {
9594
- sawStart(player);
9595
- follower.heard();
9596
- };
9597
- try {
9598
- return player.play(events, {
9599
- sound: settings.sound,
9600
- volume: settings.volume,
9601
- onEnd,
9602
- onStart
9603
- });
9604
- } catch (error) {
9605
- follower.stop();
9606
- throw error;
9607
- }
9608
- };
9609
- try {
9610
- return run(playerFor(here, options));
9611
- } catch {
9612
- return run(lightFor(here));
9613
- }
9614
- };
9615
- const start = () => {
9616
- stop();
9617
- if (!wrap.isConnected)
9618
- return;
9619
- const tones = tonesOf(shown);
9620
- const events = sequenceOf(data.kind, pitchesShown(), {
9621
- ...settings,
9622
- root: rootShown(),
9623
- ...tones ? { tones } : {},
9624
- ...shown.getAttribute("data-mn-order") === "written" ? { ordered: true } : {}
9625
- });
9626
- playing = play(events, () => {
9627
- playing = null;
9628
- if (settings.loop && wrap.isConnected)
9629
- start();
9630
- else
9631
- show();
9632
- }, noteTargets(shown, events, data.kind));
9633
- show();
9634
- };
9635
- toggle.addEventListener("click", () => playing ? stop() : start());
9636
- show();
9637
- bar.appendChild(toggle);
9638
- const loop = html(doc, "button", "mn-play-loop");
9639
- loop.type = "button";
9640
- loop.appendChild(icon(doc, "loop"));
9641
- loop.title = "Loop";
9642
- loop.setAttribute("aria-label", "Loop");
9643
- loop.setAttribute("aria-pressed", "false");
9644
- loop.addEventListener("click", () => {
9645
- settings.loop = !settings.loop;
9646
- loop.setAttribute("aria-pressed", String(settings.loop));
9647
- loop.classList.toggle("mn-on", settings.loop);
9648
- });
9649
- bar.appendChild(loop);
9650
- const slider = (label, min, max, value, set, mark) => {
9651
- const field = html(doc, "label", "mn-play-field");
9652
- field.title = `${label}: ${value}`;
9653
- const tag = html(doc, "span", "mn-play-label");
9654
- tag.setAttribute("aria-hidden", "true");
9655
- tag.append(mark);
9656
- const input = html(doc, "input");
9657
- input.type = "range";
9658
- input.min = String(min);
9659
- input.max = String(max);
9660
- input.value = String(value);
9661
- input.setAttribute("aria-label", label);
9662
- input.addEventListener("input", () => {
9663
- set(Number(input.value));
9664
- field.title = `${label}: ${input.value}`;
10316
+ const timed = [...el.querySelectorAll("[data-mn-progression-play]")];
10317
+ const byBlock = new Map;
10318
+ const byDrawing = new Map;
10319
+ for (const diagram of [...el.querySelectorAll("svg[data-mn-pitches]")]) {
10320
+ const data = dataOf(diagram);
10321
+ if (!data)
10322
+ continue;
10323
+ const drawing = timed.find((t) => t.contains(diagram));
10324
+ const key = drawing ?? diagram.closest(".mn-block") ?? el;
10325
+ const map = drawing ? byDrawing : byBlock;
10326
+ map.set(key, [...map.get(key) ?? [], { diagram, data }]);
10327
+ }
10328
+ for (const [block, diagrams] of byBlock)
10329
+ stops.push(blockBarFor(doc, win, block, diagrams, options));
10330
+ for (const drawing of timed) {
10331
+ const diagrams = byDrawing.get(drawing);
10332
+ const group = diagrams?.length ? diagramGroup(doc, win, diagrams, options, { bar: false }).group : null;
10333
+ const bar = progressionBarFor(doc, win, drawing, options, group);
10334
+ stops.push(() => {
10335
+ bar();
10336
+ group?.destroy();
9665
10337
  });
9666
- field.append(tag, input);
9667
- bar.appendChild(field);
9668
- return (n) => {
9669
- input.value = String(n);
9670
- field.title = `${label}: ${n}`;
9671
- };
9672
- };
9673
- let showStrum = null;
9674
- if (data.pitches.length > 1) {
9675
- if (data.kind === "scale")
9676
- slider("Tempo (BPM)", 20, 240, settings.bpm, (n) => settings.bpm = n, "♩");
9677
- else
9678
- showStrum = slider("Strum (ms between strings)", 0, 200, settings.strum, (n) => {
9679
- settings.strum = n;
9680
- strums[settings.sound] = n;
9681
- }, "≋");
9682
- }
9683
- slider("Volume", 0, 100, Math.round(settings.volume * 100), (n) => settings.volume = n / 100, icon(doc, "volume"));
9684
- const sound = html(doc, "select", "mn-play-sound");
9685
- sound.setAttribute("aria-label", "Sound");
9686
- for (const value of ["guitar", "piano"]) {
9687
- const option = html(doc, "option", undefined, value === "guitar" ? "Guitar" : "Piano");
9688
- option.value = value;
9689
- option.selected = value === settings.sound;
9690
- sound.appendChild(option);
9691
10338
  }
9692
- let other;
9693
- const redraws = diagram.getAttribute("data-mn-redraw") !== "no";
9694
- const drawFor = () => {
9695
- if (!redraws)
9696
- return;
9697
- if (settings.sound !== data.sound)
9698
- other ??= redrawFor(doc, diagram, data, options.hand);
9699
- const next = settings.sound === data.sound ? diagram : other ?? diagram;
9700
- if (next !== shown && shown.parentNode === wrap) {
9701
- wrap.replaceChild(next, shown);
9702
- shown = next;
9703
- }
9704
- };
9705
- sound.addEventListener("change", () => {
9706
- stop();
9707
- settings.sound = sound.value === "piano" ? "piano" : "guitar";
9708
- settings.strum = strums[settings.sound];
9709
- showStrum?.(settings.strum);
9710
- drawFor();
9711
- });
9712
- drawFor();
9713
- bar.appendChild(sound);
9714
- wrap.addEventListener("click", (event) => {
9715
- const node = event.target;
9716
- const target = typeof node?.closest === "function" ? node.closest("[data-midi]") ?? node.closest(".mn-mark")?.querySelector("[data-midi]") ?? null : null;
9717
- const midi = Number(target?.getAttribute("data-midi"));
9718
- if (!target || !Number.isFinite(midi))
9719
- return;
9720
- stop();
9721
- const strum = (target.getAttribute("data-mn-strum") ?? "").split(" ").filter(Boolean).map(Number).filter((n) => Number.isFinite(n));
9722
- const events = strum.length ? sequenceOf("chord", strum, settings) : [{ midi, time: 0, duration: 1.5 }];
9723
- playing = play(events, () => {
9724
- playing = null;
9725
- show();
9726
- }, events.map(() => [target]));
9727
- show();
9728
- });
9729
- wrap.addEventListener("pointerdown", (event) => {
9730
- if (event.pointerType !== "touch" || bar.contains(event.target))
9731
- return;
9732
- wrap.classList.toggle("mn-play-open");
9733
- });
9734
- return stop;
10339
+ return () => stops.forEach((stop) => stop());
9735
10340
  }
9736
10341
 
9737
10342
  // src/blocks/properties.ts
@@ -9931,7 +10536,7 @@ function blockFromProperties(language, properties, options = {}) {
9931
10536
  }
9932
10537
 
9933
10538
  // src/chord/triads.ts
9934
- import { Key as Key3 } from "tonal";
10539
+ import { Key as Key4 } from "tonal";
9935
10540
  var inversionName = (inversion) => inversion === 0 ? "root position" : inversion === 1 ? "1st inversion" : "2nd inversion";
9936
10541
  function triadVoicings(symbol, options) {
9937
10542
  const tuning = options.tuning ?? STANDARD_TUNING;
@@ -9984,7 +10589,7 @@ function keyTriads(key, options) {
9984
10589
  const parsed = parseKey(key);
9985
10590
  if (!parsed)
9986
10591
  return null;
9987
- const scale = parsed.minor ? Key3.minorKey(parsed.tonic).natural : Key3.majorKey(parsed.tonic);
10592
+ const scale = parsed.minor ? Key4.minorKey(parsed.tonic).natural : Key4.majorKey(parsed.tonic);
9988
10593
  if (!scale.triads.length)
9989
10594
  return null;
9990
10595
  const inversion = options.inversion ?? 0;
@@ -10042,7 +10647,7 @@ function renderBlock(language, source, host, given = {}) {
10042
10647
  try {
10043
10648
  if ((language === "fretboard" || language === "keyboard") && !splitParts(text))
10044
10649
  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;
10650
+ 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
10651
  } catch (e) {
10047
10652
  return failed(el, host, language, messageOf(e));
10048
10653
  }
@@ -10217,6 +10822,39 @@ function positionParts(language, source) {
10217
10822
  return [...header.length ? [header.join(`
10218
10823
  `)] : [], ...diagrams];
10219
10824
  }
10825
+ function handParts(language, source) {
10826
+ if (language !== "keyboard")
10827
+ return null;
10828
+ let block;
10829
+ try {
10830
+ block = parseBlockSource(source);
10831
+ } catch {
10832
+ return null;
10833
+ }
10834
+ const fingering = block.fields.get("fingering");
10835
+ if (fingering === undefined || !isBothHandsFingering(fingering))
10836
+ return null;
10837
+ block = scalesForBlock(block);
10838
+ const set = noteSetOf(block);
10839
+ if (set.root === null || set.list || set.pitches || !set.scaleType) {
10840
+ throw new Error(AUTO_FINGERING_NEEDS_SCALE);
10841
+ }
10842
+ if (!standardScaleFingering(set.root, set.scaleType, "right")) {
10843
+ throw new Error(autoFingeringUnknown(set.title));
10844
+ }
10845
+ const title = block.fields.get("title")?.trim();
10846
+ const others = [...block.fields].filter(([key]) => !["fingering", "title", "columns"].includes(key)).map(([key, value]) => `${key}: ${value}`);
10847
+ const head = block.head ? [block.head] : [];
10848
+ const hand = (side) => [
10849
+ ...head,
10850
+ ...others,
10851
+ `fingering: auto ${side}`,
10852
+ ...title ? [`title: ${title}, ${side} hand`] : []
10853
+ ].join(`
10854
+ `);
10855
+ const columns = block.fields.get("columns")?.trim() || "1";
10856
+ return [`columns: ${columns}`, hand("right"), hand("left")];
10857
+ }
10220
10858
  function capoIn(block) {
10221
10859
  const text = block.fields.get("capo");
10222
10860
  if (!text?.trim())
@@ -10859,5 +11497,5 @@ export {
10859
11497
  renderAll
10860
11498
  };
10861
11499
 
10862
- //# debugId=FDD304C0A12A289A64756E2164756E21
11500
+ //# debugId=E4744F393E5C5B7564756E2164756E21
10863
11501
  //# sourceMappingURL=index.js.map