@dsebastien/music-notation 0.5.3 → 0.6.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.
@@ -1,4 +1,4 @@
1
- /*! @dsebastien/music-notation 0.5.3 tab bundle | MIT | loads alphaTab (MPL-2.0) from jsDelivr */
1
+ /*! @dsebastien/music-notation 0.6.0 tab bundle | MIT | loads alphaTab (MPL-2.0) from jsDelivr */
2
2
  (()=>{var j=(t,e)=>{for(let[a,r]of Object.entries(e))if(r!==void 0)t.setAttribute(a,String(r))};function C(t,e,a={},r=[]){let o=t.createElementNS("http://www.w3.org/2000/svg",e);j(o,a);for(let n of r)if(n)o.appendChild(n);return o}function w(t,e,a,r){let o=t.createElement(e);if(a)o.className=a;if(r!==void 0)o.textContent=r;return o}var q="1.8.4",F=(t=q)=>{let e=`https://cdn.jsdelivr.net/npm/@coderline/alphatab@${t}/dist`;return{script:`${e}/alphaTab.min.js`,font:`${e}/font/Bravura.woff2`,soundFont:`${e}/soundfont/sonivox.sf3`}},_=/^\s*(staves|file|tracks?)\s*:\s*(.*)$/i;function K(t,e){let a=e.split(/\r?\n/),r={staves:t,file:null,tracks:null,tex:"",texLine:0},o=0;for(;o<a.length;o++){let n=a[o];if(!n.trim()||/^\s*\/\//.test(n))continue;let s=_.exec(n);if(!s)break;let c=s[1].toLowerCase(),d=s[2].trim();if(c==="staves"){let i=d.toLowerCase();if(i!=="tab"&&i!=="score"&&i!=="both")throw Error(`staves: use tab, score or both, got "${d}"`);r.staves=i}else if(c==="file")r.file=d.replace(/^!?\[\[|\]\]$/g,"").split(/[|#]/)[0].trim()||null;else{let i=d.split(/[\s,]+/).filter(Boolean).map(Number);if(!i.length||i.some((u)=>!Number.isInteger(u)||u<1))throw Error(`tracks: use track numbers from 1, got "${d}"`);r.tracks=i}}while(o<a.length&&!a[o].trim())o++;if(r.texLine=o,r.tex=a.slice(o).join(`
3
3
  `).trimEnd(),!r.file&&!r.tex)throw Error("Write the music in alphaTex, or give a file: [[Song.gp]]");return r}function Y(t,e){let a=t?.cause??t;for(let r of["lexerDiagnostics","parserDiagnostics","semanticDiagnostics"]){let o=a?.[r]?.items;if(!Array.isArray(o))continue;let n=o.find((s)=>s.severity===2&&s.message);if(n)return`${n.start?`line ${n.start.line+e}, column ${n.start.col}: `:""}${n.message}`}return t instanceof Error?t.message:String(t)}var J={tab:"Tab",score:"Score",both:"ScoreTab"};function L(t,e,a=1){let r=t.createElement("canvas");r.width=1,r.height=1;let o=r.getContext("2d",{willReadFrequently:!0});if(!o)return null;o.fillStyle="#000",o.fillStyle=e,o.fillRect(0,0,1,1);let n=o.getImageData(0,0,1,1).data;if(n.length<4)return null;return`rgba(${n[0]}, ${n[1]}, ${n[2]}, ${(n[3]/255*a).toFixed(3)})`}function Q(t){let e=t.ownerDocument,a=e.defaultView?.getComputedStyle(t).color||"",r=a&&L(e,a)||(/^rgba?\(/.test(a)?a:"rgba(0, 0, 0, 1)"),o=a&&L(e,a,0.6)||r;return{mainGlyphColor:r,secondaryGlyphColor:o,scoreInfoColor:r,staffLineColor:o,barSeparatorColor:r,barNumberColor:o}}var P=(t)=>{let e=t.defaultView??globalThis;return{map:(a)=>new e.Map(a),bytes:(a)=>{let r=new e.Uint8Array(a.length);return r.set(a),r}}},X={play:"M4 2.5v11l9-5.5z",pause:"M4 3h3v10H4zM9 3h3v10H9z",stop:"M4 4h8v8H4z",loop:"M3 8a5 5 0 0 1 8.5-3.5L13 6V2.5M13 8a5 5 0 0 1-8.5 3.5L3 10v3.5",metronome:"M6 2h4l3 12H3zM8 11l3-7",countIn:"M3 13h10M5 13V9M8 13V6M11 13V3",volume:"M2 6h3l4-3v10l-4-3H2zM11 5.5a3.5 3.5 0 0 1 0 5"};function E(t,e){let r=C(t,"svg",{class:`mn-play-icon${e==="play"||e==="pause"||e==="stop"?"":" mn-play-icon-loop"}`,viewBox:"0 0 16 16",width:12,height:12,"aria-hidden":"true"});return r.appendChild(C(t,"path",{d:X[e]})),r}var V=(t)=>{let e=Math.max(0,Math.round(t/1000));return`${Math.floor(e/60)}:${String(e%60).padStart(2,"0")}`};function Z(t,e,a,r){let o=w(t,"div","mn-play mn-tab-bar");o.setAttribute("role","group"),o.setAttribute("aria-label","Playback");let n={loop:!1,metronome:!1,countIn:!1,speed:1,volume:1},s=null,c=null,d=()=>(s??=new Promise((l)=>{if(e.playerReady.on(()=>l(!0)),c=()=>l(!1),e.settings.player.playerMode=a.PlayerMode.EnabledSynthesizer,e.settings.player.enableCursor=!0,typeof r.soundFont==="string")e.settings.player.soundFont=r.soundFont;if(e.updateSettings(),r.soundFont instanceof Uint8Array)e.loadSoundFont(P(t).bytes(r.soundFont),!1)}).then((l)=>{if(l)e.isLooping=n.loop,e.metronomeVolume=n.metronome?1:0,e.countInVolume=n.countIn?1:0,e.playbackSpeed=n.speed,e.masterVolume=n.volume;return l}),s),i=(l,h,y)=>{let p=w(t,"button");return p.type="button",p.title=h,p.setAttribute("aria-label",h),p.appendChild(E(t,l)),p.addEventListener("click",y),o.appendChild(p),p},u=(l)=>{if(e.player)l()},f=(l,h,y)=>{let p=i(l,h,()=>{n[y]=!n[y],u(()=>{e.isLooping=n.loop,e.metronomeVolume=n.metronome?1:0,e.countInVolume=n.countIn?1:0}),p.classList.toggle("mn-on",n[y]),p.setAttribute("aria-pressed",String(n[y]))});p.setAttribute("aria-pressed","false")},m=i("play","Play",()=>{d().then((l)=>{if(l)e.playPause()})});i("stop","Stop",()=>u(()=>e.stop())),f("loop","Loop","loop"),f("metronome","Metronome","metronome"),f("countIn","Count-in","countIn");let b=(l,h,y,p,v,k,x="")=>{let T=w(t,"label","mn-play-field"),S=w(t,"span","mn-play-label");S.setAttribute("aria-hidden","true"),S.append(h);let A=w(t,"input");A.type="range",A.min=String(y),A.max=String(p),A.value=String(v),A.setAttribute("aria-label",l),T.title=`${l}: ${v}${x}`,A.addEventListener("input",()=>{k(Number(A.value)),T.title=`${l}: ${A.value}${x}`}),T.append(S,A),o.appendChild(T)};b("Speed","%",25,150,100,(l)=>{n.speed=l/100,u(()=>e.playbackSpeed=n.speed)},"%"),b("Volume",E(t,"volume"),0,100,100,(l)=>{n.volume=l/100,u(()=>e.masterVolume=n.volume)});let g=w(t,"span","mn-tab-time","");return o.appendChild(g),e.playerStateChanged.on((l)=>{let h=Number(l.state)===Number(a.synth.PlayerState.Playing);m.replaceChildren(E(t,h?"pause":"play")),m.title=h?"Pause":"Play",m.setAttribute("aria-label",m.title)}),e.playerPositionChanged.on((l)=>{g.textContent=`${V(l.currentTime)} / ${V(l.endTime)}`}),{bar:o,failed:(l)=>{c?.(),m.disabled=!0,m.title=`Can't play: ${l}`,m.setAttribute("aria-label",m.title)}}}function O(t,e,a,r){let o=a.ownerDocument,n=w(o,"div",`mn-block mn-block-${t} mn-tab`);a.appendChild(n);let s=null,c=!1,d=!1,i=()=>{},u=new Promise((m)=>{i=(b)=>{if(d)return;d=!0,m(b)}}),f=(m)=>{n.replaceChildren(w(o,"div","mn-error-message",`${t}: ${m}`)),n.classList.add("mn-error"),i({ok:!1,error:m})};if(!e.trim())n.classList.add("mn-empty"),i({ok:!0,error:null});else(async()=>{await Promise.resolve();let m=K(t,e),b=r.alphaTab;if(!b?.AlphaTabApi)throw Error("alphaTab isn't loaded");let g=w(o,"div","mn-tab-surface");n.appendChild(g);let{assets:l}=r,h=P(o),y={core:{useWorkers:Boolean(l.scriptFile),...l.scriptFile?{scriptFile:l.scriptFile}:{},smuflFontSources:h.map([[b.FontFileFormat.Woff2,l.font]]),logLevel:b.LogLevel.Warning},display:{staveProfile:J[m.staves],resources:Q(n)},player:{playerMode:b.PlayerMode.Disabled,enableUserInteraction:!0}},p=new b.AlphaTabApi(g,y);if(s=p,c){p.destroy();return}r.onApi?.(p);let v=null;p.renderFinished.on(()=>{if(d||c)return;if(r.player!==!1)v=Z(o,p,b,l),n.appendChild(v.bar),n.addEventListener("pointerdown",(x)=>{if(x.pointerType!=="touch"||v?.bar.contains(x.target))return;n.classList.toggle("mn-play-open")});i({ok:!0,error:null})}),p.error.on((x)=>{let T=Y(x,m.texLine);if(d)v?.failed(T);else f(T)});let k=m.tracks?.map((x)=>x-1);if(m.file){let x;try{x=r.resolveFile?await r.resolveFile(m.file):null}catch(S){throw Error(`Couldn't read "${m.file}": ${S instanceof Error?S.message:String(S)}`)}if(c)return;if(!x)throw Error(`Couldn't find the file "${m.file}"`);if(!p.load(h.bytes(x),k))throw Error(`Couldn't read "${m.file}": not a score file alphaTab knows`)}else p.tex(m.tex,k??"all")})().catch((m)=>{if(!c)f(m instanceof Error?m.message:String(m))});return{el:n,ready:u,get api(){return s},destroy(){c=!0;try{s?.destroy()}catch{}n.remove(),i({ok:!1,error:null})}}}var ee={guitar:25,piano:0};function te(t,e){return{play(a,{sound:r,volume:o,onEnd:n}){let s=e(),c=s?.player;if(!s||!c)throw Error("The soundfont player is not ready");let d=new t.midi.MidiFile,i=new t.midi.AlphaSynthMidiFileHandler(d,!0),u=(g)=>Math.round(g*d.division);i.addTempo(0,60),i.addProgramChange(0,0,0,ee[r]);let f=Number.isFinite(o)?Math.min(1,Math.max(0,o)):0.8;s.masterVolume=f;for(let g of a)i.addNote(0,u(g.time),Math.max(1,u(g.duration)),g.midi,100,0);let m=Math.max(...a.map((g)=>g.time+g.duration),0);s.playbackSpeed=1,c.playOneTimeMidiFile(d);let b=setTimeout(()=>n?.(),(m+0.2)*1000);return{stop(){clearTimeout(b),c.stop()}}}}}function R(t,e,a,r){let o=null,n=null,s=null,c=()=>{if(s)return s;n=w(a,"div","mn-tab-hidden"),n.setAttribute("aria-hidden","true"),a.body.appendChild(n);let i=P(a);o=new t.AlphaTabApi(n,{core:{useWorkers:Boolean(e.scriptFile),...e.scriptFile?{scriptFile:e.scriptFile}:{},smuflFontSources:i.map([[t.FontFileFormat.Woff2,e.font]])},player:{playerMode:t.PlayerMode.EnabledSynthesizer,...typeof e.soundFont==="string"?{soundFont:e.soundFont}:{}}});let u=o;if(s=new Promise((f)=>{u.soundFontLoaded.on(()=>f(!0)),u.error.on(()=>f(!1))}),e.soundFont instanceof Uint8Array)u.loadSoundFont(i.bytes(e.soundFont),!1);return u.tex("r"),s},d=te(t,()=>o);return{play(i,u){let f=null,m=!1;return c().then((b)=>{if(m)return;try{if(b){f=d.play(i,u);return}}catch{}if(r)f=r.play(i,u)}),{stop(){m=!0,f?.stop()}}},destroy(){try{o?.destroy()}catch{}n?.remove(),o=null,s=null}}}var I=`/* Music notation. Colors follow Obsidian's theme variables when present, with fallbacks for any page. */
4
4
  .mn-block,
@@ -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,7 +899,9 @@ 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)
902
+ root.setAttribute("data-mn-set", set.title);
903
+ root.setAttribute("data-mn-frets", `${from}-${to}`);
904
+ if (set.root !== null && !set.list)
846
905
  root.setAttribute("data-mn-root", String(set.root));
847
906
  return root;
848
907
  }
@@ -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,7 +1072,8 @@ 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)
1075
+ root.setAttribute("data-mn-set", set.title);
1076
+ if (set.root !== null && !set.list)
1013
1077
  root.setAttribute("data-mn-root", String(set.root));
1014
1078
  return root;
1015
1079
  }
@@ -1366,6 +1430,29 @@ function noteSetOf(block) {
1366
1430
  const scale = block.fields.get("scale");
1367
1431
  const chord = block.fields.get("chord");
1368
1432
  const notes = block.fields.get("notes");
1433
+ const root = block.fields.get("root")?.trim() || undefined;
1434
+ if (root !== undefined) {
1435
+ if (scale !== undefined)
1436
+ throw rootNotForList("a scale");
1437
+ if (chord !== undefined)
1438
+ throw rootNotForList("a chord");
1439
+ if (rootNameOf(root) === null) {
1440
+ throw new Error(`Invalid root "${root}": use a note name, e.g. root: C`);
1441
+ }
1442
+ if (notes !== undefined)
1443
+ return orFail(listNoteSet(notes, root), `Invalid notes "${notes}"`);
1444
+ if (block.head) {
1445
+ const list = listNoteSet(block.head, root);
1446
+ if (list)
1447
+ return list;
1448
+ if (scaleNoteSet(block.head))
1449
+ throw rootNotForList("a scale");
1450
+ if (chordNoteSet(block.head))
1451
+ throw rootNotForList("a chord");
1452
+ throw new Error(`"${block.head}" is not a list of notes: use e.g. notes: C Eb G`);
1453
+ }
1454
+ throw new Error("Add the notes for the root: e.g. notes: C Eb G");
1455
+ }
1369
1456
  if (scale !== undefined) {
1370
1457
  if (isScaleWithoutRoot(scale))
1371
1458
  throw new Error(`Add a root note: C ${scale.trim()}`);
@@ -1385,6 +1472,7 @@ function noteSetOf(block) {
1385
1472
  }
1386
1473
  throw new Error('Add "scale:", "chord:" or "notes:"');
1387
1474
  }
1475
+ var rootNotForList = (what) => new Error(`root only applies to lists of notes (notes: C E G): ${what} has its own root`);
1388
1476
  function labelField(block, fallback, fingers = false) {
1389
1477
  const value = block.fields.get("labels")?.toLowerCase();
1390
1478
  if (value === undefined)
@@ -1412,7 +1500,7 @@ function marksOf(block, set) {
1412
1500
  }
1413
1501
  } else if (highlight.toLowerCase() !== "none" && highlight !== "") {
1414
1502
  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");
1503
+ 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
1504
  }
1417
1505
  const labels = highlight.replace(/♭/g, "b").replace(/♯/g, "#").split(/[\s,]+/).filter(Boolean);
1418
1506
  for (const label of labels) {
@@ -1428,12 +1516,13 @@ function marksOf(block, set) {
1428
1516
  const compare = block.fields.get("compare")?.trim();
1429
1517
  if (compare) {
1430
1518
  const tonic = Scale3.get(scaleName(compare)).tonic;
1431
- const root = set.members[0]?.name ?? "";
1519
+ const root = rootNameOf(block.fields.get("root") ?? "") ?? set.members[0]?.name ?? "";
1432
1520
  const parent = orFail(scaleNoteSet(tonic ? compare : `${root} ${compare}`), `Unknown scale "${compare}" to compare with: use e.g. compare: major`);
1433
1521
  const own = new Set(set.members.map((m) => m.chroma));
1434
1522
  const theirs = new Set(parent.members.map((m) => m.chroma));
1435
1523
  marks.different = new Set([...own].filter((c) => !theirs.has(c)));
1436
1524
  marks.ghosts = new Set([...theirs].filter((c) => !own.has(c)));
1525
+ marks.ghostNames = new Map(parent.members.filter((m) => !own.has(m.chroma)).map((m) => [m.chroma, m.name]));
1437
1526
  }
1438
1527
  return marks;
1439
1528
  }
@@ -1481,23 +1570,61 @@ function pentatonicOf(set) {
1481
1570
  }
1482
1571
  return null;
1483
1572
  }
1484
- function scalePosition(set, tuning, system, n) {
1573
+ var MAX_FRET = 36;
1574
+ var isMajorPentatonic = (set) => set.members.map((m) => m.interval).join(" ") === MAJOR_PENTATONIC.join(" ");
1575
+ var relativeMinorOf = (set) => isMajorPentatonic(set) ? set.members[4].name : undefined;
1576
+ function numberingOf(text, set, system) {
1577
+ const value = text?.trim().toLowerCase().replace(/\s+/g, " ");
1578
+ if (!value)
1579
+ return "root";
1580
+ if (value !== "minor" && value !== "relative minor") {
1581
+ throw new Error(`numbering: use minor (positions from the relative minor), got "${text}"`);
1582
+ }
1583
+ if (!isMajorPentatonic(set)) {
1584
+ throw new Error(`numbering: minor is for major pentatonic positions (e.g. A major pentatonic), not ${set.title}`);
1585
+ }
1586
+ if (system === "caged") {
1587
+ throw new Error("numbering: minor numbers boxes and 3nps positions, not CAGED shapes");
1588
+ }
1589
+ return "minor";
1590
+ }
1591
+ 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;
1592
+ var lowestFret = (cells) => Math.min(...cells.map((c) => c.fret));
1593
+ var highestFret = (cells) => Math.max(...cells.map((c) => c.fret));
1594
+ function scalePosition(set, tuning, system, n, options = {}) {
1595
+ const octaves = octavesOf(set, tuning, system, fromRoot(set, system, n, options.numbering));
1596
+ const within = options.within;
1597
+ const inside = within ? octaves.find((cells) => lowestFret(cells) >= within[0] && highestFret(cells) <= within[1]) : undefined;
1598
+ return inside ?? octaves[0] ?? null;
1599
+ }
1600
+ function neckPositions(set, tuning, system, numbering = "root") {
1601
+ let floor = 0;
1602
+ return Array.from({ length: positionCount(set, system) }, (_, i) => {
1603
+ const octaves = octavesOf(set, tuning, system, fromRoot(set, system, i + 1, numbering));
1604
+ const cells = octaves.find((c) => lowestFret(c) >= floor && highestFret(c) <= MAX_FRET) ?? octaves[0] ?? null;
1605
+ if (cells)
1606
+ floor = lowestFret(cells);
1607
+ return cells;
1608
+ });
1609
+ }
1610
+ function octavesOf(set, tuning, system, n) {
1485
1611
  if (set.root === null || n < 1 || n > positionCount(set, system))
1486
- return null;
1612
+ return [];
1487
1613
  const open = tuning[0];
1488
1614
  const chromas = chromasOf(set);
1489
1615
  const notes = tuning.length * 3;
1490
1616
  const nps = system === "3nps" || system === "caged" && chromas.length !== 5 && !pentatonicOf(set);
1491
1617
  const pentatonic = chromas.length === 5 ? chromas : pentatonicOf(set);
1492
1618
  if (!nps && !pentatonic)
1493
- return null;
1619
+ return [];
1494
1620
  const startChroma = nps ? chromas[(n - 1) % chromas.length] : pentatonic[(n - 1) % 5];
1495
- for (let start = fretOn(open, startChroma, 0);start <= 36; start += 12) {
1621
+ const out = [];
1622
+ for (let start = fretOn(open, startChroma, 0);start <= MAX_FRET; start += 12) {
1496
1623
  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
1624
  if (cells && cells.every((c) => c.fret >= 0))
1498
- return cells;
1625
+ out.push(cells);
1499
1626
  }
1500
- return null;
1627
+ return out;
1501
1628
  }
1502
1629
  function withOther(box, chromas, tuning) {
1503
1630
  if (box.length < tuning.length * 2)
@@ -1555,6 +1682,7 @@ var SHARED_KEYS = {
1555
1682
  "compare",
1556
1683
  "position",
1557
1684
  "shape",
1685
+ "numbering",
1558
1686
  "strings"
1559
1687
  ]
1560
1688
  };
@@ -1681,14 +1809,14 @@ var renderChord = (doc, block, options) => {
1681
1809
  const fingers = fingering ? fingersFor(set.pitches, fingering) : new Map;
1682
1810
  const range = field(block, "range");
1683
1811
  handOf(block, options);
1684
- return renderKeyboard(doc, set, {
1812
+ return named(renderKeyboard(doc, set, {
1685
1813
  playAs: "chord",
1686
1814
  title,
1687
1815
  label: labelField(block, fingers.size ? "fingers" : "notes", fingers.size > 0),
1688
1816
  fingers,
1689
1817
  range: keyRange(range ? rangeOf(range) : keyRangeOf(set)),
1690
1818
  orientation: orientationOf(block, options.orientation?.keyboard)
1691
- });
1819
+ }), symbol);
1692
1820
  }
1693
1821
  if (instrument && instrument !== "guitar" && !field(block, "tuning")) {
1694
1822
  throw new Error(`Unknown instrument "${instrument}": use guitar or piano, or give a tuning`);
@@ -1746,7 +1874,7 @@ var renderChord = (doc, block, options) => {
1746
1874
  const anchors = marked("anchors");
1747
1875
  const guides = marked("guides");
1748
1876
  const marks = voicing.frets.map((_, s) => anchors.includes(s) ? "anchor" : guides.includes(s) ? "guide" : null);
1749
- return renderGuitarDiagram(doc, voicing, {
1877
+ return named(renderGuitarDiagram(doc, voicing, {
1750
1878
  title,
1751
1879
  root,
1752
1880
  tuning,
@@ -1754,8 +1882,13 @@ var renderChord = (doc, block, options) => {
1754
1882
  ...anchors.length || guides.length ? { marks } : {},
1755
1883
  orientation: orientationOf(block, options.orientation?.chord),
1756
1884
  hand: handOf(block, options)
1757
- });
1885
+ }), symbol);
1758
1886
  };
1887
+ function named(el, symbol) {
1888
+ if (symbol)
1889
+ el.setAttribute("data-mn-chord", symbol);
1890
+ return el;
1891
+ }
1759
1892
  function dotLabels(text, symbol, voicing, tuning) {
1760
1893
  const value = text?.toLowerCase();
1761
1894
  if (value === undefined || value === "fingers")
@@ -1794,7 +1927,7 @@ var renderKeyboardBlock = (doc, block, options) => {
1794
1927
  const fingering = field(block, "fingering");
1795
1928
  const keys = range ? rangeOf(range) : undefined;
1796
1929
  let fingers;
1797
- if (fingering && set.root !== null && !set.pitches) {
1930
+ if (fingering && set.root !== null && !set.list && !set.pitches) {
1798
1931
  let start = 60 + set.root;
1799
1932
  if (keys) {
1800
1933
  const first = keys[0] + ((set.root - keys[0]) % 12 + 12) % 12;
@@ -1809,7 +1942,7 @@ var renderKeyboardBlock = (doc, block, options) => {
1809
1942
  set.pitches = octave;
1810
1943
  }
1811
1944
  return renderKeyboard(doc, set, {
1812
- playAs: !set.scaleType && set.root !== null ? "chord" : "scale",
1945
+ playAs: !set.scaleType && !set.list && set.root !== null ? "chord" : "scale",
1813
1946
  title: field(block, "title"),
1814
1947
  label: labelField(block, fingers ? "fingers" : "notes", fingers !== undefined),
1815
1948
  fingers,
@@ -1823,19 +1956,30 @@ var renderFretboardBlock = (doc, block, options) => {
1823
1956
  const at = positionOf(field(block, "position"), field(block, "shape"));
1824
1957
  const fretsText = field(block, "frets");
1825
1958
  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");
1959
+ if (frets && frets[1] > MAX_FRET)
1960
+ throw new Error(`Frets go up to ${MAX_FRET}`);
1828
1961
  const tuningText = field(block, "tuning");
1829
1962
  const tuning = tuningText ? tuningOf(tuningText) : undefined;
1830
1963
  let cells;
1964
+ if (!at && field(block, "numbering")) {
1965
+ throw new Error("numbering goes with a position: e.g. position: 1 or positions: all");
1966
+ }
1831
1967
  if (at) {
1832
- if (set.root === null)
1968
+ if (set.root === null || set.list) {
1833
1969
  throw new Error("Positions need a scale: e.g. scale: A minor");
1970
+ }
1834
1971
  if (at.system === "box" && set.members.length !== 5)
1835
1972
  at.system = "caged";
1836
1973
  const count = positionCount(set, at.system);
1837
1974
  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}`);
1975
+ const numbering = numberingOf(field(block, "numbering"), set, at.system);
1976
+ cells = orFail(scalePosition(set, tuning ?? STANDARD_TUNING, at.system, at.n, {
1977
+ within: frets,
1978
+ numbering
1979
+ }), `${set.title} has ${count} ${named} positions: use position 1 to ${count}`);
1980
+ if (frets && cells.some((cell) => cell.fret < frets[0] || cell.fret > frets[1])) {
1981
+ throw new Error(`${set.title}, position ${at.n} doesn't fit in frets ${frets[0]}-${frets[1]}: widen frets: or leave it out`);
1982
+ }
1839
1983
  }
1840
1984
  const stringsText = field(block, "strings");
1841
1985
  const count = (tuning ?? STANDARD_TUNING).length;
@@ -2755,7 +2899,7 @@ function stringName(tuning, s) {
2755
2899
  const lowest = tuning.findIndex((p) => noteOf(p).replace(/-?\d+$/, "") === name);
2756
2900
  return `the ${s === lowest ? "low" : "high"} ${name} string`;
2757
2901
  }
2758
- var lowestFret = (frets) => {
2902
+ var lowestFret2 = (frets) => {
2759
2903
  const fretted = frets.filter((f) => f !== null && f > 0);
2760
2904
  return fretted.length ? Math.min(...fretted) : 0;
2761
2905
  };
@@ -2783,7 +2927,7 @@ function move(from, fromFingers, to, tuning) {
2783
2927
  const placed = new Set(to.frets.flatMap((f, s) => f && to.fingers[s] && !anchors.includes(s) && !guides.includes(s) ? [to.fingers[s]] : []));
2784
2928
  const strings = new Set(to.frets.flatMap((f, s) => f && to.fingers[s] && !anchors.includes(s) && !guides.includes(s) ? [s] : []));
2785
2929
  movement -= strings.size - placed.size;
2786
- const shift = Math.abs(lowestFret(to.frets) - lowestFret(from));
2930
+ const shift = Math.abs(lowestFret2(to.frets) - lowestFret2(from));
2787
2931
  movement += 0.3 * shift;
2788
2932
  const fingerName = (f) => FINGER_NAMES[f ?? ""] ?? "finger";
2789
2933
  const seen = new Set;
@@ -2802,7 +2946,7 @@ function move(from, fromFingers, to, tuning) {
2802
2946
  tips.push(`Slide your ${fingerName(f)} along ${stringName(tuning, s)} from fret ${from[s]} to ${to.frets[s]}.`);
2803
2947
  }
2804
2948
  if (shift >= 2) {
2805
- const up = lowestFret(to.frets) > lowestFret(from);
2949
+ const up = lowestFret2(to.frets) > lowestFret2(from);
2806
2950
  tips.push(`Move your hand ${up ? "up" : "down"} ${shift} frets.`);
2807
2951
  }
2808
2952
  if (!anchors.length && !guides.length && shift < 2) {
@@ -3049,16 +3193,28 @@ function positionParts(language, source) {
3049
3193
  if (bad !== undefined) {
3050
3194
  throw new Error(`positions: use all, or numbers from 1 to ${count} for ${set.title}`);
3051
3195
  }
3196
+ const tuningText = block.fields.get("tuning");
3197
+ const numbering = numberingOf(block.fields.get("numbering"), set, system);
3198
+ const neck = neckPositions(set, tuningText && parseTuning(tuningText) || STANDARD_TUNING, system, numbering);
3199
+ const numbered = numbering === "minor" ? ["numbering: minor"] : [];
3200
+ const from = numbering === "minor" ? ` (from ${relativeMinorOf(set)}m)` : "";
3201
+ const fretsOf = (n) => {
3202
+ const cells = neck[n - 1];
3203
+ if (!cells?.length)
3204
+ return [];
3205
+ const frets = cells.map((c) => c.fret);
3206
+ return [`frets: ${Math.min(...frets)}-${Math.max(...frets)}`];
3207
+ };
3052
3208
  const shared = SHARED_KEYS.fretboard;
3053
- const others = [...block.fields].filter(([key]) => !["positions", "scale", "shape", "position", "title"].includes(key));
3209
+ const others = [...block.fields].filter(([key]) => !["positions", "scale", "shape", "position", "numbering", "title", "frets"].includes(key));
3054
3210
  const header = others.filter(([key]) => key === "columns" || shared.includes(key)).map(([key, v]) => `${key}: ${v}`);
3055
3211
  const own = others.filter(([key]) => key !== "columns" && !shared.includes(key)).map(([key, v]) => `${key}: ${v}`);
3056
3212
  const diagrams = wanted.map((n) => {
3057
3213
  const at = system === "caged" ? [
3058
3214
  `shape: ${CAGED_SHAPES[n - 1]}`,
3059
3215
  `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(`
3216
+ ] : system === "3nps" ? ["shape: 3nps", `position: ${n}`, `title: ${set.title}, 3nps ${n}${from}`] : [`position: ${n}`, `title: ${set.title}, box ${n}${from}`];
3217
+ return [`scale: ${scale}`, ...at, ...numbered, ...fretsOf(n), ...own].join(`
3062
3218
  `);
3063
3219
  });
3064
3220
  return [...header.length ? [header.join(`
@@ -3675,5 +3831,5 @@ export {
3675
3831
  renderAll
3676
3832
  };
3677
3833
 
3678
- //# debugId=9FF779587F259D3664756E2164756E21
3834
+ //# debugId=4DA24EFA15D7239964756E2164756E21
3679
3835
  //# sourceMappingURL=index.js.map