@dsebastien/music-notation 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,1605 @@
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;
21
+ }
22
+ function svgLabel(doc, text, [x, y], cls, anchor = "middle") {
23
+ return svgText(doc, text, { class: cls, x, y: y + 4, "text-anchor": anchor });
24
+ }
25
+ function svgLine(doc, [x1, y1], [x2, y2], cls) {
26
+ return svg(doc, "line", { class: cls, x1, y1, x2, y2 });
27
+ }
28
+ function html(doc, tag, cls, text) {
29
+ const el = doc.createElement(tag);
30
+ if (cls)
31
+ el.className = cls;
32
+ if (text !== undefined)
33
+ el.textContent = text;
34
+ return el;
35
+ }
36
+ function svgRoot(doc, width, height, cls, label) {
37
+ return svg(doc, "svg", {
38
+ xmlns: SVG_NS,
39
+ viewBox: `0 0 ${width} ${height}`,
40
+ width,
41
+ class: `mn-svg ${cls}`,
42
+ role: "img",
43
+ "aria-label": label
44
+ });
45
+ }
46
+
47
+ // src/render/layout.ts
48
+ function parseOrientation(text) {
49
+ const value = text.trim().toLowerCase();
50
+ if (value === "vertical" || value === "horizontal")
51
+ return value;
52
+ throw new Error(`Unknown orientation "${text}": use vertical or horizontal`);
53
+ }
54
+ function parseHand(text) {
55
+ const value = text.trim().toLowerCase();
56
+ if (value === "left" || value === "right")
57
+ return value;
58
+ throw new Error(`Unknown hand "${text}": use left or right`);
59
+ }
60
+ function layoutDefaults(value) {
61
+ const result = {};
62
+ if (!value || typeof value !== "object")
63
+ return result;
64
+ const word = (v) => typeof v === "string" ? v.trim().toLowerCase() : undefined;
65
+ try {
66
+ const { orientation, hand } = value;
67
+ const h = word(hand);
68
+ if (h === "left" || h === "right")
69
+ result.hand = h;
70
+ if (orientation && typeof orientation === "object") {
71
+ for (const language of ["chord", "keyboard", "fretboard"]) {
72
+ const o = word(orientation[language]);
73
+ if (o === "vertical" || o === "horizontal")
74
+ (result.orientation ??= {})[language] = o;
75
+ }
76
+ }
77
+ } catch {}
78
+ return result;
79
+ }
80
+ function titleWidth(title) {
81
+ if (!title)
82
+ return 0;
83
+ let width = 8;
84
+ for (const ch of title) {
85
+ width += ch.codePointAt(0) > 591 ? 15 : /[A-Z0-9#♯♭]/.test(ch) ? 10.5 : 8;
86
+ }
87
+ return Math.ceil(width);
88
+ }
89
+ function neckFrame(n) {
90
+ const vertical = n.orientation === "vertical";
91
+ const left = n.hand === "left";
92
+ const content = vertical ? n.low + n.across + n.high : n.before + n.along + n.after;
93
+ const shift = n.minWidth && n.minWidth > content ? (n.minWidth - content) / 2 : 0;
94
+ const height = n.top + (vertical ? n.before + n.along + n.after : n.high + n.across + n.low);
95
+ const at = (across, along) => {
96
+ if (vertical) {
97
+ const x = left ? n.high + (n.across - across) : n.low + across;
98
+ return [shift + x, n.top + n.before + along];
99
+ }
100
+ const x = left ? content - n.before - along : n.before + along;
101
+ return [shift + x, n.top + n.high + (n.across - across)];
102
+ };
103
+ const box = (a1, l1, a2, l2) => {
104
+ const [x1, y1] = at(a1, l1);
105
+ const [x2, y2] = at(a2, l2);
106
+ return {
107
+ x: Math.min(x1, x2),
108
+ y: Math.min(y1, y2),
109
+ width: Math.abs(x2 - x1),
110
+ height: Math.abs(y2 - y1)
111
+ };
112
+ };
113
+ return { width: content + 2 * shift, height, at, box };
114
+ }
115
+
116
+ // src/chord/guitar.ts
117
+ var STANDARD_TUNING = [40, 45, 50, 55, 59, 64];
118
+ function parseFrets(text) {
119
+ const trimmed = text.trim();
120
+ const tokens = /[\s,-]/.test(trimmed) ? trimmed.split(/[\s,-]+/) : [...trimmed];
121
+ const frets = tokens.filter(Boolean).map((t) => /^[xX]$/.test(t) ? null : /^\d+$/.test(t) ? Number(t) : NaN);
122
+ return frets.length >= 2 && frets.every((f) => f === null || Number.isInteger(f) && f <= 36) ? frets : null;
123
+ }
124
+ function parseFingers(text) {
125
+ const trimmed = text.trim();
126
+ const tokens = /[\s,]/.test(trimmed) || trimmed.includes("-", 1) ? trimmed.split(/[\s,-]+/) : [...trimmed];
127
+ return tokens.filter(Boolean).map((t) => /^[0xX]$/.test(t) ? null : t.toUpperCase());
128
+ }
129
+ function baseFretOf(frets) {
130
+ const fretted = frets.filter((f) => f !== null && f > 0);
131
+ if (!fretted.length || Math.max(...fretted) <= 4)
132
+ return 1;
133
+ return Math.min(...fretted);
134
+ }
135
+ function barresOf(voicing) {
136
+ const byKey = new Map;
137
+ voicing.frets.forEach((fret, string) => {
138
+ const finger = voicing.fingers[string];
139
+ if (fret === null || fret === 0 || !finger)
140
+ return;
141
+ const key = `${finger}@${fret}`;
142
+ byKey.set(key, [...byKey.get(key) ?? [], string]);
143
+ });
144
+ const barres = [];
145
+ for (const [key, strings] of byKey) {
146
+ if (strings.length < 2)
147
+ continue;
148
+ const [finger, fret] = key.split("@");
149
+ barres.push({
150
+ fret: Number(fret),
151
+ from: Math.min(...strings),
152
+ to: Math.max(...strings),
153
+ finger
154
+ });
155
+ }
156
+ return barres;
157
+ }
158
+ var SPACING = 18;
159
+ var ROW = 20;
160
+ var MARKERS = 16;
161
+ var BASE = 30;
162
+ var TITLE = 22;
163
+ function renderGuitarDiagram(doc, voicing, options = {}) {
164
+ const strings = voicing.frets.length;
165
+ const base = voicing.baseFret ?? baseFretOf(voicing.frets);
166
+ const fretted = voicing.frets.filter((f) => f !== null && f > 0);
167
+ const rows = Math.max(4, fretted.length ? Math.max(...fretted) - base + 1 : 0);
168
+ const orientation = options.orientation ?? "vertical";
169
+ const vertical = orientation === "vertical";
170
+ const frame = neckFrame({
171
+ orientation,
172
+ hand: options.hand ?? "right",
173
+ across: (strings - 1) * SPACING,
174
+ along: rows * ROW,
175
+ before: MARKERS,
176
+ after: 10,
177
+ low: vertical || base > 1 ? BASE : 10,
178
+ high: vertical ? 14 : 10,
179
+ top: options.title ? TITLE : 4,
180
+ minWidth: titleWidth(options.title)
181
+ });
182
+ const across = (string) => string * SPACING;
183
+ const along = (row) => row * ROW;
184
+ const at = (string, row) => frame.at(across(string), along(row));
185
+ const label = options.title ? `${options.title} chord diagram` : "Chord diagram";
186
+ const root = svgRoot(doc, frame.width, frame.height, "mn-guitar-chord", label);
187
+ if (options.title) {
188
+ root.appendChild(svgText(doc, options.title, {
189
+ class: "mn-title",
190
+ x: frame.width / 2,
191
+ y: 15,
192
+ "text-anchor": "middle"
193
+ }));
194
+ }
195
+ for (let row = 0;row <= rows; row++) {
196
+ const cls = row === 0 && base === 1 ? "mn-nut" : "mn-fret";
197
+ root.appendChild(svgLine(doc, at(0, row), at(strings - 1, row), cls));
198
+ }
199
+ for (let s = 0;s < strings; s++) {
200
+ root.appendChild(svgLine(doc, at(s, 0), at(s, rows), "mn-string"));
201
+ }
202
+ if (base > 1) {
203
+ const label = `${base}fr`;
204
+ 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"));
205
+ }
206
+ for (const barre of barresOf(voicing)) {
207
+ const middle = along(barre.fret - base + 0.5);
208
+ root.appendChild(svg(doc, "rect", {
209
+ class: "mn-barre",
210
+ ...frame.box(across(barre.from) - 7, middle - 7, across(barre.to) + 7, middle + 7),
211
+ rx: 7
212
+ }));
213
+ }
214
+ const tuning = options.tuning ?? (strings === 6 ? STANDARD_TUNING : undefined);
215
+ voicing.frets.forEach((fret, s) => {
216
+ const mark = frame.at(across(s), -8);
217
+ if (fret === null) {
218
+ root.appendChild(svgLabel(doc, "×", mark, "mn-muted"));
219
+ return;
220
+ }
221
+ const open = tuning?.[s];
222
+ const isRoot = options.root !== undefined && options.root !== null && open !== undefined && (open + fret) % 12 === options.root;
223
+ if (fret === 0) {
224
+ const [cx, cy] = mark;
225
+ root.appendChild(svg(doc, "circle", { class: `mn-open${isRoot ? " mn-root" : ""}`, cx, cy, r: 4 }));
226
+ return;
227
+ }
228
+ const center = at(s, fret - base + 0.5);
229
+ const [cx, cy] = center;
230
+ root.appendChild(svg(doc, "circle", { class: `mn-dot${isRoot ? " mn-root" : ""}`, cx, cy, r: 7 }));
231
+ const finger = voicing.fingers[s];
232
+ if (finger)
233
+ root.appendChild(svgLabel(doc, finger, center, "mn-dot-text"));
234
+ });
235
+ return root;
236
+ }
237
+
238
+ // src/chords/chordpro.ts
239
+ var ALIASES = {
240
+ t: "title",
241
+ st: "subtitle",
242
+ c: "comment",
243
+ ci: "comment",
244
+ comment_italic: "comment",
245
+ cb: "comment",
246
+ comment_box: "comment",
247
+ highlight: "comment",
248
+ soc: "start_of_chorus",
249
+ eoc: "end_of_chorus",
250
+ sov: "start_of_verse",
251
+ eov: "end_of_verse",
252
+ sob: "start_of_bridge",
253
+ eob: "end_of_bridge",
254
+ sot: "start_of_tab",
255
+ eot: "end_of_tab",
256
+ sog: "start_of_grid",
257
+ eog: "end_of_grid"
258
+ };
259
+ var SECTION_KINDS = new Set(["verse", "chorus", "bridge", "tab", "grid"]);
260
+ function parseLyrics(line) {
261
+ const segments = [];
262
+ const re = /\[([^\]]*)\]/g;
263
+ let last = 0;
264
+ let chord = null;
265
+ let m;
266
+ while (m = re.exec(line)) {
267
+ const text = line.slice(last, m.index);
268
+ if (text || chord !== null)
269
+ segments.push({ chord, text });
270
+ chord = m[1].trim();
271
+ last = m.index + m[0].length;
272
+ }
273
+ const rest = line.slice(last);
274
+ if (rest || chord !== null)
275
+ segments.push({ chord, text: rest });
276
+ return segments;
277
+ }
278
+ function parseDirective(line) {
279
+ const trimmed = line.trim();
280
+ if (!trimmed.startsWith("{") || !trimmed.endsWith("}"))
281
+ return null;
282
+ const inner = trimmed.slice(1, -1).trim();
283
+ const m = /^[\w-]+/.exec(inner);
284
+ if (!m)
285
+ return null;
286
+ const rest = inner.slice(m[0].length);
287
+ if (rest && !/^[\s:]/.test(rest))
288
+ return null;
289
+ return { name: m[0].toLowerCase(), value: rest.replace(/^\s*:?/, "").trim() };
290
+ }
291
+ function parseChordPro(source) {
292
+ const song = {
293
+ title: null,
294
+ subtitle: null,
295
+ artist: null,
296
+ key: null,
297
+ capo: null,
298
+ tempo: null,
299
+ time: null,
300
+ transpose: 0,
301
+ sections: []
302
+ };
303
+ let section = { kind: "none", label: null, lines: [] };
304
+ const open = (kind, label) => {
305
+ if (section.lines.length || section.kind !== "none")
306
+ song.sections.push(section);
307
+ section = { kind, label, lines: [] };
308
+ };
309
+ for (const raw of source.split(/\r?\n/)) {
310
+ const line = raw.replace(/\s+$/, "");
311
+ if (/^\s*#/.test(line))
312
+ continue;
313
+ const directive = parseDirective(line);
314
+ if (directive) {
315
+ const { name, value } = directive;
316
+ const key = ALIASES[name] ?? name;
317
+ const start = /^start_of_(\w+)$/.exec(key);
318
+ const end = /^end_of_(\w+)$/.exec(key);
319
+ if (start) {
320
+ const kind = SECTION_KINDS.has(start[1]) ? start[1] : "verse";
321
+ open(kind, value.replace(/^label\s*=\s*"?|"$/g, "") || null);
322
+ } else if (end) {
323
+ open("none", null);
324
+ } else if (key === "comment") {
325
+ section.lines.push({ kind: "comment", text: value });
326
+ } else if (key === "title" || key === "subtitle" || key === "artist" || key === "key" || key === "tempo" || key === "time") {
327
+ song[key] = value || null;
328
+ } else if (key === "capo") {
329
+ const capo = Number(value);
330
+ song.capo = Number.isInteger(capo) && capo > 0 ? capo : null;
331
+ } else if (key === "transpose") {
332
+ const semitones = Number(value);
333
+ if (Number.isInteger(semitones))
334
+ song.transpose = semitones;
335
+ }
336
+ continue;
337
+ }
338
+ if (!line.trim())
339
+ section.lines.push({ kind: "empty" });
340
+ else if (section.kind === "tab" || section.kind === "grid")
341
+ section.lines.push({ kind: "text", text: line });
342
+ else
343
+ section.lines.push({ kind: "lyrics", segments: parseLyrics(line) });
344
+ }
345
+ open("none", null);
346
+ for (const s of song.sections) {
347
+ while (s.lines[0]?.kind === "empty")
348
+ s.lines.shift();
349
+ while (s.lines[s.lines.length - 1]?.kind === "empty")
350
+ s.lines.pop();
351
+ }
352
+ song.sections = song.sections.filter((s) => s.lines.length || s.label);
353
+ return song;
354
+ }
355
+
356
+ // src/theory/pitch.ts
357
+ var SHARP_NAMES = [
358
+ "C",
359
+ "C#",
360
+ "D",
361
+ "D#",
362
+ "E",
363
+ "F",
364
+ "F#",
365
+ "G",
366
+ "G#",
367
+ "A",
368
+ "A#",
369
+ "B"
370
+ ];
371
+ var FLAT_NAMES = ["C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"];
372
+ var LETTER_CHROMA = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };
373
+ function chromaOf(name) {
374
+ const m = /^([A-Ga-g])([#♯b♭]*)$/.exec(name.trim());
375
+ if (!m)
376
+ return null;
377
+ let chroma = LETTER_CHROMA[m[1].toUpperCase()];
378
+ for (const accidental of m[2])
379
+ chroma += accidental === "#" || accidental === "♯" ? 1 : -1;
380
+ return (chroma % 12 + 12) % 12;
381
+ }
382
+ function midiOf(note) {
383
+ const m = /^([A-Ga-g][#♯b♭]*)(-?\d)$/.exec(note.trim());
384
+ if (!m)
385
+ return null;
386
+ const chroma = chromaOf(m[1]);
387
+ if (chroma === null)
388
+ return null;
389
+ const letter = LETTER_CHROMA[m[1][0].toUpperCase()];
390
+ const shift = Math.round((chroma - letter) / 12);
391
+ return (Number(m[2]) + 1) * 12 + chroma - shift * 12;
392
+ }
393
+ var nameOf = (chroma, preferFlats = false) => (preferFlats ? FLAT_NAMES : SHARP_NAMES)[((Math.round(chroma) || 0) % 12 + 12) % 12];
394
+ function splitChordSymbol(symbol) {
395
+ const normalized = symbol.trim().replace(/♯/g, "#").replace(/♭/g, "b");
396
+ const m = /^([A-G][#b]?)(.*?)(?:\/([A-G][#b]?))?$/.exec(normalized);
397
+ return m ? { root: m[1], suffix: m[2], bass: m[3] ?? null } : null;
398
+ }
399
+ var noteOf = (midi, preferFlats = false) => `${nameOf(midi, preferFlats)}${Math.floor(midi / 12) - 1}`;
400
+ var isFlat = (name) => /^[A-Ga-g][b♭]/.test(name.trim());
401
+
402
+ // src/theory/transpose.ts
403
+ var FLAT_KEYS = new Set([5, 10, 3, 8, 1]);
404
+ var FLAT_MINOR_KEYS = new Set([2, 7, 0, 5, 10, 3]);
405
+ function keyPrefersFlats(key) {
406
+ const m = /^([A-G][#♯b♭]?)(m|min|minor)?\b/.exec(key.trim());
407
+ if (!m)
408
+ return false;
409
+ const chroma = chromaOf(m[1]);
410
+ if (chroma === null)
411
+ return false;
412
+ if (isFlat(m[1]))
413
+ return true;
414
+ return m[2] ? FLAT_MINOR_KEYS.has(chroma) : FLAT_KEYS.has(chroma);
415
+ }
416
+ var shift = (note, semitones, preferFlats) => {
417
+ const chroma = chromaOf(note);
418
+ return chroma === null ? note : nameOf(chroma + semitones, preferFlats);
419
+ };
420
+ function transposeChord(symbol, semitones, preferFlats) {
421
+ const trimmed = symbol.trim();
422
+ const parts = splitChordSymbol(trimmed);
423
+ const steps = Math.round(semitones) || 0;
424
+ if (!parts || steps % 12 === 0)
425
+ return trimmed;
426
+ const flats = preferFlats ?? isFlat(parts.root);
427
+ const bass = parts.bass ? `/${shift(parts.bass, steps, flats)}` : "";
428
+ return `${shift(parts.root, steps, flats)}${parts.suffix}${bass}`;
429
+ }
430
+ function transposeKey(key, semitones) {
431
+ const m = /^([A-G][#♯b♭]?)(.*)$/.exec(key.trim());
432
+ const chroma = m ? chromaOf(m[1]) : null;
433
+ const steps = Math.round(semitones) || 0;
434
+ if (!m || chroma === null || steps % 12 === 0)
435
+ return key.trim();
436
+ const target = ((chroma + steps) % 12 + 12) % 12;
437
+ const minor = /^\s*(m|min|minor)\b/.test(m[2]);
438
+ const flats = minor ? FLAT_MINOR_KEYS.has(target) : FLAT_KEYS.has(target);
439
+ return `${nameOf(target, flats)}${m[2]}`;
440
+ }
441
+
442
+ // src/chords/chart.ts
443
+ var SECTION_LABELS = {
444
+ chorus: "Chorus",
445
+ bridge: "Bridge",
446
+ tab: "Tab",
447
+ grid: "Grid"
448
+ };
449
+ function renderChart(doc, song, options = {}) {
450
+ const extra = options.transpose ?? 0;
451
+ const semitones = song.transpose + (Number.isFinite(extra) ? Math.round(extra) : 0);
452
+ const key = song.key ? transposeKey(song.key, semitones) : null;
453
+ const flats = key ? keyPrefersFlats(key) : undefined;
454
+ const chord = (symbol) => transposeChord(symbol, semitones, flats);
455
+ const root = html(doc, "div", "mn-chart");
456
+ if (song.title || song.subtitle || song.artist) {
457
+ const header = html(doc, "div", "mn-chart-header");
458
+ if (song.title)
459
+ header.appendChild(html(doc, "div", "mn-chart-title", song.title));
460
+ const by = [song.subtitle, song.artist].filter(Boolean).join(" · ");
461
+ if (by)
462
+ header.appendChild(html(doc, "div", "mn-chart-subtitle", by));
463
+ root.appendChild(header);
464
+ }
465
+ const meta = [
466
+ key ? `Key ${key}` : null,
467
+ song.capo ? `Capo ${song.capo}` : null,
468
+ song.tempo ? `${song.tempo} BPM` : null,
469
+ song.time ? song.time : null,
470
+ semitones % 12 ? `Transposed ${semitones > 0 ? "+" : ""}${semitones}` : null
471
+ ].filter((m) => m !== null);
472
+ if (meta.length)
473
+ root.appendChild(html(doc, "div", "mn-chart-meta", meta.join(" · ")));
474
+ for (const section of song.sections) {
475
+ const el = html(doc, "div", `mn-section mn-section-${section.kind}`);
476
+ const label = section.label ?? SECTION_LABELS[section.kind];
477
+ if (label)
478
+ el.appendChild(html(doc, "div", "mn-section-label", label));
479
+ for (const line of section.lines) {
480
+ if (line.kind === "empty")
481
+ el.appendChild(html(doc, "div", "mn-line mn-line-empty"));
482
+ else if (line.kind === "comment")
483
+ el.appendChild(html(doc, "div", "mn-line mn-comment", line.text));
484
+ else if (line.kind === "text")
485
+ el.appendChild(html(doc, "pre", "mn-line mn-pre", line.text));
486
+ else {
487
+ const row = html(doc, "div", "mn-line");
488
+ const chordsOnly = line.segments.every((s) => !s.text.trim());
489
+ if (chordsOnly)
490
+ row.classList.add("mn-chords-only");
491
+ for (const segment of line.segments) {
492
+ const seg = html(doc, "span", "mn-seg");
493
+ seg.appendChild(html(doc, "span", "mn-chord", segment.chord === null ? "" : chord(segment.chord)));
494
+ seg.appendChild(html(doc, "span", "mn-lyric", segment.text || (chordsOnly ? "" : " ")));
495
+ row.appendChild(seg);
496
+ }
497
+ el.appendChild(row);
498
+ }
499
+ }
500
+ root.appendChild(el);
501
+ }
502
+ return root;
503
+ }
504
+
505
+ // src/theory/note-set.ts
506
+ import { Chord, Scale } from "tonal";
507
+
508
+ // src/theory/suffix.ts
509
+ var CANONICAL = new Map([
510
+ ["M", ""],
511
+ ["maj", ""],
512
+ ["min", "m"],
513
+ ["-", "m"],
514
+ ["M7", "maj7"],
515
+ ["Δ", "maj7"],
516
+ ["Δ7", "maj7"],
517
+ ["M9", "maj9"],
518
+ ["Δ9", "maj9"],
519
+ ["min6", "m6"],
520
+ ["-6", "m6"],
521
+ ["min7", "m7"],
522
+ ["-7", "m7"],
523
+ ["min9", "m9"],
524
+ ["-9", "m9"],
525
+ ["ø", "m7b5"],
526
+ ["ø7", "m7b5"],
527
+ ["m7-5", "m7b5"],
528
+ ["mmaj7", "mMaj7"],
529
+ ["mM7", "mMaj7"],
530
+ ["m(maj7)", "mMaj7"],
531
+ ["-(maj7)", "mMaj7"],
532
+ ["°", "dim"],
533
+ ["°7", "dim7"],
534
+ ["+", "aug"],
535
+ ["sus", "sus4"],
536
+ ["add2", "add9"],
537
+ ["69", "6/9"]
538
+ ]);
539
+ var canonicalSuffix = (suffix) => CANONICAL.get(suffix) ?? suffix;
540
+
541
+ // src/theory/note-set.ts
542
+ var memberFor = (set, chroma) => set.members.find((m) => m.chroma === chroma);
543
+ var memberOf = (set, midi) => set.pitches && !set.pitches.includes(midi) ? undefined : memberFor(set, (midi % 12 + 12) % 12);
544
+ function intervalLabel(interval) {
545
+ const m = /^(\d+)([PMmdA]+)$/.exec(interval);
546
+ if (!m)
547
+ return interval;
548
+ const [, number, quality] = m;
549
+ if (number === "1" && quality === "P")
550
+ return "R";
551
+ const perfect = ["1", "4", "5", "8", "11", "12"].includes(String((Number(number) - 1) % 7 + 1));
552
+ if (quality === "P" || quality === "M")
553
+ return number;
554
+ if (quality === "m")
555
+ return `b${number}`;
556
+ if (quality.startsWith("A"))
557
+ return `${"#".repeat(quality.length)}${number}`;
558
+ return `${"b".repeat(quality.length + (perfect ? 0 : 1))}${number}`;
559
+ }
560
+ function labelOf(member, label, finger) {
561
+ switch (label) {
562
+ case "none":
563
+ return "";
564
+ case "degrees":
565
+ return member.degree === null ? member.name : String(member.degree);
566
+ case "intervals":
567
+ return member.interval === null ? member.name : intervalLabel(member.interval);
568
+ case "fingers":
569
+ return finger ?? "";
570
+ default:
571
+ return member.name;
572
+ }
573
+ }
574
+ var fromNames = (title, names, intervals, chord = false) => {
575
+ const members = [];
576
+ names.forEach((name, i) => {
577
+ const chroma = chromaOf(name);
578
+ if (chroma === null || members.some((m) => m.chroma === chroma))
579
+ return;
580
+ members.push({
581
+ chroma,
582
+ name,
583
+ degree: intervals ? chord ? Number(/^\d+/.exec(intervals[i] ?? "")?.[0] ?? i + 1) : i + 1 : null,
584
+ interval: intervals?.[i] ?? null
585
+ });
586
+ });
587
+ if (!members.length)
588
+ return null;
589
+ return {
590
+ title,
591
+ members,
592
+ root: intervals ? members[0].chroma : null,
593
+ pitches: null,
594
+ preferFlats: names.some(isFlat)
595
+ };
596
+ };
597
+ function chordNoteSet(symbol) {
598
+ const parts = splitChordSymbol(symbol);
599
+ if (!parts)
600
+ return null;
601
+ const chord = Chord.get(parts.root + canonicalSuffix(parts.suffix));
602
+ if (chord.empty)
603
+ return null;
604
+ const bass = parts.bass;
605
+ const set = fromNames(symbol.trim(), chord.notes, chord.intervals, true);
606
+ const bassChroma = bass ? chromaOf(bass) : null;
607
+ if (set && bass && bassChroma !== null && !memberFor(set, bassChroma)) {
608
+ set.members.push({ chroma: bassChroma, name: bass, degree: null, interval: null });
609
+ }
610
+ return set;
611
+ }
612
+ function scaleNoteSet(name) {
613
+ const scale = Scale.get(name.trim());
614
+ if (scale.empty || !scale.tonic)
615
+ return null;
616
+ return fromNames(name.trim(), scale.notes, scale.intervals);
617
+ }
618
+ function listNoteSet(text) {
619
+ const tokens = text.split(/[\s,]+/).filter(Boolean);
620
+ if (!tokens.length)
621
+ return null;
622
+ const withOctaves = tokens.every((t) => midiOf(t) !== null);
623
+ const names = withOctaves ? tokens.map((t) => t.replace(/-?\d$/, "")) : tokens;
624
+ if (!withOctaves && names.some((n) => chromaOf(n) === null))
625
+ return null;
626
+ const set = fromNames(tokens.join(" "), names, null);
627
+ if (set && withOctaves)
628
+ set.pitches = tokens.map((t) => midiOf(t));
629
+ return set;
630
+ }
631
+
632
+ // src/fretboard/fretboard.ts
633
+ var STRING_GAP = 20;
634
+ var FRET_W = 44;
635
+ var OPEN_W = 30;
636
+ var NUMBERS = 30;
637
+ var TITLE2 = 22;
638
+ var SINGLE_INLAYS = new Set([3, 5, 7, 9, 15, 17, 19, 21]);
639
+ function renderFretboard(doc, set, options = {}) {
640
+ const tuning = options.tuning ?? STANDARD_TUNING;
641
+ const [from, to] = options.frets ?? [0, 12];
642
+ const first = Math.max(from, 1);
643
+ const strings = tuning.length;
644
+ const label = options.label ?? "notes";
645
+ const orientation = options.orientation ?? "horizontal";
646
+ const vertical = orientation === "vertical";
647
+ const openW = from === 0 ? OPEN_W : 0;
648
+ const acrossLength = (strings - 1) * STRING_GAP;
649
+ const frame = neckFrame({
650
+ orientation,
651
+ hand: options.hand ?? "right",
652
+ across: acrossLength,
653
+ along: openW + (to - first + 1) * FRET_W,
654
+ before: vertical ? 20 : 24,
655
+ after: 8,
656
+ low: NUMBERS,
657
+ high: 12,
658
+ top: options.title ? TITLE2 : 0,
659
+ minWidth: titleWidth(options.title)
660
+ });
661
+ const across = (string) => string * STRING_GAP;
662
+ const wire = (fret) => openW + (fret - first + 1) * FRET_W;
663
+ const center = (fret) => fret === 0 ? OPEN_W / 2 : wire(fret) - FRET_W / 2;
664
+ const root = svgRoot(doc, frame.width, frame.height, "mn-fretboard", options.title ?? `Fretboard: ${set.title}`);
665
+ if (options.title) {
666
+ root.appendChild(svgText(doc, options.title, {
667
+ class: "mn-title",
668
+ x: frame.width / 2,
669
+ y: 15,
670
+ "text-anchor": "middle"
671
+ }));
672
+ }
673
+ const inlay = (a, fret) => {
674
+ const [cx, cy] = frame.at(a, center(fret));
675
+ root.appendChild(svg(doc, "circle", { class: "mn-inlay", cx, cy, r: 4 }));
676
+ };
677
+ const pair = (strings > 4 ? 1.5 : 0.5) * STRING_GAP;
678
+ for (let fret = first;fret <= to; fret++) {
679
+ if (SINGLE_INLAYS.has(fret))
680
+ inlay(acrossLength / 2, fret);
681
+ if (fret % 12 === 0) {
682
+ inlay(acrossLength - pair, fret);
683
+ inlay(pair, fret);
684
+ }
685
+ root.appendChild(svgLabel(doc, String(fret), frame.at(-18, center(fret)), "mn-fret-number"));
686
+ }
687
+ root.appendChild(svgLine(doc, frame.at(acrossLength, openW), frame.at(0, openW), first === 1 ? "mn-nut" : "mn-fret"));
688
+ for (let fret = first;fret <= to; fret++) {
689
+ root.appendChild(svgLine(doc, frame.at(acrossLength, wire(fret)), frame.at(0, wire(fret)), "mn-fret"));
690
+ }
691
+ for (let s = strings - 1;s >= 0; s--) {
692
+ const open = tuning[s];
693
+ root.appendChild(svgLine(doc, frame.at(across(s), 0), frame.at(across(s), wire(to)), "mn-string"));
694
+ const name = nameOf(open, set.preferFlats);
695
+ 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"));
696
+ for (let fret = from;fret <= to; fret++) {
697
+ const member = memberOf(set, open + fret);
698
+ if (!member)
699
+ continue;
700
+ const isRoot = set.root === member.chroma;
701
+ const point = frame.at(across(s), center(fret));
702
+ const [cx, cy] = point;
703
+ root.appendChild(svg(doc, "circle", { class: `mn-dot${isRoot ? " mn-root" : ""}`, cx, cy, r: 8 }));
704
+ const text = labelOf(member, label);
705
+ if (text)
706
+ root.appendChild(svgLabel(doc, text, point, "mn-dot-text"));
707
+ }
708
+ }
709
+ return root;
710
+ }
711
+
712
+ // src/fretboard/tuning.ts
713
+ var NAMED = new Map(Object.entries({
714
+ standard: "E2 A2 D3 G3 B3 E4",
715
+ "drop d": "D2 A2 D3 G3 B3 E4",
716
+ dadgad: "D2 A2 D3 G3 A3 D4",
717
+ "open g": "D2 G2 D3 G3 B3 D4",
718
+ "open d": "D2 A2 D3 F#3 A3 D4",
719
+ "open e": "E2 B2 E3 G#3 B3 E4",
720
+ "half step down": "Eb2 Ab2 Db3 Gb3 Bb3 Eb4",
721
+ bass: "E1 A1 D2 G2",
722
+ ukulele: "G4 C4 E4 A4"
723
+ }));
724
+ function parseTuning(text) {
725
+ const trimmed = text.trim();
726
+ const named = NAMED.get(trimmed.toLowerCase().replace(/\s*\(.*\)$/, ""));
727
+ if (named)
728
+ return parseTuning(named);
729
+ const spaced = trimmed.split(/[\s,]+/).filter(Boolean);
730
+ if (spaced.length > 1 && spaced.every((t) => midiOf(t) !== null)) {
731
+ return spaced.map((t) => midiOf(t));
732
+ }
733
+ const names = spaced.length > 1 ? spaced : trimmed.match(/[A-G][#♯b♭]?|[a-g][#♯♭]?/g) ?? [];
734
+ if (names.length < 2 || names.join("") !== spaced.join(""))
735
+ return null;
736
+ const midis = [];
737
+ for (const name of names) {
738
+ const chroma = chromaOf(name);
739
+ if (chroma === null)
740
+ return null;
741
+ const previous = midis[midis.length - 1];
742
+ if (previous === undefined) {
743
+ const candidates = [28, 40, 52].map((c) => c - c % 12 + chroma);
744
+ midis.push(candidates.reduce((a, b) => Math.abs(b - 40) < Math.abs(a - 40) ? b : a));
745
+ } else {
746
+ let midi = previous - previous % 12 + chroma;
747
+ while (midi <= previous)
748
+ midi += 12;
749
+ midis.push(midi);
750
+ }
751
+ }
752
+ return midis;
753
+ }
754
+
755
+ // src/keyboard/keyboard.ts
756
+ var BLACK = new Set([1, 3, 6, 8, 10]);
757
+ var WHITE_W = 22;
758
+ var WHITE_H = 104;
759
+ var BLACK_W = 14;
760
+ var BLACK_H = 64;
761
+ var TITLE3 = 22;
762
+ var isBlack = (midi) => BLACK.has((midi % 12 + 12) % 12);
763
+ function parseKeyRange(text) {
764
+ const parts = text.split(/\s*-\s*(?=[A-Ga-g])/);
765
+ if (parts.length !== 2)
766
+ return null;
767
+ const [from, to] = parts.map((n) => midiOf(n));
768
+ return from !== undefined && from !== null && to !== undefined && to !== null && from < to ? [from, to] : null;
769
+ }
770
+ function keyRangeOf(set) {
771
+ if (!set.pitches?.length)
772
+ return [60, 83];
773
+ const low = Math.min(...set.pitches);
774
+ const high = Math.max(...set.pitches);
775
+ return [low - (low % 12 + 12) % 12, high + 11 - (high % 12 + 12) % 12];
776
+ }
777
+ function renderKeyboard(doc, set, options = {}) {
778
+ let [from, to] = options.range ?? keyRangeOf(set);
779
+ if (isBlack(from))
780
+ from--;
781
+ if (isBlack(to))
782
+ to++;
783
+ const whites = [];
784
+ for (let midi = from;midi <= to; midi++)
785
+ if (!isBlack(midi))
786
+ whites.push(midi);
787
+ const vertical = options.orientation === "vertical";
788
+ const top = options.title ? TITLE3 : 0;
789
+ const length = whites.length * WHITE_W;
790
+ const content = (vertical ? WHITE_H : length) + 2;
791
+ const width = Math.max(content, titleWidth(options.title));
792
+ const shift = (width - content) / 2;
793
+ const height = top + (vertical ? length : WHITE_H) + 2;
794
+ const at = (along, depth) => vertical ? [shift + 1 + depth, top + 1 + length - along] : [shift + 1 + along, top + 1 + depth];
795
+ const key = (along, size, depth) => {
796
+ const [x1, y1] = at(along, 0);
797
+ const [x2, y2] = at(along + size, depth);
798
+ return {
799
+ x: Math.min(x1, x2),
800
+ y: Math.min(y1, y2),
801
+ width: Math.abs(x2 - x1),
802
+ height: Math.abs(y2 - y1)
803
+ };
804
+ };
805
+ const label = options.label ?? "notes";
806
+ const root = svgRoot(doc, width, height, "mn-keyboard", options.title ?? `Keyboard: ${set.title}`);
807
+ if (options.title) {
808
+ root.appendChild(svgText(doc, options.title, {
809
+ class: "mn-title",
810
+ x: width / 2,
811
+ y: 15,
812
+ "text-anchor": "middle"
813
+ }));
814
+ }
815
+ const keyClass = (midi, black) => {
816
+ const member = memberOf(set, midi);
817
+ const classes = [black ? "mn-key-black" : "mn-key-white"];
818
+ if (member)
819
+ classes.push("mn-on");
820
+ if (member && set.root === member.chroma)
821
+ classes.push("mn-root");
822
+ return classes.join(" ");
823
+ };
824
+ const caption = (midi, point, black) => {
825
+ const member = memberOf(set, midi);
826
+ if (!member)
827
+ return;
828
+ const text = labelOf(member, label, options.fingers?.get(midi));
829
+ if (!text)
830
+ return;
831
+ root.appendChild(svgLabel(doc, text, point, black ? "mn-key-label mn-key-label-black" : "mn-key-label"));
832
+ };
833
+ whites.forEach((midi, i) => {
834
+ const along = i * WHITE_W;
835
+ root.appendChild(svg(doc, "rect", {
836
+ class: keyClass(midi, false),
837
+ ...key(along, WHITE_W, WHITE_H),
838
+ rx: 2
839
+ }));
840
+ caption(midi, at(along + WHITE_W / 2, WHITE_H - 13), false);
841
+ });
842
+ whites.forEach((midi, i) => {
843
+ const black = midi + 1;
844
+ if (black > to || !isBlack(black))
845
+ return;
846
+ const along = (i + 1) * WHITE_W - BLACK_W / 2;
847
+ root.appendChild(svg(doc, "rect", {
848
+ class: keyClass(black, true),
849
+ ...key(along, BLACK_W, BLACK_H),
850
+ rx: 2
851
+ }));
852
+ caption(black, at(along + BLACK_W / 2, BLACK_H - 13), true);
853
+ });
854
+ return root;
855
+ }
856
+
857
+ // src/theory/chord-symbol.ts
858
+ var QUALITY_SUFFIXES = [
859
+ [/^(m7b5|m7-5|ø7?)$/, "Minor 7 flat 5"],
860
+ [/^(dim7|°7)$/, "Diminished 7"],
861
+ [/^(maj9|M9|Δ9)$/, "Major 9"],
862
+ [/^(maj7|M7|Δ7?)$/, "Major 7"],
863
+ [/^(7sus4)$/, "7sus4"],
864
+ [/^(m9|min9|-9)$/, "Minor 9"],
865
+ [/^(m7|min7|-7)$/, "Minor 7"],
866
+ [/^(m6|min6|-6)$/, "Minor 6"],
867
+ [/^(m|min|-)$/, "Minor"],
868
+ [/^(dim|°)$/, "Diminished"],
869
+ [/^(aug|\+)$/, "Augmented"],
870
+ [/^(sus2)$/, "Sus2"],
871
+ [/^(sus4|sus)$/, "Sus4"],
872
+ [/^(add9|add2)$/, "Add9"],
873
+ [/^5$/, "5 (Power)"],
874
+ [/^(6\/9|69)$/, "6/9"],
875
+ [/^(mM7|mMaj7|mmaj7|m\(maj7\)|-\(maj7\))$/, "Minor major 7"],
876
+ [/^(13|11|9|7|6)$/, "$1"],
877
+ [/^(maj|M)?$/, "Major"]
878
+ ];
879
+ var spell = (note) => note[0] + (note[1] === "#" ? " Sharp" : note[1] === "b" ? " Flat" : "");
880
+ var plain = (quality) => quality.replace(/\s*\([^)]*\)/g, "").trim();
881
+ function parseChord(symbol) {
882
+ const parts = splitChordSymbol(symbol);
883
+ if (!parts)
884
+ return null;
885
+ const trimmed = symbol.trim();
886
+ const { root, suffix, bass } = parts;
887
+ let quality = null;
888
+ for (const [re, label] of QUALITY_SUFFIXES) {
889
+ const hit = re.exec(suffix);
890
+ if (hit) {
891
+ quality = label.replace("$1", hit[1] ?? "");
892
+ break;
893
+ }
894
+ }
895
+ if (!quality && chordNoteSet(trimmed))
896
+ quality = suffix;
897
+ if (!quality)
898
+ return null;
899
+ return {
900
+ symbol: trimmed,
901
+ root,
902
+ quality,
903
+ bass,
904
+ name: `${spell(root)} ${plain(quality)}${bass ? ` over ${spell(bass)}` : ""}`
905
+ };
906
+ }
907
+
908
+ // src/blocks/block-source.ts
909
+ var FIELD = /^([A-Za-z][\w-]*)\s*:\s*(.*)$/;
910
+ function parseBlockSource(source) {
911
+ const fields = new Map;
912
+ let head = null;
913
+ source.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).forEach((line, i) => {
914
+ const m = FIELD.exec(line);
915
+ if (m)
916
+ fields.set(m[1].toLowerCase(), m[2].trim());
917
+ else if (i === 0)
918
+ head = line;
919
+ else
920
+ throw new Error(`Expected "key: value", got "${line}"`);
921
+ });
922
+ return { head, fields };
923
+ }
924
+ function parseRange(text) {
925
+ const m = /^(\d+)\s*(?:-\s*(\d+))?$/.exec(text.trim());
926
+ if (!m)
927
+ return null;
928
+ const from = Number(m[1]);
929
+ const to = m[2] === undefined ? from : Number(m[2]);
930
+ return from <= to ? [from, to] : null;
931
+ }
932
+ var SEPARATOR = /^\s*-{3,}\s*$/;
933
+ function splitParts(source) {
934
+ const lines = source.split(/\r?\n/);
935
+ if (!lines.some((line) => SEPARATOR.test(line)))
936
+ return null;
937
+ const parts = [[]];
938
+ for (const line of lines) {
939
+ if (SEPARATOR.test(line))
940
+ parts.push([]);
941
+ else
942
+ parts[parts.length - 1].push(line);
943
+ }
944
+ return parts.map((part) => part.join(`
945
+ `)).filter((part) => part.trim() !== "");
946
+ }
947
+
948
+ // src/blocks/note-set-field.ts
949
+ var LABELS = new Set(["notes", "degrees", "intervals", "none"]);
950
+ function noteSetOf(block) {
951
+ const scale = block.fields.get("scale");
952
+ const chord = block.fields.get("chord");
953
+ const notes = block.fields.get("notes");
954
+ if (scale !== undefined)
955
+ return orFail(scaleNoteSet(scale), `Unknown scale "${scale}"`);
956
+ if (chord !== undefined)
957
+ return orFail(chordNoteSet(chord), `Unknown chord "${chord}"`);
958
+ if (notes !== undefined)
959
+ return orFail(listNoteSet(notes), `Invalid notes "${notes}"`);
960
+ if (block.head) {
961
+ const exact = listNoteSet(block.head);
962
+ const set = scaleNoteSet(block.head) ?? (exact?.pitches ? exact : null) ?? chordNoteSet(block.head) ?? exact;
963
+ return orFail(set, `"${block.head}" is not a scale, chord or list of notes`);
964
+ }
965
+ throw new Error('Add "scale:", "chord:" or "notes:"');
966
+ }
967
+ function labelField(block, fallback, fingers = false) {
968
+ const value = block.fields.get("labels")?.toLowerCase();
969
+ if (value === undefined)
970
+ return fallback;
971
+ if (!LABELS.has(value) && !(fingers && value === "fingers")) {
972
+ const choices = fingers ? "notes, degrees, intervals, fingers or none" : "notes, degrees, intervals or none";
973
+ throw new Error(`Unknown labels "${value}": use ${choices}`);
974
+ }
975
+ return value;
976
+ }
977
+ function orFail(value, message) {
978
+ if (value === null)
979
+ throw new Error(message);
980
+ return value;
981
+ }
982
+
983
+ // src/blocks/renderers.ts
984
+ var SHARED_KEYS = {
985
+ chord: ["orientation", "hand", "labels", "instrument", "tuning", "range"],
986
+ keyboard: ["orientation", "hand", "labels", "range"],
987
+ fretboard: ["orientation", "hand", "labels", "tuning", "frets"]
988
+ };
989
+ var field = (block, ...names) => {
990
+ for (const name of names) {
991
+ const value = block.fields.get(name);
992
+ if (value !== undefined && value !== "")
993
+ return value;
994
+ }
995
+ return;
996
+ };
997
+ var MAX_STRINGS = 12;
998
+ var MAX_KEYS = 88;
999
+ var tuningOf = (text) => {
1000
+ const tuning = orFail(parseTuning(text), `Unknown tuning "${text}"`);
1001
+ if (tuning.length > MAX_STRINGS)
1002
+ throw new Error(`At most ${MAX_STRINGS} strings`);
1003
+ return tuning;
1004
+ };
1005
+ var rangeOf = (text) => orFail(parseKeyRange(text), `Invalid range "${text}": use e.g. C3-B4`);
1006
+ var keyRange = (range) => {
1007
+ if (range[1] - range[0] + 1 > MAX_KEYS) {
1008
+ throw new Error(`At most ${MAX_KEYS} keys: give a smaller range, e.g. range: C3-B5`);
1009
+ }
1010
+ return range;
1011
+ };
1012
+ var orientationOf = (block, fallback) => {
1013
+ const text = field(block, "orientation");
1014
+ return text ? parseOrientation(text) : fallback;
1015
+ };
1016
+ var handOf = (block, options) => {
1017
+ const text = field(block, "hand");
1018
+ return text ? parseHand(text) : options.hand;
1019
+ };
1020
+ var rootOf = (symbol) => {
1021
+ const parts = splitChordSymbol(symbol);
1022
+ return parts && parseChord(symbol) ? chromaOf(parts.root) : null;
1023
+ };
1024
+ var positiveInt = (text, what) => {
1025
+ const n = Number(text);
1026
+ if (!Number.isInteger(n) || n < 1)
1027
+ throw new Error(`${what} must be a whole number from 1, got "${text}"`);
1028
+ return n;
1029
+ };
1030
+ function shorthand(head) {
1031
+ const tokens = head?.split(/\s+/).filter(Boolean) ?? [];
1032
+ const symbol = tokens[0] && !parseFrets(tokens[0]) ? tokens.shift() : undefined;
1033
+ return { symbol, frets: tokens[0], fingers: tokens[1] };
1034
+ }
1035
+ function pianoPitches(symbol) {
1036
+ const set = orFail(chordNoteSet(symbol), `Unknown chord "${symbol}"`);
1037
+ const bassName = splitChordSymbol(symbol)?.bass;
1038
+ const bass = bassName ? chromaOf(bassName) : null;
1039
+ const pitches = [];
1040
+ let previous = 59;
1041
+ for (const member of set.members) {
1042
+ if (bass !== null && member.chroma === bass && member.degree === null)
1043
+ continue;
1044
+ let midi = 60 + member.chroma;
1045
+ while (midi <= previous)
1046
+ midi += 12;
1047
+ while (midi - 12 > previous)
1048
+ midi -= 12;
1049
+ pitches.push(midi);
1050
+ previous = midi;
1051
+ }
1052
+ if (bass !== null)
1053
+ pitches.unshift(48 + bass);
1054
+ return { ...set, pitches };
1055
+ }
1056
+ var renderChord = (doc, block, options) => {
1057
+ const short = shorthand(block.head);
1058
+ const name = field(block, "name");
1059
+ const symbol = field(block, "symbol", "chord") ?? short.symbol ?? (name && parseChord(name) ? name : undefined);
1060
+ const title = field(block, "title") ?? name ?? symbol;
1061
+ const instrument = field(block, "instrument")?.toLowerCase();
1062
+ const pitchesText = field(block, "pitches", "notes");
1063
+ if (instrument === "piano" || instrument === "keyboard" || pitchesText && !instrument) {
1064
+ let set;
1065
+ if (pitchesText) {
1066
+ set = orFail(listNoteSet(pitchesText), `Invalid pitches "${pitchesText}"`);
1067
+ if (!set.pitches) {
1068
+ let previous = 59;
1069
+ set.pitches = set.members.map((m) => {
1070
+ let midi = 60 + m.chroma;
1071
+ while (midi <= previous)
1072
+ midi += 12;
1073
+ previous = midi;
1074
+ return midi;
1075
+ });
1076
+ }
1077
+ const chord = symbol ? chordNoteSet(symbol) : null;
1078
+ if (chord)
1079
+ set.root = chord.root;
1080
+ } else if (symbol) {
1081
+ set = pianoPitches(symbol);
1082
+ } else {
1083
+ throw new Error('Add a chord symbol or "pitches:"');
1084
+ }
1085
+ const fingering = field(block, "fingering", "fingers");
1086
+ const fingers = new Map;
1087
+ if (fingering) {
1088
+ const sorted = [...set.pitches].sort((a, b) => a - b);
1089
+ fingering.split(/[\s,-]+/).filter(Boolean).forEach((finger, i) => {
1090
+ if (sorted[i] !== undefined)
1091
+ fingers.set(sorted[i], finger);
1092
+ });
1093
+ }
1094
+ const range = field(block, "range");
1095
+ handOf(block, options);
1096
+ return renderKeyboard(doc, set, {
1097
+ title,
1098
+ label: labelField(block, fingers.size ? "fingers" : "notes", fingers.size > 0),
1099
+ fingers,
1100
+ range: keyRange(range ? rangeOf(range) : keyRangeOf(set)),
1101
+ orientation: orientationOf(block, options.orientation?.keyboard)
1102
+ });
1103
+ }
1104
+ if (instrument && instrument !== "guitar" && !field(block, "tuning")) {
1105
+ throw new Error(`Unknown instrument "${instrument}": use guitar or piano, or give a tuning`);
1106
+ }
1107
+ const fretsText = field(block, "frets") ?? short.frets;
1108
+ let voicing;
1109
+ if (fretsText) {
1110
+ const frets = orFail(parseFrets(fretsText), `Invalid frets "${fretsText}": use e.g. x02220`);
1111
+ if (frets.length > MAX_STRINGS)
1112
+ throw new Error(`At most ${MAX_STRINGS} strings`);
1113
+ const fingersText = field(block, "fingers") ?? short.fingers;
1114
+ const fingers = fingersText ? parseFingers(fingersText) : [];
1115
+ if (fingersText && fingers.length !== frets.length) {
1116
+ throw new Error(`"${fingersText}" has ${fingers.length} fingers for ${frets.length} strings`);
1117
+ }
1118
+ voicing = { frets, fingers: frets.map((_, i) => fingers[i] ?? null) };
1119
+ } else if (symbol && options.voicings) {
1120
+ const n = field(block, "voicing");
1121
+ const index = n ? positiveInt(n, "voicing") - 1 : 0;
1122
+ voicing = orFail(options.voicings(symbol, index), `No voicing ${index + 1} found for "${symbol}": add "frets:"`);
1123
+ } else {
1124
+ throw new Error(symbol ? `Add "frets:" for ${symbol} (e.g. frets: x02220)` : 'Add a chord symbol and "frets:"');
1125
+ }
1126
+ const position = field(block, "position", "base");
1127
+ if (position) {
1128
+ const base = positiveInt(position, "position");
1129
+ const fretted = voicing.frets.filter((f) => f !== null && f > 0);
1130
+ if (fretted.length && base > Math.min(...fretted)) {
1131
+ throw new Error(`position ${base} is above the lowest fretted note (fret ${Math.min(...fretted)})`);
1132
+ }
1133
+ voicing.baseFret = base;
1134
+ } else
1135
+ voicing.baseFret ??= baseFretOf(voicing.frets);
1136
+ const tuningText = field(block, "tuning");
1137
+ const tuning = tuningText ? tuningOf(tuningText) : undefined;
1138
+ if (tuning && tuning.length !== voicing.frets.length) {
1139
+ throw new Error(`The tuning has ${tuning.length} strings, the frets ${voicing.frets.length}`);
1140
+ }
1141
+ const root = symbol ? chordNoteSet(symbol)?.root ?? rootOf(symbol) : null;
1142
+ return renderGuitarDiagram(doc, voicing, {
1143
+ title,
1144
+ root,
1145
+ tuning,
1146
+ orientation: orientationOf(block, options.orientation?.chord),
1147
+ hand: handOf(block, options)
1148
+ });
1149
+ };
1150
+ var renderKeyboardBlock = (doc, block, options) => {
1151
+ const set = noteSetOf(block);
1152
+ const range = field(block, "range");
1153
+ handOf(block, options);
1154
+ return renderKeyboard(doc, set, {
1155
+ title: field(block, "title"),
1156
+ label: labelField(block, "notes"),
1157
+ range: keyRange(range ? rangeOf(range) : keyRangeOf(set)),
1158
+ orientation: orientationOf(block, options.orientation?.keyboard)
1159
+ });
1160
+ };
1161
+ var renderFretboardBlock = (doc, block, options) => {
1162
+ const set = noteSetOf(block);
1163
+ const fretsText = field(block, "frets");
1164
+ const frets = fretsText ? orFail(parseRange(fretsText), `Invalid frets "${fretsText}": use e.g. 5-8`) : undefined;
1165
+ if (frets && frets[1] > 36)
1166
+ throw new Error("Frets go up to 36");
1167
+ const tuningText = field(block, "tuning");
1168
+ return renderFretboard(doc, set, {
1169
+ title: field(block, "title"),
1170
+ label: labelField(block, "notes"),
1171
+ frets,
1172
+ tuning: tuningText ? tuningOf(tuningText) : undefined,
1173
+ orientation: orientationOf(block, options.orientation?.fretboard),
1174
+ hand: handOf(block, options)
1175
+ });
1176
+ };
1177
+ var DIAGRAMS = {
1178
+ chord: renderChord,
1179
+ keyboard: renderKeyboardBlock,
1180
+ fretboard: renderFretboardBlock
1181
+ };
1182
+ var fromSource = (render) => (doc, source, options) => render(doc, parseBlockSource(source), options);
1183
+ var renderChordsBlock = (doc, source, options) => renderChart(doc, parseChordPro(source), { transpose: options.transpose });
1184
+ var RENDERERS = {
1185
+ chord: fromSource(renderChord),
1186
+ chords: renderChordsBlock,
1187
+ keyboard: fromSource(renderKeyboardBlock),
1188
+ fretboard: fromSource(renderFretboardBlock)
1189
+ };
1190
+
1191
+ // src/render/render-block.ts
1192
+ var LANGUAGES = Object.keys(RENDERERS);
1193
+ var isNotationLanguage = (language) => Object.prototype.hasOwnProperty.call(RENDERERS, language);
1194
+ var isDiagramLanguage = (language) => Object.prototype.hasOwnProperty.call(DIAGRAMS, language);
1195
+ var MAX_DIAGRAMS = 32;
1196
+ var messageOf = (e) => e instanceof Error ? e.message : String(e);
1197
+ function renderBlock(language, source, host, given = {}) {
1198
+ const doc = host.ownerDocument;
1199
+ const el = html(doc, "div", `mn-block mn-block-${language}`);
1200
+ let error = null;
1201
+ const layout = layoutDefaults(given);
1202
+ const options = {
1203
+ ...given ?? {},
1204
+ orientation: layout.orientation ?? {},
1205
+ hand: layout.hand ?? "right"
1206
+ };
1207
+ const parts = isDiagramLanguage(language) ? splitParts(source) : null;
1208
+ if (!source.trim() || parts?.length === 0) {
1209
+ el.classList.add("mn-empty");
1210
+ host.appendChild(el);
1211
+ return { ok: true, el, error: null, destroy: () => el.remove() };
1212
+ }
1213
+ try {
1214
+ if (parts && isDiagramLanguage(language)) {
1215
+ error = renderRow(doc, language, parts, el, options);
1216
+ } else {
1217
+ el.appendChild(RENDERERS[language](doc, source, options));
1218
+ }
1219
+ } catch (e) {
1220
+ error = messageOf(e);
1221
+ el.replaceChildren();
1222
+ el.classList.add("mn-error");
1223
+ el.appendChild(html(doc, "div", "mn-error-message", `${language}: ${error}`));
1224
+ }
1225
+ host.appendChild(el);
1226
+ return { ok: error === null, el, error, destroy: () => el.remove() };
1227
+ }
1228
+ var filled = (block) => ({
1229
+ head: block.head,
1230
+ fields: new Map([...block.fields].filter(([, value]) => value !== ""))
1231
+ });
1232
+ function headerOf(language, part) {
1233
+ if (part === undefined)
1234
+ return null;
1235
+ let block;
1236
+ try {
1237
+ block = filled(parseBlockSource(part));
1238
+ } catch {
1239
+ return null;
1240
+ }
1241
+ if (block.head !== null)
1242
+ return null;
1243
+ const shared = SHARED_KEYS[language];
1244
+ const others = [...block.fields.keys()].filter((key) => key !== "columns" && !shared.includes(key));
1245
+ if (!others.length)
1246
+ return block.fields.size ? block : null;
1247
+ if (!block.fields.has("columns"))
1248
+ return null;
1249
+ throw new Error(`"${others[0]}" can't be shared: move it to a diagram. Shared settings: ${shared.join(", ")}, columns`);
1250
+ }
1251
+ function checkShared(header) {
1252
+ const orientation = header.fields.get("orientation");
1253
+ if (orientation !== undefined)
1254
+ parseOrientation(orientation);
1255
+ const hand = header.fields.get("hand");
1256
+ if (hand !== undefined)
1257
+ parseHand(hand);
1258
+ }
1259
+ function sharesSomething(language, part) {
1260
+ try {
1261
+ const block = parseBlockSource(part);
1262
+ return block.head === null && [...block.fields.keys()].some((k) => SHARED_KEYS[language].includes(k));
1263
+ } catch {
1264
+ return false;
1265
+ }
1266
+ }
1267
+ function columnsOf(header) {
1268
+ const text = header?.fields.get("columns");
1269
+ if (text === undefined)
1270
+ return null;
1271
+ const n = Number(text);
1272
+ if (!Number.isInteger(n) || n < 1 || n > 12) {
1273
+ throw new Error(`columns must be a whole number from 1 to 12, got "${text}"`);
1274
+ }
1275
+ return n;
1276
+ }
1277
+ function renderRow(doc, language, parts, el, options) {
1278
+ const header = headerOf(language, parts[0]);
1279
+ const diagrams = header ? parts.slice(1) : parts;
1280
+ if (header && !diagrams.length) {
1281
+ throw new Error('Add a diagram after the shared settings: a "---" line, then the diagram');
1282
+ }
1283
+ if (header)
1284
+ checkShared(header);
1285
+ if (diagrams.length > MAX_DIAGRAMS) {
1286
+ throw new Error(`At most ${MAX_DIAGRAMS} diagrams per block, found ${diagrams.length}`);
1287
+ }
1288
+ const columns = columnsOf(header);
1289
+ const shared = [...header?.fields ?? []].filter(([key]) => key !== "columns");
1290
+ const row = html(doc, "div", columns ? `mn-grid mn-cols-${columns}` : "mn-row");
1291
+ const errors = [];
1292
+ diagrams.forEach((part, i) => {
1293
+ const cell = html(doc, "div", "mn-cell");
1294
+ try {
1295
+ const block = filled(parseBlockSource(part));
1296
+ if (block.fields.has("columns")) {
1297
+ throw new Error('"columns" goes in the shared settings, before the first "---"');
1298
+ }
1299
+ const fields = new Map([...shared, ...block.fields]);
1300
+ cell.appendChild(DIAGRAMS[language](doc, { head: block.head, fields }, options));
1301
+ } catch (e) {
1302
+ let message = `diagram ${i + 1}: ${messageOf(e)}`;
1303
+ if (i === 0 && !header && sharesSomething(language, part)) {
1304
+ message += ` (shared settings before the first "---" may only hold: ${SHARED_KEYS[language].join(", ")}, columns)`;
1305
+ }
1306
+ errors.push(message);
1307
+ cell.classList.add("mn-error");
1308
+ cell.appendChild(html(doc, "div", "mn-error-message", `${language}, ${message}`));
1309
+ }
1310
+ row.appendChild(cell);
1311
+ });
1312
+ el.appendChild(row);
1313
+ return errors.length ? errors.join("; ") : null;
1314
+ }
1315
+ // src/styles.css
1316
+ var styles_default = `/* Music notation. Colors follow Obsidian's theme variables when present, with fallbacks for any page. */
1317
+ .mn-block,
1318
+ .mn-svg,
1319
+ .mn-chart {
1320
+ --mn-fg: var(--text-normal, currentColor);
1321
+ --mn-muted: var(--text-muted, #8a8a8a);
1322
+ --mn-faint: var(--background-modifier-border, #d0d0d0);
1323
+ --mn-accent: var(--interactive-accent, #7c3aed);
1324
+ --mn-on-accent: var(--text-on-accent, #fff);
1325
+ /* Dark enough for white labels in light and dark themes. */
1326
+ --mn-root: #c2410c;
1327
+ /* Piano keys keep their real colors in every theme. */
1328
+ --mn-key-white: #fafafa;
1329
+ --mn-key-black: #222;
1330
+ font-family: var(--font-interface, system-ui, sans-serif);
1331
+ }
1332
+
1333
+ .mn-block {
1334
+ color: var(--mn-fg);
1335
+ margin: 0.5em 0;
1336
+ overflow-x: auto;
1337
+ }
1338
+
1339
+ .mn-svg {
1340
+ display: block;
1341
+ max-width: 100%;
1342
+ height: auto;
1343
+ }
1344
+
1345
+ .mn-svg text {
1346
+ fill: var(--mn-fg);
1347
+ font-size: 11px;
1348
+ }
1349
+
1350
+ .mn-svg .mn-title {
1351
+ font-size: 14px;
1352
+ font-weight: 600;
1353
+ }
1354
+
1355
+ .mn-svg .mn-string,
1356
+ .mn-svg .mn-fret {
1357
+ stroke: var(--mn-muted);
1358
+ stroke-width: 1;
1359
+ }
1360
+
1361
+ .mn-svg .mn-nut {
1362
+ stroke: var(--mn-fg);
1363
+ stroke-width: 4;
1364
+ }
1365
+
1366
+ .mn-svg .mn-dot,
1367
+ .mn-svg .mn-barre {
1368
+ fill: var(--mn-accent);
1369
+ }
1370
+
1371
+ .mn-svg .mn-dot.mn-root {
1372
+ fill: var(--mn-root);
1373
+ }
1374
+
1375
+ .mn-svg .mn-dot-text {
1376
+ fill: var(--mn-on-accent);
1377
+ font-size: 10px;
1378
+ font-weight: 600;
1379
+ }
1380
+
1381
+ .mn-svg .mn-open {
1382
+ fill: none;
1383
+ stroke: var(--mn-fg);
1384
+ stroke-width: 1.5;
1385
+ }
1386
+
1387
+ .mn-svg .mn-open.mn-root {
1388
+ stroke: var(--mn-root);
1389
+ }
1390
+
1391
+ .mn-svg .mn-muted,
1392
+ .mn-svg .mn-base-fret,
1393
+ .mn-svg .mn-fret-number,
1394
+ .mn-svg .mn-string-name {
1395
+ fill: var(--mn-muted);
1396
+ }
1397
+
1398
+ .mn-svg .mn-inlay {
1399
+ fill: var(--mn-faint);
1400
+ }
1401
+
1402
+ .mn-svg .mn-key-white {
1403
+ fill: var(--mn-key-white);
1404
+ stroke: #888;
1405
+ }
1406
+
1407
+ .mn-svg .mn-key-black {
1408
+ fill: var(--mn-key-black);
1409
+ stroke: var(--mn-key-black);
1410
+ }
1411
+
1412
+ .mn-svg .mn-key-white.mn-on,
1413
+ .mn-svg .mn-key-black.mn-on {
1414
+ fill: var(--mn-accent);
1415
+ }
1416
+
1417
+ .mn-svg .mn-key-white.mn-on.mn-root,
1418
+ .mn-svg .mn-key-black.mn-on.mn-root {
1419
+ fill: var(--mn-root);
1420
+ }
1421
+
1422
+ .mn-svg .mn-key-label {
1423
+ font-size: 10px;
1424
+ fill: var(--mn-on-accent);
1425
+ font-weight: 600;
1426
+ }
1427
+
1428
+ /* Several diagrams in one block: a row that wraps, or a grid of at most \`columns\` columns that
1429
+ also wraps on narrow screens rather than shrinking diagrams to nothing. */
1430
+ .mn-block .mn-row {
1431
+ display: flex;
1432
+ flex-wrap: wrap;
1433
+ align-items: flex-start;
1434
+ gap: 0.75em 1.25em;
1435
+ }
1436
+
1437
+ .mn-block .mn-grid {
1438
+ --mn-gap: 1.25em;
1439
+ display: grid;
1440
+ align-items: start;
1441
+ gap: 0.75em var(--mn-gap);
1442
+ grid-template-columns: repeat(
1443
+ auto-fill,
1444
+ minmax(
1445
+ max(110px, calc((100% - (var(--mn-columns) - 1) * var(--mn-gap)) / var(--mn-columns))),
1446
+ 1fr
1447
+ )
1448
+ );
1449
+ }
1450
+
1451
+ .mn-block .mn-grid .mn-cell {
1452
+ display: flex;
1453
+ justify-content: center;
1454
+ }
1455
+
1456
+ .mn-block .mn-cell {
1457
+ min-width: 0;
1458
+ }
1459
+
1460
+ .mn-block .mn-cols-1 {
1461
+ --mn-columns: 1;
1462
+ }
1463
+
1464
+ .mn-block .mn-cols-2 {
1465
+ --mn-columns: 2;
1466
+ }
1467
+
1468
+ .mn-block .mn-cols-3 {
1469
+ --mn-columns: 3;
1470
+ }
1471
+
1472
+ .mn-block .mn-cols-4 {
1473
+ --mn-columns: 4;
1474
+ }
1475
+
1476
+ .mn-block .mn-cols-5 {
1477
+ --mn-columns: 5;
1478
+ }
1479
+
1480
+ .mn-block .mn-cols-6 {
1481
+ --mn-columns: 6;
1482
+ }
1483
+
1484
+ .mn-block .mn-cols-7 {
1485
+ --mn-columns: 7;
1486
+ }
1487
+
1488
+ .mn-block .mn-cols-8 {
1489
+ --mn-columns: 8;
1490
+ }
1491
+
1492
+ .mn-block .mn-cols-9 {
1493
+ --mn-columns: 9;
1494
+ }
1495
+
1496
+ .mn-block .mn-cols-10 {
1497
+ --mn-columns: 10;
1498
+ }
1499
+
1500
+ .mn-block .mn-cols-11 {
1501
+ --mn-columns: 11;
1502
+ }
1503
+
1504
+ .mn-block .mn-cols-12 {
1505
+ --mn-columns: 12;
1506
+ }
1507
+
1508
+ /* Chord charts */
1509
+ .mn-chart {
1510
+ line-height: 1.3;
1511
+ }
1512
+
1513
+ .mn-chart-title {
1514
+ font-size: 1.3em;
1515
+ font-weight: 700;
1516
+ }
1517
+
1518
+ .mn-chart-subtitle,
1519
+ .mn-chart-meta {
1520
+ color: var(--mn-muted);
1521
+ }
1522
+
1523
+ .mn-chart-meta {
1524
+ font-size: 0.9em;
1525
+ margin-top: 0.2em;
1526
+ }
1527
+
1528
+ .mn-section {
1529
+ margin-top: 0.9em;
1530
+ }
1531
+
1532
+ .mn-section-chorus {
1533
+ border-left: 3px solid var(--mn-accent);
1534
+ padding-left: 0.75em;
1535
+ }
1536
+
1537
+ .mn-section-label {
1538
+ font-weight: 600;
1539
+ font-size: 0.85em;
1540
+ color: var(--mn-muted);
1541
+ text-transform: uppercase;
1542
+ letter-spacing: 0.04em;
1543
+ }
1544
+
1545
+ .mn-line {
1546
+ display: flex;
1547
+ flex-wrap: wrap;
1548
+ align-items: flex-end;
1549
+ min-height: 1.3em;
1550
+ }
1551
+
1552
+ .mn-seg {
1553
+ display: inline-flex;
1554
+ flex-direction: column;
1555
+ min-width: 0;
1556
+ max-width: 100%;
1557
+ white-space: pre-wrap;
1558
+ }
1559
+
1560
+ .mn-chord {
1561
+ color: var(--mn-accent);
1562
+ font-weight: 700;
1563
+ min-height: 1.3em;
1564
+ padding-right: 0.4em;
1565
+ }
1566
+
1567
+ .mn-chords-only .mn-seg {
1568
+ margin-right: 0.6em;
1569
+ }
1570
+
1571
+ .mn-comment {
1572
+ font-style: italic;
1573
+ color: var(--mn-muted);
1574
+ }
1575
+
1576
+ .mn-pre {
1577
+ font-family: var(--font-monospace, ui-monospace, monospace);
1578
+ margin: 0;
1579
+ white-space: pre;
1580
+ }
1581
+
1582
+ .mn-error-message {
1583
+ color: var(--text-error, #c92a2a);
1584
+ font-size: 0.9em;
1585
+ }
1586
+ `;
1587
+
1588
+ // src/styles.ts
1589
+ var STYLES = styles_default;
1590
+ var STYLE_ID = "music-notation-styles";
1591
+ function injectStyles(doc) {
1592
+ if (doc.getElementById(STYLE_ID))
1593
+ return;
1594
+ const style = doc.createElement("style");
1595
+ style.id = STYLE_ID;
1596
+ style.textContent = STYLES;
1597
+ doc.head.appendChild(style);
1598
+ }
1
1599
  export {
2
1600
  FLAT_NAMES,
3
1601
  LANGUAGES,
1602
+ MAX_DIAGRAMS,
4
1603
  SHARP_NAMES,
5
1604
  STANDARD_TUNING,
6
1605
  STYLES,
@@ -14,6 +1613,7 @@ export {
14
1613
  keyPrefersFlats,
15
1614
  keyRangeOf,
16
1615
  labelOf,
1616
+ layoutDefaults,
17
1617
  listNoteSet,
18
1618
  memberOf,
19
1619
  midiOf,
@@ -23,8 +1623,10 @@ export {
23
1623
  parseChordPro,
24
1624
  parseFingers,
25
1625
  parseFrets,
1626
+ parseHand,
26
1627
  parseKeyRange,
27
1628
  parseLyrics,
1629
+ parseOrientation,
28
1630
  parseTuning,
29
1631
  renderBlock,
30
1632
  renderChart,
@@ -36,5 +1638,5 @@ export {
36
1638
  transposeKey
37
1639
  };
38
1640
 
39
- //# debugId=95429F22282564C864756E2164756E21
1641
+ //# debugId=30E7F9B963C1BF2964756E2164756E21
40
1642
  //# sourceMappingURL=index.js.map