@dsebastien/music-notation 0.15.0 → 0.17.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,886 +1,1346 @@
1
- // src/render/dom.ts
2
- var SVG_NS = "http://www.w3.org/2000/svg";
3
- var apply = (el, attrs) => {
4
- for (const [name, value] of Object.entries(attrs)) {
5
- if (value !== undefined)
6
- el.setAttribute(name, String(value));
7
- }
8
- };
9
- function svg(doc, tag, attrs = {}, children = []) {
10
- const el = doc.createElementNS(SVG_NS, tag);
11
- apply(el, attrs);
12
- for (const child of children)
13
- if (child)
14
- el.appendChild(child);
15
- return el;
16
- }
17
- function svgText(doc, text, attrs = {}) {
18
- const el = svg(doc, "text", attrs);
19
- el.textContent = text;
20
- return el;
1
+ // src/theory/pitch.ts
2
+ var SHARP_NAMES = [
3
+ "C",
4
+ "C#",
5
+ "D",
6
+ "D#",
7
+ "E",
8
+ "F",
9
+ "F#",
10
+ "G",
11
+ "G#",
12
+ "A",
13
+ "A#",
14
+ "B"
15
+ ];
16
+ var FLAT_NAMES = ["C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"];
17
+ var LETTER_CHROMA = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };
18
+ function chromaOf(name) {
19
+ const m = /^([A-Ga-g])([#♯b♭]*)$/.exec(name.trim());
20
+ if (!m)
21
+ return null;
22
+ let chroma = LETTER_CHROMA[m[1].toUpperCase()];
23
+ for (const accidental of m[2])
24
+ chroma += accidental === "#" || accidental === "♯" ? 1 : -1;
25
+ return (chroma % 12 + 12) % 12;
21
26
  }
22
- function svgLabel(doc, text, [x, y], cls, anchor = "middle") {
23
- return svgText(doc, text, { class: cls, x, y: y + 4, "text-anchor": anchor });
27
+ function midiOf(note) {
28
+ const m = /^([A-Ga-g][#♯b♭]*)(-?\d)$/.exec(note.trim());
29
+ if (!m)
30
+ return null;
31
+ const chroma = chromaOf(m[1]);
32
+ if (chroma === null)
33
+ return null;
34
+ const letter = LETTER_CHROMA[m[1][0].toUpperCase()];
35
+ const shift = Math.round((chroma - letter) / 12);
36
+ return (Number(m[2]) + 1) * 12 + chroma - shift * 12;
24
37
  }
25
- function dotLabel(doc, text, point, r) {
26
- const label = svgLabel(doc, text, point, "mn-dot-text");
27
- if ([...text].length >= 3) {
28
- label.classList.add("mn-dot-text-long");
29
- label.setAttribute("textLength", String(2 * r - 2));
30
- label.setAttribute("lengthAdjust", "spacingAndGlyphs");
31
- }
32
- return label;
38
+ var nameOf = (chroma, preferFlats = false) => (preferFlats ? FLAT_NAMES : SHARP_NAMES)[((Math.round(chroma) || 0) % 12 + 12) % 12];
39
+ var doubleSharp = (name) => name.replace(/x$/, "##");
40
+ function splitChordSymbol(symbol) {
41
+ const normalized = symbol.trim().replace(/♯/g, "#").replace(/♭/g, "b").replace(/𝄪/g, "x").replace(/𝄫/g, "bb");
42
+ const m = /^([A-G](?:##|x(?!\d)|bb|#|b)?)(.*?)(?:\/([A-G](?:##|x|bb|#|b)?))?$/.exec(normalized);
43
+ return m ? { root: doubleSharp(m[1]), suffix: m[2], bass: m[3] ? doubleSharp(m[3]) : null } : null;
33
44
  }
34
- function svgLine(doc, [x1, y1], [x2, y2], cls) {
35
- return svg(doc, "line", { class: cls, x1, y1, x2, y2 });
45
+ var noteOf = (midi, preferFlats = false) => `${nameOf(midi, preferFlats)}${Math.floor(midi / 12) - 1}`;
46
+ var isFlat = (name) => /^[A-Ga-g][b♭]/.test(name.trim());
47
+
48
+ // src/theory/note-set.ts
49
+ import { Chord, Interval, Scale as Scale2 } from "tonal";
50
+
51
+ // src/theory/suffix.ts
52
+ var CANONICAL = new Map([
53
+ ["M", ""],
54
+ ["maj", ""],
55
+ ["min", "m"],
56
+ ["-", "m"],
57
+ ["M7", "maj7"],
58
+ ["Δ", "maj7"],
59
+ ["Δ7", "maj7"],
60
+ ["M9", "maj9"],
61
+ ["Δ9", "maj9"],
62
+ ["min6", "m6"],
63
+ ["-6", "m6"],
64
+ ["min7", "m7"],
65
+ ["-7", "m7"],
66
+ ["min9", "m9"],
67
+ ["-9", "m9"],
68
+ ["ø", "m7b5"],
69
+ ["ø7", "m7b5"],
70
+ ["m7-5", "m7b5"],
71
+ ["mmaj7", "mMaj7"],
72
+ ["mM7", "mMaj7"],
73
+ ["m(maj7)", "mMaj7"],
74
+ ["-(maj7)", "mMaj7"],
75
+ ["°", "dim"],
76
+ ["°7", "dim7"],
77
+ ["+", "aug"],
78
+ ["sus", "sus4"],
79
+ ["add2", "add9"],
80
+ ["69", "6/9"],
81
+ ["alt", "7alt"],
82
+ ["-5", "Mb5"],
83
+ ["#5", "aug"],
84
+ ["b5", "Mb5"],
85
+ ["maj7b5", "M7b5"],
86
+ ["mmaj9", "mMaj9"],
87
+ ["m6/9", "m69"],
88
+ ["m6add9", "m69"],
89
+ ["sus2sus4", "sus24"]
90
+ ]);
91
+ function withoutParentheses(suffix) {
92
+ if (!/[(),]/.test(suffix))
93
+ return suffix;
94
+ if (!/^[^(),]*(?:\([^(),]+(?:,[^(),]+)*\)[^(),]*)+$/.test(suffix))
95
+ return null;
96
+ return suffix.replace(/[(),\s]/g, "");
36
97
  }
37
- function html(doc, tag, cls, text) {
38
- const el = doc.createElement(tag);
39
- if (cls)
40
- el.className = cls;
41
- if (text !== undefined)
42
- el.textContent = text;
43
- return el;
98
+ function canonicalSuffix(suffix) {
99
+ const direct = CANONICAL.get(suffix);
100
+ if (direct !== undefined)
101
+ return direct;
102
+ const flat = withoutParentheses(suffix);
103
+ if (flat === null || flat === suffix)
104
+ return suffix;
105
+ return CANONICAL.get(flat) ?? flat;
44
106
  }
45
- var NAME_PREFIX = `mn-name-${Math.random().toString(36).slice(2, 8)}-`;
46
- var names = 0;
47
- var uniqueId = () => `${NAME_PREFIX}${++names}`;
48
- function svgRoot(doc, width, height, cls, label) {
49
- const id = `${NAME_PREFIX}${++names}`;
50
- const title = svg(doc, "title", { class: "mn-name", id });
51
- title.textContent = label;
52
- return svg(doc, "svg", {
53
- xmlns: SVG_NS,
54
- viewBox: `0 0 ${width} ${height}`,
55
- width,
56
- class: `mn-svg ${cls}`,
57
- role: "img",
58
- "aria-labelledby": id
59
- }, [svg(doc, "defs", {}, [title])]);
107
+
108
+ // src/theory/scales.ts
109
+ import { Note, Scale } from "tonal";
110
+ var ALIASES = new Map([
111
+ ["natural minor", "minor"],
112
+ ["blues", "minor blues"],
113
+ ["whole-tone", "whole tone"],
114
+ ["pentatonic major", "major pentatonic"],
115
+ ["pentatonic minor", "minor pentatonic"]
116
+ ]);
117
+ function scaleName(text) {
118
+ const m = /^\s*([A-Ga-g](?:#|b|♯|♭)?)\s+(.+?)\s*$/.exec(text);
119
+ const [tonic, type] = m ? [m[1], m[2]] : ["", text.trim()];
120
+ const lower = type.toLowerCase().replace(/\s+/g, " ");
121
+ const name = ALIASES.get(lower) ?? lower;
122
+ return tonic ? `${tonic[0].toUpperCase()}${tonic.slice(1).replace("♯", "#").replace("♭", "b")} ${name}` : name;
60
123
  }
61
- var nameElement = (el) => {
62
- const id = el.getAttribute("aria-labelledby");
63
- if (!id)
64
- return null;
65
- for (const candidate of el.querySelectorAll("[id]")) {
66
- if (candidate.getAttribute("id") === id)
67
- return candidate;
68
- }
69
- return el.ownerDocument.getElementById(id);
124
+ var isScaleWithoutRoot = (text) => {
125
+ const scale = Scale.get(scaleName(text));
126
+ return !scale.empty && !scale.tonic;
70
127
  };
71
- function accessibleName(el) {
72
- const named = nameElement(el);
73
- if (named)
74
- return named.textContent;
75
- return el.getAttribute("aria-label");
76
- }
77
- function setAccessibleName(el, name) {
78
- const named = nameElement(el);
79
- if (named)
80
- named.textContent = name;
81
- else
82
- el.setAttribute("aria-label", name);
128
+ var CHARACTERISTIC = {
129
+ lydian: ["4A"],
130
+ dorian: ["6M"],
131
+ mixolydian: ["7m"],
132
+ phrygian: ["2m"],
133
+ locrian: ["5d"],
134
+ minor: ["6m"],
135
+ "minor blues": ["5d"],
136
+ "major blues": ["3m"],
137
+ "harmonic minor": ["7M"],
138
+ "melodic minor": ["6M", "7M"],
139
+ "phrygian dominant": ["2m", "3M"]
140
+ };
141
+ var MODE_WORDS = /\b(dorian|phrygian|lydian|mixolydian|aeolian|locrian|blues)\b/i;
142
+ var characteristicIntervals = (type) => CHARACTERISTIC[type] ?? [];
143
+ var marksByDefault = (written) => MODE_WORDS.test(written);
144
+ function modesOf(text) {
145
+ const scale = Scale.get(scaleName(text));
146
+ if (scale.empty || !scale.tonic)
147
+ return null;
148
+ const modes = Scale.modeNames(scale.name);
149
+ if (new Set(modes.map(([, mode]) => mode)).size < 2)
150
+ return null;
151
+ return modes.map(([tonic, mode]) => `${tonic} ${mode}`);
83
152
  }
84
- function playableMark(doc, area, ...children) {
85
- const hit = svg(doc, "rect", {
86
- class: "mn-hit",
87
- x: area.x,
88
- y: area.y,
89
- width: area.width,
90
- height: area.height,
91
- fill: "transparent",
92
- "pointer-events": "all"
93
- });
94
- return svg(doc, "g", { class: "mn-mark" }, [hit, ...children]);
153
+ var DOUBLE_ACCIDENTAL = /^[A-G](##|bb)/;
154
+ var SUPERLOCRIAN = ["1P", "2m", "3m", "4d", "5d", "6m", "7m"];
155
+ function scaleSpelling(scale) {
156
+ const hasDouble = (notes) => notes.some((n) => DOUBLE_ACCIDENTAL.test(n));
157
+ if (!hasDouble(scale.notes))
158
+ return { notes: scale.notes, intervals: scale.intervals };
159
+ if (scale.type === "altered" && scale.tonic) {
160
+ const notes = SUPERLOCRIAN.map((interval) => Note.transpose(scale.tonic, interval));
161
+ if (!hasDouble(notes))
162
+ return { notes, intervals: SUPERLOCRIAN };
163
+ }
164
+ return { notes: scale.notes, intervals: scale.intervals };
95
165
  }
166
+ var scaleTypes = () => Scale.names();
96
167
 
97
- // src/render/layout.ts
98
- function parseOrientation(text) {
99
- const value = text.trim().toLowerCase();
100
- if (value === "vertical" || value === "horizontal")
101
- return value;
102
- throw new Error(`Unknown orientation "${text}": use vertical or horizontal`);
168
+ // src/theory/note-set.ts
169
+ function markClasses(set, chroma, marks = {}) {
170
+ const classes = [];
171
+ if (set.root === chroma)
172
+ classes.push("mn-root");
173
+ else if (marks.characteristic?.has(chroma))
174
+ classes.push("mn-char");
175
+ if (marks.different?.has(chroma))
176
+ classes.push("mn-diff");
177
+ if (marks.chordTones)
178
+ classes.push(marks.chordTones.has(chroma) ? "mn-tone" : "mn-passing");
179
+ return classes.length ? ` ${classes.join(" ")}` : "";
103
180
  }
104
- function parseHand(text) {
105
- const value = text.trim().toLowerCase();
106
- if (value === "left" || value === "right")
107
- return value;
108
- throw new Error(`Unknown hand "${text}": use left or right`);
109
- }
110
- function layoutDefaults(value) {
111
- const result = {};
112
- if (!value || typeof value !== "object")
113
- return result;
114
- const word = (v) => typeof v === "string" ? v.trim().toLowerCase() : undefined;
115
- try {
116
- const { orientation, hand } = value;
117
- const h = word(hand);
118
- if (h === "left" || h === "right")
119
- result.hand = h;
120
- if (orientation && typeof orientation === "object") {
121
- for (const language of ["chord", "keyboard", "fretboard"]) {
122
- const o = word(orientation[language]);
123
- if (o === "vertical" || o === "horizontal")
124
- (result.orientation ??= {})[language] = o;
125
- }
126
- }
127
- } catch {}
128
- return result;
129
- }
130
- function titleWidth(title) {
131
- if (!title)
132
- return 0;
133
- let width = 8;
134
- for (const ch of title) {
135
- width += ch.codePointAt(0) > 591 ? 15 : /[A-Z0-9#♯♭]/.test(ch) ? 10.5 : 8;
136
- }
137
- return Math.ceil(width);
181
+ function describeMarks(set, marks = {}) {
182
+ const names = (chromas) => set.members.filter((m) => chromas?.has(m.chroma)).map((m) => m.name);
183
+ const characteristic = names(marks.characteristic);
184
+ const different = names(marks.different);
185
+ const tones = names(marks.chordTones);
186
+ return (characteristic.length ? `, characteristic notes: ${characteristic.join(" ")}` : "") + (different.length ? `, different from the compared scale: ${different.join(" ")}` : "") + (tones.length ? `, chord tones: ${tones.join(" ")}` : "");
138
187
  }
139
- var MAX_TITLE_LINES = 3;
140
- var TITLE_LINE = 17;
141
- function titleLineWidth(text) {
142
- if (!text)
143
- return 0;
144
- let width = 8;
145
- for (const ch of text) {
146
- const code = ch.codePointAt(0);
147
- width += code > 591 ? 15 : ch === " " || ".,:;'!|".includes(ch) ? 4 : "()[]-/".includes(ch) || "iljfrt".includes(ch) ? 5 : "mwMW".includes(ch) ? 12 : /[A-Z0-9#♯♭]/.test(ch) ? 9.5 : 7.8;
148
- }
149
- return Math.ceil(width);
188
+ var memberFor = (set, chroma) => set.members.find((m) => m.chroma === chroma);
189
+ var memberOf = (set, midi) => set.pitches && !set.pitches.includes(midi) ? undefined : memberFor(set, (midi % 12 + 12) % 12);
190
+ function intervalLabel(interval) {
191
+ const m = /^(\d+)([PMmdA]+)$/.exec(interval);
192
+ if (!m)
193
+ return interval;
194
+ const [, number, quality] = m;
195
+ if (number === "1" && quality === "P")
196
+ return "R";
197
+ const perfect = ["1", "4", "5", "8", "11", "12"].includes(String((Number(number) - 1) % 7 + 1));
198
+ if (quality === "P" || quality === "M")
199
+ return number;
200
+ if (quality === "m")
201
+ return `b${number}`;
202
+ if (quality.startsWith("A"))
203
+ return `${"#".repeat(quality.length)}${number}`;
204
+ return `${"b".repeat(quality.length + (perfect ? 0 : 1))}${number}`;
150
205
  }
151
- function titleLines(title, width) {
152
- const fits = (text) => titleLineWidth(text) <= width;
153
- const squeeze = (text) => ({
154
- text,
155
- textLength: fits(text) ? null : Math.max(1, width - 8)
156
- });
157
- if (fits(title))
158
- return [{ text: title, textLength: null }];
159
- const phrases = title.split(/(?<=,)\s+|\s+(?=\()/).flatMap((phrase) => fits(phrase) ? [phrase] : phrase.split(/\s+/)).filter(Boolean);
160
- const lines = [];
161
- let line = "";
162
- for (const phrase of phrases) {
163
- const next = line ? `${line} ${phrase}` : phrase;
164
- if (!line || fits(next))
165
- line = next;
166
- else {
167
- lines.push(line);
168
- line = phrase;
169
- }
170
- }
171
- if (line)
172
- lines.push(line);
173
- if (lines.length > MAX_TITLE_LINES) {
174
- const kept = lines.slice(0, MAX_TITLE_LINES - 1);
175
- kept.push(lines.slice(MAX_TITLE_LINES - 1).join(" "));
176
- return kept.map(squeeze);
206
+ function labelOf(member, label, finger) {
207
+ switch (label) {
208
+ case "none":
209
+ return "";
210
+ case "degrees":
211
+ return member.degree === null ? member.name : String(member.degree);
212
+ case "intervals":
213
+ return member.interval === null ? member.name : intervalLabel(member.interval);
214
+ case "fingers":
215
+ return finger ?? "";
216
+ default:
217
+ return member.name;
177
218
  }
178
- return lines.map(squeeze);
179
219
  }
180
- function drawTitle(doc, root, lines, x, y) {
181
- const NS = "http://www.w3.org/2000/svg";
182
- const text = doc.createElementNS(NS, "text");
183
- text.setAttribute("class", "mn-title");
184
- text.setAttribute("x", String(x));
185
- text.setAttribute("y", String(y));
186
- text.setAttribute("text-anchor", "middle");
187
- const squeeze = (el, line) => {
188
- if (line.textLength === null)
220
+ var fromNames = (title, names, intervals, chord = false) => {
221
+ const members = [];
222
+ names.forEach((name, i) => {
223
+ const chroma = chromaOf(name);
224
+ if (chroma === null || members.some((m) => m.chroma === chroma))
189
225
  return;
190
- el.setAttribute("textLength", String(line.textLength));
191
- el.setAttribute("lengthAdjust", "spacingAndGlyphs");
192
- };
193
- if (lines.length === 1) {
194
- text.textContent = lines[0].text;
195
- squeeze(text, lines[0]);
196
- } else {
197
- lines.forEach((line, i) => {
198
- const span = doc.createElementNS(NS, "tspan");
199
- span.setAttribute("x", String(x));
200
- if (i > 0)
201
- span.setAttribute("dy", String(TITLE_LINE));
202
- span.textContent = i > 0 ? ` ${line.text}` : line.text;
203
- squeeze(span, line);
204
- text.appendChild(span);
226
+ members.push({
227
+ chroma,
228
+ name,
229
+ degree: intervals ? chord ? Number(/^\d+/.exec(intervals[i] ?? "")?.[0] ?? i + 1) : i + 1 : null,
230
+ interval: intervals?.[i] ?? null
205
231
  });
232
+ });
233
+ if (!members.length)
234
+ return null;
235
+ return {
236
+ title,
237
+ members,
238
+ root: intervals ? members[0].chroma : null,
239
+ pitches: null,
240
+ preferFlats: names.some(isFlat)
241
+ };
242
+ };
243
+ function chordNoteSet(symbol) {
244
+ const parts = splitChordSymbol(symbol);
245
+ if (!parts)
246
+ return null;
247
+ const chord = Chord.getChord(canonicalSuffix(parts.suffix), parts.root);
248
+ if (chord.empty)
249
+ return null;
250
+ const bass = parts.bass;
251
+ const set = fromNames(symbol.trim(), chord.notes, chord.intervals, true);
252
+ const bassChroma = bass ? chromaOf(bass) : null;
253
+ if (set && bass && bassChroma !== null && !memberFor(set, bassChroma)) {
254
+ set.members.push({ chroma: bassChroma, name: bass, degree: null, interval: null });
206
255
  }
207
- root.setAttribute("data-mn-title-lines", String(lines.length));
208
- root.appendChild(text);
209
- return text;
256
+ return set;
210
257
  }
211
- function alignTitleLines(diagrams) {
212
- const list = [...diagrams].filter((d) => d.hasAttribute("data-mn-title-lines"));
213
- const most = Math.max(0, ...list.map((d) => Number(d.getAttribute("data-mn-title-lines"))));
214
- for (const d of list) {
215
- const missing = most - Number(d.getAttribute("data-mn-title-lines"));
216
- if (missing <= 0)
217
- continue;
218
- const shift = missing * TITLE_LINE;
219
- const doc = d.ownerDocument;
220
- const g = doc.createElementNS("http://www.w3.org/2000/svg", "g");
221
- g.setAttribute("class", "mn-title-pad");
222
- g.setAttribute("transform", `translate(0 ${shift})`);
223
- for (const child of [...d.children]) {
224
- if (child.tagName.toLowerCase() !== "defs")
225
- g.appendChild(child);
226
- }
227
- d.appendChild(g);
228
- const [x, y, w, h] = (d.getAttribute("viewBox") ?? "0 0 0 0").split(/\s+/).map(Number);
229
- d.setAttribute("viewBox", `${x} ${y} ${w} ${h + shift}`);
230
- if (d.hasAttribute("height"))
231
- d.setAttribute("height", String(Number(d.getAttribute("height")) + shift));
232
- d.setAttribute("data-mn-title-lines", String(most));
258
+ function respell(set, chord) {
259
+ set.root = chord.root;
260
+ for (const member of set.members) {
261
+ const own = memberFor(chord, member.chroma);
262
+ if (own)
263
+ member.name = own.name;
233
264
  }
234
265
  }
235
- function neckFrame(n) {
236
- const vertical = n.orientation === "vertical";
237
- const left = n.hand === "left";
238
- const content = vertical ? n.low + n.across + n.high : n.before + n.along + n.after;
239
- const shift = n.minWidth && n.minWidth > content ? (n.minWidth - content) / 2 : 0;
240
- const height = n.top + (vertical ? n.before + n.along + n.after : n.high + n.across + n.low);
241
- const at = (across, along) => {
242
- if (vertical) {
243
- const x = left ? n.high + (n.across - across) : n.low + across;
244
- return [shift + x, n.top + n.before + along];
245
- }
246
- const x = left ? content - n.before - along : n.before + along;
247
- return [shift + x, n.top + n.high + (n.across - across)];
248
- };
249
- const box = (a1, l1, a2, l2) => {
250
- const [x1, y1] = at(a1, l1);
251
- const [x2, y2] = at(a2, l2);
252
- return {
253
- x: Math.min(x1, x2),
254
- y: Math.min(y1, y2),
255
- width: Math.abs(x2 - x1),
256
- height: Math.abs(y2 - y1)
257
- };
258
- };
259
- return { width: content + 2 * shift, height, at, box };
260
- }
261
-
262
- // src/theory/pitch.ts
263
- var SHARP_NAMES = [
264
- "C",
265
- "C#",
266
- "D",
267
- "D#",
268
- "E",
269
- "F",
270
- "F#",
271
- "G",
272
- "G#",
273
- "A",
274
- "A#",
275
- "B"
276
- ];
277
- var FLAT_NAMES = ["C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"];
278
- var LETTER_CHROMA = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };
279
- function chromaOf(name) {
280
- const m = /^([A-Ga-g])([#♯b♭]*)$/.exec(name.trim());
281
- if (!m)
266
+ function scaleNoteSet(name) {
267
+ const scale = Scale2.get(scaleName(name));
268
+ if (scale.empty || !scale.tonic)
282
269
  return null;
283
- let chroma = LETTER_CHROMA[m[1].toUpperCase()];
284
- for (const accidental of m[2])
285
- chroma += accidental === "#" || accidental === "♯" ? 1 : -1;
286
- return (chroma % 12 + 12) % 12;
270
+ const { notes, intervals } = scaleSpelling(scale);
271
+ const set = fromNames(name.trim(), notes, intervals);
272
+ if (set)
273
+ set.scaleType = scale.type;
274
+ return set;
287
275
  }
288
- function midiOf(note) {
289
- const m = /^([A-Ga-g][#♯b♭]*)(-?\d)$/.exec(note.trim());
290
- if (!m)
276
+ function rootNameOf(text) {
277
+ const name = text.trim().replace(/-?\d$/, "").replace(/♯/g, "#").replace(/♭/g, "b");
278
+ if (chromaOf(name) === null)
291
279
  return null;
292
- const chroma = chromaOf(m[1]);
293
- if (chroma === null)
280
+ return name[0].toUpperCase() + name.slice(1);
281
+ }
282
+ var PLAIN_INTERVALS = ["1P", "2m", "2M", "3m", "3M", "4P", "5d", "5P", "6m", "6M", "7m", "7M"];
283
+ function intervalFrom(root, name) {
284
+ const from = rootNameOf(root);
285
+ const to = rootNameOf(name);
286
+ if (from === null || to === null)
294
287
  return null;
295
- const letter = LETTER_CHROMA[m[1][0].toUpperCase()];
296
- const shift = Math.round((chroma - letter) / 12);
297
- return (Number(m[2]) + 1) * 12 + chroma - shift * 12;
288
+ const semitones = (chromaOf(to) - chromaOf(from) + 12) % 12;
289
+ if (semitones === 0)
290
+ return "1P";
291
+ const spelled = Interval.distance(from, to);
292
+ const m = /^(\d+)([PMmdA]+)$/.exec(spelled);
293
+ return m && m[1] !== "1" && m[1] !== "8" ? spelled : PLAIN_INTERVALS[semitones];
298
294
  }
299
- var nameOf = (chroma, preferFlats = false) => (preferFlats ? FLAT_NAMES : SHARP_NAMES)[((Math.round(chroma) || 0) % 12 + 12) % 12];
300
- var doubleSharp = (name) => name.replace(/x$/, "##");
301
- function splitChordSymbol(symbol) {
302
- const normalized = symbol.trim().replace(/♯/g, "#").replace(/♭/g, "b").replace(/𝄪/g, "x").replace(/𝄫/g, "bb");
303
- const m = /^([A-G](?:##|x(?!\d)|bb|#|b)?)(.*?)(?:\/([A-G](?:##|x|bb|#|b)?))?$/.exec(normalized);
304
- return m ? { root: doubleSharp(m[1]), suffix: m[2], bass: m[3] ? doubleSharp(m[3]) : null } : null;
295
+ function emptyNoteSet(title = "no notes") {
296
+ return { title, members: [], root: null, pitches: null, preferFlats: false, list: true };
297
+ }
298
+ function listNoteSet(text, root) {
299
+ const tokens = text.split(/[\s,]+/).filter(Boolean);
300
+ if (!tokens.length)
301
+ return null;
302
+ const withOctaves = tokens.every((t) => midiOf(t) !== null);
303
+ const names = withOctaves ? tokens.map((t) => t.replace(/-?\d$/, "")) : tokens;
304
+ if (!withOctaves && names.some((n) => chromaOf(n) === null))
305
+ return null;
306
+ const set = fromNames(tokens.join(" "), names, null);
307
+ if (!set)
308
+ return null;
309
+ set.list = true;
310
+ if (withOctaves)
311
+ set.pitches = tokens.map((t) => midiOf(t));
312
+ if (root === undefined)
313
+ return set;
314
+ const rootName = rootNameOf(root);
315
+ if (rootName === null)
316
+ return null;
317
+ set.root = chromaOf(rootName);
318
+ for (const member of set.members) {
319
+ member.interval = intervalFrom(rootName, member.name);
320
+ member.degree = Number(/^\d+/.exec(member.interval ?? "")?.[0] ?? 1);
321
+ }
322
+ return set;
305
323
  }
306
- var noteOf = (midi, preferFlats = false) => `${nameOf(midi, preferFlats)}${Math.floor(midi / 12) - 1}`;
307
- var isFlat = (name) => /^[A-Ga-g][b♭]/.test(name.trim());
308
324
 
309
- // src/chord/guitar.ts
310
- var STANDARD_TUNING = [40, 45, 50, 55, 59, 64];
311
- function chartNoteName(name) {
312
- if (!/^[A-G](##|bb)$/.test(name))
313
- return name;
314
- return nameOf(chromaOf(name), name.endsWith("b"));
325
+ // src/theory/chord-symbol.ts
326
+ var QUALITY_SUFFIXES = [
327
+ [/^(m7b5|m7-5|ø7?)$/, "Minor 7 flat 5"],
328
+ [/^(dim7|°7)$/, "Diminished 7"],
329
+ [/^(maj9|M9|Δ9)$/, "Major 9"],
330
+ [/^(maj7|M7|Δ7?)$/, "Major 7"],
331
+ [/^(7sus4)$/, "7sus4"],
332
+ [/^(m9|min9|-9)$/, "Minor 9"],
333
+ [/^(m7|min7|-7)$/, "Minor 7"],
334
+ [/^(m6|min6|-6)$/, "Minor 6"],
335
+ [/^(m|min|-)$/, "Minor"],
336
+ [/^(dim|°)$/, "Diminished"],
337
+ [/^(aug|\+|\+5|#5)$/, "Augmented"],
338
+ [/^(sus2)$/, "Sus2"],
339
+ [/^(sus4|sus)$/, "Sus4"],
340
+ [/^(add9|add2)$/, "Add9"],
341
+ [/^5$/, "5 (Power)"],
342
+ [/^(6\/9|69)$/, "6/9"],
343
+ [/^(m6\/9|m69|m6add9)$/, "Minor 6/9"],
344
+ [/^(Mb5|b5|-5)$/, "Major flat 5"],
345
+ [/^(mM7|mMaj7|mmaj7|m\(maj7\)|-\(maj7\))$/, "Minor major 7"],
346
+ [/^(13|11|9|7|6)$/, "$1"],
347
+ [/^(maj|M)?$/, "Major"]
348
+ ];
349
+ var ACCIDENTAL_WORDS = {
350
+ "#": " Sharp",
351
+ "##": " Double Sharp",
352
+ b: " Flat",
353
+ bb: " Double Flat"
354
+ };
355
+ var spellNote = (note) => note[0] + (ACCIDENTAL_WORDS[note.slice(1)] ?? "");
356
+ var plain = (quality) => quality.replace(/\s*\([^)]*\)/g, "").trim();
357
+ function parseChord(symbol) {
358
+ const parts = splitChordSymbol(symbol);
359
+ if (!parts)
360
+ return null;
361
+ const trimmed = symbol.trim();
362
+ const { root, bass } = parts;
363
+ const suffix = withoutParentheses(parts.suffix);
364
+ let quality = null;
365
+ for (const written of suffix === null || suffix === parts.suffix ? [parts.suffix] : [parts.suffix, suffix]) {
366
+ for (const [re, label] of QUALITY_SUFFIXES) {
367
+ const hit = re.exec(written);
368
+ if (hit) {
369
+ quality = label.replace("$1", hit[1] ?? "");
370
+ break;
371
+ }
372
+ }
373
+ if (quality)
374
+ break;
375
+ }
376
+ if (suffix === null && !quality)
377
+ return null;
378
+ if (!quality && suffix !== null && chordNoteSet(trimmed))
379
+ quality = suffix;
380
+ if (!quality)
381
+ return null;
382
+ return {
383
+ symbol: trimmed,
384
+ root,
385
+ quality,
386
+ bass,
387
+ name: `${spellNote(root)} ${plain(quality)}${bass ? ` over ${spellNote(bass)}` : ""}`
388
+ };
315
389
  }
316
- function parseFrets(text) {
317
- const trimmed = text.trim();
318
- const tokens = /[\s,-]/.test(trimmed) ? trimmed.split(/[\s,-]+/) : [...trimmed];
319
- const frets = tokens.filter(Boolean).map((t) => /^[xX]$/.test(t) ? null : /^\d+$/.test(t) ? Number(t) : NaN);
320
- return frets.length >= 2 && frets.every((f) => f === null || Number.isInteger(f) && f <= 36) ? frets : null;
390
+
391
+ // src/theory/naming.ts
392
+ var NAMINGS = ["letters", "solfege", "german"];
393
+ var NAMING_ERROR = "naming: write letters, solfege or german";
394
+ var DIRECTIVE_ERROR = "naming: write {naming: letters}, {naming: solfege} or {naming: german}";
395
+ var plain2 = (text) => text.trim().toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "");
396
+ function parseNaming(text) {
397
+ const value = plain2(text);
398
+ if (NAMINGS.includes(value))
399
+ return value;
400
+ throw new Error(NAMING_ERROR);
321
401
  }
322
- function parseFingers(text) {
323
- const trimmed = text.trim();
324
- const tokens = /[\s,]/.test(trimmed) || trimmed.includes("-", 1) ? trimmed.split(/[\s,-]+/) : [...trimmed];
325
- return tokens.filter(Boolean).map((t) => /^[0xX]$/.test(t) ? null : t.toUpperCase());
402
+ function namingOf(value) {
403
+ if (typeof value !== "string")
404
+ return null;
405
+ try {
406
+ return parseNaming(value);
407
+ } catch {
408
+ return null;
409
+ }
326
410
  }
327
- function baseFretOf(frets) {
328
- const fretted = frets.filter((f) => f !== null && f > 0);
329
- if (!fretted.length || Math.max(...fretted) <= 4)
330
- return 1;
331
- return Math.min(...fretted);
411
+ var SYLLABLE_LETTER = {
412
+ do: "C",
413
+ re: "D",
414
+ mi: "E",
415
+ fa: "F",
416
+ sol: "G",
417
+ la: "A",
418
+ si: "B"
419
+ };
420
+ var SYLLABLE = "(Do|DO|R[eé]|R[EÉ]|Mi|MI|Fa|FA|Sol|SOL|La|LA|Si|SI)";
421
+ var SIGN = "(##|bb|#|b|♯|♭)?";
422
+ var syllableLetter = (syllable) => SYLLABLE_LETTER[plain2(syllable)];
423
+ var AFTER_ROOT = /^(?:$|[0-9/(+°øΔ^-]|m|M|a(?:dd|ug|lt)|sus|dim)/;
424
+ var QUALITY_WORD = /^(?:[0-9(+°øΔ^]|m|M|a(?:dd|ug|lt)|sus|dim)/;
425
+ var WORD_QUALITY = /^(?:major|minor)$/i;
426
+ var joinsAsQuality = (word) => QUALITY_WORD.test(word) && !WORD_QUALITY.test(word);
427
+ var reads = (letters) => midiOf(letters) !== null || /^[A-G]/.test(letters) && parseChord(letters) !== null;
428
+ function rootToken(token, naming, h, solfegeLine = false) {
429
+ const b = naming === "german" ? /^B(?![#♯b♭x])(.*)$/.exec(token) : null;
430
+ if (b && AFTER_ROOT.test(b[1])) {
431
+ const letters = `Bb${b[1]}`;
432
+ if (reads(letters))
433
+ return letters;
434
+ }
435
+ if (naming !== "solfege" && !solfegeLine && reads(token))
436
+ return null;
437
+ const solfege = new RegExp(`^${SYLLABLE}${SIGN}(.*)$`).exec(token);
438
+ if (solfege) {
439
+ for (const sign of [solfege[2] ?? "", ""].filter((s, i, all) => all.indexOf(s) === i)) {
440
+ const rest = token.slice(solfege[1].length + sign.length);
441
+ const letters = `${syllableLetter(solfege[1])}${sign}${rest}`;
442
+ if (AFTER_ROOT.test(rest) && reads(letters))
443
+ return letters;
444
+ }
445
+ }
446
+ if (h) {
447
+ const hm = /^H(##|bb|#|b|♯|♭|x)?(.*)$/.exec(token);
448
+ if (hm && AFTER_ROOT.test(hm[2])) {
449
+ const letters = `B${hm[1] ?? ""}${hm[2]}`;
450
+ if (reads(letters))
451
+ return letters;
452
+ }
453
+ }
454
+ return null;
332
455
  }
333
- function barresOf(voicing, capoFret) {
334
- const byKey = new Map;
335
- voicing.frets.forEach((fret, string) => {
336
- const finger = voicing.fingers[string];
337
- if (fret === null || fret === 0 || fret === capoFret || !finger)
338
- return;
339
- const key = `${finger}@${fret}`;
340
- byKey.set(key, [...byKey.get(key) ?? [], string]);
341
- });
342
- const barres = [];
343
- for (const [key, strings] of byKey) {
344
- if (strings.length < 2)
456
+ var NOTE_ONLY = /^[A-G](?:##|bb|#|b|♯|♭|x)?$/;
457
+ function letterPiece(piece, naming, h, line = false) {
458
+ if (!piece)
459
+ return piece;
460
+ const lower = plain2(piece);
461
+ if (/^majeure?$/.test(lower))
462
+ return "major";
463
+ if (/^mineure?$/.test(lower))
464
+ return "minor";
465
+ const range = /^(.+\d)-(.+\d)$/.exec(piece);
466
+ if (range) {
467
+ const [from, to] = [range[1], range[2]].map((n) => rootToken(n, naming, h, line) ?? n);
468
+ return `${from}-${to}`;
469
+ }
470
+ const slash = piece.indexOf("/");
471
+ if (slash > 0) {
472
+ const head = piece.slice(0, slash);
473
+ const bass = piece.slice(slash + 1);
474
+ const bassLetters = rootToken(bass, naming, h, line) ?? (NOTE_ONLY.test(bass) ? bass : null);
475
+ if (bassLetters && NOTE_ONLY.test(bassLetters)) {
476
+ const headLetters = rootToken(head, naming, h, line) ?? head;
477
+ const whole = `${headLetters}/${bassLetters}`;
478
+ if (whole !== piece && !(naming === "letters" && !line && reads(piece)))
479
+ return whole;
480
+ return piece;
481
+ }
482
+ }
483
+ return rootToken(piece, naming, h, line) ?? piece;
484
+ }
485
+ function letterWord(word, naming, h, changes, line = false) {
486
+ const out = word.split(/([,|;])/).map((piece, i) => i % 2 ? piece : letterPiece(piece, naming, h, line)).join("");
487
+ if (out !== word)
488
+ changes.push([word, out]);
489
+ return out;
490
+ }
491
+ var syllableOnly = (word) => new RegExp(`^${SYLLABLE}${SIGN}$`).test(word);
492
+ function read(text, naming, options, changes) {
493
+ const h = options.h ?? true;
494
+ let out = text.normalize("NFC").replace(new RegExp(`(^|[\\s,/|])${SYLLABLE}\\s+(dièse|diese|bémol|bemol)(?=$|[\\s,|])`, "g"), (_, before, syllable, sign) => `${before}${syllable}${/^d/.test(sign) ? "#" : "b"}`);
495
+ if (options.chord) {
496
+ const joined = new RegExp(`^\\s*${SYLLABLE}${SIGN}\\s+(\\S+)\\s*$`).exec(out);
497
+ if (joined && joinsAsQuality(joined[3])) {
498
+ const word = `${joined[1]}${joined[2] ?? ""}${joined[3]}`;
499
+ const letters = rootToken(word, naming, h) ?? letterPiece(word, naming, h);
500
+ if (letters !== word) {
501
+ changes.push([out.trim(), letters]);
502
+ return letters;
503
+ }
504
+ }
505
+ }
506
+ const words = out.split(/(\s+)/);
507
+ for (let i = 0;i + 2 < words.length; i += 2) {
508
+ const head = words[i];
509
+ const next = words[i + 2];
510
+ if (!syllableOnly(head) || !joinsAsQuality(next))
345
511
  continue;
346
- const [finger, fretText] = key.split("@");
347
- const fret = Number(fretText);
348
- const from = Math.min(...strings);
349
- const to = Math.max(...strings);
350
- let under = false;
351
- for (let s = from + 1;s < to; s++) {
352
- const f = voicing.frets[s];
353
- if (!strings.includes(s) && f !== null && f !== undefined && f > fret)
354
- under = true;
512
+ if (naming !== "solfege" && reads(head))
513
+ continue;
514
+ const joined = `${head}${next}`;
515
+ const letters = letterPiece(joined, naming, h);
516
+ if (letters !== joined) {
517
+ words.splice(i, 3, joined);
518
+ i -= 2;
355
519
  }
356
- barres.push({ fret, from, to, finger, strings, full: under || strings.length > 3 });
357
520
  }
358
- return barres;
521
+ out = words.join("");
522
+ const line = out.split(/[\s,|;]+/).some((w) => w !== "" && !/^Do/.test(w) && !reads(w) && rootToken(w, "solfege", false) !== null);
523
+ return out.replace(/\S+/g, (word) => letterWord(word, naming, h, changes, line));
359
524
  }
360
- function barreKind(voicing) {
361
- const barres = barresOf(voicing, null);
362
- if (!barres.length)
363
- return null;
364
- return barres.some((b) => b.full) ? "full" : "partial";
525
+ function toLetters(text, naming = "letters", options = {}) {
526
+ return read(text, naming, options, []);
365
527
  }
366
- var isBarreVoicing = (voicing) => barreKind(voicing) !== null;
367
- var SPACING = 18;
368
- var ROW = 20;
369
- var MARKERS = 16;
370
- var HIT_ALONG = 44;
371
- var BASE = 30;
372
- var TITLE = 22;
373
- var CAPTION = 18;
374
- var capoCaption = (capo, sounds) => `Capo ${capo}${sounds ? `, sounds ${sounds}` : ""}`;
375
- function renderGuitarDiagram(doc, voicing, options = {}) {
376
- const strings = voicing.frets.length;
377
- const base = voicing.baseFret ?? baseFretOf(voicing.frets);
378
- const fretted = voicing.frets.filter((f) => f !== null && f > 0);
379
- const rows = Math.max(4, fretted.length ? Math.max(...fretted) - base + 1 : 0);
380
- const orientation = options.orientation ?? "vertical";
381
- const vertical = orientation === "vertical";
382
- const capo = options.capo && options.capo > 0 ? options.capo : 0;
383
- const fromNut = capo > 0 && options.fretsFrom === "nut";
384
- const capoFret = fromNut ? capo : null;
385
- const caption = capo && options.caption !== false ? capoCaption(capo, options.sounds) : undefined;
386
- const layout = {
387
- orientation,
388
- hand: options.hand ?? "right",
389
- across: (strings - 1) * SPACING,
390
- along: rows * ROW,
391
- before: MARKERS,
392
- after: 10,
393
- low: vertical || base > 1 ? BASE : 10,
394
- high: vertical ? 14 : 10,
395
- top: 4,
396
- minWidth: titleWidth(caption)
397
- };
398
- const lines = options.title ? titleLines(options.title, neckFrame(layout).width) : [];
399
- const frame = neckFrame({
400
- ...layout,
401
- top: lines.length ? TITLE + (lines.length - 1) * TITLE_LINE : 4
402
- });
403
- const across = (string) => string * SPACING;
404
- const along = (row) => row * ROW;
405
- const at = (string, row) => frame.at(across(string), along(row));
406
- const label = `${options.title ? `${options.title} chord diagram` : "Chord diagram"}${capo ? `, ${capoCaption(capo, options.sounds).replace(/^Capo/, "capo")}` : ""}`;
407
- const height = frame.height + (caption ? CAPTION : 0);
408
- const root = svgRoot(doc, frame.width, height, "mn-guitar-chord", label);
409
- root.setAttribute("data-mn-hand", options.hand ?? "right");
410
- const fretText = voicing.frets.map((f) => f === null ? "x" : String(f));
411
- root.setAttribute("data-mn-voicing", fretText.some((f) => f.length > 1) ? fretText.join("-") : fretText.join(""));
412
- if (caption) {
413
- root.appendChild(svgText(doc, caption, {
414
- class: "mn-caption",
415
- x: frame.width / 2,
416
- y: height - 6,
417
- "text-anchor": "middle"
418
- }));
528
+ var NOTE_KEYS = new Set([
529
+ "chord",
530
+ "chords",
531
+ "symbol",
532
+ "name",
533
+ "from",
534
+ "to",
535
+ "scale",
536
+ "notes",
537
+ "root",
538
+ "key",
539
+ "arpeggio",
540
+ "compare",
541
+ "scales-for",
542
+ "scales-for-notes",
543
+ "modes",
544
+ "progression",
545
+ "tuning",
546
+ "range",
547
+ "highlight",
548
+ "pitches",
549
+ "sounds",
550
+ "mode"
551
+ ]);
552
+ var SINGLE_CHORD_KEYS = new Set(["chord", "symbol", "from", "to", "sounds"]);
553
+ var KEY_LINE = /^(\s*)([A-Za-z][A-Za-z-]*)(\s*:\s*)(.*)$/;
554
+ var NAMING_LINE = /^\s*naming\s*:\s*(.*)$/i;
555
+ var NAMING_DIRECTIVE = /^\s*\{\s*naming\s*:\s*([^}]*)\}\s*$/i;
556
+ var DIAGRAM_SHORTHAND = new Set(["chord", "keyboard", "fretboard", "circle"]);
557
+ function spacedTuning(value, naming) {
558
+ const compact = /^\s*((?:[A-Ha-h](?:#|b|♯|♭)?){4,})\s*$/.exec(value);
559
+ if (!compact || naming !== "german" && !/h/i.test(compact[1]))
560
+ return value;
561
+ return compact[1].match(/[A-Ha-h](?:#|b|♯|♭)?/g).map((n) => n[0].toUpperCase() + n.slice(1)).join(" ");
562
+ }
563
+ function lettersInBlock(language, text) {
564
+ const result = { text, naming: null, changes: [], titles: [], warning: null };
565
+ if (language === "tab" || language === "score")
566
+ return result;
567
+ const lines = [];
568
+ for (const line of text.split(`
569
+ `)) {
570
+ const own = (language === "chords" ? NAMING_DIRECTIVE : NAMING_LINE).exec(line);
571
+ if (!own) {
572
+ lines.push(line);
573
+ continue;
574
+ }
575
+ if (language !== "chords")
576
+ result.naming = parseNaming(own[1]);
577
+ else {
578
+ const naming = namingOf(own[1]);
579
+ if (naming)
580
+ result.naming = naming;
581
+ else
582
+ result.warning = DIRECTIVE_ERROR;
583
+ }
419
584
  }
420
- if (capo) {
421
- root.setAttribute("data-mn-capo", String(capo));
422
- root.setAttribute("data-mn-frets-from", fromNut ? "nut" : "capo");
423
- }
424
- if (lines.length)
425
- drawTitle(doc, root, lines, frame.width / 2, 15);
426
- for (let row = 0;row <= rows; row++) {
427
- const cls = row === 0 && base === 1 && (!capo || fromNut) ? "mn-nut" : "mn-fret";
428
- root.appendChild(svgLine(doc, at(0, row), at(strings - 1, row), cls));
429
- }
430
- const capoRow = fromNut ? capo - base + 0.5 : base === 1 ? 0 : null;
431
- if (capo && capoRow !== null && capoRow >= 0 && capoRow <= rows) {
432
- root.appendChild(svg(doc, "rect", {
433
- class: "mn-capo",
434
- ...frame.box(across(0) - 8, along(capoRow) - 3, across(strings - 1) + 8, along(capoRow) + 3),
435
- rx: 3
436
- }));
437
- }
438
- for (let s = 0;s < strings; s++) {
439
- root.appendChild(svgLine(doc, at(s, 0), at(s, rows), "mn-string"));
440
- }
441
- if (base > 1) {
442
- const label = `${base}fr`;
443
- root.appendChild(vertical ? svgLabel(doc, label, frame.at(-10, along(0.5)), "mn-base-fret", options.hand === "left" ? "start" : "end") : svgLabel(doc, label, frame.at(-16, along(0.5)), "mn-base-fret"));
444
- }
445
- const textOf = (s) => (options.labels ? options.labels[s] : voicing.fingers[s]) ?? null;
446
- const quiet = new Set;
447
- const fingered = voicing.fingers.some((f) => f);
448
- const barres = fingered ? barresOf(voicing, capoFret) : options.barreFingers ? barresOf({ frets: voicing.frets, fingers: [...options.barreFingers] }, capoFret).filter((b) => b.full) : [];
449
- for (const barre of barres) {
450
- const texts = new Set(barre.strings.map(textOf));
451
- if (texts.size === 1) {
452
- for (const s of barre.strings)
453
- if (s !== barre.from)
454
- quiet.add(s);
455
- } else if (!barre.full) {
456
- continue;
457
- }
458
- const middle = along(barre.fret - base + 0.5);
459
- root.appendChild(svg(doc, "rect", {
460
- class: "mn-barre",
461
- ...frame.box(across(barre.from) - 7, middle - 7, across(barre.to) + 7, middle + 7),
462
- rx: 7,
463
- "data-mn-fret": barre.fret,
464
- "data-mn-finger": barre.finger,
465
- "data-mn-from": strings - barre.from,
466
- "data-mn-to": strings - barre.to
467
- }));
585
+ const naming = result.naming ?? "letters";
586
+ const named = result.naming !== null;
587
+ const changes = result.changes;
588
+ if (language === "chords") {
589
+ if (!named) {
590
+ result.text = lines.join(`
591
+ `);
592
+ return result;
593
+ }
594
+ result.text = lines.map((line) => line.replace(/\[([^\]]+)\]/g, (whole, inside) => {
595
+ const letters = read(inside, naming, { chord: true }, changes);
596
+ return letters === inside ? whole : `[${letters}]`;
597
+ }).replace(/^(\s*\{\s*(?:key|define|chord)\s*:\s*)([^}]*?)(\s*\}\s*)$/i, (_, head, value, tail) => {
598
+ if (/^\s*\{\s*key/i.test(head))
599
+ return `${head}${read(value, naming, {}, changes)}${tail}`;
600
+ const [name, ...rest] = value.split(/(\s+)/);
601
+ return `${head}${read(name, naming, { chord: true }, changes)}${rest.join("")}${tail}`;
602
+ })).join(`
603
+ `);
604
+ return result;
468
605
  }
469
- const tuning = options.tuning ?? (strings === 6 ? STANDARD_TUNING : undefined);
470
- voicing.frets.forEach((fret, s) => {
471
- const markAlong = -8;
472
- const mark = frame.at(across(s), markAlong);
473
- const string = strings - s;
474
- if (fret === null) {
475
- const [x, y] = mark;
476
- const d = 3.5;
477
- root.appendChild(svg(doc, "path", {
478
- class: "mn-muted",
479
- d: `M${x - d} ${y - d}L${x + d} ${y + d}M${x + d} ${y - d}L${x - d} ${y + d}`,
480
- "data-mn-string": string
481
- }));
482
- return;
483
- }
484
- const openString = tuning?.[s];
485
- const open = openString === undefined ? undefined : openString + (fromNut ? 0 : capo);
486
- const isRoot = options.root !== undefined && options.root !== null && open !== undefined && (open + fret) % 12 === options.root;
487
- const midi = {
488
- "data-mn-string": string,
489
- "data-mn-fret": fret,
490
- ...open !== undefined ? { "data-midi": open + fret } : {}
491
- };
492
- const place = (markAt, ...els) => {
493
- if (open === undefined) {
494
- for (const el of els)
495
- root.appendChild(el);
496
- return;
606
+ const shorthand = DIAGRAM_SHORTHAND.has(language);
607
+ result.text = lines.map((line) => {
608
+ if (/^\s*-{3,}\s*$/.test(line) || !line.trim())
609
+ return line;
610
+ const kv = KEY_LINE.exec(line);
611
+ if (kv) {
612
+ const key = kv[2].toLowerCase();
613
+ if (key === "title") {
614
+ result.titles.push(kv[4].trim());
615
+ return line;
497
616
  }
498
- const area = frame.box(across(s) - SPACING / 2, markAt - HIT_ALONG / 2, across(s) + SPACING / 2, markAt + HIT_ALONG / 2);
499
- root.appendChild(playableMark(doc, area, ...els));
500
- };
501
- if (fret === 0) {
502
- const [cx, cy] = mark;
503
- place(markAlong, svg(doc, "circle", {
504
- class: `mn-open${isRoot ? " mn-root" : ""}`,
505
- cx,
506
- cy,
507
- r: 4,
508
- ...midi
509
- }));
510
- return;
511
- }
512
- const row = along(fret - base + 0.5);
513
- const center = at(s, fret - base + 0.5);
514
- const [cx, cy] = center;
515
- if (fret === capoFret) {
516
- place(row, svg(doc, "circle", {
517
- class: `mn-capo-open${isRoot ? " mn-root" : ""}`,
518
- cx,
519
- cy,
520
- r: 4,
521
- ...midi
522
- }));
523
- return;
524
- }
525
- const text = quiet.has(s) ? null : textOf(s);
526
- place(row, svg(doc, "circle", {
527
- class: `mn-dot${isRoot ? " mn-root" : ""}${options.marks?.[s] ? ` mn-${options.marks[s]}` : ""}`,
528
- cx,
529
- cy,
530
- r: 7,
531
- ...midi
532
- }), ...text ? [dotLabel(doc, text, center, 7)] : []);
533
- });
534
- if (tuning) {
535
- const shift = fromNut ? 0 : capo;
536
- const pitches = voicing.frets.flatMap((f, s) => f === null ? [] : [tuning[s] + shift + f]);
537
- root.setAttribute("data-mn-pitches", pitches.join(" "));
538
- root.setAttribute("data-mn-play", "chord");
539
- root.setAttribute("data-mn-sound", "guitar");
617
+ if (!NOTE_KEYS.has(key))
618
+ return line;
619
+ if (key === "name")
620
+ result.titles.push(kv[4].trim());
621
+ const value = key === "tuning" ? spacedTuning(kv[4], naming) : kv[4];
622
+ const letters = read(value, naming, { chord: SINGLE_CHORD_KEYS.has(key) }, changes);
623
+ if (letters !== kv[4])
624
+ changes.push([kv[4].trim(), letters.trim()]);
625
+ return `${kv[1]}${kv[2]}${kv[3]}${letters}`;
626
+ }
627
+ if (shorthand)
628
+ return read(line, naming, { chord: language === "chord", h: named }, changes);
629
+ if (language === "progression")
630
+ return read(line, naming, { h: named }, changes);
631
+ if (language === "strum" || language === "picking")
632
+ return line.replace(/\[([^\]]+)\]/g, (whole, inside) => {
633
+ const letters = read(inside, naming, { chord: true, h: named }, changes);
634
+ return letters === inside ? whole : `[${letters}]`;
635
+ });
636
+ return line;
637
+ }).join(`
638
+ `);
639
+ return result;
640
+ }
641
+ function quoteAsWritten(message, changes) {
642
+ let out = message;
643
+ for (const [written, letters] of [...changes].sort((a, b) => b[1].length - a[1].length)) {
644
+ if (written !== letters)
645
+ out = out.split(`"${letters}"`).join(`"${written}"`);
540
646
  }
541
- return root;
647
+ return out;
542
648
  }
543
-
544
- // src/theory/transpose.ts
545
- import { Interval, Note } from "tonal";
546
- var FLAT_KEYS = new Set([5, 10, 3, 8, 1]);
547
- var FLAT_MINOR_KEYS = new Set([2, 7, 0, 5, 10, 3]);
548
- function tonicOf(key) {
549
- const m = /^([A-G][#♯b♭]?)\s*(.*)$/.exec(key.trim());
649
+ var LETTER_SYLLABLE = {
650
+ C: "Do",
651
+ D: "Ré",
652
+ E: "Mi",
653
+ F: "Fa",
654
+ G: "Sol",
655
+ A: "La",
656
+ B: "Si"
657
+ };
658
+ var SOLFEGE_SIGNS = {
659
+ "#": "♯",
660
+ "♯": "♯",
661
+ b: "♭",
662
+ "♭": "♭",
663
+ "##": "♯♯",
664
+ x: "♯♯",
665
+ bb: "♭♭",
666
+ "♭♭": "♭♭",
667
+ "♯♯": "♯♯"
668
+ };
669
+ var ROOT = /^([A-G])(##|bb|♯♯|♭♭|#|b|♯|♭|x)?/;
670
+ function noteInNaming(name, naming) {
671
+ if (naming === "letters")
672
+ return name;
673
+ const m = /^([A-G])(##|bb|♯♯|♭♭|#|b|♯|♭|x)?$/.exec(name.trim());
550
674
  if (!m)
551
- return null;
552
- return { tonic: m[1], minor: /^(m|min|minor)(?![a-z])/i.test(m[2]) && !/^maj/i.test(m[2]) };
675
+ return name;
676
+ const [, letter, sign = ""] = m;
677
+ if (naming === "solfege")
678
+ return `${LETTER_SYLLABLE[letter]}${SOLFEGE_SIGNS[sign] ?? ""}`;
679
+ if (letter !== "B")
680
+ return name.trim();
681
+ return sign === "b" || sign === "♭" ? "B" : `H${sign}`;
682
+ }
683
+ function chordInNaming(symbol, naming) {
684
+ if (naming === "letters")
685
+ return symbol;
686
+ const text = symbol.trim();
687
+ const root = ROOT.exec(text);
688
+ if (!root || !parseChord(text))
689
+ return symbol;
690
+ const rest = text.slice(root[0].length);
691
+ const slash = /^(.*)\/([A-G](?:##|bb|♯♯|♭♭|#|b|♯|♭|x)?)$/.exec(rest);
692
+ const suffix = slash ? slash[1] : rest;
693
+ const bass = slash ? `/${noteInNaming(slash[2], naming)}` : "";
694
+ const shownSuffix = naming === "solfege" && suffix ? ` ${suffix}` : suffix;
695
+ return `${noteInNaming(root[0], naming)}${shownSuffix}${bass}`;
696
+ }
697
+ var AFTER_A_NOTE = new Set([
698
+ "major",
699
+ "minor",
700
+ "pentatonic",
701
+ "blues",
702
+ "dorian",
703
+ "phrygian",
704
+ "lydian",
705
+ "mixolydian",
706
+ "aeolian",
707
+ "ionian",
708
+ "locrian",
709
+ "harmonic",
710
+ "melodic",
711
+ "chromatic",
712
+ "whole",
713
+ "augmented",
714
+ "diminished",
715
+ "bebop",
716
+ "arpeggio",
717
+ "chord",
718
+ "string",
719
+ "position",
720
+ "box",
721
+ "scale",
722
+ "mode"
723
+ ]);
724
+ var OCTAVE = /^([A-G](?:##|bb|#|b|♯|♭|x)?)(-?\d)$/;
725
+ function shownText(text, naming) {
726
+ if (naming === "letters" || !text)
727
+ return text;
728
+ const parts = text.split(/(\s+|[,;:()])/);
729
+ const word = (i, step) => {
730
+ for (let j = i + step;j >= 0 && j < parts.length; j += step) {
731
+ const p = parts[j];
732
+ if (!p.trim())
733
+ continue;
734
+ return /^[,;:()]$/.test(p) ? null : p;
735
+ }
736
+ return null;
737
+ };
738
+ return parts.map((part, i) => {
739
+ if (!/^[A-G]/.test(part))
740
+ return part;
741
+ const next = word(i, 1);
742
+ if (next === "shape")
743
+ return part;
744
+ const octave = OCTAVE.exec(part);
745
+ if (octave) {
746
+ const amongNotes = [word(i, -1), next].some((w) => w !== null && OCTAVE.test(w));
747
+ if (amongNotes || !/^[5679]$/.test(octave[2]))
748
+ return `${noteInNaming(octave[1], naming)}${octave[2]}`;
749
+ }
750
+ if (part === "A" && next && /^[a-z]/.test(next) && !AFTER_A_NOTE.has(next))
751
+ return part;
752
+ if (parseChord(part))
753
+ return chordInNaming(part, naming);
754
+ const both = part.split("/");
755
+ if (both.length === 2 && both.every((p) => /^[A-G]/.test(p) && parseChord(p)))
756
+ return both.map((p) => chordInNaming(p, naming)).join("/");
757
+ return part;
758
+ }).join("");
759
+ }
760
+ var current = "letters";
761
+ var verbatim = [];
762
+ function withNaming(naming, draw, titles = []) {
763
+ const before = [current, verbatim];
764
+ current = naming;
765
+ verbatim = titles.filter(Boolean);
766
+ try {
767
+ return draw();
768
+ } finally {
769
+ [current, verbatim] = before;
770
+ }
553
771
  }
554
- function keyPrefersFlats(key) {
555
- const parts = tonicOf(key);
556
- const chroma = parts ? chromaOf(parts.tonic) : null;
557
- if (!parts || chroma === null)
558
- return false;
559
- if (isFlat(parts.tonic))
560
- return true;
561
- if (/[#♯]/.test(parts.tonic))
562
- return false;
563
- return parts.minor ? FLAT_MINOR_KEYS.has(chroma) : FLAT_KEYS.has(chroma);
772
+ function shown(text) {
773
+ if (current === "letters" || !text)
774
+ return text;
775
+ for (const title of verbatim) {
776
+ if (text === title)
777
+ return text;
778
+ if (text.startsWith(`${title},`))
779
+ return title + shownText(text.slice(title.length), current);
780
+ }
781
+ return shownText(text, current);
564
782
  }
565
- var shift = (note, semitones, preferFlats) => {
566
- const chroma = chromaOf(note);
567
- return chroma === null ? note : nameOf(chroma + semitones, preferFlats);
783
+
784
+ // src/render/dom.ts
785
+ var SVG_NS = "http://www.w3.org/2000/svg";
786
+ var apply = (el, attrs) => {
787
+ for (const [name, value] of Object.entries(attrs)) {
788
+ if (value !== undefined)
789
+ el.setAttribute(name, String(value));
790
+ }
568
791
  };
569
- function moveByLetter(note, interval) {
570
- const moved = Note.transpose(note, interval);
571
- return /^[A-G](#{3,}|b{3,})$/.test(moved) ? Note.simplify(moved) : moved;
792
+ function svg(doc, tag, attrs = {}, children = []) {
793
+ const el = doc.createElementNS(SVG_NS, tag);
794
+ apply(el, attrs);
795
+ for (const child of children)
796
+ if (child)
797
+ el.appendChild(child);
798
+ return el;
572
799
  }
573
- function transposeChord(symbol, semitones, spelling) {
574
- const trimmed = symbol.trim();
575
- const parts = splitChordSymbol(trimmed);
576
- const steps = Math.round(semitones) || 0;
577
- if (!parts || steps % 12 === 0)
578
- return trimmed;
579
- if (typeof spelling === "object") {
580
- const interval = Interval.distance(spelling.from.replace("♯", "#").replace("♭", "b"), spelling.to.replace("♯", "#").replace("♭", "b"));
581
- const moves = Interval.semitones(interval);
582
- if (moves !== undefined && ((moves - steps) % 12 + 12) % 12 === 0) {
583
- const bass = parts.bass ? `/${moveByLetter(parts.bass, interval)}` : "";
584
- return `${moveByLetter(parts.root, interval)}${parts.suffix}${bass}`;
585
- }
586
- spelling = keyPrefersFlats(spelling.to);
800
+ function svgText(doc, text, attrs = {}) {
801
+ const el = svg(doc, "text", attrs);
802
+ el.textContent = text;
803
+ return el;
804
+ }
805
+ function svgLabel(doc, text, [x, y], cls, anchor = "middle") {
806
+ return svgText(doc, text, { class: cls, x, y: y + 4, "text-anchor": anchor });
807
+ }
808
+ function dotLabel(doc, text, point, r) {
809
+ const label = svgLabel(doc, shown(text), point, "mn-dot-text");
810
+ if ([...shown(text)].length >= 3) {
811
+ label.classList.add("mn-dot-text-long");
812
+ label.setAttribute("textLength", String(2 * r - 2));
813
+ label.setAttribute("lengthAdjust", "spacingAndGlyphs");
587
814
  }
588
- const flats = spelling ?? isFlat(parts.root);
589
- const bass = parts.bass ? `/${shift(parts.bass, steps, flats)}` : "";
590
- return `${shift(parts.root, steps, flats)}${parts.suffix}${bass}`;
815
+ return label;
591
816
  }
592
- function transposeKey(key, semitones) {
593
- const m = /^([A-G][#♯b♭]?)(.*)$/.exec(key.trim());
594
- const chroma = m ? chromaOf(m[1]) : null;
595
- const steps = Math.round(semitones) || 0;
596
- if (!m || chroma === null || steps % 12 === 0)
597
- return key.trim();
598
- const target = ((chroma + steps) % 12 + 12) % 12;
599
- const minor = /^\s*(m|min|minor)\b/.test(m[2]);
600
- const flats = minor ? FLAT_MINOR_KEYS.has(target) : FLAT_KEYS.has(target);
601
- return `${nameOf(target, flats)}${m[2]}`;
817
+ function svgLine(doc, [x1, y1], [x2, y2], cls) {
818
+ return svg(doc, "line", { class: cls, x1, y1, x2, y2 });
602
819
  }
603
- function keyMove(key, semitones) {
604
- const from = tonicOf(key);
605
- const to = tonicOf(transposeKey(key, semitones));
606
- return from && to && chromaOf(from.tonic) !== null ? { from: from.tonic, to: to.tonic } : null;
820
+ function html(doc, tag, cls, text) {
821
+ const el = doc.createElement(tag);
822
+ if (cls)
823
+ el.className = cls;
824
+ if (text !== undefined)
825
+ el.textContent = text;
826
+ return el;
607
827
  }
608
-
609
- // src/theory/note-set.ts
610
- import { Chord, Interval as Interval2, Scale as Scale2 } from "tonal";
611
-
612
- // src/theory/suffix.ts
613
- var CANONICAL = new Map([
614
- ["M", ""],
615
- ["maj", ""],
616
- ["min", "m"],
617
- ["-", "m"],
618
- ["M7", "maj7"],
619
- ["Δ", "maj7"],
620
- ["Δ7", "maj7"],
621
- ["M9", "maj9"],
622
- ["Δ9", "maj9"],
623
- ["min6", "m6"],
624
- ["-6", "m6"],
625
- ["min7", "m7"],
626
- ["-7", "m7"],
627
- ["min9", "m9"],
628
- ["-9", "m9"],
629
- ["ø", "m7b5"],
630
- ["ø7", "m7b5"],
631
- ["m7-5", "m7b5"],
632
- ["mmaj7", "mMaj7"],
633
- ["mM7", "mMaj7"],
634
- ["m(maj7)", "mMaj7"],
635
- ["-(maj7)", "mMaj7"],
636
- ["°", "dim"],
637
- ["°7", "dim7"],
638
- ["+", "aug"],
639
- ["sus", "sus4"],
640
- ["add2", "add9"],
641
- ["69", "6/9"],
642
- ["alt", "7alt"],
643
- ["-5", "Mb5"],
644
- ["#5", "aug"],
645
- ["b5", "Mb5"],
646
- ["maj7b5", "M7b5"],
647
- ["mmaj9", "mMaj9"],
648
- ["m6/9", "m69"],
649
- ["m6add9", "m69"],
650
- ["sus2sus4", "sus24"]
651
- ]);
652
- function withoutParentheses(suffix) {
653
- if (!/[(),]/.test(suffix))
654
- return suffix;
655
- if (!/^[^(),]*(?:\([^(),]+(?:,[^(),]+)*\)[^(),]*)+$/.test(suffix))
656
- return null;
657
- return suffix.replace(/[(),\s]/g, "");
658
- }
659
- function canonicalSuffix(suffix) {
660
- const direct = CANONICAL.get(suffix);
661
- if (direct !== undefined)
662
- return direct;
663
- const flat = withoutParentheses(suffix);
664
- if (flat === null || flat === suffix)
665
- return suffix;
666
- return CANONICAL.get(flat) ?? flat;
667
- }
668
-
669
- // src/theory/scales.ts
670
- import { Note as Note2, Scale } from "tonal";
671
- var ALIASES = new Map([
672
- ["natural minor", "minor"],
673
- ["blues", "minor blues"],
674
- ["whole-tone", "whole tone"],
675
- ["pentatonic major", "major pentatonic"],
676
- ["pentatonic minor", "minor pentatonic"]
677
- ]);
678
- function scaleName(text) {
679
- const m = /^\s*([A-Ga-g](?:#|b|♯|♭)?)\s+(.+?)\s*$/.exec(text);
680
- const [tonic, type] = m ? [m[1], m[2]] : ["", text.trim()];
681
- const lower = type.toLowerCase().replace(/\s+/g, " ");
682
- const name = ALIASES.get(lower) ?? lower;
683
- return tonic ? `${tonic[0].toUpperCase()}${tonic.slice(1).replace("♯", "#").replace("♭", "b")} ${name}` : name;
828
+ var NAME_PREFIX = `mn-name-${Math.random().toString(36).slice(2, 8)}-`;
829
+ var names = 0;
830
+ var uniqueId = () => `${NAME_PREFIX}${++names}`;
831
+ var SHOWN_NAMES = /\bmn-(guitar-chord|fretboard|keyboard|circle)\b/;
832
+ function svgRoot(doc, width, height, cls, label) {
833
+ const id = `${NAME_PREFIX}${++names}`;
834
+ const title = svg(doc, "title", { class: "mn-name", id });
835
+ title.textContent = SHOWN_NAMES.test(cls) ? shown(label) : label;
836
+ return svg(doc, "svg", {
837
+ xmlns: SVG_NS,
838
+ viewBox: `0 0 ${width} ${height}`,
839
+ width,
840
+ class: `mn-svg ${cls}`,
841
+ role: "img",
842
+ "aria-labelledby": id
843
+ }, [svg(doc, "defs", {}, [title])]);
684
844
  }
685
- var isScaleWithoutRoot = (text) => {
686
- const scale = Scale.get(scaleName(text));
687
- return !scale.empty && !scale.tonic;
688
- };
689
- var CHARACTERISTIC = {
690
- lydian: ["4A"],
691
- dorian: ["6M"],
692
- mixolydian: ["7m"],
693
- phrygian: ["2m"],
694
- locrian: ["5d"],
695
- minor: ["6m"],
696
- "minor blues": ["5d"],
697
- "major blues": ["3m"],
698
- "harmonic minor": ["7M"],
699
- "melodic minor": ["6M", "7M"],
700
- "phrygian dominant": ["2m", "3M"]
701
- };
702
- var MODE_WORDS = /\b(dorian|phrygian|lydian|mixolydian|aeolian|locrian|blues)\b/i;
703
- var characteristicIntervals = (type) => CHARACTERISTIC[type] ?? [];
704
- var marksByDefault = (written) => MODE_WORDS.test(written);
705
- function modesOf(text) {
706
- const scale = Scale.get(scaleName(text));
707
- if (scale.empty || !scale.tonic)
708
- return null;
709
- const modes = Scale.modeNames(scale.name);
710
- if (new Set(modes.map(([, mode]) => mode)).size < 2)
845
+ var nameElement = (el) => {
846
+ const id = el.getAttribute("aria-labelledby");
847
+ if (!id)
711
848
  return null;
712
- return modes.map(([tonic, mode]) => `${tonic} ${mode}`);
713
- }
714
- var DOUBLE_ACCIDENTAL = /^[A-G](##|bb)/;
715
- var SUPERLOCRIAN = ["1P", "2m", "3m", "4d", "5d", "6m", "7m"];
716
- function scaleSpelling(scale) {
717
- const hasDouble = (notes) => notes.some((n) => DOUBLE_ACCIDENTAL.test(n));
718
- if (!hasDouble(scale.notes))
719
- return { notes: scale.notes, intervals: scale.intervals };
720
- if (scale.type === "altered" && scale.tonic) {
721
- const notes = SUPERLOCRIAN.map((interval) => Note2.transpose(scale.tonic, interval));
722
- if (!hasDouble(notes))
723
- return { notes, intervals: SUPERLOCRIAN };
849
+ for (const candidate of el.querySelectorAll("[id]")) {
850
+ if (candidate.getAttribute("id") === id)
851
+ return candidate;
724
852
  }
725
- return { notes: scale.notes, intervals: scale.intervals };
853
+ return el.ownerDocument.getElementById(id);
854
+ };
855
+ function accessibleName(el) {
856
+ const named = nameElement(el);
857
+ if (named)
858
+ return named.textContent;
859
+ return el.getAttribute("aria-label");
860
+ }
861
+ function setAccessibleName(el, name) {
862
+ const named = nameElement(el);
863
+ if (named)
864
+ named.textContent = name;
865
+ else
866
+ el.setAttribute("aria-label", name);
867
+ }
868
+ function playableMark(doc, area, ...children) {
869
+ const hit = svg(doc, "rect", {
870
+ class: "mn-hit",
871
+ x: area.x,
872
+ y: area.y,
873
+ width: area.width,
874
+ height: area.height,
875
+ fill: "transparent",
876
+ "pointer-events": "all"
877
+ });
878
+ return svg(doc, "g", { class: "mn-mark" }, [hit, ...children]);
726
879
  }
727
- var scaleTypes = () => Scale.names();
728
880
 
729
- // src/theory/note-set.ts
730
- function markClasses(set, chroma, marks = {}) {
731
- const classes = [];
732
- if (set.root === chroma)
733
- classes.push("mn-root");
734
- else if (marks.characteristic?.has(chroma))
735
- classes.push("mn-char");
736
- if (marks.different?.has(chroma))
737
- classes.push("mn-diff");
738
- if (marks.chordTones)
739
- classes.push(marks.chordTones.has(chroma) ? "mn-tone" : "mn-passing");
740
- return classes.length ? ` ${classes.join(" ")}` : "";
881
+ // src/render/layout.ts
882
+ function parseOrientation(text) {
883
+ const value = text.trim().toLowerCase();
884
+ if (value === "vertical" || value === "horizontal")
885
+ return value;
886
+ throw new Error(`Unknown orientation "${text}": use vertical or horizontal`);
741
887
  }
742
- function describeMarks(set, marks = {}) {
743
- const names = (chromas) => set.members.filter((m) => chromas?.has(m.chroma)).map((m) => m.name);
744
- const characteristic = names(marks.characteristic);
745
- const different = names(marks.different);
746
- const tones = names(marks.chordTones);
747
- return (characteristic.length ? `, characteristic notes: ${characteristic.join(" ")}` : "") + (different.length ? `, different from the compared scale: ${different.join(" ")}` : "") + (tones.length ? `, chord tones: ${tones.join(" ")}` : "");
888
+ function parseHand(text) {
889
+ const value = text.trim().toLowerCase();
890
+ if (value === "left" || value === "right")
891
+ return value;
892
+ throw new Error(`Unknown hand "${text}": use left or right`);
748
893
  }
749
- var memberFor = (set, chroma) => set.members.find((m) => m.chroma === chroma);
750
- var memberOf = (set, midi) => set.pitches && !set.pitches.includes(midi) ? undefined : memberFor(set, (midi % 12 + 12) % 12);
751
- function intervalLabel(interval) {
752
- const m = /^(\d+)([PMmdA]+)$/.exec(interval);
753
- if (!m)
754
- return interval;
755
- const [, number, quality] = m;
756
- if (number === "1" && quality === "P")
757
- return "R";
758
- const perfect = ["1", "4", "5", "8", "11", "12"].includes(String((Number(number) - 1) % 7 + 1));
759
- if (quality === "P" || quality === "M")
760
- return number;
761
- if (quality === "m")
762
- return `b${number}`;
763
- if (quality.startsWith("A"))
764
- return `${"#".repeat(quality.length)}${number}`;
765
- return `${"b".repeat(quality.length + (perfect ? 0 : 1))}${number}`;
894
+ function layoutDefaults(value) {
895
+ const result = {};
896
+ if (!value || typeof value !== "object")
897
+ return result;
898
+ const word = (v) => typeof v === "string" ? v.trim().toLowerCase() : undefined;
899
+ try {
900
+ const { orientation, hand } = value;
901
+ const h = word(hand);
902
+ if (h === "left" || h === "right")
903
+ result.hand = h;
904
+ if (orientation && typeof orientation === "object") {
905
+ for (const language of ["chord", "keyboard", "fretboard"]) {
906
+ const o = word(orientation[language]);
907
+ if (o === "vertical" || o === "horizontal")
908
+ (result.orientation ??= {})[language] = o;
909
+ }
910
+ }
911
+ } catch {}
912
+ return result;
766
913
  }
767
- function labelOf(member, label, finger) {
768
- switch (label) {
769
- case "none":
770
- return "";
771
- case "degrees":
772
- return member.degree === null ? member.name : String(member.degree);
773
- case "intervals":
774
- return member.interval === null ? member.name : intervalLabel(member.interval);
775
- case "fingers":
776
- return finger ?? "";
777
- default:
778
- return member.name;
914
+ function titleWidth(title) {
915
+ if (!title)
916
+ return 0;
917
+ let width = 8;
918
+ for (const ch of title) {
919
+ width += ch.codePointAt(0) > 591 ? 15 : /[A-Z0-9#♯♭]/.test(ch) ? 10.5 : 8;
779
920
  }
921
+ return Math.ceil(width);
780
922
  }
781
- var fromNames = (title, names, intervals, chord = false) => {
782
- const members = [];
783
- names.forEach((name, i) => {
784
- const chroma = chromaOf(name);
785
- if (chroma === null || members.some((m) => m.chroma === chroma))
786
- return;
787
- members.push({
788
- chroma,
789
- name,
790
- degree: intervals ? chord ? Number(/^\d+/.exec(intervals[i] ?? "")?.[0] ?? i + 1) : i + 1 : null,
791
- interval: intervals?.[i] ?? null
792
- });
923
+ var MAX_TITLE_LINES = 3;
924
+ var TITLE_LINE = 17;
925
+ function titleLineWidth(text) {
926
+ if (!text)
927
+ return 0;
928
+ let width = 8;
929
+ for (const ch of text) {
930
+ const code = ch.codePointAt(0);
931
+ width += code > 591 ? 15 : ch === " " || ".,:;'!|".includes(ch) ? 4 : "()[]-/".includes(ch) || "iljfrt".includes(ch) ? 5 : "mwMW".includes(ch) ? 12 : /[A-Z0-9#♯♭]/.test(ch) ? 9.5 : 7.8;
932
+ }
933
+ return Math.ceil(width);
934
+ }
935
+ function titleLines(title, width) {
936
+ const fits = (text) => titleLineWidth(text) <= width;
937
+ const squeeze = (text) => ({
938
+ text,
939
+ textLength: fits(text) ? null : Math.max(1, width - 8)
793
940
  });
794
- if (!members.length)
795
- return null;
796
- return {
797
- title,
798
- members,
799
- root: intervals ? members[0].chroma : null,
800
- pitches: null,
801
- preferFlats: names.some(isFlat)
941
+ if (fits(title))
942
+ return [{ text: title, textLength: null }];
943
+ const phrases = title.split(/(?<=,)\s+|\s+(?=\()/).flatMap((phrase) => fits(phrase) ? [phrase] : phrase.split(/\s+/)).filter(Boolean);
944
+ const lines = [];
945
+ let line = "";
946
+ for (const phrase of phrases) {
947
+ const next = line ? `${line} ${phrase}` : phrase;
948
+ if (!line || fits(next))
949
+ line = next;
950
+ else {
951
+ lines.push(line);
952
+ line = phrase;
953
+ }
954
+ }
955
+ if (line)
956
+ lines.push(line);
957
+ if (lines.length > MAX_TITLE_LINES) {
958
+ const kept = lines.slice(0, MAX_TITLE_LINES - 1);
959
+ kept.push(lines.slice(MAX_TITLE_LINES - 1).join(" "));
960
+ return kept.map(squeeze);
961
+ }
962
+ return lines.map(squeeze);
963
+ }
964
+ function drawTitle(doc, root, lines, x, y) {
965
+ const NS = "http://www.w3.org/2000/svg";
966
+ const text = doc.createElementNS(NS, "text");
967
+ text.setAttribute("class", "mn-title");
968
+ text.setAttribute("x", String(x));
969
+ text.setAttribute("y", String(y));
970
+ text.setAttribute("text-anchor", "middle");
971
+ const squeeze = (el, line) => {
972
+ if (line.textLength === null)
973
+ return;
974
+ el.setAttribute("textLength", String(line.textLength));
975
+ el.setAttribute("lengthAdjust", "spacingAndGlyphs");
802
976
  };
803
- };
804
- function chordNoteSet(symbol) {
805
- const parts = splitChordSymbol(symbol);
806
- if (!parts)
807
- return null;
808
- const chord = Chord.getChord(canonicalSuffix(parts.suffix), parts.root);
809
- if (chord.empty)
810
- return null;
811
- const bass = parts.bass;
812
- const set = fromNames(symbol.trim(), chord.notes, chord.intervals, true);
813
- const bassChroma = bass ? chromaOf(bass) : null;
814
- if (set && bass && bassChroma !== null && !memberFor(set, bassChroma)) {
815
- set.members.push({ chroma: bassChroma, name: bass, degree: null, interval: null });
977
+ if (lines.length === 1) {
978
+ text.textContent = lines[0].text;
979
+ squeeze(text, lines[0]);
980
+ } else {
981
+ lines.forEach((line, i) => {
982
+ const span = doc.createElementNS(NS, "tspan");
983
+ span.setAttribute("x", String(x));
984
+ if (i > 0)
985
+ span.setAttribute("dy", String(TITLE_LINE));
986
+ span.textContent = i > 0 ? ` ${line.text}` : line.text;
987
+ squeeze(span, line);
988
+ text.appendChild(span);
989
+ });
816
990
  }
817
- return set;
991
+ root.setAttribute("data-mn-title-lines", String(lines.length));
992
+ root.appendChild(text);
993
+ return text;
818
994
  }
819
- function respell(set, chord) {
820
- set.root = chord.root;
821
- for (const member of set.members) {
822
- const own = memberFor(chord, member.chroma);
823
- if (own)
824
- member.name = own.name;
995
+ function alignTitleLines(diagrams) {
996
+ const list = [...diagrams].filter((d) => d.hasAttribute("data-mn-title-lines"));
997
+ const most = Math.max(0, ...list.map((d) => Number(d.getAttribute("data-mn-title-lines"))));
998
+ for (const d of list) {
999
+ const missing = most - Number(d.getAttribute("data-mn-title-lines"));
1000
+ if (missing <= 0)
1001
+ continue;
1002
+ const shift = missing * TITLE_LINE;
1003
+ const doc = d.ownerDocument;
1004
+ const g = doc.createElementNS("http://www.w3.org/2000/svg", "g");
1005
+ g.setAttribute("class", "mn-title-pad");
1006
+ g.setAttribute("transform", `translate(0 ${shift})`);
1007
+ for (const child of [...d.children]) {
1008
+ if (child.tagName.toLowerCase() !== "defs")
1009
+ g.appendChild(child);
1010
+ }
1011
+ d.appendChild(g);
1012
+ const [x, y, w, h] = (d.getAttribute("viewBox") ?? "0 0 0 0").split(/\s+/).map(Number);
1013
+ d.setAttribute("viewBox", `${x} ${y} ${w} ${h + shift}`);
1014
+ if (d.hasAttribute("height"))
1015
+ d.setAttribute("height", String(Number(d.getAttribute("height")) + shift));
1016
+ d.setAttribute("data-mn-title-lines", String(most));
1017
+ }
1018
+ }
1019
+ function neckFrame(n) {
1020
+ const vertical = n.orientation === "vertical";
1021
+ const left = n.hand === "left";
1022
+ const content = vertical ? n.low + n.across + n.high : n.before + n.along + n.after;
1023
+ const shift = n.minWidth && n.minWidth > content ? (n.minWidth - content) / 2 : 0;
1024
+ const height = n.top + (vertical ? n.before + n.along + n.after : n.high + n.across + n.low);
1025
+ const at = (across, along) => {
1026
+ if (vertical) {
1027
+ const x = left ? n.high + (n.across - across) : n.low + across;
1028
+ return [shift + x, n.top + n.before + along];
1029
+ }
1030
+ const x = left ? content - n.before - along : n.before + along;
1031
+ return [shift + x, n.top + n.high + (n.across - across)];
1032
+ };
1033
+ const box = (a1, l1, a2, l2) => {
1034
+ const [x1, y1] = at(a1, l1);
1035
+ const [x2, y2] = at(a2, l2);
1036
+ return {
1037
+ x: Math.min(x1, x2),
1038
+ y: Math.min(y1, y2),
1039
+ width: Math.abs(x2 - x1),
1040
+ height: Math.abs(y2 - y1)
1041
+ };
1042
+ };
1043
+ return { width: content + 2 * shift, height, at, box };
1044
+ }
1045
+
1046
+ // src/chord/guitar.ts
1047
+ var STANDARD_TUNING = [40, 45, 50, 55, 59, 64];
1048
+ function chartNoteName(name) {
1049
+ if (!/^[A-G](##|bb)$/.test(name))
1050
+ return name;
1051
+ return nameOf(chromaOf(name), name.endsWith("b"));
1052
+ }
1053
+ function parseFrets(text) {
1054
+ const trimmed = text.trim();
1055
+ const tokens = /[\s,-]/.test(trimmed) ? trimmed.split(/[\s,-]+/) : [...trimmed];
1056
+ const frets = tokens.filter(Boolean).map((t) => /^[xX]$/.test(t) ? null : /^\d+$/.test(t) ? Number(t) : NaN);
1057
+ return frets.length >= 2 && frets.every((f) => f === null || Number.isInteger(f) && f <= 36) ? frets : null;
1058
+ }
1059
+ function parseFingers(text) {
1060
+ const trimmed = text.trim();
1061
+ const tokens = /[\s,]/.test(trimmed) || trimmed.includes("-", 1) ? trimmed.split(/[\s,-]+/) : [...trimmed];
1062
+ return tokens.filter(Boolean).map((t) => /^[0xX]$/.test(t) ? null : t.toUpperCase());
1063
+ }
1064
+ function baseFretOf(frets) {
1065
+ const fretted = frets.filter((f) => f !== null && f > 0);
1066
+ if (!fretted.length || Math.max(...fretted) <= 4)
1067
+ return 1;
1068
+ return Math.min(...fretted);
1069
+ }
1070
+ function barresOf(voicing, capoFret) {
1071
+ const byKey = new Map;
1072
+ voicing.frets.forEach((fret, string) => {
1073
+ const finger = voicing.fingers[string];
1074
+ if (fret === null || fret === 0 || fret === capoFret || !finger)
1075
+ return;
1076
+ const key = `${finger}@${fret}`;
1077
+ byKey.set(key, [...byKey.get(key) ?? [], string]);
1078
+ });
1079
+ const barres = [];
1080
+ for (const [key, strings] of byKey) {
1081
+ if (strings.length < 2)
1082
+ continue;
1083
+ const [finger, fretText] = key.split("@");
1084
+ const fret = Number(fretText);
1085
+ const from = Math.min(...strings);
1086
+ const to = Math.max(...strings);
1087
+ let under = false;
1088
+ for (let s = from + 1;s < to; s++) {
1089
+ const f = voicing.frets[s];
1090
+ if (!strings.includes(s) && f !== null && f !== undefined && f > fret)
1091
+ under = true;
1092
+ }
1093
+ barres.push({ fret, from, to, finger, strings, full: under || strings.length > 3 });
1094
+ }
1095
+ return barres;
1096
+ }
1097
+ function barreKind(voicing) {
1098
+ const barres = barresOf(voicing, null);
1099
+ if (!barres.length)
1100
+ return null;
1101
+ return barres.some((b) => b.full) ? "full" : "partial";
1102
+ }
1103
+ var isBarreVoicing = (voicing) => barreKind(voicing) !== null;
1104
+ var SPACING = 18;
1105
+ var ROW = 20;
1106
+ var MARKERS = 16;
1107
+ var HIT_ALONG = 44;
1108
+ var BASE = 30;
1109
+ var TITLE = 22;
1110
+ var CAPTION = 18;
1111
+ var capoCaption = (capo, sounds) => `Capo ${capo}${sounds ? `, sounds ${sounds}` : ""}`;
1112
+ function renderGuitarDiagram(doc, voicing, options = {}) {
1113
+ const strings = voicing.frets.length;
1114
+ const base = voicing.baseFret ?? baseFretOf(voicing.frets);
1115
+ const fretted = voicing.frets.filter((f) => f !== null && f > 0);
1116
+ const rows = Math.max(4, fretted.length ? Math.max(...fretted) - base + 1 : 0);
1117
+ const orientation = options.orientation ?? "vertical";
1118
+ const vertical = orientation === "vertical";
1119
+ const capo = options.capo && options.capo > 0 ? options.capo : 0;
1120
+ const fromNut = capo > 0 && options.fretsFrom === "nut";
1121
+ const capoFret = fromNut ? capo : null;
1122
+ const caption = capo && options.caption !== false ? shown(capoCaption(capo, options.sounds)) : undefined;
1123
+ const layout = {
1124
+ orientation,
1125
+ hand: options.hand ?? "right",
1126
+ across: (strings - 1) * SPACING,
1127
+ along: rows * ROW,
1128
+ before: MARKERS,
1129
+ after: 10,
1130
+ low: vertical || base > 1 ? BASE : 10,
1131
+ high: vertical ? 14 : 10,
1132
+ top: 4,
1133
+ minWidth: titleWidth(caption)
1134
+ };
1135
+ const lines = options.title ? titleLines(shown(options.title), neckFrame(layout).width) : [];
1136
+ const frame = neckFrame({
1137
+ ...layout,
1138
+ top: lines.length ? TITLE + (lines.length - 1) * TITLE_LINE : 4
1139
+ });
1140
+ const across = (string) => string * SPACING;
1141
+ const along = (row) => row * ROW;
1142
+ const at = (string, row) => frame.at(across(string), along(row));
1143
+ const label = `${options.title ? `${options.title} chord diagram` : "Chord diagram"}${capo ? `, ${capoCaption(capo, options.sounds).replace(/^Capo/, "capo")}` : ""}`;
1144
+ const height = frame.height + (caption ? CAPTION : 0);
1145
+ const root = svgRoot(doc, frame.width, height, "mn-guitar-chord", label);
1146
+ root.setAttribute("data-mn-hand", options.hand ?? "right");
1147
+ const fretText = voicing.frets.map((f) => f === null ? "x" : String(f));
1148
+ root.setAttribute("data-mn-voicing", fretText.some((f) => f.length > 1) ? fretText.join("-") : fretText.join(""));
1149
+ if (caption) {
1150
+ root.appendChild(svgText(doc, caption, {
1151
+ class: "mn-caption",
1152
+ x: frame.width / 2,
1153
+ y: height - 6,
1154
+ "text-anchor": "middle"
1155
+ }));
1156
+ }
1157
+ if (capo) {
1158
+ root.setAttribute("data-mn-capo", String(capo));
1159
+ root.setAttribute("data-mn-frets-from", fromNut ? "nut" : "capo");
1160
+ }
1161
+ if (lines.length)
1162
+ drawTitle(doc, root, lines, frame.width / 2, 15);
1163
+ for (let row = 0;row <= rows; row++) {
1164
+ const cls = row === 0 && base === 1 && (!capo || fromNut) ? "mn-nut" : "mn-fret";
1165
+ root.appendChild(svgLine(doc, at(0, row), at(strings - 1, row), cls));
1166
+ }
1167
+ const capoRow = fromNut ? capo - base + 0.5 : base === 1 ? 0 : null;
1168
+ if (capo && capoRow !== null && capoRow >= 0 && capoRow <= rows) {
1169
+ root.appendChild(svg(doc, "rect", {
1170
+ class: "mn-capo",
1171
+ ...frame.box(across(0) - 8, along(capoRow) - 3, across(strings - 1) + 8, along(capoRow) + 3),
1172
+ rx: 3
1173
+ }));
1174
+ }
1175
+ for (let s = 0;s < strings; s++) {
1176
+ root.appendChild(svgLine(doc, at(s, 0), at(s, rows), "mn-string"));
1177
+ }
1178
+ if (base > 1) {
1179
+ const label = `${base}fr`;
1180
+ root.appendChild(vertical ? svgLabel(doc, label, frame.at(-10, along(0.5)), "mn-base-fret", options.hand === "left" ? "start" : "end") : svgLabel(doc, label, frame.at(-16, along(0.5)), "mn-base-fret"));
1181
+ }
1182
+ const textOf = (s) => (options.labels ? options.labels[s] : voicing.fingers[s]) ?? null;
1183
+ const quiet = new Set;
1184
+ const fingered = voicing.fingers.some((f) => f);
1185
+ const barres = fingered ? barresOf(voicing, capoFret) : options.barreFingers ? barresOf({ frets: voicing.frets, fingers: [...options.barreFingers] }, capoFret).filter((b) => b.full) : [];
1186
+ for (const barre of barres) {
1187
+ const texts = new Set(barre.strings.map(textOf));
1188
+ if (texts.size === 1) {
1189
+ for (const s of barre.strings)
1190
+ if (s !== barre.from)
1191
+ quiet.add(s);
1192
+ } else if (!barre.full) {
1193
+ continue;
1194
+ }
1195
+ const middle = along(barre.fret - base + 0.5);
1196
+ root.appendChild(svg(doc, "rect", {
1197
+ class: "mn-barre",
1198
+ ...frame.box(across(barre.from) - 7, middle - 7, across(barre.to) + 7, middle + 7),
1199
+ rx: 7,
1200
+ "data-mn-fret": barre.fret,
1201
+ "data-mn-finger": barre.finger,
1202
+ "data-mn-from": strings - barre.from,
1203
+ "data-mn-to": strings - barre.to
1204
+ }));
1205
+ }
1206
+ const tuning = options.tuning ?? (strings === 6 ? STANDARD_TUNING : undefined);
1207
+ voicing.frets.forEach((fret, s) => {
1208
+ const markAlong = -8;
1209
+ const mark = frame.at(across(s), markAlong);
1210
+ const string = strings - s;
1211
+ if (fret === null) {
1212
+ const [x, y] = mark;
1213
+ const d = 3.5;
1214
+ root.appendChild(svg(doc, "path", {
1215
+ class: "mn-muted",
1216
+ d: `M${x - d} ${y - d}L${x + d} ${y + d}M${x + d} ${y - d}L${x - d} ${y + d}`,
1217
+ "data-mn-string": string
1218
+ }));
1219
+ return;
1220
+ }
1221
+ const openString = tuning?.[s];
1222
+ const open = openString === undefined ? undefined : openString + (fromNut ? 0 : capo);
1223
+ const isRoot = options.root !== undefined && options.root !== null && open !== undefined && (open + fret) % 12 === options.root;
1224
+ const midi = {
1225
+ "data-mn-string": string,
1226
+ "data-mn-fret": fret,
1227
+ ...open !== undefined ? { "data-midi": open + fret } : {}
1228
+ };
1229
+ const place = (markAt, ...els) => {
1230
+ if (open === undefined) {
1231
+ for (const el of els)
1232
+ root.appendChild(el);
1233
+ return;
1234
+ }
1235
+ const area = frame.box(across(s) - SPACING / 2, markAt - HIT_ALONG / 2, across(s) + SPACING / 2, markAt + HIT_ALONG / 2);
1236
+ root.appendChild(playableMark(doc, area, ...els));
1237
+ };
1238
+ if (fret === 0) {
1239
+ const [cx, cy] = mark;
1240
+ place(markAlong, svg(doc, "circle", {
1241
+ class: `mn-open${isRoot ? " mn-root" : ""}`,
1242
+ cx,
1243
+ cy,
1244
+ r: 4,
1245
+ ...midi
1246
+ }));
1247
+ return;
1248
+ }
1249
+ const row = along(fret - base + 0.5);
1250
+ const center = at(s, fret - base + 0.5);
1251
+ const [cx, cy] = center;
1252
+ if (fret === capoFret) {
1253
+ place(row, svg(doc, "circle", {
1254
+ class: `mn-capo-open${isRoot ? " mn-root" : ""}`,
1255
+ cx,
1256
+ cy,
1257
+ r: 4,
1258
+ ...midi
1259
+ }));
1260
+ return;
1261
+ }
1262
+ const text = quiet.has(s) ? null : textOf(s);
1263
+ place(row, svg(doc, "circle", {
1264
+ class: `mn-dot${isRoot ? " mn-root" : ""}${options.marks?.[s] ? ` mn-${options.marks[s]}` : ""}`,
1265
+ cx,
1266
+ cy,
1267
+ r: 7,
1268
+ ...midi
1269
+ }), ...text ? [dotLabel(doc, text, center, 7)] : []);
1270
+ });
1271
+ if (tuning) {
1272
+ const shift = fromNut ? 0 : capo;
1273
+ const pitches = voicing.frets.flatMap((f, s) => f === null ? [] : [tuning[s] + shift + f]);
1274
+ root.setAttribute("data-mn-pitches", pitches.join(" "));
1275
+ root.setAttribute("data-mn-play", "chord");
1276
+ root.setAttribute("data-mn-sound", "guitar");
825
1277
  }
1278
+ return root;
826
1279
  }
827
- function scaleNoteSet(name) {
828
- const scale = Scale2.get(scaleName(name));
829
- if (scale.empty || !scale.tonic)
830
- return null;
831
- const { notes, intervals } = scaleSpelling(scale);
832
- const set = fromNames(name.trim(), notes, intervals);
833
- if (set)
834
- set.scaleType = scale.type;
835
- return set;
836
- }
837
- function rootNameOf(text) {
838
- const name = text.trim().replace(/-?\d$/, "").replace(/♯/g, "#").replace(/♭/g, "b");
839
- if (chromaOf(name) === null)
1280
+
1281
+ // src/theory/transpose.ts
1282
+ import { Interval as Interval2, Note as Note2 } from "tonal";
1283
+ var FLAT_KEYS = new Set([5, 10, 3, 8, 1]);
1284
+ var FLAT_MINOR_KEYS = new Set([2, 7, 0, 5, 10, 3]);
1285
+ function tonicOf(key) {
1286
+ const m = /^([A-G][#♯b♭]?)\s*(.*)$/.exec(key.trim());
1287
+ if (!m)
840
1288
  return null;
841
- return name[0].toUpperCase() + name.slice(1);
1289
+ return { tonic: m[1], minor: /^(m|min|minor)(?![a-z])/i.test(m[2]) && !/^maj/i.test(m[2]) };
842
1290
  }
843
- var PLAIN_INTERVALS = ["1P", "2m", "2M", "3m", "3M", "4P", "5d", "5P", "6m", "6M", "7m", "7M"];
844
- function intervalFrom(root, name) {
845
- const from = rootNameOf(root);
846
- const to = rootNameOf(name);
847
- if (from === null || to === null)
848
- return null;
849
- const semitones = (chromaOf(to) - chromaOf(from) + 12) % 12;
850
- if (semitones === 0)
851
- return "1P";
852
- const spelled = Interval2.distance(from, to);
853
- const m = /^(\d+)([PMmdA]+)$/.exec(spelled);
854
- return m && m[1] !== "1" && m[1] !== "8" ? spelled : PLAIN_INTERVALS[semitones];
1291
+ function keyPrefersFlats(key) {
1292
+ const parts = tonicOf(key);
1293
+ const chroma = parts ? chromaOf(parts.tonic) : null;
1294
+ if (!parts || chroma === null)
1295
+ return false;
1296
+ if (isFlat(parts.tonic))
1297
+ return true;
1298
+ if (/[#♯]/.test(parts.tonic))
1299
+ return false;
1300
+ return parts.minor ? FLAT_MINOR_KEYS.has(chroma) : FLAT_KEYS.has(chroma);
855
1301
  }
856
- function emptyNoteSet(title = "no notes") {
857
- return { title, members: [], root: null, pitches: null, preferFlats: false, list: true };
1302
+ var shift = (note, semitones, preferFlats) => {
1303
+ const chroma = chromaOf(note);
1304
+ return chroma === null ? note : nameOf(chroma + semitones, preferFlats);
1305
+ };
1306
+ function moveByLetter(note, interval) {
1307
+ const moved = Note2.transpose(note, interval);
1308
+ return /^[A-G](#{3,}|b{3,})$/.test(moved) ? Note2.simplify(moved) : moved;
858
1309
  }
859
- function listNoteSet(text, root) {
860
- const tokens = text.split(/[\s,]+/).filter(Boolean);
861
- if (!tokens.length)
862
- return null;
863
- const withOctaves = tokens.every((t) => midiOf(t) !== null);
864
- const names = withOctaves ? tokens.map((t) => t.replace(/-?\d$/, "")) : tokens;
865
- if (!withOctaves && names.some((n) => chromaOf(n) === null))
866
- return null;
867
- const set = fromNames(tokens.join(" "), names, null);
868
- if (!set)
869
- return null;
870
- set.list = true;
871
- if (withOctaves)
872
- set.pitches = tokens.map((t) => midiOf(t));
873
- if (root === undefined)
874
- return set;
875
- const rootName = rootNameOf(root);
876
- if (rootName === null)
877
- return null;
878
- set.root = chromaOf(rootName);
879
- for (const member of set.members) {
880
- member.interval = intervalFrom(rootName, member.name);
881
- member.degree = Number(/^\d+/.exec(member.interval ?? "")?.[0] ?? 1);
1310
+ function transposeChord(symbol, semitones, spelling) {
1311
+ const trimmed = symbol.trim();
1312
+ const parts = splitChordSymbol(trimmed);
1313
+ const steps = Math.round(semitones) || 0;
1314
+ if (!parts || steps % 12 === 0)
1315
+ return trimmed;
1316
+ if (typeof spelling === "object") {
1317
+ const interval = Interval2.distance(spelling.from.replace("♯", "#").replace("♭", "b"), spelling.to.replace("♯", "#").replace("♭", "b"));
1318
+ const moves = Interval2.semitones(interval);
1319
+ if (moves !== undefined && ((moves - steps) % 12 + 12) % 12 === 0) {
1320
+ const bass = parts.bass ? `/${moveByLetter(parts.bass, interval)}` : "";
1321
+ return `${moveByLetter(parts.root, interval)}${parts.suffix}${bass}`;
1322
+ }
1323
+ spelling = keyPrefersFlats(spelling.to);
882
1324
  }
883
- return set;
1325
+ const flats = spelling ?? isFlat(parts.root);
1326
+ const bass = parts.bass ? `/${shift(parts.bass, steps, flats)}` : "";
1327
+ return `${shift(parts.root, steps, flats)}${parts.suffix}${bass}`;
1328
+ }
1329
+ function transposeKey(key, semitones) {
1330
+ const m = /^([A-G][#♯b♭]?)(.*)$/.exec(key.trim());
1331
+ const chroma = m ? chromaOf(m[1]) : null;
1332
+ const steps = Math.round(semitones) || 0;
1333
+ if (!m || chroma === null || steps % 12 === 0)
1334
+ return key.trim();
1335
+ const target = ((chroma + steps) % 12 + 12) % 12;
1336
+ const minor = /^\s*(m|min|minor)\b/.test(m[2]);
1337
+ const flats = minor ? FLAT_MINOR_KEYS.has(target) : FLAT_KEYS.has(target);
1338
+ return `${nameOf(target, flats)}${m[2]}`;
1339
+ }
1340
+ function keyMove(key, semitones) {
1341
+ const from = tonicOf(key);
1342
+ const to = tonicOf(transposeKey(key, semitones));
1343
+ return from && to && chromaOf(from.tonic) !== null ? { from: from.tonic, to: to.tonic } : null;
884
1344
  }
885
1345
 
886
1346
  // src/chord/capo.ts
@@ -1269,72 +1729,6 @@ function parseChordPro(source) {
1269
1729
  // src/theory/find.ts
1270
1730
  import { Interval as Interval4, ScaleType, Scale as Scale4 } from "tonal";
1271
1731
 
1272
- // src/theory/chord-symbol.ts
1273
- var QUALITY_SUFFIXES = [
1274
- [/^(m7b5|m7-5|ø7?)$/, "Minor 7 flat 5"],
1275
- [/^(dim7|°7)$/, "Diminished 7"],
1276
- [/^(maj9|M9|Δ9)$/, "Major 9"],
1277
- [/^(maj7|M7|Δ7?)$/, "Major 7"],
1278
- [/^(7sus4)$/, "7sus4"],
1279
- [/^(m9|min9|-9)$/, "Minor 9"],
1280
- [/^(m7|min7|-7)$/, "Minor 7"],
1281
- [/^(m6|min6|-6)$/, "Minor 6"],
1282
- [/^(m|min|-)$/, "Minor"],
1283
- [/^(dim|°)$/, "Diminished"],
1284
- [/^(aug|\+|\+5|#5)$/, "Augmented"],
1285
- [/^(sus2)$/, "Sus2"],
1286
- [/^(sus4|sus)$/, "Sus4"],
1287
- [/^(add9|add2)$/, "Add9"],
1288
- [/^5$/, "5 (Power)"],
1289
- [/^(6\/9|69)$/, "6/9"],
1290
- [/^(m6\/9|m69|m6add9)$/, "Minor 6/9"],
1291
- [/^(Mb5|b5|-5)$/, "Major flat 5"],
1292
- [/^(mM7|mMaj7|mmaj7|m\(maj7\)|-\(maj7\))$/, "Minor major 7"],
1293
- [/^(13|11|9|7|6)$/, "$1"],
1294
- [/^(maj|M)?$/, "Major"]
1295
- ];
1296
- var ACCIDENTAL_WORDS = {
1297
- "#": " Sharp",
1298
- "##": " Double Sharp",
1299
- b: " Flat",
1300
- bb: " Double Flat"
1301
- };
1302
- var spellNote = (note) => note[0] + (ACCIDENTAL_WORDS[note.slice(1)] ?? "");
1303
- var plain = (quality) => quality.replace(/\s*\([^)]*\)/g, "").trim();
1304
- function parseChord(symbol) {
1305
- const parts = splitChordSymbol(symbol);
1306
- if (!parts)
1307
- return null;
1308
- const trimmed = symbol.trim();
1309
- const { root, bass } = parts;
1310
- const suffix = withoutParentheses(parts.suffix);
1311
- let quality = null;
1312
- for (const written of suffix === null || suffix === parts.suffix ? [parts.suffix] : [parts.suffix, suffix]) {
1313
- for (const [re, label] of QUALITY_SUFFIXES) {
1314
- const hit = re.exec(written);
1315
- if (hit) {
1316
- quality = label.replace("$1", hit[1] ?? "");
1317
- break;
1318
- }
1319
- }
1320
- if (quality)
1321
- break;
1322
- }
1323
- if (suffix === null && !quality)
1324
- return null;
1325
- if (!quality && suffix !== null && chordNoteSet(trimmed))
1326
- quality = suffix;
1327
- if (!quality)
1328
- return null;
1329
- return {
1330
- symbol: trimmed,
1331
- root,
1332
- quality,
1333
- bass,
1334
- name: `${spellNote(root)} ${plain(quality)}${bass ? ` over ${spellNote(bass)}` : ""}`
1335
- };
1336
- }
1337
-
1338
1732
  // src/theory/keys.ts
1339
1733
  import { Interval as Interval3, Key, Note as Note3, Scale as Scale3 } from "tonal";
1340
1734
  var MODES = [
@@ -3825,6 +4219,11 @@ function lightPlayer(win, random = Math.random) {
3825
4219
  } catch {}
3826
4220
  }
3827
4221
  cleanup = win.setTimeout(finish, 80);
4222
+ },
4223
+ setVolume(next) {
4224
+ if (stopped || !Number.isFinite(next))
4225
+ return;
4226
+ gain.gain.setTargetAtTime(Math.min(1, Math.max(0, next)), ctx.currentTime, 0.015);
3828
4227
  }
3829
4228
  };
3830
4229
  }
@@ -3974,6 +4373,32 @@ function followNotes(win, drawing, targets, events, wait = START_WAIT) {
3974
4373
  };
3975
4374
  }
3976
4375
 
4376
+ // src/playback/live-volume.ts
4377
+ var listeners = new Set;
4378
+ var level = (value) => typeof value === "number" && Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : null;
4379
+ function volumeChanged() {
4380
+ for (const listener of [...listeners]) {
4381
+ try {
4382
+ listener();
4383
+ } catch {}
4384
+ }
4385
+ }
4386
+ function followVolume(read, handles, start) {
4387
+ let last = level(start);
4388
+ const listener = () => {
4389
+ const now = level(read());
4390
+ if (now === null || now === last)
4391
+ return;
4392
+ last = now;
4393
+ for (const h of handles())
4394
+ h.setVolume?.(now);
4395
+ };
4396
+ listeners.add(listener);
4397
+ return () => {
4398
+ listeners.delete(listener);
4399
+ };
4400
+ }
4401
+
3977
4402
  // src/strum/play.ts
3978
4403
  function scoreOf(pattern, voicing) {
3979
4404
  const changes = pattern.slots.filter((s) => s.chord);
@@ -4082,14 +4507,16 @@ function runPasses(make, player, settings, timers, onEnd, follow) {
4082
4507
  let stopped = false;
4083
4508
  let timer;
4084
4509
  let pass = 0;
4510
+ const handles = [];
4511
+ const unfollow = followVolume(() => settings().volume, () => handles, settings().volume);
4085
4512
  let anchor = null;
4086
4513
  let elapsed = 0;
4087
- const handles = [];
4088
4514
  const followers = [];
4089
4515
  const finish = () => {
4090
4516
  if (stopped)
4091
4517
  return;
4092
4518
  stopped = true;
4519
+ unfollow();
4093
4520
  onEnd?.();
4094
4521
  };
4095
4522
  const schedule = (looping) => {
@@ -4158,6 +4585,7 @@ function runPasses(make, player, settings, timers, onEnd, follow) {
4158
4585
  return {
4159
4586
  stop() {
4160
4587
  stopped = true;
4588
+ unfollow();
4161
4589
  timers.clearTimeout(timer);
4162
4590
  for (const h of handles)
4163
4591
  h.stop();
@@ -4570,7 +4998,7 @@ function renderFretboard(doc, set, options = {}) {
4570
4998
  top: 0,
4571
4999
  minWidth: titleWidth(caption)
4572
5000
  };
4573
- const lines = options.title ? titleLines(options.title, neckFrame(layout).width) : [];
5001
+ const lines = options.title ? titleLines(shown(options.title), neckFrame(layout).width) : [];
4574
5002
  const frame = neckFrame({
4575
5003
  ...layout,
4576
5004
  top: lines.length ? TITLE2 + (lines.length - 1) * TITLE_LINE : 0
@@ -4636,7 +5064,7 @@ function renderFretboard(doc, set, options = {}) {
4636
5064
  for (let s = strings - 1;s >= 0; s--) {
4637
5065
  const open = tuning[s];
4638
5066
  root.appendChild(svgLine(doc, frame.at(across(s), 0), frame.at(across(s), wire(to)), "mn-string"));
4639
- const name = nameOf(names[s], set.preferFlats);
5067
+ const name = shown(nameOf(names[s], set.preferFlats));
4640
5068
  root.appendChild(vertical ? svgLabel(doc, name, frame.at(across(s), -10), "mn-string-name") : svgLabel(doc, name, frame.at(across(s), -8), "mn-string-name", options.hand === "left" ? "start" : "end"));
4641
5069
  for (let fret = from;fret <= to; fret++) {
4642
5070
  const point = frame.at(across(s), center(fret));
@@ -5805,17 +6233,32 @@ function diagramGroup(doc, win, diagrams, options, how) {
5805
6233
  sawStart(player);
5806
6234
  follower.heard();
5807
6235
  };
6236
+ const volume = volumeOf(options.volume);
6237
+ let handle = null;
6238
+ const unfollow = followVolume(() => volumeOf(options.volume), () => handle ? [handle] : [], volume);
5808
6239
  try {
5809
- return player.play(events, {
6240
+ handle = player.play(events, {
5810
6241
  sound: soundOf(item),
5811
- volume: volumeOf(options.volume),
5812
- onEnd,
6242
+ volume,
6243
+ onEnd: () => {
6244
+ unfollow();
6245
+ onEnd();
6246
+ },
5813
6247
  onStart
5814
6248
  });
5815
6249
  } catch (error) {
6250
+ unfollow();
5816
6251
  follower.stop();
5817
6252
  throw error;
5818
6253
  }
6254
+ const played = handle;
6255
+ return {
6256
+ stop() {
6257
+ unfollow();
6258
+ played.stop();
6259
+ },
6260
+ setVolume: (next) => played.setVolume?.(next)
6261
+ };
5819
6262
  };
5820
6263
  try {
5821
6264
  return run(playerFor(here, options));
@@ -6138,6 +6581,18 @@ function spelledNote(name, midi) {
6138
6581
  return `${nameOf(midi)}${octave}`;
6139
6582
  }
6140
6583
  function redrawFor(doc, diagram, data, pageHand = "right") {
6584
+ const naming = namingOf(diagram.closest("[data-mn-naming]")?.getAttribute("data-mn-naming"));
6585
+ if (!naming)
6586
+ return redrawLetters(doc, diagram, data, pageHand);
6587
+ const title = diagram.querySelector(".mn-title")?.textContent ?? "";
6588
+ const name = accessibleName(diagram) ?? "";
6589
+ return withNaming(naming, () => redrawLetters(doc, diagram, data, pageHand), [
6590
+ title,
6591
+ title.replace(/,\s*(left|right) hand$/, ""),
6592
+ name
6593
+ ]);
6594
+ }
6595
+ function redrawLetters(doc, diagram, data, pageHand) {
6141
6596
  const own = diagram.getAttribute("data-mn-hand");
6142
6597
  const hand = own === "left" || own === "right" ? own : pageHand;
6143
6598
  const toGuitar = data.sound === "piano";
@@ -6295,6 +6750,7 @@ var DIRECTIONS = {
6295
6750
  ArrowUp: [0, -1],
6296
6751
  ArrowDown: [0, 1]
6297
6752
  };
6753
+ var TOUCH = ["touchstart", "touchend"];
6298
6754
  var RESULT_CLASS = { right: "mn-pick-right", wrong: "mn-pick-wrong" };
6299
6755
  var num = (el, name) => Number(el.getAttribute(name));
6300
6756
  var optional = (el, name) => el.hasAttribute(name) ? num(el, name) : null;
@@ -6459,6 +6915,8 @@ function attachPick(diagram, options = {}) {
6459
6915
  }
6460
6916
  for (const type of ["pointerdown", "mousedown"])
6461
6917
  diagram.addEventListener(type, onPress);
6918
+ for (const type of TOUCH)
6919
+ diagram.addEventListener(type, onPress, { passive: true });
6462
6920
  diagram.addEventListener("click", onClick);
6463
6921
  diagram.addEventListener("keydown", onKey);
6464
6922
  const groups = new Set(targets.map((t) => t.parentElement));
@@ -6572,6 +7030,8 @@ function attachPick(diagram, options = {}) {
6572
7030
  marks = null;
6573
7031
  for (const type of ["pointerdown", "mousedown"])
6574
7032
  diagram.removeEventListener(type, onPress);
7033
+ for (const type of TOUCH)
7034
+ diagram.removeEventListener(type, onPress);
6575
7035
  diagram.removeEventListener("click", onClick);
6576
7036
  diagram.removeEventListener("keydown", onKey);
6577
7037
  for (const el of targets) {
@@ -6673,7 +7133,7 @@ function renderKeyboard(doc, set, options = {}) {
6673
7133
  const handRow = [...options.hands?.keys() ?? []].some((midi) => midi >= from && midi <= to) ? HAND_ROW : 0;
6674
7134
  const depth = WHITE_H + fingerRow + handRow;
6675
7135
  const content = (vertical ? depth : length) + 2;
6676
- const width = Math.max(content, titleWidth(options.title));
7136
+ const width = Math.max(content, titleWidth(options.title && shown(options.title)));
6677
7137
  const shift = (width - content) / 2;
6678
7138
  const height = top + (vertical ? length : depth) + 2;
6679
7139
  const at = (along, depth) => vertical ? [shift + 1 + depth, top + 1 + length - along] : [shift + 1 + along, top + 1 + depth];
@@ -6693,7 +7153,7 @@ function renderKeyboard(doc, set, options = {}) {
6693
7153
  }).filter(Boolean).join(", ");
6694
7154
  const root = svgRoot(doc, width, height, "mn-keyboard", `${options.title ?? `Keyboard: ${set.title}`}${handWords ? `, ${handWords}` : ""}${describeMarks(set, options.marks)}`);
6695
7155
  if (options.title) {
6696
- root.appendChild(svgText(doc, options.title, {
7156
+ root.appendChild(svgText(doc, shown(options.title), {
6697
7157
  class: "mn-title",
6698
7158
  x: width / 2,
6699
7159
  y: 15,
@@ -6717,7 +7177,13 @@ function renderKeyboard(doc, set, options = {}) {
6717
7177
  const text = labelOf(member, label, options.fingers?.get(midi));
6718
7178
  if (!text)
6719
7179
  return;
6720
- root.appendChild(svgLabel(doc, text, point, black ? "mn-key-label mn-key-label-black" : "mn-key-label"));
7180
+ const words = shown(text);
7181
+ const el = svgLabel(doc, words, point, black ? "mn-key-label mn-key-label-black" : "mn-key-label");
7182
+ if (words !== text && [...words].length >= 3) {
7183
+ el.setAttribute("textLength", String((black ? BLACK_W : WHITE_W) - 2));
7184
+ el.setAttribute("lengthAdjust", "spacingAndGlyphs");
7185
+ }
7186
+ root.appendChild(el);
6721
7187
  };
6722
7188
  whites.forEach((midi, i) => {
6723
7189
  const along = i * WHITE_W;
@@ -7206,7 +7672,7 @@ function renderChart(doc, song, options = {}) {
7206
7672
  root.appendChild(header);
7207
7673
  }
7208
7674
  const meta = [
7209
- key ? `Key ${key}` : null,
7675
+ key ? shown(`Key ${key}`) : null,
7210
7676
  song.capo ? `Capo ${song.capo}` : null,
7211
7677
  song.tempo ? `${song.tempo} BPM` : null,
7212
7678
  song.time ? song.time : null,
@@ -7265,7 +7731,7 @@ function renderChart(doc, song, options = {}) {
7265
7731
  rests.set(step.segment, step.rest);
7266
7732
  line.segments.forEach((segment, index) => {
7267
7733
  const seg = html(doc, "span", "mn-seg");
7268
- const mark = html(doc, "span", "mn-chord", segment.chord === null ? "" : chord(segment.chord));
7734
+ const mark = html(doc, "span", "mn-chord", segment.chord === null ? "" : shown(chord(segment.chord)));
7269
7735
  if (segment.chord !== null) {
7270
7736
  const shown = chord(segment.chord);
7271
7737
  const voicing = soundOf(segment.chord, shown);
@@ -9387,9 +9853,9 @@ function renderSection(doc, section, options, renderChord) {
9387
9853
  const el = html(doc, "div", "mn-progression-section");
9388
9854
  const others = section.others.length ? ` (or ${section.others.join(", ")})` : "";
9389
9855
  const blues = section.blues ? " (blues)" : "";
9390
- el.appendChild(html(doc, "div", "mn-progression-key", `Key: ${section.name ?? section.key.name}${blues}${others}`));
9856
+ el.appendChild(html(doc, "div", "mn-progression-key", shown(`Key: ${section.name ?? section.key.name}${blues}${others}`)));
9391
9857
  if (section.note)
9392
- el.appendChild(html(doc, "div", "mn-progression-note", section.note));
9858
+ el.appendChild(html(doc, "div", "mn-progression-note", shown(section.note)));
9393
9859
  const instrument = (field(block, "instrument") ?? options.instrument ?? "guitar").toLowerCase();
9394
9860
  if (!["guitar", "piano", "keyboard"].includes(instrument)) {
9395
9861
  throw new Error(`Unknown instrument "${instrument}": use guitar or piano`);
@@ -9487,11 +9953,11 @@ function renderSection(doc, section, options, renderChord) {
9487
9953
  }
9488
9954
  cell.appendChild(renderChord(doc, diagramBlock(block, lines), options));
9489
9955
  } catch (e) {
9490
- cell.appendChild(html(doc, "div", "mn-progression-name", chord.symbol));
9956
+ cell.appendChild(html(doc, "div", "mn-progression-name", shown(chord.symbol)));
9491
9957
  cell.appendChild(html(doc, "div", "mn-error-message", e instanceof Error ? e.message : String(e)));
9492
9958
  }
9493
9959
  } else
9494
- cell.appendChild(html(doc, "div", "mn-progression-name", chord.symbol));
9960
+ cell.appendChild(html(doc, "div", "mn-progression-name", shown(chord.symbol)));
9495
9961
  if (functions) {
9496
9962
  cell.appendChild(html(doc, "div", "mn-progression-function", chord.function));
9497
9963
  }
@@ -9619,7 +10085,7 @@ function renderCircle(doc, options = {}) {
9619
10085
  const chords = placed(key, options.sevenths ?? false, minor && options.dominant !== "minor");
9620
10086
  const neighbours = options.neighbours ?? true;
9621
10087
  const top = options.title ? TITLE4 : 0;
9622
- const width = Math.max(SIZE, titleWidth(options.title));
10088
+ const width = Math.max(SIZE, titleWidth(options.title && shown(options.title)));
9623
10089
  const chipsTop = top + SIZE + 8;
9624
10090
  const height = chipsTop + CHIP_H + 2;
9625
10091
  const signature = keySignature(key);
@@ -9628,7 +10094,7 @@ function renderCircle(doc, options = {}) {
9628
10094
  const shift = (width - SIZE) / 2;
9629
10095
  const g = svg(doc, "g", shift ? { transform: `translate(${shift} 0)` } : {});
9630
10096
  if (options.title) {
9631
- root.appendChild(svgText(doc, options.title, {
10097
+ root.appendChild(svgText(doc, shown(options.title), {
9632
10098
  class: "mn-title",
9633
10099
  x: width / 2,
9634
10100
  y: 16,
@@ -9671,7 +10137,7 @@ function renderCircle(doc, options = {}) {
9671
10137
  "data-mn-strum": pitches.join(" "),
9672
10138
  "data-mn-chroma": chord && pitches.length ? pitches[0] % 12 : undefined
9673
10139
  });
9674
- const name = chord ? pretty(chord.symbol) : pretty(defaults[ring][position]);
10140
+ const name = shown(chord ? pretty(chord.symbol) : pretty(defaults[ring][position]));
9675
10141
  const title = svg(doc, "title");
9676
10142
  title.textContent = chord ? `${chord.numeral}: ${name}` : name.replace("/", " or ");
9677
10143
  cell.appendChild(title);
@@ -9710,11 +10176,14 @@ function renderCircle(doc, options = {}) {
9710
10176
  }
9711
10177
  const centerY = top + CENTER2;
9712
10178
  const centerLines = [
9713
- [pretty(key.tonic) + ` ${key.mode}`, "mn-circle-key"],
10179
+ [shown(pretty(key.tonic) + ` ${key.mode}`), "mn-circle-key"],
9714
10180
  [signatureText(signature.count), "mn-circle-key-sig"]
9715
10181
  ];
9716
10182
  if (signature.accidentals.length && signature.accidentals.length <= 7) {
9717
- centerLines.push([signature.accidentals.map(pretty).join(" "), "mn-circle-key-notes"]);
10183
+ centerLines.push([
10184
+ shown(signature.accidentals.map(pretty).join(" ")),
10185
+ "mn-circle-key-notes"
10186
+ ]);
9718
10187
  }
9719
10188
  centerLines.forEach(([text, cls], i) => {
9720
10189
  g.appendChild(svgText(doc, text, {
@@ -9741,7 +10210,7 @@ function renderCircle(doc, options = {}) {
9741
10210
  "data-mn-chroma": pitches.length ? pitches[0] % 12 : undefined
9742
10211
  });
9743
10212
  const tip = svg(doc, "title");
9744
- tip.textContent = `${chord.numeral}: ${pretty(chord.symbol)}`;
10213
+ tip.textContent = `${chord.numeral}: ${shown(pretty(chord.symbol))}`;
9745
10214
  chip.appendChild(tip);
9746
10215
  g.appendChild(chip);
9747
10216
  const solid = chord.degree === 1 || neighbours && (chord.degree === 4 || chord.degree === 5);
@@ -9752,7 +10221,7 @@ function renderCircle(doc, options = {}) {
9752
10221
  y: chipsTop + 15,
9753
10222
  "text-anchor": "middle"
9754
10223
  }));
9755
- g.appendChild(svgText(doc, pretty(chord.symbol), {
10224
+ g.appendChild(svgText(doc, shown(pretty(chord.symbol)), {
9756
10225
  class: `mn-circle-label${on}`,
9757
10226
  x: x + chipW / 2,
9758
10227
  y: chipsTop + 31,
@@ -9970,7 +10439,7 @@ function renderStrum(doc, pattern, options = {}) {
9970
10439
  g.appendChild(svgLabel(doc, countOf(i, slotsPerBeat, slotsPerBar), [x, countY], onBeat ? "mn-strum-count mn-strum-count-beat" : "mn-strum-count"));
9971
10440
  const chord = slot.chord ?? (i === 0 ? pattern.chord : null);
9972
10441
  if (chord) {
9973
- const label = svgLabel(doc, chord, [x - width / 2 + 3, chordY], "mn-strum-chord", "start");
10442
+ const label = svgLabel(doc, shown(chord), [x - width / 2 + 3, chordY], "mn-strum-chord", "start");
9974
10443
  g.appendChild(label);
9975
10444
  g.setAttribute("data-mn-chord", chord);
9976
10445
  if (options.voicing && slot.chord)
@@ -10108,7 +10577,7 @@ function renderPicking(doc, pattern, options = {}) {
10108
10577
  const chord = score.chords[bar];
10109
10578
  const starts = i % slotsPerBar === 0 && chord && (bar === 0 || score.chords[bar - 1] !== chord);
10110
10579
  if (starts) {
10111
- g.appendChild(svgLabel(doc, chord, [x - width / 2 + 3, chordY], "mn-strum-chord", "start"));
10580
+ g.appendChild(svgLabel(doc, shown(chord), [x - width / 2 + 3, chordY], "mn-strum-chord", "start"));
10112
10581
  g.setAttribute("data-mn-chord", chord);
10113
10582
  }
10114
10583
  if (i % slotsPerBar === 0)
@@ -10395,6 +10864,8 @@ var renderChord = (doc, block, options) => {
10395
10864
  }
10396
10865
  const sounding = symbol && capo ? soundingChord(symbol, capo) : symbol;
10397
10866
  const sounds = soundsField(field2(block, "sounds"), symbol, capo);
10867
+ if (capo && sounding && soundsInTitle(field2(block, "sounds")) && !field2(block, "title"))
10868
+ title = `${sounding} (${title ?? symbol} shape)`;
10398
10869
  const root = sounding ? chordNoteSet(sounding)?.root ?? rootOf2(sounding) : null;
10399
10870
  const strings = tuning ?? (voicing.frets.length === 6 ? STANDARD_TUNING : undefined);
10400
10871
  const labels = dotLabels(field2(block, "labels"), sounding, shape, strings && capo ? capoTuning(strings, capo) : tuning);
@@ -10444,10 +10915,17 @@ function captioned(doc, diagram, sentences) {
10444
10915
  figure.append(diagram, html(doc, "figcaption", "mn-fingering", sentences.join(" ")));
10445
10916
  return figure;
10446
10917
  }
10918
+ var soundsInTitle = (text) => /^title$/i.test(text?.trim() ?? "");
10447
10919
  function soundsField(text, shape, capo) {
10448
10920
  const value = text?.trim();
10449
10921
  if (!value || /^(no|false|off)$/i.test(value))
10450
10922
  return;
10923
+ if (soundsInTitle(value)) {
10924
+ if (capo && (!shape || !chordNoteSet(shape))) {
10925
+ throw new Error("sounds: title needs a chord the library knows: add its symbol (e.g. symbol: A)");
10926
+ }
10927
+ return;
10928
+ }
10451
10929
  const auto = /^(yes|true|on|auto)$/i.test(value);
10452
10930
  if (!capo) {
10453
10931
  if (auto)
@@ -11049,78 +11527,103 @@ function renderBlock(language, source, host, given = {}) {
11049
11527
  el.classList.add("mn-from-properties");
11050
11528
  }
11051
11529
  }
11052
- let parts = null;
11530
+ let reading;
11053
11531
  try {
11054
- if ((language === "fretboard" || language === "keyboard") && !splitParts(text))
11055
- text = resolveScalesFor(text);
11056
- 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;
11532
+ reading = lettersInBlock(language, text);
11057
11533
  } catch (e) {
11058
11534
  return failed(el, host, language, messageOf(e));
11059
11535
  }
11060
- if (!text.trim() || parts?.length === 0) {
11061
- el.classList.add("mn-empty");
11062
- host.appendChild(el);
11063
- return { ok: true, el, error: null, picks: [], destroy: () => el.remove() };
11064
- }
11065
- try {
11066
- if (parts && isDiagramLanguage(language)) {
11067
- error = renderRow(doc, language, parts, el, options);
11068
- } else {
11069
- el.appendChild(RENDERERS[language](doc, text, options));
11070
- const warnings = [
11071
- ...el.querySelectorAll(".mn-chart > .mn-error-message, .mn-chart-chord > .mn-error-message")
11072
- ];
11073
- if (warnings.length)
11074
- error = warnings.map((w) => w.textContent ?? "").join("; ");
11536
+ text = reading.text;
11537
+ const naming = reading.naming ?? namingOf(options.naming) ?? "letters";
11538
+ if (naming !== "letters")
11539
+ el.setAttribute("data-mn-naming", naming);
11540
+ const quoted = (e) => quoteAsWritten(messageOf(e), reading.changes);
11541
+ const draw = () => {
11542
+ let parts = null;
11543
+ try {
11544
+ if ((language === "fretboard" || language === "keyboard") && !splitParts(text))
11545
+ text = resolveScalesFor(text);
11546
+ 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;
11547
+ } catch (e) {
11548
+ return failed(el, host, language, quoted(e));
11075
11549
  }
11076
- } catch (e) {
11077
- return failed(el, host, language, messageOf(e));
11078
- }
11079
- alignTitleLines(el.querySelectorAll("svg.mn-guitar-chord, svg.mn-fretboard"));
11080
- host.appendChild(el);
11081
- const freeTabs = [];
11082
- if (options.tab) {
11083
- for (const pre of el.querySelectorAll("pre.mn-exercise")) {
11084
- const holder = html(doc, "div", "mn-exercise-tab");
11085
- for (const { name, value } of [...pre.attributes]) {
11086
- if (name.startsWith("data-mn-"))
11087
- holder.setAttribute(name, value);
11550
+ if (!text.trim() || parts?.length === 0) {
11551
+ el.classList.add("mn-empty");
11552
+ host.appendChild(el);
11553
+ return { ok: true, el, error: null, picks: [], destroy: () => el.remove() };
11554
+ }
11555
+ try {
11556
+ if (parts && isDiagramLanguage(language)) {
11557
+ error = renderRow(doc, language, parts, el, options);
11558
+ if (error !== null && reading.changes.length) {
11559
+ error = quoteAsWritten(error, reading.changes);
11560
+ for (const m of el.querySelectorAll(".mn-error-message"))
11561
+ m.textContent = quoteAsWritten(m.textContent ?? "", reading.changes);
11562
+ }
11563
+ } else {
11564
+ el.appendChild(RENDERERS[language](doc, text, options));
11565
+ const warnings = [
11566
+ ...el.querySelectorAll(".mn-chart > .mn-error-message, .mn-chart-chord > .mn-error-message")
11567
+ ];
11568
+ if (reading.warning) {
11569
+ const chart = el.querySelector(".mn-chart");
11570
+ chart?.insertBefore(html(doc, "div", "mn-error-message", reading.warning), chart.firstChild);
11571
+ if (chart)
11572
+ warnings.unshift(chart.firstElementChild);
11573
+ }
11574
+ if (warnings.length)
11575
+ error = warnings.map((w) => w.textContent ?? "").join("; ");
11088
11576
  }
11089
- pre.replaceWith(holder);
11090
- try {
11091
- const free = options.tab(pre.textContent ?? "", holder);
11092
- if (typeof free === "function")
11093
- freeTabs.push(free);
11094
- } catch {
11095
- holder.replaceWith(pre);
11577
+ } catch (e) {
11578
+ return failed(el, host, language, quoted(e));
11579
+ }
11580
+ alignTitleLines(el.querySelectorAll("svg.mn-guitar-chord, svg.mn-fretboard"));
11581
+ host.appendChild(el);
11582
+ const freeTabs = [];
11583
+ if (options.tab) {
11584
+ for (const pre of el.querySelectorAll("pre.mn-exercise")) {
11585
+ const holder = html(doc, "div", "mn-exercise-tab");
11586
+ for (const { name, value } of [...pre.attributes]) {
11587
+ if (name.startsWith("data-mn-"))
11588
+ holder.setAttribute(name, value);
11589
+ }
11590
+ pre.replaceWith(holder);
11591
+ try {
11592
+ const free = options.tab(pre.textContent ?? "", holder);
11593
+ if (typeof free === "function")
11594
+ freeTabs.push(free);
11595
+ } catch {
11596
+ holder.replaceWith(pre);
11597
+ }
11096
11598
  }
11097
11599
  }
11600
+ const picks = options.pick ? [...el.querySelectorAll("svg[data-mn-pick]")].map((svg) => attachPick(svg, pickOptions(options))) : [];
11601
+ const stopPlayback = options.play ? attachPlayback(el, {
11602
+ hand: options.hand,
11603
+ ...typeof options.play === "object" ? options.play : {}
11604
+ }) : null;
11605
+ return {
11606
+ ok: error === null,
11607
+ el,
11608
+ error,
11609
+ picks,
11610
+ destroy: () => {
11611
+ stopPlayback?.();
11612
+ for (const layer of picks)
11613
+ layer.destroy();
11614
+ for (const free of freeTabs)
11615
+ free();
11616
+ el.remove();
11617
+ }
11618
+ };
11619
+ };
11620
+ function pickOptions(options) {
11621
+ const pick = typeof options.pick === "object" ? options.pick : {};
11622
+ if (pick.play !== true)
11623
+ return pick;
11624
+ return { ...pick, play: typeof options.play === "object" ? options.play : true };
11098
11625
  }
11099
- const picks = options.pick ? [...el.querySelectorAll("svg[data-mn-pick]")].map((svg) => attachPick(svg, pickOptions(options))) : [];
11100
- const stopPlayback = options.play ? attachPlayback(el, {
11101
- hand: options.hand,
11102
- ...typeof options.play === "object" ? options.play : {}
11103
- }) : null;
11104
- return {
11105
- ok: error === null,
11106
- el,
11107
- error,
11108
- picks,
11109
- destroy: () => {
11110
- stopPlayback?.();
11111
- for (const layer of picks)
11112
- layer.destroy();
11113
- for (const free of freeTabs)
11114
- free();
11115
- el.remove();
11116
- }
11117
- };
11118
- }
11119
- function pickOptions(options) {
11120
- const pick = typeof options.pick === "object" ? options.pick : {};
11121
- if (pick.play !== true)
11122
- return pick;
11123
- return { ...pick, play: typeof options.play === "object" ? options.play : true };
11626
+ return withNaming(naming, draw, reading.titles);
11124
11627
  }
11125
11628
  function failed(el, host, language, error) {
11126
11629
  el.replaceChildren();
@@ -11913,5 +12416,5 @@ export {
11913
12416
  renderAll
11914
12417
  };
11915
12418
 
11916
- //# debugId=C83B58E4E4DB90E464756E2164756E21
12419
+ //# debugId=4DB731EAAFD5FD5E64756E2164756E21
11917
12420
  //# sourceMappingURL=index.js.map