@dsebastien/music-notation 0.5.3 → 0.7.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.
package/dist/index.js CHANGED
@@ -214,13 +214,20 @@ function renderGuitarDiagram(doc, voicing, options = {}) {
214
214
  const tuning = options.tuning ?? (strings === 6 ? STANDARD_TUNING : undefined);
215
215
  voicing.frets.forEach((fret, s) => {
216
216
  const mark = frame.at(across(s), -8);
217
+ const string = strings - s;
217
218
  if (fret === null) {
218
- root.appendChild(svgLabel(doc, "×", mark, "mn-muted"));
219
+ const muted = svgLabel(doc, "×", mark, "mn-muted");
220
+ muted.setAttribute("data-mn-string", String(string));
221
+ root.appendChild(muted);
219
222
  return;
220
223
  }
221
224
  const open = tuning?.[s];
222
225
  const isRoot = options.root !== undefined && options.root !== null && open !== undefined && (open + fret) % 12 === options.root;
223
- const midi = open !== undefined ? { "data-midi": open + fret } : {};
226
+ const midi = {
227
+ "data-mn-string": string,
228
+ "data-mn-fret": fret,
229
+ ...open !== undefined ? { "data-midi": open + fret } : {}
230
+ };
224
231
  if (fret === 0) {
225
232
  const [cx, cy] = mark;
226
233
  root.appendChild(svg(doc, "circle", {
@@ -522,7 +529,7 @@ function renderChart(doc, song, options = {}) {
522
529
  }
523
530
 
524
531
  // src/theory/note-set.ts
525
- import { Chord, Scale as Scale2 } from "tonal";
532
+ import { Chord, Interval, Scale as Scale2 } from "tonal";
526
533
 
527
534
  // src/theory/suffix.ts
528
535
  var CANONICAL = new Map([
@@ -738,7 +745,26 @@ function scaleNoteSet(name) {
738
745
  set.scaleType = scale.type;
739
746
  return set;
740
747
  }
741
- function listNoteSet(text) {
748
+ function rootNameOf(text) {
749
+ const name = text.trim().replace(/-?\d$/, "").replace(/♯/g, "#").replace(/♭/g, "b");
750
+ if (chromaOf(name) === null)
751
+ return null;
752
+ return name[0].toUpperCase() + name.slice(1);
753
+ }
754
+ var PLAIN_INTERVALS = ["1P", "2m", "2M", "3m", "3M", "4P", "5d", "5P", "6m", "6M", "7m", "7M"];
755
+ function intervalFrom(root, name) {
756
+ const from = rootNameOf(root);
757
+ const to = rootNameOf(name);
758
+ if (from === null || to === null)
759
+ return null;
760
+ const semitones = (chromaOf(to) - chromaOf(from) + 12) % 12;
761
+ if (semitones === 0)
762
+ return "1P";
763
+ const spelled = Interval.distance(from, to);
764
+ const m = /^(\d+)([PMmdA]+)$/.exec(spelled);
765
+ return m && m[1] !== "1" && m[1] !== "8" ? spelled : PLAIN_INTERVALS[semitones];
766
+ }
767
+ function listNoteSet(text, root) {
742
768
  const tokens = text.split(/[\s,]+/).filter(Boolean);
743
769
  if (!tokens.length)
744
770
  return null;
@@ -747,8 +773,21 @@ function listNoteSet(text) {
747
773
  if (!withOctaves && names.some((n) => chromaOf(n) === null))
748
774
  return null;
749
775
  const set = fromNames(tokens.join(" "), names, null);
750
- if (set && withOctaves)
776
+ if (!set)
777
+ return null;
778
+ set.list = true;
779
+ if (withOctaves)
751
780
  set.pitches = tokens.map((t) => midiOf(t));
781
+ if (root === undefined)
782
+ return set;
783
+ const rootName = rootNameOf(root);
784
+ if (rootName === null)
785
+ return null;
786
+ set.root = chromaOf(rootName);
787
+ for (const member of set.members) {
788
+ member.interval = intervalFrom(rootName, member.name);
789
+ member.degree = Number(/^\d+/.exec(member.interval ?? "")?.[0] ?? 1);
790
+ }
752
791
  return set;
753
792
  }
754
793
 
@@ -827,12 +866,30 @@ function renderFretboard(doc, set, options = {}) {
827
866
  const hidden = options.strings !== undefined && !options.strings.includes(s);
828
867
  if (!member || hidden || played && !played.has(`${s}:${fret}`)) {
829
868
  if (!member && !hidden && options.marks?.ghosts?.has(chroma)) {
830
- root.appendChild(svg(doc, "circle", { class: "mn-ghost", cx, cy, r: 7 }));
869
+ root.appendChild(svg(doc, "circle", {
870
+ class: "mn-ghost",
871
+ cx,
872
+ cy,
873
+ r: 7,
874
+ "data-mn-ghost-string": strings - s,
875
+ "data-mn-fret": fret,
876
+ "data-mn-note": options.marks?.ghostNames?.get(chroma) ?? nameOf(chroma, set.preferFlats),
877
+ "data-mn-pitch": open + fret
878
+ }));
831
879
  }
832
880
  continue;
833
881
  }
834
882
  const cls = `mn-dot${markClasses(set, member.chroma, options.marks)}`;
835
- root.appendChild(svg(doc, "circle", { class: cls, cx, cy, r: 8, "data-midi": open + fret }));
883
+ root.appendChild(svg(doc, "circle", {
884
+ class: cls,
885
+ cx,
886
+ cy,
887
+ r: 8,
888
+ "data-midi": open + fret,
889
+ "data-mn-string": strings - s,
890
+ "data-mn-fret": fret,
891
+ "data-mn-note": member.name
892
+ }));
836
893
  sounding.add(open + fret);
837
894
  const text = labelOf(member, label);
838
895
  if (text)
@@ -842,8 +899,10 @@ function renderFretboard(doc, set, options = {}) {
842
899
  root.setAttribute("data-mn-pitches", [...sounding].sort((a, b) => a - b).join(" "));
843
900
  root.setAttribute("data-mn-play", "scale");
844
901
  root.setAttribute("data-mn-sound", "guitar");
845
- if (set.root !== null)
846
- root.setAttribute("data-mn-root", String(set.root));
902
+ root.setAttribute("data-mn-set", set.title);
903
+ root.setAttribute("data-mn-labels", label);
904
+ root.setAttribute("data-mn-orientation", orientation);
905
+ root.setAttribute("data-mn-frets", `${from}-${to}`);
847
906
  return root;
848
907
  }
849
908
 
@@ -976,7 +1035,8 @@ function renderKeyboard(doc, set, options = {}) {
976
1035
  class: keyClass(midi, false),
977
1036
  ...key(along, WHITE_W, WHITE_H),
978
1037
  rx: 2,
979
- "data-midi": midi
1038
+ "data-midi": midi,
1039
+ "data-mn-note": memberOf(set, midi)?.name ?? (options.marks?.ghosts?.has((midi % 12 + 12) % 12) ? options.marks?.ghostNames?.get((midi % 12 + 12) % 12) ?? nameOf(midi, set.preferFlats) : undefined)
980
1040
  }));
981
1041
  caption(midi, at(along + WHITE_W / 2, WHITE_H - 13), false);
982
1042
  });
@@ -989,7 +1049,8 @@ function renderKeyboard(doc, set, options = {}) {
989
1049
  class: keyClass(black, true),
990
1050
  ...key(along, BLACK_W, BLACK_H),
991
1051
  rx: 2,
992
- "data-midi": black
1052
+ "data-midi": black,
1053
+ "data-mn-note": memberOf(set, black)?.name ?? (options.marks?.ghosts?.has((black % 12 + 12) % 12) ? options.marks?.ghostNames?.get((black % 12 + 12) % 12) ?? nameOf(black, set.preferFlats) : undefined)
993
1054
  }));
994
1055
  caption(black, at(along + BLACK_W / 2, BLACK_H - 13), true);
995
1056
  });
@@ -999,7 +1060,9 @@ function renderKeyboard(doc, set, options = {}) {
999
1060
  continue;
1000
1061
  const whitesBelow = whites.filter((w) => w < midi).length;
1001
1062
  const along = isBlack(midi) ? whitesBelow * WHITE_W : whitesBelow * WHITE_W + WHITE_W / 2;
1002
- root.appendChild(svgLabel(doc, finger, at(along, WHITE_H + FINGER_ROW / 2 - 1), "mn-key-finger"));
1063
+ const label = svgLabel(doc, finger, at(along, WHITE_H + FINGER_ROW / 2 - 1), "mn-key-finger");
1064
+ label.setAttribute("data-mn-key", String(midi));
1065
+ root.appendChild(label);
1003
1066
  }
1004
1067
  }
1005
1068
  const played = [];
@@ -1009,8 +1072,9 @@ function renderKeyboard(doc, set, options = {}) {
1009
1072
  root.setAttribute("data-mn-pitches", played.join(" "));
1010
1073
  root.setAttribute("data-mn-play", options.playAs ?? "scale");
1011
1074
  root.setAttribute("data-mn-sound", "piano");
1012
- if (set.root !== null)
1013
- root.setAttribute("data-mn-root", String(set.root));
1075
+ root.setAttribute("data-mn-set", set.title);
1076
+ root.setAttribute("data-mn-labels", label);
1077
+ root.setAttribute("data-mn-orientation", vertical ? "vertical" : "horizontal");
1014
1078
  return root;
1015
1079
  }
1016
1080
 
@@ -1283,8 +1347,16 @@ function namesOf(pitches, flats) {
1283
1347
  }
1284
1348
  return names;
1285
1349
  }
1350
+ function isStepwiseRun(pitches) {
1351
+ let sorted = [...new Set(pitches)].sort((a, b) => a - b);
1352
+ if (sorted.length > 1 && sorted[sorted.length - 1] - sorted[0] === 12)
1353
+ sorted = sorted.slice(0, -1);
1354
+ if (sorted.length < 5 || sorted[sorted.length - 1] - sorted[0] >= 12)
1355
+ return false;
1356
+ return sorted.every((pitch, i) => i === 0 || pitch - sorted[i - 1] <= 2);
1357
+ }
1286
1358
  function detectChordFromPitches(pitches) {
1287
- if (pitches.length < 2)
1359
+ if (pitches.length < 2 || isStepwiseRun(pitches))
1288
1360
  return null;
1289
1361
  const readings = new Set;
1290
1362
  for (const flats of [false, true]) {
@@ -1366,6 +1438,29 @@ function noteSetOf(block) {
1366
1438
  const scale = block.fields.get("scale");
1367
1439
  const chord = block.fields.get("chord");
1368
1440
  const notes = block.fields.get("notes");
1441
+ const root = block.fields.get("root")?.trim() || undefined;
1442
+ if (root !== undefined) {
1443
+ if (scale !== undefined)
1444
+ throw rootNotForList("a scale");
1445
+ if (chord !== undefined)
1446
+ throw rootNotForList("a chord");
1447
+ if (rootNameOf(root) === null) {
1448
+ throw new Error(`Invalid root "${root}": use a note name, e.g. root: C`);
1449
+ }
1450
+ if (notes !== undefined)
1451
+ return orFail(listNoteSet(notes, root), `Invalid notes "${notes}"`);
1452
+ if (block.head) {
1453
+ const list = listNoteSet(block.head, root);
1454
+ if (list)
1455
+ return list;
1456
+ if (scaleNoteSet(block.head))
1457
+ throw rootNotForList("a scale");
1458
+ if (chordNoteSet(block.head))
1459
+ throw rootNotForList("a chord");
1460
+ throw new Error(`"${block.head}" is not a list of notes: use e.g. notes: C Eb G`);
1461
+ }
1462
+ throw new Error("Add the notes for the root: e.g. notes: C Eb G");
1463
+ }
1369
1464
  if (scale !== undefined) {
1370
1465
  if (isScaleWithoutRoot(scale))
1371
1466
  throw new Error(`Add a root note: C ${scale.trim()}`);
@@ -1385,6 +1480,7 @@ function noteSetOf(block) {
1385
1480
  }
1386
1481
  throw new Error('Add "scale:", "chord:" or "notes:"');
1387
1482
  }
1483
+ var rootNotForList = (what) => new Error(`root only applies to lists of notes (notes: C E G): ${what} has its own root`);
1388
1484
  function labelField(block, fallback, fingers = false) {
1389
1485
  const value = block.fields.get("labels")?.toLowerCase();
1390
1486
  if (value === undefined)
@@ -1412,7 +1508,7 @@ function marksOf(block, set) {
1412
1508
  }
1413
1509
  } else if (highlight.toLowerCase() !== "none" && highlight !== "") {
1414
1510
  if (set.members.every((m) => m.interval === null)) {
1415
- throw new Error("highlight needs a scale or a chord: a list of notes has no intervals");
1511
+ throw new Error("highlight needs a scale, a chord or a root: a list of notes has no intervals (add e.g. root: C)");
1416
1512
  }
1417
1513
  const labels = highlight.replace(/♭/g, "b").replace(/♯/g, "#").split(/[\s,]+/).filter(Boolean);
1418
1514
  for (const label of labels) {
@@ -1428,12 +1524,13 @@ function marksOf(block, set) {
1428
1524
  const compare = block.fields.get("compare")?.trim();
1429
1525
  if (compare) {
1430
1526
  const tonic = Scale3.get(scaleName(compare)).tonic;
1431
- const root = set.members[0]?.name ?? "";
1527
+ const root = rootNameOf(block.fields.get("root") ?? "") ?? set.members[0]?.name ?? "";
1432
1528
  const parent = orFail(scaleNoteSet(tonic ? compare : `${root} ${compare}`), `Unknown scale "${compare}" to compare with: use e.g. compare: major`);
1433
1529
  const own = new Set(set.members.map((m) => m.chroma));
1434
1530
  const theirs = new Set(parent.members.map((m) => m.chroma));
1435
1531
  marks.different = new Set([...own].filter((c) => !theirs.has(c)));
1436
1532
  marks.ghosts = new Set([...theirs].filter((c) => !own.has(c)));
1533
+ marks.ghostNames = new Map(parent.members.filter((m) => !own.has(m.chroma)).map((m) => [m.chroma, m.name]));
1437
1534
  }
1438
1535
  return marks;
1439
1536
  }
@@ -1481,23 +1578,61 @@ function pentatonicOf(set) {
1481
1578
  }
1482
1579
  return null;
1483
1580
  }
1484
- function scalePosition(set, tuning, system, n) {
1581
+ var MAX_FRET = 36;
1582
+ var isMajorPentatonic = (set) => set.members.map((m) => m.interval).join(" ") === MAJOR_PENTATONIC.join(" ");
1583
+ var relativeMinorOf = (set) => isMajorPentatonic(set) ? set.members[4].name : undefined;
1584
+ function numberingOf(text, set, system) {
1585
+ const value = text?.trim().toLowerCase().replace(/\s+/g, " ");
1586
+ if (!value)
1587
+ return "root";
1588
+ if (value !== "minor" && value !== "relative minor") {
1589
+ throw new Error(`numbering: use minor (positions from the relative minor), got "${text}"`);
1590
+ }
1591
+ if (!isMajorPentatonic(set)) {
1592
+ throw new Error(`numbering: minor is for major pentatonic positions (e.g. A major pentatonic), not ${set.title}`);
1593
+ }
1594
+ if (system === "caged") {
1595
+ throw new Error("numbering: minor numbers boxes and 3nps positions, not CAGED shapes");
1596
+ }
1597
+ return "minor";
1598
+ }
1599
+ var fromRoot = (set, system, n, numbering) => numbering === "minor" && system !== "caged" && isMajorPentatonic(set) && n >= 1 && n <= positionCount(set, system) ? (n + 3) % positionCount(set, system) + 1 : n;
1600
+ var lowestFret = (cells) => Math.min(...cells.map((c) => c.fret));
1601
+ var highestFret = (cells) => Math.max(...cells.map((c) => c.fret));
1602
+ function scalePosition(set, tuning, system, n, options = {}) {
1603
+ const octaves = octavesOf(set, tuning, system, fromRoot(set, system, n, options.numbering));
1604
+ const within = options.within;
1605
+ const inside = within ? octaves.find((cells) => lowestFret(cells) >= within[0] && highestFret(cells) <= within[1]) : undefined;
1606
+ return inside ?? octaves[0] ?? null;
1607
+ }
1608
+ function neckPositions(set, tuning, system, numbering = "root") {
1609
+ let floor = 0;
1610
+ return Array.from({ length: positionCount(set, system) }, (_, i) => {
1611
+ const octaves = octavesOf(set, tuning, system, fromRoot(set, system, i + 1, numbering));
1612
+ const cells = octaves.find((c) => lowestFret(c) >= floor && highestFret(c) <= MAX_FRET) ?? octaves[0] ?? null;
1613
+ if (cells)
1614
+ floor = lowestFret(cells);
1615
+ return cells;
1616
+ });
1617
+ }
1618
+ function octavesOf(set, tuning, system, n) {
1485
1619
  if (set.root === null || n < 1 || n > positionCount(set, system))
1486
- return null;
1620
+ return [];
1487
1621
  const open = tuning[0];
1488
1622
  const chromas = chromasOf(set);
1489
1623
  const notes = tuning.length * 3;
1490
1624
  const nps = system === "3nps" || system === "caged" && chromas.length !== 5 && !pentatonicOf(set);
1491
1625
  const pentatonic = chromas.length === 5 ? chromas : pentatonicOf(set);
1492
1626
  if (!nps && !pentatonic)
1493
- return null;
1627
+ return [];
1494
1628
  const startChroma = nps ? chromas[(n - 1) % chromas.length] : pentatonic[(n - 1) % 5];
1495
- for (let start = fretOn(open, startChroma, 0);start <= 36; start += 12) {
1629
+ const out = [];
1630
+ for (let start = fretOn(open, startChroma, 0);start <= MAX_FRET; start += 12) {
1496
1631
  const cells = nps ? fill(ascending(chromas, open + start, notes), tuning, 3) : withOther(fill(ascending(pentatonic, open + start, tuning.length * 2), tuning, 2), system === "caged" && chromas.length !== 5 ? chromas : null, tuning);
1497
1632
  if (cells && cells.every((c) => c.fret >= 0))
1498
- return cells;
1633
+ out.push(cells);
1499
1634
  }
1500
- return null;
1635
+ return out;
1501
1636
  }
1502
1637
  function withOther(box, chromas, tuning) {
1503
1638
  if (box.length < tuning.length * 2)
@@ -1555,6 +1690,7 @@ var SHARED_KEYS = {
1555
1690
  "compare",
1556
1691
  "position",
1557
1692
  "shape",
1693
+ "numbering",
1558
1694
  "strings"
1559
1695
  ]
1560
1696
  };
@@ -1636,7 +1772,10 @@ function pianoPitches(symbol) {
1636
1772
  pitches.unshift(48 + bass);
1637
1773
  return { ...set, pitches };
1638
1774
  }
1775
+ var ROOT_FOR_LISTS_ONLY = "root only applies to lists of notes on fretboards and keyboards (notes: C E G with root: C): a chord has its own root";
1639
1776
  var renderChord = (doc, block, options) => {
1777
+ if (block.fields.get("root")?.trim())
1778
+ throw new Error(ROOT_FOR_LISTS_ONLY);
1640
1779
  const short = shorthand(block.head);
1641
1780
  const name = field(block, "name");
1642
1781
  const written = field(block, "symbol", "chord") ?? short.symbol;
@@ -1681,14 +1820,14 @@ var renderChord = (doc, block, options) => {
1681
1820
  const fingers = fingering ? fingersFor(set.pitches, fingering) : new Map;
1682
1821
  const range = field(block, "range");
1683
1822
  handOf(block, options);
1684
- return renderKeyboard(doc, set, {
1823
+ return named(renderKeyboard(doc, set, {
1685
1824
  playAs: "chord",
1686
1825
  title,
1687
1826
  label: labelField(block, fingers.size ? "fingers" : "notes", fingers.size > 0),
1688
1827
  fingers,
1689
1828
  range: keyRange(range ? rangeOf(range) : keyRangeOf(set)),
1690
1829
  orientation: orientationOf(block, options.orientation?.keyboard)
1691
- });
1830
+ }), symbol);
1692
1831
  }
1693
1832
  if (instrument && instrument !== "guitar" && !field(block, "tuning")) {
1694
1833
  throw new Error(`Unknown instrument "${instrument}": use guitar or piano, or give a tuning`);
@@ -1746,7 +1885,7 @@ var renderChord = (doc, block, options) => {
1746
1885
  const anchors = marked("anchors");
1747
1886
  const guides = marked("guides");
1748
1887
  const marks = voicing.frets.map((_, s) => anchors.includes(s) ? "anchor" : guides.includes(s) ? "guide" : null);
1749
- return renderGuitarDiagram(doc, voicing, {
1888
+ return named(renderGuitarDiagram(doc, voicing, {
1750
1889
  title,
1751
1890
  root,
1752
1891
  tuning,
@@ -1754,8 +1893,13 @@ var renderChord = (doc, block, options) => {
1754
1893
  ...anchors.length || guides.length ? { marks } : {},
1755
1894
  orientation: orientationOf(block, options.orientation?.chord),
1756
1895
  hand: handOf(block, options)
1757
- });
1896
+ }), symbol);
1758
1897
  };
1898
+ function named(el, symbol) {
1899
+ if (symbol)
1900
+ el.setAttribute("data-mn-chord", symbol);
1901
+ return el;
1902
+ }
1759
1903
  function dotLabels(text, symbol, voicing, tuning) {
1760
1904
  const value = text?.toLowerCase();
1761
1905
  if (value === undefined || value === "fingers")
@@ -1794,7 +1938,7 @@ var renderKeyboardBlock = (doc, block, options) => {
1794
1938
  const fingering = field(block, "fingering");
1795
1939
  const keys = range ? rangeOf(range) : undefined;
1796
1940
  let fingers;
1797
- if (fingering && set.root !== null && !set.pitches) {
1941
+ if (fingering && set.root !== null && !set.list && !set.pitches) {
1798
1942
  let start = 60 + set.root;
1799
1943
  if (keys) {
1800
1944
  const first = keys[0] + ((set.root - keys[0]) % 12 + 12) % 12;
@@ -1807,13 +1951,40 @@ var renderKeyboardBlock = (doc, block, options) => {
1807
1951
  fingers = fingersFor(octave, fingering);
1808
1952
  if (!keys)
1809
1953
  set.pitches = octave;
1954
+ } else if (fingering && set.list) {
1955
+ const fingerList = fingering.split(/[\s,-]+/).filter(Boolean);
1956
+ let pitches = set.pitches;
1957
+ if (!pitches) {
1958
+ const chromas = set.title.split(/[\s,]+/).filter(Boolean).map((name) => chromaOf(name) ?? 0);
1959
+ const first = chromas[0] ?? 0;
1960
+ let at = keys ? keys[0] + ((first - keys[0]) % 12 + 12) % 12 : 60 + first;
1961
+ pitches = chromas.map((chroma, i) => {
1962
+ if (i > 0) {
1963
+ const up = ((chroma - at) % 12 + 12) % 12;
1964
+ at += up === 0 ? 12 : up <= 6 ? up : up - 12;
1965
+ }
1966
+ return at;
1967
+ });
1968
+ if (!keys)
1969
+ set.pitches = pitches;
1970
+ }
1971
+ if (fingerList.length !== pitches.length) {
1972
+ throw new Error(`fingering has ${fingerList.length} fingers for ${pitches.length} notes: one finger per note, in the order written`);
1973
+ }
1974
+ if (new Set(pitches).size !== pitches.length) {
1975
+ throw new Error("A key is listed twice: one finger per key");
1976
+ }
1977
+ if (keys && pitches.some((midi) => midi < keys[0] || midi > keys[1])) {
1978
+ throw new Error("The fingered notes go past the range: widen range: or leave it out");
1979
+ }
1980
+ fingers = new Map(pitches.map((midi, i) => [midi, fingerList[i]]));
1810
1981
  }
1811
1982
  return renderKeyboard(doc, set, {
1812
- playAs: !set.scaleType && set.root !== null ? "chord" : "scale",
1983
+ playAs: !set.scaleType && !set.list && set.root !== null ? "chord" : "scale",
1813
1984
  title: field(block, "title"),
1814
1985
  label: labelField(block, fingers ? "fingers" : "notes", fingers !== undefined),
1815
1986
  fingers,
1816
- range: keyRange(keys ? keys : fingers && set.pitches ? [set.pitches[0], set.pitches[set.pitches.length - 1]] : keyRangeOf(set)),
1987
+ range: keyRange(keys ? keys : fingers && set.pitches ? [Math.min(...set.pitches), Math.max(...set.pitches)] : keyRangeOf(set)),
1817
1988
  orientation: orientationOf(block, options.orientation?.keyboard),
1818
1989
  marks: marksOf(block, set)
1819
1990
  });
@@ -1823,19 +1994,30 @@ var renderFretboardBlock = (doc, block, options) => {
1823
1994
  const at = positionOf(field(block, "position"), field(block, "shape"));
1824
1995
  const fretsText = field(block, "frets");
1825
1996
  const frets = fretsText ? orFail(parseRange(fretsText), `Invalid frets "${fretsText}": use e.g. 5-8`) : undefined;
1826
- if (frets && frets[1] > 36)
1827
- throw new Error("Frets go up to 36");
1997
+ if (frets && frets[1] > MAX_FRET)
1998
+ throw new Error(`Frets go up to ${MAX_FRET}`);
1828
1999
  const tuningText = field(block, "tuning");
1829
2000
  const tuning = tuningText ? tuningOf(tuningText) : undefined;
1830
2001
  let cells;
2002
+ if (!at && field(block, "numbering")) {
2003
+ throw new Error("numbering goes with a position: e.g. position: 1 or positions: all");
2004
+ }
1831
2005
  if (at) {
1832
- if (set.root === null)
2006
+ if (set.root === null || set.list) {
1833
2007
  throw new Error("Positions need a scale: e.g. scale: A minor");
2008
+ }
1834
2009
  if (at.system === "box" && set.members.length !== 5)
1835
2010
  at.system = "caged";
1836
2011
  const count = positionCount(set, at.system);
1837
2012
  const named = { box: "box", caged: "CAGED", "3nps": "3nps" }[at.system];
1838
- cells = orFail(scalePosition(set, tuning ?? STANDARD_TUNING, at.system, at.n), `${set.title} has ${count} ${named} positions: use position 1 to ${count}`);
2013
+ const numbering = numberingOf(field(block, "numbering"), set, at.system);
2014
+ cells = orFail(scalePosition(set, tuning ?? STANDARD_TUNING, at.system, at.n, {
2015
+ within: frets,
2016
+ numbering
2017
+ }), `${set.title} has ${count} ${named} positions: use position 1 to ${count}`);
2018
+ if (frets && cells.some((cell) => cell.fret < frets[0] || cell.fret > frets[1])) {
2019
+ throw new Error(`${set.title}, position ${at.n} doesn't fit in frets ${frets[0]}-${frets[1]}: widen frets: or leave it out`);
2020
+ }
1839
2021
  }
1840
2022
  const stringsText = field(block, "strings");
1841
2023
  const count = (tuning ?? STANDARD_TUNING).length;
@@ -1869,7 +2051,7 @@ var RENDERERS = {
1869
2051
  // src/playback/player.ts
1870
2052
  var DEFAULT_SEQUENCE = { bpm: 90, strum: 40 };
1871
2053
  var RING = 2.5;
1872
- function sequenceOf(kind, pitches, options = DEFAULT_SEQUENCE, root = null) {
2054
+ function sequenceOf(kind, pitches, options = DEFAULT_SEQUENCE) {
1873
2055
  if (!pitches.length)
1874
2056
  return [];
1875
2057
  if (kind === "chord") {
@@ -1883,12 +2065,7 @@ function sequenceOf(kind, pitches, options = DEFAULT_SEQUENCE, root = null) {
1883
2065
  }
1884
2066
  const bpm = Number.isFinite(options.bpm) ? options.bpm : DEFAULT_SEQUENCE.bpm;
1885
2067
  const beat = 60 / Math.min(240, Math.max(20, bpm));
1886
- let up = [...pitches].sort((a, b) => a - b);
1887
- if (root !== null) {
1888
- const roots = up.filter((p) => (p % 12 + 12) % 12 === root);
1889
- if (roots.length >= 2)
1890
- up = up.filter((p) => p >= roots[0] && p <= roots[roots.length - 1]);
1891
- }
2068
+ const up = [...pitches].sort((a, b) => a - b);
1892
2069
  const order = [...up, ...up.slice(0, -1).reverse()];
1893
2070
  return order.map((midi, i) => ({ midi, time: i * beat, duration: beat * 0.95 }));
1894
2071
  }
@@ -2063,10 +2240,60 @@ function dataOf(diagram) {
2063
2240
  return {
2064
2241
  kind: diagram.getAttribute("data-mn-play") === "chord" ? "chord" : "scale",
2065
2242
  pitches,
2066
- sound: diagram.getAttribute("data-mn-sound") === "piano" ? "piano" : "guitar",
2067
- root: Number.isInteger(Number(diagram.getAttribute("data-mn-root") ?? "x")) ? Number(diagram.getAttribute("data-mn-root")) : null
2243
+ sound: diagram.getAttribute("data-mn-sound") === "piano" ? "piano" : "guitar"
2068
2244
  };
2069
2245
  }
2246
+ var LABELS2 = new Set(["notes", "degrees", "intervals", "none"]);
2247
+ function spelledNote(name, midi) {
2248
+ const octave = Math.floor(midi / 12) - 1;
2249
+ for (const o of [octave, octave + 1, octave - 1])
2250
+ if (midiOf(`${name}${o}`) === midi)
2251
+ return `${name}${o}`;
2252
+ return `${nameOf(midi)}${octave}`;
2253
+ }
2254
+ function redrawFor(doc, diagram, data) {
2255
+ const toGuitar = data.sound === "piano";
2256
+ const pitches = [...new Set(data.pitches)].sort((a, b) => a - b).filter((midi) => !toGuitar || midi >= 40 && midi <= 88);
2257
+ if (!pitches.length)
2258
+ return null;
2259
+ const chord = diagram.getAttribute("data-mn-chord");
2260
+ const named = diagram.getAttribute("data-mn-set");
2261
+ let set = chord && chordNoteSet(chord) || named && (scaleNoteSet(named) ?? (named.includes(" ") ? null : chordNoteSet(named))) || null;
2262
+ if (set && !pitches.every((midi) => set.members.some((m) => m.chroma === midi % 12)))
2263
+ set = null;
2264
+ if (set)
2265
+ set.pitches = pitches;
2266
+ else {
2267
+ const flats = [...diagram.querySelectorAll("[data-mn-note]")].some((el) => /^[A-G]b/.test(el.getAttribute("data-mn-note") ?? ""));
2268
+ const nameAt = (midi) => diagram.querySelector(`[data-midi="${midi}"][data-mn-note]`)?.getAttribute("data-mn-note") ?? nameOf(midi, flats);
2269
+ const rootEl = diagram.querySelector(".mn-root[data-midi]");
2270
+ const rootMidi = rootEl ? Number(rootEl.getAttribute("data-midi")) : null;
2271
+ set = listNoteSet(pitches.map((midi) => spelledNote(nameAt(midi), midi)).join(" "), rootMidi === null ? undefined : nameAt(rootMidi));
2272
+ if (!set)
2273
+ return null;
2274
+ }
2275
+ const written = diagram.getAttribute("data-mn-labels");
2276
+ const label = written && LABELS2.has(written) && (set.root !== null || written === "notes" || written === "none") ? written : "notes";
2277
+ const title = diagram.querySelector(".mn-title")?.textContent ?? undefined;
2278
+ const orientation = diagram.getAttribute("data-mn-orientation") === "vertical" ? "vertical" : undefined;
2279
+ const drawn = toGuitar ? renderFretboard(doc, set, {
2280
+ label,
2281
+ ...title ? { title } : {},
2282
+ ...orientation ? { orientation } : {},
2283
+ frets: [0, Math.max(12, Math.min(24, pitches[pitches.length - 1] - 64))]
2284
+ }) : renderKeyboard(doc, set, {
2285
+ label,
2286
+ ...title ? { title } : {},
2287
+ ...orientation ? { orientation } : {},
2288
+ range: keyRangeOf(set),
2289
+ playAs: data.kind
2290
+ });
2291
+ const name = diagram.getAttribute("aria-label");
2292
+ if (name)
2293
+ drawn.setAttribute("aria-label", `${name}, drawn for ${toGuitar ? "guitar" : "piano"}`);
2294
+ drawn.classList.add("mn-redrawn");
2295
+ return drawn;
2296
+ }
2070
2297
  function attachPlayback(el, options = {}) {
2071
2298
  const doc = el.ownerDocument;
2072
2299
  const win = doc.defaultView;
@@ -2098,6 +2325,8 @@ function barFor(doc, win, diagram, data, options) {
2098
2325
  loop: false
2099
2326
  };
2100
2327
  let playing = null;
2328
+ let shown = diagram;
2329
+ const pitchesShown = () => shown === diagram ? data.pitches : dataOf(shown)?.pitches ?? data.pitches;
2101
2330
  const toggle = html(doc, "button", "mn-play-toggle");
2102
2331
  toggle.type = "button";
2103
2332
  const show = () => {
@@ -2123,7 +2352,7 @@ function barFor(doc, win, diagram, data, options) {
2123
2352
  stop();
2124
2353
  if (!wrap.isConnected)
2125
2354
  return;
2126
- playing = play(sequenceOf(data.kind, data.pitches, settings, data.root), () => {
2355
+ playing = play(sequenceOf(data.kind, pitchesShown(), settings), () => {
2127
2356
  playing = null;
2128
2357
  if (settings.loop && wrap.isConnected)
2129
2358
  start();
@@ -2181,11 +2410,24 @@ function barFor(doc, win, diagram, data, options) {
2181
2410
  option.selected = value === settings.sound;
2182
2411
  sound.appendChild(option);
2183
2412
  }
2413
+ let other;
2414
+ const drawFor = () => {
2415
+ if (settings.sound !== data.sound)
2416
+ other ??= redrawFor(doc, diagram, data);
2417
+ const next = settings.sound === data.sound ? diagram : other ?? diagram;
2418
+ if (next !== shown && shown.parentNode === wrap) {
2419
+ wrap.replaceChild(next, shown);
2420
+ shown = next;
2421
+ }
2422
+ };
2184
2423
  sound.addEventListener("change", () => {
2424
+ stop();
2185
2425
  settings.sound = sound.value === "piano" ? "piano" : "guitar";
2426
+ drawFor();
2186
2427
  });
2428
+ drawFor();
2187
2429
  bar.appendChild(sound);
2188
- diagram.addEventListener("click", (event) => {
2430
+ wrap.addEventListener("click", (event) => {
2189
2431
  const node = event.target;
2190
2432
  const target = typeof node?.closest === "function" ? node.closest("[data-midi]") : null;
2191
2433
  const midi = Number(target?.getAttribute("data-midi"));
@@ -2755,7 +2997,7 @@ function stringName(tuning, s) {
2755
2997
  const lowest = tuning.findIndex((p) => noteOf(p).replace(/-?\d+$/, "") === name);
2756
2998
  return `the ${s === lowest ? "low" : "high"} ${name} string`;
2757
2999
  }
2758
- var lowestFret = (frets) => {
3000
+ var lowestFret2 = (frets) => {
2759
3001
  const fretted = frets.filter((f) => f !== null && f > 0);
2760
3002
  return fretted.length ? Math.min(...fretted) : 0;
2761
3003
  };
@@ -2783,7 +3025,7 @@ function move(from, fromFingers, to, tuning) {
2783
3025
  const placed = new Set(to.frets.flatMap((f, s) => f && to.fingers[s] && !anchors.includes(s) && !guides.includes(s) ? [to.fingers[s]] : []));
2784
3026
  const strings = new Set(to.frets.flatMap((f, s) => f && to.fingers[s] && !anchors.includes(s) && !guides.includes(s) ? [s] : []));
2785
3027
  movement -= strings.size - placed.size;
2786
- const shift = Math.abs(lowestFret(to.frets) - lowestFret(from));
3028
+ const shift = Math.abs(lowestFret2(to.frets) - lowestFret2(from));
2787
3029
  movement += 0.3 * shift;
2788
3030
  const fingerName = (f) => FINGER_NAMES[f ?? ""] ?? "finger";
2789
3031
  const seen = new Set;
@@ -2802,7 +3044,7 @@ function move(from, fromFingers, to, tuning) {
2802
3044
  tips.push(`Slide your ${fingerName(f)} along ${stringName(tuning, s)} from fret ${from[s]} to ${to.frets[s]}.`);
2803
3045
  }
2804
3046
  if (shift >= 2) {
2805
- const up = lowestFret(to.frets) > lowestFret(from);
3047
+ const up = lowestFret2(to.frets) > lowestFret2(from);
2806
3048
  tips.push(`Move your hand ${up ? "up" : "down"} ${shift} frets.`);
2807
3049
  }
2808
3050
  if (!anchors.length && !guides.length && shift < 2) {
@@ -3049,16 +3291,28 @@ function positionParts(language, source) {
3049
3291
  if (bad !== undefined) {
3050
3292
  throw new Error(`positions: use all, or numbers from 1 to ${count} for ${set.title}`);
3051
3293
  }
3294
+ const tuningText = block.fields.get("tuning");
3295
+ const numbering = numberingOf(block.fields.get("numbering"), set, system);
3296
+ const neck = neckPositions(set, tuningText && parseTuning(tuningText) || STANDARD_TUNING, system, numbering);
3297
+ const numbered = numbering === "minor" ? ["numbering: minor"] : [];
3298
+ const from = numbering === "minor" ? ` (from ${relativeMinorOf(set)}m)` : "";
3299
+ const fretsOf = (n) => {
3300
+ const cells = neck[n - 1];
3301
+ if (!cells?.length)
3302
+ return [];
3303
+ const frets = cells.map((c) => c.fret);
3304
+ return [`frets: ${Math.min(...frets)}-${Math.max(...frets)}`];
3305
+ };
3052
3306
  const shared = SHARED_KEYS.fretboard;
3053
- const others = [...block.fields].filter(([key]) => !["positions", "scale", "shape", "position", "title"].includes(key));
3307
+ const others = [...block.fields].filter(([key]) => !["positions", "scale", "shape", "position", "numbering", "title", "frets"].includes(key));
3054
3308
  const header = others.filter(([key]) => key === "columns" || shared.includes(key)).map(([key, v]) => `${key}: ${v}`);
3055
3309
  const own = others.filter(([key]) => key !== "columns" && !shared.includes(key)).map(([key, v]) => `${key}: ${v}`);
3056
3310
  const diagrams = wanted.map((n) => {
3057
3311
  const at = system === "caged" ? [
3058
3312
  `shape: ${CAGED_SHAPES[n - 1]}`,
3059
3313
  `title: ${set.title}, ${CAGED_SHAPES[n - 1]} shape`
3060
- ] : system === "3nps" ? ["shape: 3nps", `position: ${n}`, `title: ${set.title}, 3nps ${n}`] : [`position: ${n}`, `title: ${set.title}, box ${n}`];
3061
- return [`scale: ${scale}`, ...at, ...own].join(`
3314
+ ] : system === "3nps" ? ["shape: 3nps", `position: ${n}`, `title: ${set.title}, 3nps ${n}${from}`] : [`position: ${n}`, `title: ${set.title}, box ${n}${from}`];
3315
+ return [`scale: ${scale}`, ...at, ...numbered, ...fretsOf(n), ...own].join(`
3062
3316
  `);
3063
3317
  });
3064
3318
  return [...header.length ? [header.join(`
@@ -3125,6 +3379,8 @@ function voicingParts(language, source) {
3125
3379
  if (instrument === "piano" || instrument === "keyboard" || fields.has("pitches") || fields.has("notes")) {
3126
3380
  throw new Error("voicings are for guitar and other fretted instruments");
3127
3381
  }
3382
+ if (fields.get("root")?.trim())
3383
+ throw new Error(ROOT_FOR_LISTS_ONLY);
3128
3384
  const refused = NOT_WITH_VOICINGS.find((key) => fields.has(key));
3129
3385
  if (refused)
3130
3386
  throw new Error(`voicings finds the frets itself: remove "${refused}"`);
@@ -3242,6 +3498,8 @@ function triadParts(language, source) {
3242
3498
  const fields = block.fields;
3243
3499
  if (fields.has("voicings"))
3244
3500
  throw new Error("Use triads or voicings, not both");
3501
+ if (fields.get("root")?.trim())
3502
+ throw new Error(ROOT_FOR_LISTS_ONLY);
3245
3503
  const refused = NOT_WITH_VOICINGS.find((key) => fields.has(key));
3246
3504
  if (refused)
3247
3505
  throw new Error(`triads finds the frets itself: remove "${refused}"`);
@@ -3366,6 +3624,8 @@ function transitionParts(language, source) {
3366
3624
  if (fromText !== undefined && progressionText !== undefined) {
3367
3625
  throw new Error("Use from and to, or progression, not both");
3368
3626
  }
3627
+ if (fields.get("root")?.trim())
3628
+ throw new Error(ROOT_FOR_LISTS_ONLY);
3369
3629
  const refused = [...NOT_WITH_VOICINGS, "voicings", "triads"].find((key) => fields.has(key));
3370
3630
  if (refused)
3371
3631
  throw new Error(`"${refused}" can't be used with ${fromText ? "from" : "progression"}`);
@@ -4310,6 +4570,7 @@ export {
4310
4570
  FLAT_NAMES,
4311
4571
  LANGUAGES,
4312
4572
  MAX_DIAGRAMS,
4573
+ MAX_FRET,
4313
4574
  MAX_GENERATED_STRINGS,
4314
4575
  SHARP_NAMES,
4315
4576
  STANDARD_TUNING,
@@ -4344,6 +4605,7 @@ export {
4344
4605
  midiOf,
4345
4606
  modesOf,
4346
4607
  nameOf,
4608
+ neckPositions,
4347
4609
  noteOf,
4348
4610
  parseChord,
4349
4611
  parseChordName,
@@ -4380,5 +4642,5 @@ export {
4380
4642
  voicingShape
4381
4643
  };
4382
4644
 
4383
- //# debugId=823E4F97D1DB047E64756E2164756E21
4645
+ //# debugId=F64C39781E3B43C164756E2164756E21
4384
4646
  //# sourceMappingURL=index.js.map