@dsebastien/music-notation 0.14.0 → 0.16.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/tab/index.js CHANGED
@@ -1,99 +1,3 @@
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 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;
33
- }
34
- function svgLine(doc, [x1, y1], [x2, y2], cls) {
35
- return svg(doc, "line", { class: cls, x1, y1, x2, y2 });
36
- }
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;
44
- }
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])]);
60
- }
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);
70
- };
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);
83
- }
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]);
95
- }
96
-
97
1
  // src/theory/pitch.ts
98
2
  var SHARP_NAMES = [
99
3
  "C",
@@ -141,1237 +45,1728 @@ function splitChordSymbol(symbol) {
141
45
  var noteOf = (midi, preferFlats = false) => `${nameOf(midi, preferFlats)}${Math.floor(midi / 12) - 1}`;
142
46
  var isFlat = (name) => /^[A-Ga-g][b♭]/.test(name.trim());
143
47
 
144
- // src/fretboard/tuning.ts
145
- var NAMED = new Map(Object.entries({
146
- standard: "E2 A2 D3 G3 B3 E4",
147
- "drop d": "D2 A2 D3 G3 B3 E4",
148
- "drop c": "C2 G2 C3 F3 A3 D4",
149
- "drop b": "B1 F#2 B2 E3 G#3 C#4",
150
- "drop a": "A1 E2 A2 D3 F#3 B3",
151
- "double drop d": "D2 A2 D3 G3 B3 D4",
152
- dadgad: "D2 A2 D3 G3 A3 D4",
153
- "open g": "D2 G2 D3 G3 B3 D4",
154
- "open d": "D2 A2 D3 F#3 A3 D4",
155
- "open e": "E2 B2 E3 G#3 B3 E4",
156
- "open c": "C2 G2 C3 G3 C4 E4",
157
- "open a": "E2 A2 E3 A3 C#4 E4",
158
- "half step down": "Eb2 Ab2 Db3 Gb3 Bb3 Eb4",
159
- "whole step down": "D2 G2 C3 F3 A3 D4",
160
- "modal c6": "C2 A2 C3 G3 C4 E4",
161
- c6: "C2 A2 C3 G3 C4 E4",
162
- bass: "E1 A1 D2 G2",
163
- ukulele: "G4 C4 E4 A4"
164
- }));
165
- function parseTuning(text) {
166
- const trimmed = text.trim();
167
- const named = NAMED.get(trimmed.toLowerCase().replace(/\s*\(.*\)$/, ""));
168
- if (named)
169
- return parseTuning(named);
170
- const spaced = trimmed.split(/[\s,]+/).filter(Boolean);
171
- if (spaced.length > 1 && spaced.every((t) => midiOf(t) !== null)) {
172
- return spaced.map((t) => midiOf(t));
173
- }
174
- const names = spaced.length > 1 ? spaced : trimmed.match(/[A-G][#♯b♭]?|[a-g][#♯♭]?/g) ?? [];
175
- if (names.length < 2 || names.join("") !== spaced.join(""))
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))
176
95
  return null;
177
- const midis = [];
178
- for (const name of names) {
179
- const chroma = chromaOf(name);
180
- if (chroma === null)
181
- return null;
182
- const previous = midis[midis.length - 1];
183
- if (previous === undefined) {
184
- const candidates = [28, 40, 52].map((c) => c - c % 12 + chroma);
185
- midis.push(candidates.reduce((a, b) => Math.abs(b - 40) < Math.abs(a - 40) ? b : a));
186
- } else {
187
- let midi = previous - previous % 12 + chroma;
188
- while (midi <= previous)
189
- midi += 12;
190
- midis.push(midi);
191
- }
192
- }
193
- return midis;
96
+ return suffix.replace(/[(),\s]/g, "");
194
97
  }
195
- function tuningNames(text) {
196
- const trimmed = text.trim();
197
- const named = NAMED.get(trimmed.toLowerCase().replace(/\s*\(.*\)$/, ""));
198
- if (named)
199
- return tuningNames(named);
200
- if (!parseTuning(trimmed))
201
- return null;
202
- const spaced = trimmed.split(/[\s,]+/).filter(Boolean);
203
- const names = spaced.length > 1 ? spaced : trimmed.match(/[A-G][#♯b♭]?|[a-g][#♯♭]?/g) ?? [];
204
- return names.map((n) => {
205
- const letter = n.charAt(0).toUpperCase();
206
- const accidental = n.slice(1).replace(/-?\d+$/, "").replace("♯", "#").replace("♭", "b");
207
- return letter + accidental;
208
- });
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;
209
106
  }
210
107
 
211
- // src/convert/text-tab.ts
212
- var STRING_PREFIX = /^\s*([A-Ga-g][#b]?|[1-8](?=\s*[|:]))?\s*[|:]?/;
213
- var STRING_BODY = /^[-0-9xX|:hpbrsvt/\\~^().*<>\s]*$/;
214
- var DRUM_LINE = /^\s*([A-Za-z][A-Za-z0-9. -]{0,14}?)\s*[|:]([-xXoOgfdb#@*+|:\s]*)$/;
215
- var DRUM_NAMES = new Map(Object.entries({
216
- hihat: "h hh hat hihat hihats",
217
- "hihat-open": "oh openhat openhihat",
218
- "hihat-foot": "hf fh hp ph pedal hihatfoot hihatpedal",
219
- crash: "c c1 cc cr cy cym crash crash1 cymbal",
220
- crash2: "c2 cr2 crash2",
221
- ride: "r rd rc ride",
222
- splash: "sp spl splash",
223
- china: "ch cn chi china",
224
- cowbell: "cb cow cowbell",
225
- snare: "s sd sn sr snare snaredrum",
226
- tom1: "t t1 ht tom1 hightom hitom",
227
- tom2: "t2 mt tom2 midtom",
228
- tom3: "t3 lt tom3 lowtom",
229
- floor: "f ft fl t4 tom4 floor floortom",
230
- kick: "b bd bs k kd bass kick bassdrum kickdrum"
231
- }).flatMap(([drum, list]) => list.split(" ").map((name) => [name, drum])));
232
- function articulationOf(drum, hit) {
233
- const choke = hit === "#";
234
- switch (drum) {
235
- case "hihat":
236
- return hit === "o" || hit === "O" ? "HiHatOpen" : "HiHatClosed";
237
- case "hihat-open":
238
- return "HiHatOpen";
239
- case "hihat-foot":
240
- return "PedalHiHatHit";
241
- case "crash":
242
- return choke ? "CrashHighChoke" : "CrashHighHit";
243
- case "crash2":
244
- return choke ? "CrashMediumChoke" : "CrashMediumHit";
245
- case "ride":
246
- return choke ? "RideChoke" : "RideMiddle";
247
- case "splash":
248
- return choke ? "SplashChoke" : "SplashHit";
249
- case "china":
250
- return choke ? "ChinaChoke" : "ChinaHit";
251
- case "cowbell":
252
- return "CowbellMediumHit";
253
- case "snare":
254
- return "SnareHit";
255
- case "tom1":
256
- return "HighTomHit";
257
- case "tom2":
258
- return "MidTomHit";
259
- case "tom3":
260
- return "LowTomHit";
261
- case "floor":
262
- return "VeryLowTomHit";
263
- case "kick":
264
- return "KickHit";
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;
123
+ }
124
+ var isScaleWithoutRoot = (text) => {
125
+ const scale = Scale.get(scaleName(text));
126
+ return !scale.empty && !scale.tonic;
127
+ };
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}`);
152
+ }
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 };
265
163
  }
164
+ return { notes: scale.notes, intervals: scale.intervals };
266
165
  }
267
- var effectOf = (hit) => hit === "X" || hit === "O" ? ["ac"] : hit === "g" ? ["g"] : [];
268
- var NOT_TAB = /[^-0-9xXoOgfdbhprsvt/\\~^().*<>#@+|:\s]|<(?!\d)/;
269
- var COUNT = /^\s*(?:[xX]\s*\d{1,3}|\d{1,3}\s*[xX])\s*$/;
270
- function splitText(line) {
271
- const last = line.lastIndexOf("|");
272
- if (last < 0)
273
- return { line, text: null };
274
- const rest = line.slice(last + 1);
275
- const text = rest.trim();
276
- if (!text)
277
- return { line, text: null };
278
- const isText = NOT_TAB.test(text) || COUNT.test(text) || /^\s/.test(rest) && !text.includes("--");
279
- return isText ? { line: line.slice(0, last + 1), text } : { line, text: null };
166
+ var scaleTypes = () => Scale.names();
167
+
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(" ")}` : "";
280
180
  }
281
- function tabLineOf(raw) {
282
- const { line, text } = splitText(raw.trimEnd());
283
- let string = null;
284
- const m = STRING_PREFIX.exec(line);
285
- const body = line.slice(m[0].length);
286
- if (STRING_BODY.test(body) && (line.match(/-/g)?.length ?? 0) >= 4 && (line.includes("|") || /^\s*[A-Ga-g][#b]?\s*[-|:]/.test(line)))
287
- string = { name: m[1] ?? null, body, offset: m[0].length, barred: /[|:]$/.test(m[0]) };
288
- let drum = null;
289
- const d = DRUM_LINE.exec(line);
290
- const name = d ? d[1].toLowerCase().replace(/[ .-]/g, "") : "";
291
- const known = DRUM_NAMES.get(name);
292
- if (d && known && (d[2].match(/[^\s|:]/g)?.length ?? 0) >= 4)
293
- drum = { drum: known, name, body: d[2], lettered: /^[A-Ga-g]$/.test(d[1]) };
294
- return string || drum ? { string, drum, text } : null;
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(" ")}` : "");
295
187
  }
296
- var textsOf = (run) => [
297
- ...new Set(run.map((l) => l.text).filter((t) => t !== null))
298
- ];
299
- function splitStrings(run) {
300
- const out = [];
301
- let start = 0;
302
- for (let i = 2;i < run.length - 1; i++) {
303
- const [a, b] = [run[start].string.name, run[start + 1].string.name];
304
- if (a !== null && run[i].string.name === a && run[i + 1].string.name === b && i - start >= 2) {
305
- out.push(run.slice(start, i));
306
- start = i;
307
- }
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}`;
205
+ }
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;
308
218
  }
309
- out.push(run.slice(start));
310
- return out;
311
219
  }
312
- function splitDrums(run) {
313
- const out = [];
314
- let current = [];
315
- for (const line of run) {
316
- if (current.some((l) => l.drum.name === line.drum.name)) {
317
- out.push(current);
318
- current = [];
319
- }
320
- current.push(line);
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))
225
+ return;
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
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 });
321
255
  }
322
- out.push(current);
323
- return out;
256
+ return set;
324
257
  }
325
- var PM_LINE = /^[\sPpMm.\-_|=~]*$/;
326
- var PM_MARK = /P\.?M/i;
327
- function palmMutesOf(line) {
328
- if (!PM_LINE.test(line) || !PM_MARK.test(line))
329
- return [];
330
- const ranges = [];
331
- for (let i = 0;i < line.length; i++) {
332
- const c = line[i];
333
- const mark = (c === "P" || c === "p") && /^\.?[Mm]/.test(line.slice(i + 1, i + 3));
334
- if (mark)
335
- ranges.push([i, i]);
336
- else if (c !== " " && ranges.length)
337
- ranges[ranges.length - 1][1] = i;
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;
338
264
  }
339
- return ranges;
340
265
  }
341
- function stringSystems(run, above = null) {
342
- return splitStrings(run).flatMap((part, index) => {
343
- const names = part.map((l) => l.string.name);
344
- if (part.length < 3 && names.some((n) => n === null))
345
- return [];
346
- const lines = part.map((l) => l.string.body);
347
- const offset = part[0].string.offset;
348
- const muted = new Set;
349
- if (index === 0 && above !== null)
350
- for (const [a, b] of palmMutesOf(above))
351
- for (let col = Math.max(a, offset);col <= b; col++)
352
- muted.add(col - offset);
353
- const openStart = part.some((l) => !l.string.barred);
354
- return [{ kind: "strings", names, lines, texts: textsOf(part), muted, openStart }];
355
- });
266
+ function scaleNoteSet(name) {
267
+ const scale = Scale2.get(scaleName(name));
268
+ if (scale.empty || !scale.tonic)
269
+ return null;
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;
356
275
  }
357
- function systemsOfRun(run, above) {
358
- if (!run.length)
359
- return [];
360
- if (run.every((l) => l.drum) && run.some((l) => !l.string || !l.drum.lettered || /[xXoOgfdb#@*+]/.test(l.drum.body)))
361
- return splitDrums(run).map((part) => ({
362
- kind: "drums",
363
- drums: part.map((l) => l.drum.drum),
364
- lines: part.map((l) => l.drum.body),
365
- texts: textsOf(part)
366
- }));
367
- if (run.every((l) => l.string))
368
- return stringSystems(run, above);
369
- const out = [];
370
- let stretch = [];
371
- for (const l of [...run, null]) {
372
- if (l?.string)
373
- stretch.push(l);
374
- else {
375
- if (stretch.length)
376
- out.push(...stringSystems(stretch, out.length ? null : above));
377
- stretch = [];
276
+ function rootNameOf(text) {
277
+ const name = text.trim().replace(/-?\d$/, "").replace(/♯/g, "#").replace(/♭/g, "b");
278
+ if (chromaOf(name) === null)
279
+ return 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)
287
+ return null;
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];
294
+ }
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;
323
+ }
324
+
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
+ }
378
372
  }
373
+ if (quality)
374
+ break;
379
375
  }
380
- return out;
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
+ };
381
389
  }
382
- function systemsOf(text) {
383
- const systems = [];
384
- let run = [];
385
- let above = null;
386
- let previous = null;
387
- for (const raw of text.split(/\r?\n/)) {
388
- const line = tabLineOf(raw);
389
- if (line) {
390
- if (!run.length)
391
- above = previous;
392
- run.push(line);
393
- } else {
394
- systems.push(...systemsOfRun(run, above));
395
- run = [];
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);
401
+ }
402
+ function namingOf(value) {
403
+ if (typeof value !== "string")
404
+ return null;
405
+ try {
406
+ return parseNaming(value);
407
+ } catch {
408
+ return null;
409
+ }
410
+ }
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 reads = (letters) => midiOf(letters) !== null || /^[A-G]/.test(letters) && parseChord(letters) !== null;
426
+ function rootToken(token, naming, h, solfegeLine = false) {
427
+ const b = naming === "german" ? /^B(?![#♯b♭x])(.*)$/.exec(token) : null;
428
+ if (b && AFTER_ROOT.test(b[1])) {
429
+ const letters = `Bb${b[1]}`;
430
+ if (reads(letters))
431
+ return letters;
432
+ }
433
+ if (naming !== "solfege" && !solfegeLine && reads(token))
434
+ return null;
435
+ const solfege = new RegExp(`^${SYLLABLE}${SIGN}(.*)$`).exec(token);
436
+ if (solfege) {
437
+ for (const sign of [solfege[2] ?? "", ""].filter((s, i, all) => all.indexOf(s) === i)) {
438
+ const rest = token.slice(solfege[1].length + sign.length);
439
+ const letters = `${syllableLetter(solfege[1])}${sign}${rest}`;
440
+ if (AFTER_ROOT.test(rest) && reads(letters))
441
+ return letters;
396
442
  }
397
- previous = raw;
398
443
  }
399
- systems.push(...systemsOfRun(run, above));
400
- return systems;
444
+ if (h) {
445
+ const hm = /^H(##|bb|#|b|♯|♭|x)?(.*)$/.exec(token);
446
+ if (hm && AFTER_ROOT.test(hm[2])) {
447
+ const letters = `B${hm[1] ?? ""}${hm[2]}`;
448
+ if (reads(letters))
449
+ return letters;
450
+ }
451
+ }
452
+ return null;
401
453
  }
402
- function barsOf(lines, beatAt) {
403
- const width = Math.max(...lines.map((l) => l.length));
404
- const padded = lines.map((l) => l.padEnd(width, "-"));
405
- const bars = [];
406
- let beats = [];
407
- let filled = false;
408
- let start = 0;
409
- for (let col = 0;col < width; col++) {
410
- if (padded.every((l) => l[col] === "|" || l[col] === ":")) {
411
- if (filled)
412
- bars.push({ beats, start, end: col });
413
- beats = [];
414
- filled = false;
415
- start = col + 1;
416
- continue;
454
+ var NOTE_ONLY = /^[A-G](?:##|bb|#|b|♯|♭|x)?$/;
455
+ function letterPiece(piece, naming, h, line = false) {
456
+ if (!piece)
457
+ return piece;
458
+ const lower = plain2(piece);
459
+ if (/^majeure?$/.test(lower))
460
+ return "major";
461
+ if (/^mineure?$/.test(lower))
462
+ return "minor";
463
+ const range = /^(.+\d)-(.+\d)$/.exec(piece);
464
+ if (range) {
465
+ const [from, to] = [range[1], range[2]].map((n) => rootToken(n, naming, h, line) ?? n);
466
+ return `${from}-${to}`;
467
+ }
468
+ const slash = piece.indexOf("/");
469
+ if (slash > 0) {
470
+ const head = piece.slice(0, slash);
471
+ const bass = piece.slice(slash + 1);
472
+ const bassLetters = rootToken(bass, naming, h, line) ?? (NOTE_ONLY.test(bass) ? bass : null);
473
+ if (bassLetters && NOTE_ONLY.test(bassLetters)) {
474
+ const headLetters = rootToken(head, naming, h, line) ?? head;
475
+ const whole = `${headLetters}/${bassLetters}`;
476
+ if (whole !== piece && !(naming === "letters" && !line && reads(piece)))
477
+ return whole;
478
+ return piece;
417
479
  }
418
- if (padded.some((l) => l[col] !== " "))
419
- filled = true;
420
- const { beat, skip, at } = beatAt(padded, col);
421
- if (beat.length)
422
- beats.push({ notes: beat, col: at ?? col });
423
- col += skip;
424
480
  }
425
- if (filled)
426
- bars.push({ beats, start, end: width });
427
- return bars;
481
+ return rootToken(piece, naming, h, line) ?? piece;
428
482
  }
429
- var isDigit = (c) => c !== undefined && c >= "0" && c <= "9";
430
- var twoDigits = (a, b) => (a === "1" || a === "2") && isDigit(b) && Number(a + b) <= 24;
431
- function techniquesOf(body) {
432
- const frets = new Map;
433
- const effects = new Map;
434
- const hidden = new Set;
435
- const target = (at) => {
436
- let j = at;
437
- const open = body[j] === "(";
438
- if (open)
439
- j++;
440
- if (!isDigit(body[j]))
441
- return { fret: null, next: at };
442
- const width = twoDigits(body[j], body[j + 1]) ? 2 : 1;
443
- const fret = Number(body.slice(j, j + width));
444
- for (let w = 0;w < width; w++)
445
- hidden.add(j + w);
446
- j += width;
447
- if (open && body[j] === ")")
448
- j++;
449
- return { fret, next: j };
450
- };
451
- for (let i = 0;i < body.length; ) {
452
- if (!isDigit(body[i]) || hidden.has(i)) {
453
- i++;
483
+ function letterWord(word, naming, h, changes, line = false) {
484
+ const out = word.split(/([,|;])/).map((piece, i) => i % 2 ? piece : letterPiece(piece, naming, h, line)).join("");
485
+ if (out !== word)
486
+ changes.push([word, out]);
487
+ return out;
488
+ }
489
+ var syllableOnly = (word) => new RegExp(`^${SYLLABLE}${SIGN}$`).test(word);
490
+ function read(text, naming, options, changes) {
491
+ const h = options.h ?? true;
492
+ 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"}`);
493
+ if (options.chord) {
494
+ const joined = new RegExp(`^\\s*${SYLLABLE}${SIGN}\\s+(\\S+)\\s*$`).exec(out);
495
+ if (joined && QUALITY_WORD.test(joined[3])) {
496
+ const word = `${joined[1]}${joined[2] ?? ""}${joined[3]}`;
497
+ const letters = rootToken(word, naming, h) ?? letterPiece(word, naming, h);
498
+ if (letters !== word) {
499
+ changes.push([out.trim(), letters]);
500
+ return letters;
501
+ }
502
+ }
503
+ }
504
+ const words = out.split(/(\s+)/);
505
+ for (let i = 0;i + 2 < words.length; i += 2) {
506
+ const head = words[i];
507
+ const next = words[i + 2];
508
+ if (!syllableOnly(head) || !QUALITY_WORD.test(next))
454
509
  continue;
510
+ if (naming !== "solfege" && reads(head))
511
+ continue;
512
+ const joined = `${head}${next}`;
513
+ const letters = letterPiece(joined, naming, h);
514
+ if (letters !== joined) {
515
+ words.splice(i, 3, joined);
516
+ i -= 2;
455
517
  }
456
- const width = twoDigits(body[i], body[i + 1]) ? 2 : 1;
457
- const fret = Number(body.slice(i, i + width));
458
- frets.set(i, { fret, width });
459
- const fx = [];
460
- const before = body[i - 1];
461
- let k = i + width;
462
- if (before === "<" && body[k] === ">") {
463
- fx.push("nh");
464
- k++;
465
- } else if ((before === "/" || before === "\\") && !/[\d)>]/.test(body[i - 2] ?? "-"))
466
- fx.push(before === "/" ? "sib" : "sia");
467
- if (body[k] === "b" || body[k] === "^") {
468
- const up = target(k + 1);
469
- k = up.next;
470
- const semitones = up.fret !== null && up.fret > fret ? Math.min(up.fret - fret, 4) : 2;
471
- const points = [0, semitones * 2];
472
- if (body[k] === "r") {
473
- const down = target(k + 1);
474
- k = down.next;
475
- const back = down.fret === null ? 0 : (down.fret - fret) * 2;
476
- points.push(Math.min(points[1], Math.max(0, back)));
477
- }
478
- fx.push(`b (${points.join(" ")})`);
518
+ }
519
+ out = words.join("");
520
+ const line = out.split(/[\s,|;]+/).some((w) => w !== "" && !/^Do/.test(w) && !reads(w) && rootToken(w, "solfege", false) !== null);
521
+ return out.replace(/\S+/g, (word) => letterWord(word, naming, h, changes, line));
522
+ }
523
+ function toLetters(text, naming = "letters", options = {}) {
524
+ return read(text, naming, options, []);
525
+ }
526
+ var NOTE_KEYS = new Set([
527
+ "chord",
528
+ "chords",
529
+ "symbol",
530
+ "name",
531
+ "from",
532
+ "to",
533
+ "scale",
534
+ "notes",
535
+ "root",
536
+ "key",
537
+ "arpeggio",
538
+ "compare",
539
+ "scales-for",
540
+ "scales-for-notes",
541
+ "modes",
542
+ "progression",
543
+ "tuning",
544
+ "range",
545
+ "highlight",
546
+ "pitches",
547
+ "sounds",
548
+ "mode"
549
+ ]);
550
+ var SINGLE_CHORD_KEYS = new Set(["chord", "symbol", "from", "to", "sounds"]);
551
+ var KEY_LINE = /^(\s*)([A-Za-z][A-Za-z-]*)(\s*:\s*)(.*)$/;
552
+ var NAMING_LINE = /^\s*naming\s*:\s*(.*)$/i;
553
+ var NAMING_DIRECTIVE = /^\s*\{\s*naming\s*:\s*([^}]*)\}\s*$/i;
554
+ var DIAGRAM_SHORTHAND = new Set(["chord", "keyboard", "fretboard", "circle"]);
555
+ function spacedTuning(value, naming) {
556
+ const compact = /^\s*((?:[A-Ha-h](?:#|b|♯|♭)?){4,})\s*$/.exec(value);
557
+ if (!compact || naming !== "german" && !/h/i.test(compact[1]))
558
+ return value;
559
+ return compact[1].match(/[A-Ha-h](?:#|b|♯|♭)?/g).map((n) => n[0].toUpperCase() + n.slice(1)).join(" ");
560
+ }
561
+ function lettersInBlock(language, text) {
562
+ const result = { text, naming: null, changes: [], titles: [], warning: null };
563
+ if (language === "tab" || language === "score")
564
+ return result;
565
+ const lines = [];
566
+ for (const line of text.split(`
567
+ `)) {
568
+ const own = (language === "chords" ? NAMING_DIRECTIVE : NAMING_LINE).exec(line);
569
+ if (!own) {
570
+ lines.push(line);
571
+ continue;
479
572
  }
480
- if (body[k] === "~" || body[k] === "v") {
481
- fx.push("v");
482
- while (body[k] === "~" || body[k] === "v")
483
- k++;
573
+ if (language !== "chords")
574
+ result.naming = parseNaming(own[1]);
575
+ else {
576
+ const naming = namingOf(own[1]);
577
+ if (naming)
578
+ result.naming = naming;
579
+ else
580
+ result.warning = DIRECTIVE_ERROR;
484
581
  }
485
- const next = body[k];
486
- const onto = isDigit(body[k + 1]) || body[k + 1] === "(" && isDigit(body[k + 2]);
487
- if ((next === "h" || next === "p") && onto)
488
- fx.push("h");
489
- else if (next === "/" || next === "\\" || next === "s") {
490
- if (onto)
491
- fx.push("sl");
492
- else if (next !== "s")
493
- fx.push(next === "/" ? "sou" : "sod");
582
+ }
583
+ const naming = result.naming ?? "letters";
584
+ const named = result.naming !== null;
585
+ const changes = result.changes;
586
+ if (language === "chords") {
587
+ if (!named) {
588
+ result.text = lines.join(`
589
+ `);
590
+ return result;
494
591
  }
495
- if (fx.length)
496
- effects.set(i, fx);
497
- i += width;
592
+ result.text = lines.map((line) => line.replace(/\[([^\]]+)\]/g, (whole, inside) => {
593
+ const letters = read(inside, naming, { chord: true }, changes);
594
+ return letters === inside ? whole : `[${letters}]`;
595
+ }).replace(/^(\s*\{\s*(?:key|define|chord)\s*:\s*)([^}]*?)(\s*\}\s*)$/i, (_, head, value, tail) => {
596
+ if (/^\s*\{\s*key/i.test(head))
597
+ return `${head}${read(value, naming, {}, changes)}${tail}`;
598
+ const [name, ...rest] = value.split(/(\s+)/);
599
+ return `${head}${read(name, naming, { chord: true }, changes)}${rest.join("")}${tail}`;
600
+ })).join(`
601
+ `);
602
+ return result;
498
603
  }
499
- return { frets, effects };
500
- }
501
- var stringBeatAt = (lines, muted, numbers = []) => (padded, col) => {
502
- const beat = [];
503
- const strings = new Set;
504
- let start = col;
505
- let wide = false;
506
- const read = (i, at) => {
507
- const c = padded[i][at];
508
- const pm = muted.has(at) ? ["pm"] : [];
509
- if (c === "x" || c === "X") {
510
- beat.push({ tex: `x.${numbers[i] ?? i + 1}`, effects: pm });
511
- strings.add(i);
512
- return;
604
+ const shorthand = DIAGRAM_SHORTHAND.has(language);
605
+ result.text = lines.map((line) => {
606
+ if (/^\s*-{3,}\s*$/.test(line) || !line.trim())
607
+ return line;
608
+ const kv = KEY_LINE.exec(line);
609
+ if (kv) {
610
+ const key = kv[2].toLowerCase();
611
+ if (key === "title") {
612
+ result.titles.push(kv[4].trim());
613
+ return line;
614
+ }
615
+ if (!NOTE_KEYS.has(key))
616
+ return line;
617
+ if (key === "name")
618
+ result.titles.push(kv[4].trim());
619
+ const value = key === "tuning" ? spacedTuning(kv[4], naming) : kv[4];
620
+ const letters = read(value, naming, { chord: SINGLE_CHORD_KEYS.has(key) }, changes);
621
+ if (letters !== kv[4])
622
+ changes.push([kv[4].trim(), letters.trim()]);
623
+ return `${kv[1]}${kv[2]}${kv[3]}${letters}`;
513
624
  }
514
- const note = lines[i].frets.get(at);
515
- if (!note)
516
- return;
517
- if (note.width === 2 && at === col)
518
- wide = true;
519
- if (padded[i][at - 1] === "<")
520
- start = Math.min(start, at - 1);
521
- beat.push({
522
- tex: `${note.fret}.${numbers[i] ?? i + 1}`,
523
- effects: [...lines[i].effects.get(at) ?? [], ...pm],
524
- string: numbers[i] ?? i + 1
525
- });
526
- strings.add(i);
527
- };
528
- padded.forEach((_, i) => read(i, col));
529
- if (wide)
530
- padded.forEach((_, i) => strings.has(i) || read(i, col + 1));
531
- return { beat, skip: wide ? 1 : 0, at: start };
625
+ if (shorthand)
626
+ return read(line, naming, { chord: language === "chord", h: named }, changes);
627
+ if (language === "progression")
628
+ return read(line, naming, { h: named }, changes);
629
+ if (language === "strum" || language === "picking")
630
+ return line.replace(/\[([^\]]+)\]/g, (whole, inside) => {
631
+ const letters = read(inside, naming, { chord: true, h: named }, changes);
632
+ return letters === inside ? whole : `[${letters}]`;
633
+ });
634
+ return line;
635
+ }).join(`
636
+ `);
637
+ return result;
638
+ }
639
+ function quoteAsWritten(message, changes) {
640
+ let out = message;
641
+ for (const [written, letters] of [...changes].sort((a, b) => b[1].length - a[1].length)) {
642
+ if (written !== letters)
643
+ out = out.split(`"${letters}"`).join(`"${written}"`);
644
+ }
645
+ return out;
646
+ }
647
+ var LETTER_SYLLABLE = {
648
+ C: "Do",
649
+ D: "Ré",
650
+ E: "Mi",
651
+ F: "Fa",
652
+ G: "Sol",
653
+ A: "La",
654
+ B: "Si"
532
655
  };
533
- var BY_COUNT = {
534
- 3: [64, 59, 55],
535
- 4: [43, 38, 33, 28],
536
- 5: [43, 38, 33, 28, 23],
537
- 6: [64, 59, 55, 50, 45, 40],
538
- 7: [64, 59, 55, 50, 45, 40, 35]
656
+ var SOLFEGE_SIGNS = {
657
+ "#": "♯",
658
+ "♯": "♯",
659
+ b: "♭",
660
+ "♭": "♭",
661
+ "##": "♯♯",
662
+ x: "♯♯",
663
+ bb: "♭♭",
664
+ "♭♭": "♭♭",
665
+ "♯♯": "♯♯"
539
666
  };
540
- var BY_NUMBER = [64, 59, 55, 50, 45, 40, 35, 30];
541
- var GUITAR = { names: ["E", "A", "D", "G", "B", "E"], midis: [40, 45, 50, 55, 59, 64] };
542
- var BASS = ["E A D G", "B E A D G"];
543
- var upper = (name) => name[0].toUpperCase() + name.slice(1);
544
- function tuningOf(names) {
545
- const strings = names.length;
546
- if (names.every((n) => n !== null && /^\d$/.test(n)))
547
- return names.every((n) => BY_NUMBER[Number(n) - 1]) ? names.map((n) => BY_NUMBER[Number(n) - 1]) : null;
548
- if (names.every((n) => n !== null && /^[A-Ga-g]/.test(n))) {
549
- const lowFirst = [...names].reverse();
550
- const spelled = lowFirst.map(upper).join(" ");
551
- if (BASS.includes(spelled))
552
- return parseTuning(spelled).map((m) => m - 12).reverse();
553
- const starts = [...GUITAR.names.keys()].filter((start) => lowFirst.every((n, i) => GUITAR.names[start + i] === upper(n)));
554
- if (starts.length) {
555
- const start = starts.length > 1 && lowFirst[0] === "e" ? starts.at(-1) : starts[0];
556
- return GUITAR.midis.slice(start, start + strings).reverse();
667
+ var ROOT = /^([A-G])(##|bb|♯♯|♭♭|#|b|♯|♭|x)?/;
668
+ function noteInNaming(name, naming) {
669
+ if (naming === "letters")
670
+ return name;
671
+ const m = /^([A-G])(##|bb|♯♯|♭♭|#|b|♯|♭|x)?$/.exec(name.trim());
672
+ if (!m)
673
+ return name;
674
+ const [, letter, sign = ""] = m;
675
+ if (naming === "solfege")
676
+ return `${LETTER_SYLLABLE[letter]}${SOLFEGE_SIGNS[sign] ?? ""}`;
677
+ if (letter !== "B")
678
+ return name.trim();
679
+ return sign === "b" || sign === "♭" ? "B" : `H${sign}`;
680
+ }
681
+ function chordInNaming(symbol, naming) {
682
+ if (naming === "letters")
683
+ return symbol;
684
+ const text = symbol.trim();
685
+ const root = ROOT.exec(text);
686
+ if (!root || !parseChord(text))
687
+ return symbol;
688
+ const rest = text.slice(root[0].length);
689
+ const slash = /^(.*)\/([A-G](?:##|bb|♯♯|♭♭|#|b|♯|♭|x)?)$/.exec(rest);
690
+ const suffix = slash ? slash[1] : rest;
691
+ const bass = slash ? `/${noteInNaming(slash[2], naming)}` : "";
692
+ const shownSuffix = naming === "solfege" && suffix ? ` ${suffix}` : suffix;
693
+ return `${noteInNaming(root[0], naming)}${shownSuffix}${bass}`;
694
+ }
695
+ var AFTER_A_NOTE = new Set([
696
+ "major",
697
+ "minor",
698
+ "pentatonic",
699
+ "blues",
700
+ "dorian",
701
+ "phrygian",
702
+ "lydian",
703
+ "mixolydian",
704
+ "aeolian",
705
+ "ionian",
706
+ "locrian",
707
+ "harmonic",
708
+ "melodic",
709
+ "chromatic",
710
+ "whole",
711
+ "augmented",
712
+ "diminished",
713
+ "bebop",
714
+ "arpeggio",
715
+ "chord",
716
+ "string",
717
+ "position",
718
+ "box",
719
+ "scale",
720
+ "mode"
721
+ ]);
722
+ var OCTAVE = /^([A-G](?:##|bb|#|b|♯|♭|x)?)(-?\d)$/;
723
+ function shownText(text, naming) {
724
+ if (naming === "letters" || !text)
725
+ return text;
726
+ const parts = text.split(/(\s+|[,;:()])/);
727
+ const word = (i, step) => {
728
+ for (let j = i + step;j >= 0 && j < parts.length; j += step) {
729
+ const p = parts[j];
730
+ if (!p.trim())
731
+ continue;
732
+ return /^[,;:()]$/.test(p) ? null : p;
557
733
  }
558
- if (strings === 1) {
559
- const chroma = chromaOf(upper(names[0]));
560
- return chroma === null ? null : [48 + (chroma - 48 + 120) % 12];
734
+ return null;
735
+ };
736
+ return parts.map((part, i) => {
737
+ if (!/^[A-G]/.test(part))
738
+ return part;
739
+ const next = word(i, 1);
740
+ if (next === "shape")
741
+ return part;
742
+ const octave = OCTAVE.exec(part);
743
+ if (octave) {
744
+ const amongNotes = [word(i, -1), next].some((w) => w !== null && OCTAVE.test(w));
745
+ if (amongNotes || !/^[5679]$/.test(octave[2]))
746
+ return `${noteInNaming(octave[1], naming)}${octave[2]}`;
561
747
  }
562
- const tuning = parseTuning(spelled);
563
- if (tuning)
564
- return tuning.reverse();
748
+ if (part === "A" && next && /^[a-z]/.test(next) && !AFTER_A_NOTE.has(next))
749
+ return part;
750
+ if (parseChord(part))
751
+ return chordInNaming(part, naming);
752
+ const both = part.split("/");
753
+ if (both.length === 2 && both.every((p) => /^[A-G]/.test(p) && parseChord(p)))
754
+ return both.map((p) => chordInNaming(p, naming)).join("/");
755
+ return part;
756
+ }).join("");
757
+ }
758
+ var current = "letters";
759
+ var verbatim = [];
760
+ function withNaming(naming, draw, titles = []) {
761
+ const before = [current, verbatim];
762
+ current = naming;
763
+ verbatim = titles.filter(Boolean);
764
+ try {
765
+ return draw();
766
+ } finally {
767
+ [current, verbatim] = before;
565
768
  }
566
- return BY_COUNT[strings] ?? null;
567
769
  }
568
- function onGuitar(midi) {
569
- const tuning = [...BY_COUNT[6]];
570
- let index = tuning.indexOf(midi);
571
- if (index < 0) {
572
- index = tuning.reduce((best, m, i) => Math.abs(m - midi) < Math.abs(tuning[best] - midi) ? i : best, 0);
573
- tuning[index] = midi;
770
+ function shown(text) {
771
+ if (current === "letters" || !text)
772
+ return text;
773
+ for (const title of verbatim) {
774
+ if (text === title)
775
+ return text;
776
+ if (text.startsWith(`${title},`))
777
+ return title + shownText(text.slice(title.length), current);
574
778
  }
575
- return { tuning, string: index + 1 };
779
+ return shownText(text, current);
576
780
  }
577
- function placedOnGuitar(tuning) {
578
- if (tuning.length === 1) {
579
- const { tuning: six, string } = onGuitar(tuning[0]);
580
- return { tuning: six, strings: [string] };
781
+
782
+ // src/render/dom.ts
783
+ var SVG_NS = "http://www.w3.org/2000/svg";
784
+ var apply = (el, attrs) => {
785
+ for (const [name, value] of Object.entries(attrs)) {
786
+ if (value !== undefined)
787
+ el.setAttribute(name, String(value));
581
788
  }
582
- const standard = BY_COUNT[6];
583
- if (tuning.length > 5)
584
- return null;
585
- const at = tuning.map((m) => standard.indexOf(m));
586
- if (at[0] < 0 || at.some((i, k) => i !== at[0] + k))
587
- return null;
588
- return { tuning: [...standard], strings: at.map((i) => i + 1) };
589
- }
590
- var drumBeatAt = (drums) => (padded, col) => {
591
- const beat = [];
592
- padded.forEach((line, i) => {
593
- const hit = line[col];
594
- if (!/[xXoOgfdb#@*+]/.test(hit))
595
- return;
596
- const name = articulationOf(drums[i], hit);
597
- if (!beat.some((n) => n.tex === name))
598
- beat.push({ tex: name, effects: effectOf(hit) });
599
- });
600
- return { beat, skip: 0 };
601
789
  };
602
- var VALUES = [
603
- [24, 1, true],
604
- [16, 1, false],
605
- [12, 2, true],
606
- [8, 2, false],
607
- [6, 4, true],
608
- [4, 4, false],
609
- [3, 8, true],
610
- [2, 8, false],
611
- [1, 16, false]
612
- ];
613
- function valuesOf(sixteenths) {
614
- const out = [];
615
- for (let left = sixteenths;left > 0; ) {
616
- const [length, duration, dotted] = VALUES.find(([n]) => n <= left);
617
- out.push({ duration, dotted });
618
- left -= length;
619
- }
620
- return out;
790
+ function svg(doc, tag, attrs = {}, children = []) {
791
+ const el = doc.createElementNS(SVG_NS, tag);
792
+ apply(el, attrs);
793
+ for (const child of children)
794
+ if (child)
795
+ el.appendChild(child);
796
+ return el;
621
797
  }
622
- var COMMON = { ts: [4, 4], length: 16, beat: 4, grids: [1, 2, 4, 8, 16] };
623
- var THREE_FOUR = { ts: [3, 4], length: 12, beat: 4, grids: [1, 3, 6, 12] };
624
- var SIX_EIGHT = { ts: [6, 8], length: 12, beat: 6, grids: [1, 2, 6, 12] };
625
- var TWELVE_EIGHT = { ts: [12, 8], length: 24, beat: 6, grids: [1, 2, 4, 12, 24] };
626
- function keepsSpacing(cols, at) {
627
- const lengths = new Map;
628
- for (let i = 1;i < cols.length; i++) {
629
- const gap = cols[i] - cols[i - 1];
630
- const length = at[i] - at[i - 1];
631
- if ((lengths.get(gap) ?? length) !== length)
632
- return false;
633
- lengths.set(gap, length);
634
- }
635
- const sorted = [...lengths].sort((a, b) => a[0] - b[0]);
636
- return sorted.every(([, length], i) => i === 0 || length >= sorted[i - 1][1]);
798
+ function svgText(doc, text, attrs = {}) {
799
+ const el = svg(doc, "text", attrs);
800
+ el.textContent = text;
801
+ return el;
637
802
  }
638
- var PLAIN = new Set(VALUES.map(([n]) => n));
639
- function fit(cols, n, [origin, span], slack, ties, bar) {
640
- const step = span / n;
641
- if (step < 1 || ties && !Number.isInteger(step))
642
- return null;
643
- const at = [];
644
- let error = 0;
645
- for (const col of cols) {
646
- const exact = (col - origin) / step;
647
- const k = Math.round(exact);
648
- const off = Math.abs(exact - k) * step;
649
- if (k < 0 || k >= n || off > slack + 0.000000001 || at.length && k * (bar / n) <= at.at(-1))
650
- return null;
651
- error = Math.max(error, off);
652
- at.push(k * (bar / n));
803
+ function svgLabel(doc, text, [x, y], cls, anchor = "middle") {
804
+ return svgText(doc, text, { class: cls, x, y: y + 4, "text-anchor": anchor });
805
+ }
806
+ function dotLabel(doc, text, point, r) {
807
+ const label = svgLabel(doc, shown(text), point, "mn-dot-text");
808
+ if ([...shown(text)].length >= 3) {
809
+ label.classList.add("mn-dot-text-long");
810
+ label.setAttribute("textLength", String(2 * r - 2));
811
+ label.setAttribute("lengthAdjust", "spacingAndGlyphs");
653
812
  }
654
- if (!ties && at.some((p, i) => !PLAIN.has((at[i + 1] ?? bar) - p)))
655
- return null;
656
- return keepsSpacing(cols, at) ? { at, error } : null;
813
+ return label;
657
814
  }
658
- function positionsOf(cols, width, pad, meter = COMMON) {
659
- if (!cols.length)
660
- return [];
661
- const spans = [
662
- [pad, width - pad],
663
- [pad, width]
664
- ];
665
- for (let start = 1;start < pad; start++)
666
- spans.push([start, width - start]);
667
- if (cols[0] > pad)
668
- spans.push([0, width]);
669
- for (const [slack, ties] of [
670
- [0.4, false],
671
- [1, false],
672
- [0.4, true]
673
- ])
674
- for (const n of meter.grids) {
675
- const fits = spans.map((span) => fit(cols, n, span, slack, ties, meter.length)).filter((f) => f !== null);
676
- if (fits.length)
677
- return fits.reduce((a, b) => b.error < a.error ? b : a).at;
678
- }
679
- return null;
815
+ function svgLine(doc, [x1, y1], [x2, y2], cls) {
816
+ return svg(doc, "line", { class: cls, x1, y1, x2, y2 });
680
817
  }
681
- function restsFrom(at, meter, end = meter.length) {
682
- const out = [];
683
- const { beat, length: bar } = meter;
684
- for (let p = at;p < end; ) {
685
- const half = bar === 4 * beat && p % (2 * beat) === 0 && p <= bar / 2 ? [2 * beat] : [];
686
- const lengths = p % 2 ? [1] : p % beat ? [2, 1] : [...half, beat, 2, 1];
687
- const length = lengths.find((n) => n <= end - p);
688
- out.push({ beat: -1, sixteenths: length });
689
- p += length;
818
+ function html(doc, tag, cls, text) {
819
+ const el = doc.createElement(tag);
820
+ if (cls)
821
+ el.className = cls;
822
+ if (text !== undefined)
823
+ el.textContent = text;
824
+ return el;
825
+ }
826
+ var NAME_PREFIX = `mn-name-${Math.random().toString(36).slice(2, 8)}-`;
827
+ var names = 0;
828
+ var uniqueId = () => `${NAME_PREFIX}${++names}`;
829
+ var SHOWN_NAMES = /\bmn-(guitar-chord|fretboard|keyboard|circle)\b/;
830
+ function svgRoot(doc, width, height, cls, label) {
831
+ const id = `${NAME_PREFIX}${++names}`;
832
+ const title = svg(doc, "title", { class: "mn-name", id });
833
+ title.textContent = SHOWN_NAMES.test(cls) ? shown(label) : label;
834
+ return svg(doc, "svg", {
835
+ xmlns: SVG_NS,
836
+ viewBox: `0 0 ${width} ${height}`,
837
+ width,
838
+ class: `mn-svg ${cls}`,
839
+ role: "img",
840
+ "aria-labelledby": id
841
+ }, [svg(doc, "defs", {}, [title])]);
842
+ }
843
+ var nameElement = (el) => {
844
+ const id = el.getAttribute("aria-labelledby");
845
+ if (!id)
846
+ return null;
847
+ for (const candidate of el.querySelectorAll("[id]")) {
848
+ if (candidate.getAttribute("id") === id)
849
+ return candidate;
690
850
  }
691
- return out;
851
+ return el.ownerDocument.getElementById(id);
852
+ };
853
+ function accessibleName(el) {
854
+ const named = nameElement(el);
855
+ if (named)
856
+ return named.textContent;
857
+ return el.getAttribute("aria-label");
692
858
  }
693
- function sketchRhythmOf(cols, meter = COMMON, legato = []) {
694
- const gaps = cols.slice(1).map((c, i) => c - cols[i]);
695
- const counts = new Map;
696
- for (const g of gaps)
697
- counts.set(g, (counts.get(g) ?? 0) + 1);
698
- const unit = [...counts].reduce((best, e) => !best || e[1] > best[1] || e[1] === best[1] && e[0] < best[0] ? e : best, null)?.[0];
699
- for (const eighth of [2, 1]) {
700
- const lengths = cols.map((_, i) => eighth * (i < gaps.length ? Math.max(1, Math.round(gaps[i] / unit)) : 1));
701
- let total = lengths.reduce((a, b) => a + b, 0);
702
- if (eighth === 2)
703
- for (const i of legato) {
704
- if (total <= meter.length)
705
- break;
706
- if (i + 1 >= lengths.length || lengths[i] !== 2)
707
- continue;
708
- const next = Math.max(1, lengths[i + 1] - 1);
709
- total -= 1 + lengths[i + 1] - next;
710
- lengths[i] = 1;
711
- lengths[i + 1] = next;
712
- }
713
- if (total > meter.length)
714
- continue;
715
- return [
716
- ...lengths.map((sixteenths, beat) => ({ beat, sixteenths })),
717
- ...restsFrom(total, meter)
718
- ];
859
+ function setAccessibleName(el, name) {
860
+ const named = nameElement(el);
861
+ if (named)
862
+ named.textContent = name;
863
+ else
864
+ el.setAttribute("aria-label", name);
865
+ }
866
+ function playableMark(doc, area, ...children) {
867
+ const hit = svg(doc, "rect", {
868
+ class: "mn-hit",
869
+ x: area.x,
870
+ y: area.y,
871
+ width: area.width,
872
+ height: area.height,
873
+ fill: "transparent",
874
+ "pointer-events": "all"
875
+ });
876
+ return svg(doc, "g", { class: "mn-mark" }, [hit, ...children]);
877
+ }
878
+
879
+ // src/fretboard/tuning.ts
880
+ var NAMED = new Map(Object.entries({
881
+ standard: "E2 A2 D3 G3 B3 E4",
882
+ "drop d": "D2 A2 D3 G3 B3 E4",
883
+ "drop c": "C2 G2 C3 F3 A3 D4",
884
+ "drop b": "B1 F#2 B2 E3 G#3 C#4",
885
+ "drop a": "A1 E2 A2 D3 F#3 B3",
886
+ "double drop d": "D2 A2 D3 G3 B3 D4",
887
+ dadgad: "D2 A2 D3 G3 A3 D4",
888
+ "open g": "D2 G2 D3 G3 B3 D4",
889
+ "open d": "D2 A2 D3 F#3 A3 D4",
890
+ "open e": "E2 B2 E3 G#3 B3 E4",
891
+ "open c": "C2 G2 C3 G3 C4 E4",
892
+ "open a": "E2 A2 E3 A3 C#4 E4",
893
+ "half step down": "Eb2 Ab2 Db3 Gb3 Bb3 Eb4",
894
+ "whole step down": "D2 G2 C3 F3 A3 D4",
895
+ "modal c6": "C2 A2 C3 G3 C4 E4",
896
+ c6: "C2 A2 C3 G3 C4 E4",
897
+ bass: "E1 A1 D2 G2",
898
+ ukulele: "G4 C4 E4 A4"
899
+ }));
900
+ function parseTuning(text) {
901
+ const trimmed = text.trim();
902
+ const named = NAMED.get(trimmed.toLowerCase().replace(/\s*\(.*\)$/, ""));
903
+ if (named)
904
+ return parseTuning(named);
905
+ const spaced = trimmed.split(/[\s,]+/).filter(Boolean);
906
+ if (spaced.length > 1 && spaced.every((t) => midiOf(t) !== null)) {
907
+ return spaced.map((t) => midiOf(t));
719
908
  }
720
- return cols.map((_, beat) => ({ beat, sixteenths: 1 }));
909
+ const names = spaced.length > 1 ? spaced : trimmed.match(/[A-G][#♯b♭]?|[a-g][#♯♭]?/g) ?? [];
910
+ if (names.length < 2 || names.join("") !== spaced.join(""))
911
+ return null;
912
+ const midis = [];
913
+ for (const name of names) {
914
+ const chroma = chromaOf(name);
915
+ if (chroma === null)
916
+ return null;
917
+ const previous = midis[midis.length - 1];
918
+ if (previous === undefined) {
919
+ const candidates = [28, 40, 52].map((c) => c - c % 12 + chroma);
920
+ midis.push(candidates.reduce((a, b) => Math.abs(b - 40) < Math.abs(a - 40) ? b : a));
921
+ } else {
922
+ let midi = previous - previous % 12 + chroma;
923
+ while (midi <= previous)
924
+ midi += 12;
925
+ midis.push(midi);
926
+ }
927
+ }
928
+ return midis;
721
929
  }
722
- var LEGATO = new Set(["h", "sl"]);
723
- var legatoOf = (beats) => beats.flatMap((b, i) => b.notes.some((n) => n.effects.some((e) => LEGATO.has(e))) ? [i] : []);
724
- function rhythmOf(m, typical, meter) {
725
- const bar = meter.length;
726
- const span = m.part === "whole" ? m.width : typical;
727
- const shift = m.part === "end" ? typical - m.width : 0;
728
- const cols = m.beats.map((b) => b.col + shift);
729
- if (m.part === "start" && cols.length) {
730
- const at = positionsOf([...cols, m.width], span, m.pad, meter);
731
- if (at) {
732
- const end = at.pop();
733
- const out = at[0] > 0 ? [{ beat: -1, sixteenths: at[0] }] : [];
734
- at.forEach((p, beat) => out.push({ beat, sixteenths: (at[beat + 1] ?? end) - p }));
735
- return [...out, ...restsFrom(end, meter)];
930
+ function tuningNames(text) {
931
+ const trimmed = text.trim();
932
+ const named = NAMED.get(trimmed.toLowerCase().replace(/\s*\(.*\)$/, ""));
933
+ if (named)
934
+ return tuningNames(named);
935
+ if (!parseTuning(trimmed))
936
+ return null;
937
+ const spaced = trimmed.split(/[\s,]+/).filter(Boolean);
938
+ const names = spaced.length > 1 ? spaced : trimmed.match(/[A-G][#♯b♭]?|[a-g][#♯♭]?/g) ?? [];
939
+ return names.map((n) => {
940
+ const letter = n.charAt(0).toUpperCase();
941
+ const accidental = n.slice(1).replace(/-?\d+$/, "").replace("♯", "#").replace("♭", "b");
942
+ return letter + accidental;
943
+ });
944
+ }
945
+
946
+ // src/convert/text-tab.ts
947
+ var STRING_PREFIX = /^\s*([A-Ga-g][#b]?|[1-8](?=\s*[|:]))?\s*[|:]?/;
948
+ var STRING_BODY = /^[-0-9xX|:hpbrsvt/\\~^().*<>\s]*$/;
949
+ var DRUM_LINE = /^\s*([A-Za-z][A-Za-z0-9. -]{0,14}?)\s*[|:]([-xXoOgfdb#@*+|:\s]*)$/;
950
+ var DRUM_NAMES = new Map(Object.entries({
951
+ hihat: "h hh hat hihat hihats",
952
+ "hihat-open": "oh openhat openhihat",
953
+ "hihat-foot": "hf fh hp ph pedal hihatfoot hihatpedal",
954
+ crash: "c c1 cc cr cy cym crash crash1 cymbal",
955
+ crash2: "c2 cr2 crash2",
956
+ ride: "r rd rc ride",
957
+ splash: "sp spl splash",
958
+ china: "ch cn chi china",
959
+ cowbell: "cb cow cowbell",
960
+ snare: "s sd sn sr snare snaredrum",
961
+ tom1: "t t1 ht tom1 hightom hitom",
962
+ tom2: "t2 mt tom2 midtom",
963
+ tom3: "t3 lt tom3 lowtom",
964
+ floor: "f ft fl t4 tom4 floor floortom",
965
+ kick: "b bd bs k kd bass kick bassdrum kickdrum"
966
+ }).flatMap(([drum, list]) => list.split(" ").map((name) => [name, drum])));
967
+ function articulationOf(drum, hit) {
968
+ const choke = hit === "#";
969
+ switch (drum) {
970
+ case "hihat":
971
+ return hit === "o" || hit === "O" ? "HiHatOpen" : "HiHatClosed";
972
+ case "hihat-open":
973
+ return "HiHatOpen";
974
+ case "hihat-foot":
975
+ return "PedalHiHatHit";
976
+ case "crash":
977
+ return choke ? "CrashHighChoke" : "CrashHighHit";
978
+ case "crash2":
979
+ return choke ? "CrashMediumChoke" : "CrashMediumHit";
980
+ case "ride":
981
+ return choke ? "RideChoke" : "RideMiddle";
982
+ case "splash":
983
+ return choke ? "SplashChoke" : "SplashHit";
984
+ case "china":
985
+ return choke ? "ChinaChoke" : "ChinaHit";
986
+ case "cowbell":
987
+ return "CowbellMediumHit";
988
+ case "snare":
989
+ return "SnareHit";
990
+ case "tom1":
991
+ return "HighTomHit";
992
+ case "tom2":
993
+ return "MidTomHit";
994
+ case "tom3":
995
+ return "LowTomHit";
996
+ case "floor":
997
+ return "VeryLowTomHit";
998
+ case "kick":
999
+ return "KickHit";
1000
+ }
1001
+ }
1002
+ var effectOf = (hit) => hit === "X" || hit === "O" ? ["ac"] : hit === "g" ? ["g"] : [];
1003
+ var NOT_TAB = /[^-0-9xXoOgfdbhprsvt/\\~^().*<>#@+|:\s]|<(?!\d)/;
1004
+ var COUNT = /^\s*(?:[xX]\s*\d{1,3}|\d{1,3}\s*[xX])\s*$/;
1005
+ function splitText(line) {
1006
+ const last = line.lastIndexOf("|");
1007
+ if (last < 0)
1008
+ return { line, text: null };
1009
+ const rest = line.slice(last + 1);
1010
+ const text = rest.trim();
1011
+ if (!text)
1012
+ return { line, text: null };
1013
+ const isText = NOT_TAB.test(text) || COUNT.test(text) || /^\s/.test(rest) && !text.includes("--");
1014
+ return isText ? { line: line.slice(0, last + 1), text } : { line, text: null };
1015
+ }
1016
+ function tabLineOf(raw) {
1017
+ const { line, text } = splitText(raw.trimEnd());
1018
+ let string = null;
1019
+ const m = STRING_PREFIX.exec(line);
1020
+ const body = line.slice(m[0].length);
1021
+ if (STRING_BODY.test(body) && (line.match(/-/g)?.length ?? 0) >= 4 && (line.includes("|") || /^\s*[A-Ga-g][#b]?\s*[-|:]/.test(line)))
1022
+ string = { name: m[1] ?? null, body, offset: m[0].length, barred: /[|:]$/.test(m[0]) };
1023
+ let drum = null;
1024
+ const d = DRUM_LINE.exec(line);
1025
+ const name = d ? d[1].toLowerCase().replace(/[ .-]/g, "") : "";
1026
+ const known = DRUM_NAMES.get(name);
1027
+ if (d && known && (d[2].match(/[^\s|:]/g)?.length ?? 0) >= 4)
1028
+ drum = { drum: known, name, body: d[2], lettered: /^[A-Ga-g]$/.test(d[1]) };
1029
+ return string || drum ? { string, drum, text } : null;
1030
+ }
1031
+ var textsOf = (run) => [
1032
+ ...new Set(run.map((l) => l.text).filter((t) => t !== null))
1033
+ ];
1034
+ function splitStrings(run) {
1035
+ const out = [];
1036
+ let start = 0;
1037
+ for (let i = 2;i < run.length - 1; i++) {
1038
+ const [a, b] = [run[start].string.name, run[start + 1].string.name];
1039
+ if (a !== null && run[i].string.name === a && run[i + 1].string.name === b && i - start >= 2) {
1040
+ out.push(run.slice(start, i));
1041
+ start = i;
736
1042
  }
737
1043
  }
738
- const at = positionsOf(cols, span, m.pad, meter);
739
- if (!at) {
740
- const sketch = sketchRhythmOf(m.beats.map((b) => b.col), meter, legatoOf(m.beats));
741
- if (m.part !== "end")
742
- return sketch;
743
- const notes = sketch.filter((e) => e.beat >= 0);
744
- const total = notes.reduce((sum, e) => sum + e.sixteenths, 0);
745
- return m.pickup ? notes : [...restsFrom(0, meter, bar - total), ...notes];
1044
+ out.push(run.slice(start));
1045
+ return out;
1046
+ }
1047
+ function splitDrums(run) {
1048
+ const out = [];
1049
+ let current = [];
1050
+ for (const line of run) {
1051
+ if (current.some((l) => l.drum.name === line.drum.name)) {
1052
+ out.push(current);
1053
+ current = [];
1054
+ }
1055
+ current.push(line);
746
1056
  }
747
- const first = at[0];
748
- const out = first === 0 || m.pickup ? [] : m.part === "end" ? restsFrom(0, meter, first) : [{ beat: -1, sixteenths: first }];
749
- at.forEach((p, beat) => out.push({ beat, sixteenths: (at[beat + 1] ?? bar) - p }));
1057
+ out.push(current);
750
1058
  return out;
751
1059
  }
752
- var padOf = (bars) => bars.reduce((pad, b) => b.beats.length ? Math.min(pad, b.beats[0].col - b.start) : pad, 3);
753
- function rowOf(lines, bars, texts, openStart) {
754
- const width = Math.max(...lines.map((l) => l.length));
755
- return {
756
- bars,
757
- pad: padOf(bars),
758
- texts,
759
- openStart: openStart && bars[0]?.start === 0,
760
- openEnd: bars.at(-1)?.end === width
761
- };
1060
+ var PM_LINE = /^[\sPpMm.\-_|=~]*$/;
1061
+ var PM_MARK = /P\.?M/i;
1062
+ function palmMutesOf(line) {
1063
+ if (!PM_LINE.test(line) || !PM_MARK.test(line))
1064
+ return [];
1065
+ const ranges = [];
1066
+ for (let i = 0;i < line.length; i++) {
1067
+ const c = line[i];
1068
+ const mark = (c === "P" || c === "p") && /^\.?[Mm]/.test(line.slice(i + 1, i + 3));
1069
+ if (mark)
1070
+ ranges.push([i, i]);
1071
+ else if (c !== " " && ranges.length)
1072
+ ranges[ranges.length - 1][1] = i;
1073
+ }
1074
+ return ranges;
762
1075
  }
763
- function typicalWidth(rows) {
764
- const widths = [];
765
- for (const row of rows)
766
- row.bars.forEach((bar, i) => {
767
- const closed = (i > 0 || !row.openStart) && (i < row.bars.length - 1 || !row.openEnd);
768
- if (closed && bar.beats.length)
769
- widths.push(bar.end - bar.start);
770
- });
771
- if (widths.length < 2)
772
- return null;
773
- widths.sort((a, b) => a - b);
774
- return widths[widths.length >> 1];
1076
+ function stringSystems(run, above = null) {
1077
+ return splitStrings(run).flatMap((part, index) => {
1078
+ const names = part.map((l) => l.string.name);
1079
+ if (part.length < 3 && names.some((n) => n === null))
1080
+ return [];
1081
+ const lines = part.map((l) => l.string.body);
1082
+ const offset = part[0].string.offset;
1083
+ const muted = new Set;
1084
+ if (index === 0 && above !== null)
1085
+ for (const [a, b] of palmMutesOf(above))
1086
+ for (let col = Math.max(a, offset);col <= b; col++)
1087
+ muted.add(col - offset);
1088
+ const openStart = part.some((l) => !l.string.barred);
1089
+ return [{ kind: "strings", names, lines, texts: textsOf(part), muted, openStart }];
1090
+ });
775
1091
  }
776
- function mostFrequent(values) {
777
- const counts = new Map;
778
- for (const v of values)
779
- counts.set(v, (counts.get(v) ?? 0) + 1);
780
- let best;
781
- for (const [value, count] of counts)
782
- if (!best || count > best.count || count === best.count && value < best.value)
783
- best = { value, count };
784
- return best;
1092
+ function systemsOfRun(run, above) {
1093
+ if (!run.length)
1094
+ return [];
1095
+ if (run.every((l) => l.drum) && run.some((l) => !l.string || !l.drum.lettered || /[xXoOgfdb#@*+]/.test(l.drum.body)))
1096
+ return splitDrums(run).map((part) => ({
1097
+ kind: "drums",
1098
+ drums: part.map((l) => l.drum.drum),
1099
+ lines: part.map((l) => l.drum.body),
1100
+ texts: textsOf(part)
1101
+ }));
1102
+ if (run.every((l) => l.string))
1103
+ return stringSystems(run, above);
1104
+ const out = [];
1105
+ let stretch = [];
1106
+ for (const l of [...run, null]) {
1107
+ if (l?.string)
1108
+ stretch.push(l);
1109
+ else {
1110
+ if (stretch.length)
1111
+ out.push(...stringSystems(stretch, out.length ? null : above));
1112
+ stretch = [];
1113
+ }
1114
+ }
1115
+ return out;
785
1116
  }
786
- function meterOf(rows, typical) {
787
- if (typical === null)
788
- return COMMON;
789
- const bars = [];
790
- for (const row of rows)
791
- row.bars.forEach((bar, i) => {
792
- const closed = (i > 0 || !row.openStart) && (i < row.bars.length - 1 || !row.openEnd);
793
- const width = bar.end - bar.start;
794
- if (closed && bar.beats.length && Math.abs(width - typical) <= 1)
795
- bars.push({ bar, pad: row.pad });
796
- });
797
- const gaps = new Map;
798
- for (const { bar } of bars)
799
- for (let i = 1;i < bar.beats.length; i++) {
800
- const gap = bar.beats[i].col - bar.beats[i - 1].col;
801
- gaps.set(gap, (gaps.get(gap) ?? 0) + 1);
1117
+ function systemsOf(text) {
1118
+ const systems = [];
1119
+ let run = [];
1120
+ let above = null;
1121
+ let previous = null;
1122
+ for (const raw of text.split(/\r?\n/)) {
1123
+ const line = tabLineOf(raw);
1124
+ if (line) {
1125
+ if (!run.length)
1126
+ above = previous;
1127
+ run.push(line);
1128
+ } else {
1129
+ systems.push(...systemsOfRun(run, above));
1130
+ run = [];
802
1131
  }
803
- const top = Math.max(0, ...gaps.values());
804
- const unit = Math.min(...[...gaps].filter(([, n]) => n * 2 >= top).map(([gap]) => gap));
805
- if (bars.length < 2 || !Number.isFinite(unit))
806
- return COMMON;
807
- const counts = [];
808
- let twos = 0;
809
- let threes = 0;
810
- for (const { bar, pad } of bars) {
811
- const exact = bar.beats.map((b) => (b.col - bar.start - pad) / unit);
812
- if (exact.some((u) => Math.abs(u - Math.round(u)) * unit > 0.4 + 0.000000001)) {
813
- counts.push(0);
1132
+ previous = raw;
1133
+ }
1134
+ systems.push(...systemsOfRun(run, above));
1135
+ return systems;
1136
+ }
1137
+ function barsOf(lines, beatAt) {
1138
+ const width = Math.max(...lines.map((l) => l.length));
1139
+ const padded = lines.map((l) => l.padEnd(width, "-"));
1140
+ const bars = [];
1141
+ let beats = [];
1142
+ let filled = false;
1143
+ let start = 0;
1144
+ for (let col = 0;col < width; col++) {
1145
+ if (padded.every((l) => l[col] === "|" || l[col] === ":")) {
1146
+ if (filled)
1147
+ bars.push({ beats, start, end: col });
1148
+ beats = [];
1149
+ filled = false;
1150
+ start = col + 1;
814
1151
  continue;
815
1152
  }
816
- const at = exact.map(Math.round);
817
- const count = Math.max(Math.ceil((bar.end - bar.start - pad) / unit - 0.5), at.at(-1) + 1);
818
- counts.push(count);
819
- if (count !== 6)
1153
+ if (padded.some((l) => l[col] !== " "))
1154
+ filled = true;
1155
+ const { beat, skip, at } = beatAt(padded, col);
1156
+ if (beat.length)
1157
+ beats.push({ notes: beat, col: at ?? col });
1158
+ col += skip;
1159
+ }
1160
+ if (filled)
1161
+ bars.push({ beats, start, end: width });
1162
+ return bars;
1163
+ }
1164
+ var isDigit = (c) => c !== undefined && c >= "0" && c <= "9";
1165
+ var twoDigits = (a, b) => (a === "1" || a === "2") && isDigit(b) && Number(a + b) <= 24;
1166
+ function techniquesOf(body) {
1167
+ const frets = new Map;
1168
+ const effects = new Map;
1169
+ const hidden = new Set;
1170
+ const target = (at) => {
1171
+ let j = at;
1172
+ const open = body[j] === "(";
1173
+ if (open)
1174
+ j++;
1175
+ if (!isDigit(body[j]))
1176
+ return { fret: null, next: at };
1177
+ const width = twoDigits(body[j], body[j + 1]) ? 2 : 1;
1178
+ const fret = Number(body.slice(j, j + width));
1179
+ for (let w = 0;w < width; w++)
1180
+ hidden.add(j + w);
1181
+ j += width;
1182
+ if (open && body[j] === ")")
1183
+ j++;
1184
+ return { fret, next: j };
1185
+ };
1186
+ for (let i = 0;i < body.length; ) {
1187
+ if (!isDigit(body[i]) || hidden.has(i)) {
1188
+ i++;
820
1189
  continue;
821
- const lowest = bar.beats.reduce((low, b) => b.notes.reduce((l, n) => Math.max(l, n.string ?? 0), low), 0);
822
- const bass = at.filter((_, i) => bar.beats[i].notes.some((n) => n.string === lowest));
823
- for (const group of [at, bass.length < at.length ? bass : []]) {
824
- if (group.some((u) => u !== 0 && u % 2 === 0) && group.every((u) => u % 2 === 0))
825
- twos++;
826
- else if (group.includes(3) && group.every((u) => u % 3 === 0))
827
- threes++;
828
1190
  }
1191
+ const width = twoDigits(body[i], body[i + 1]) ? 2 : 1;
1192
+ const fret = Number(body.slice(i, i + width));
1193
+ frets.set(i, { fret, width });
1194
+ const fx = [];
1195
+ const before = body[i - 1];
1196
+ let k = i + width;
1197
+ if (before === "<" && body[k] === ">") {
1198
+ fx.push("nh");
1199
+ k++;
1200
+ } else if ((before === "/" || before === "\\") && !/[\d)>]/.test(body[i - 2] ?? "-"))
1201
+ fx.push(before === "/" ? "sib" : "sia");
1202
+ if (body[k] === "b" || body[k] === "^") {
1203
+ const up = target(k + 1);
1204
+ k = up.next;
1205
+ const semitones = up.fret !== null && up.fret > fret ? Math.min(up.fret - fret, 4) : 2;
1206
+ const points = [0, semitones * 2];
1207
+ if (body[k] === "r") {
1208
+ const down = target(k + 1);
1209
+ k = down.next;
1210
+ const back = down.fret === null ? 0 : (down.fret - fret) * 2;
1211
+ points.push(Math.min(points[1], Math.max(0, back)));
1212
+ }
1213
+ fx.push(`b (${points.join(" ")})`);
1214
+ }
1215
+ if (body[k] === "~" || body[k] === "v") {
1216
+ fx.push("v");
1217
+ while (body[k] === "~" || body[k] === "v")
1218
+ k++;
1219
+ }
1220
+ const next = body[k];
1221
+ const onto = isDigit(body[k + 1]) || body[k + 1] === "(" && isDigit(body[k + 2]);
1222
+ if ((next === "h" || next === "p") && onto)
1223
+ fx.push("h");
1224
+ else if (next === "/" || next === "\\" || next === "s") {
1225
+ if (onto)
1226
+ fx.push("sl");
1227
+ else if (next !== "s")
1228
+ fx.push(next === "/" ? "sou" : "sod");
1229
+ }
1230
+ if (fx.length)
1231
+ effects.set(i, fx);
1232
+ i += width;
829
1233
  }
830
- const most = mostFrequent(counts);
831
- if (most.count * 3 < bars.length * 2)
832
- return COMMON;
833
- if (most.value === 3)
834
- return THREE_FOUR;
835
- if (most.value === 6)
836
- return twos > threes ? THREE_FOUR : SIX_EIGHT;
837
- return most.value === 12 ? TWELVE_EIGHT : COMMON;
1234
+ return { frets, effects };
838
1235
  }
839
- function measuresOf(rows, typical) {
840
- const short = (width) => typical !== null && width <= typical * 2 / 3;
841
- const out = [];
842
- let carry = null;
843
- rows.forEach((row, r) => {
844
- const before = out.length;
845
- const next = rows[r + 1];
846
- row.bars.forEach((bar, i) => {
847
- const beats = bar.beats.map((b) => ({ notes: b.notes, col: b.col - bar.start }));
848
- let m = {
849
- beats,
850
- width: bar.end - bar.start,
851
- pad: row.pad,
852
- part: "whole",
853
- pickup: false,
854
- text: null
855
- };
856
- const joined = i === 0 && carry !== null;
857
- if (carry && i === 0) {
858
- const shift = carry.width - row.pad;
859
- m = {
860
- ...carry,
861
- beats: [
862
- ...carry.beats,
863
- ...beats.map((b) => ({ notes: b.notes, col: b.col + shift }))
864
- ],
865
- width: carry.width + m.width - row.pad
866
- };
867
- carry = null;
868
- }
869
- if (i === row.bars.length - 1 && short(m.width)) {
870
- const after = next?.bars[0];
871
- const together = after ? m.width + after.end - after.start - next.pad : 0;
872
- if (after && (row.openEnd || short(after.end - after.start) && (next.openStart || together <= typical * 1.25))) {
873
- if (m.beats.length || !row.openEnd)
874
- carry = m;
875
- return;
876
- }
877
- if (row.openEnd && !joined) {
878
- if (!m.beats.length)
879
- return;
880
- m.part = "start";
881
- }
882
- }
883
- const first = !out.length;
884
- if (i === 0 && !joined && m.part === "whole" && short(m.width) && m.beats.length) {
885
- if (first || row.openStart) {
886
- m.part = "end";
887
- m.pickup = first;
888
- }
889
- }
890
- out.push(m);
1236
+ var stringBeatAt = (lines, muted, numbers = []) => (padded, col) => {
1237
+ const beat = [];
1238
+ const strings = new Set;
1239
+ let start = col;
1240
+ let wide = false;
1241
+ const read = (i, at) => {
1242
+ const c = padded[i][at];
1243
+ const pm = muted.has(at) ? ["pm"] : [];
1244
+ if (c === "x" || c === "X") {
1245
+ beat.push({ tex: `x.${numbers[i] ?? i + 1}`, effects: pm });
1246
+ strings.add(i);
1247
+ return;
1248
+ }
1249
+ const note = lines[i].frets.get(at);
1250
+ if (!note)
1251
+ return;
1252
+ if (note.width === 2 && at === col)
1253
+ wide = true;
1254
+ if (padded[i][at - 1] === "<")
1255
+ start = Math.min(start, at - 1);
1256
+ beat.push({
1257
+ tex: `${note.fret}.${numbers[i] ?? i + 1}`,
1258
+ effects: [...lines[i].effects.get(at) ?? [], ...pm],
1259
+ string: numbers[i] ?? i + 1
891
1260
  });
892
- const target = carry ?? (out.length > before ? out.at(-1) : null);
893
- if (row.texts.length && target) {
894
- const text = row.texts.join(" / ");
895
- target.text = target.text ? `${target.text} / ${text}` : text;
1261
+ strings.add(i);
1262
+ };
1263
+ padded.forEach((_, i) => read(i, col));
1264
+ if (wide)
1265
+ padded.forEach((_, i) => strings.has(i) || read(i, col + 1));
1266
+ return { beat, skip: wide ? 1 : 0, at: start };
1267
+ };
1268
+ var BY_COUNT = {
1269
+ 3: [64, 59, 55],
1270
+ 4: [43, 38, 33, 28],
1271
+ 5: [43, 38, 33, 28, 23],
1272
+ 6: [64, 59, 55, 50, 45, 40],
1273
+ 7: [64, 59, 55, 50, 45, 40, 35]
1274
+ };
1275
+ var BY_NUMBER = [64, 59, 55, 50, 45, 40, 35, 30];
1276
+ var GUITAR = { names: ["E", "A", "D", "G", "B", "E"], midis: [40, 45, 50, 55, 59, 64] };
1277
+ var BASS = ["E A D G", "B E A D G"];
1278
+ var upper = (name) => name[0].toUpperCase() + name.slice(1);
1279
+ function tuningOf(names) {
1280
+ const strings = names.length;
1281
+ if (names.every((n) => n !== null && /^\d$/.test(n)))
1282
+ return names.every((n) => BY_NUMBER[Number(n) - 1]) ? names.map((n) => BY_NUMBER[Number(n) - 1]) : null;
1283
+ if (names.every((n) => n !== null && /^[A-Ga-g]/.test(n))) {
1284
+ const lowFirst = [...names].reverse();
1285
+ const spelled = lowFirst.map(upper).join(" ");
1286
+ if (BASS.includes(spelled))
1287
+ return parseTuning(spelled).map((m) => m - 12).reverse();
1288
+ const starts = [...GUITAR.names.keys()].filter((start) => lowFirst.every((n, i) => GUITAR.names[start + i] === upper(n)));
1289
+ if (starts.length) {
1290
+ const start = starts.length > 1 && lowFirst[0] === "e" ? starts.at(-1) : starts[0];
1291
+ return GUITAR.midis.slice(start, start + strings).reverse();
896
1292
  }
897
- });
898
- return out;
899
- }
900
- function splitUnbarred(measures, meter) {
901
- return measures.flatMap((m) => {
902
- if (m.part !== "whole" || m.beats.length < 2)
903
- return [m];
904
- const cols = m.beats.map((b) => b.col);
905
- if (positionsOf(cols, m.width, m.pad, meter))
906
- return [m];
907
- const gaps = cols.slice(1).map((c, i) => c - cols[i]);
908
- const unit = mostFrequent(gaps).value;
909
- const eighths = gaps.reduce((sum, g) => sum + Math.max(1, Math.round(g / unit)), 1);
910
- const perBar = meter.length / 2;
911
- const span = unit * perBar;
912
- if (eighths <= perBar || m.width - m.pad < span * 1.5)
913
- return [m];
914
- const count = Math.floor((cols.at(-1) - m.pad) / span) + 1;
915
- const pieces = Array.from({ length: count }, () => []);
916
- for (const b of m.beats) {
917
- let k = Math.min(count - 1, Math.max(0, Math.floor((b.col - m.pad) / span)));
918
- while (k < count - 1 && b.col >= m.pad + (k + 1) * span)
919
- k++;
920
- while (k > 0 && b.col < m.pad + k * span)
921
- k--;
922
- pieces[k].push({ notes: b.notes, col: b.col - k * span });
1293
+ if (strings === 1) {
1294
+ const chroma = chromaOf(upper(names[0]));
1295
+ return chroma === null ? null : [48 + (chroma - 48 + 120) % 12];
923
1296
  }
924
- return pieces.map((beats, k) => {
925
- return {
926
- beats,
927
- width: m.pad + span,
928
- pad: m.pad,
929
- part: "whole",
930
- pickup: false,
931
- text: k === count - 1 ? m.text : null
932
- };
933
- });
934
- });
935
- }
936
- var quoted = (text) => `"${text.replace(/[\\"]/g, (c) => `\\${c}`)}"`;
937
- var withEffects = (tex, effects) => effects.length ? `${tex}{${effects.join(" ")}}` : tex;
938
- function beatTex(notes, effects) {
939
- if (!notes.length)
940
- return withEffects("r", effects);
941
- if (notes.length === 1)
942
- return withEffects(notes[0].tex, [...notes[0].effects, ...effects]);
943
- return withEffects(`(${notes.map((n) => withEffects(n.tex, n.effects)).join(" ")})`, effects);
944
- }
945
- var LINKS = new Set(["h", "sl", "sou", "sod"]);
946
- function tied(notes, pieces) {
947
- if (pieces === 1)
948
- return [notes];
949
- const out = [notes.map((n) => ({ ...n, effects: n.effects.filter((e) => !LINKS.has(e)) }))];
950
- for (let piece = 1;piece < pieces; piece++)
951
- out.push(notes.filter((n) => n.string !== undefined).map((n) => ({
952
- tex: `-.${n.string}`,
953
- effects: n.effects.filter((e) => e === "pm" || piece === pieces - 1 && LINKS.has(e))
954
- })));
955
- return out;
1297
+ const tuning = parseTuning(spelled);
1298
+ if (tuning)
1299
+ return tuning.reverse();
1300
+ }
1301
+ return BY_COUNT[strings] ?? null;
956
1302
  }
957
- function texOf(bars, meter) {
958
- let duration = 0;
959
- const out = bars.map(({ beats, rhythm, text, pickup }) => {
960
- const items = [];
961
- if (!beats.length)
962
- for (const value of meter === COMMON ? [{ duration: 1, dotted: false }] : valuesOf(meter.length))
963
- items.push({ notes: [], ...value });
964
- for (const { beat, sixteenths } of rhythm) {
965
- const values = valuesOf(sixteenths);
966
- const notes = tied(beat >= 0 ? beats[beat] : [], values.length);
967
- values.forEach((value, i) => items.push({ notes: notes[i], ...value }));
968
- }
969
- let annotated = items.length - 1;
970
- while (annotated > 0 && !items[annotated].notes.length)
971
- annotated--;
972
- if (!items[annotated].notes.length)
973
- annotated = items.length - 1;
974
- const tex = items.map((item, i) => {
975
- const effects = item.dotted ? ["d"] : [];
976
- if (text && i === annotated)
977
- effects.push(`txt ${quoted(text)}`);
978
- const head = item.duration === duration ? "" : `:${item.duration} `;
979
- duration = item.duration;
980
- return head + beatTex(item.notes, effects);
981
- }).join(" ");
982
- return pickup ? `\\ac ${tex}` : tex;
983
- });
984
- return out.join(` |
985
- `);
1303
+ function onGuitar(midi) {
1304
+ const tuning = [...BY_COUNT[6]];
1305
+ let index = tuning.indexOf(midi);
1306
+ if (index < 0) {
1307
+ index = tuning.reduce((best, m, i) => Math.abs(m - midi) < Math.abs(tuning[best] - midi) ? i : best, 0);
1308
+ tuning[index] = midi;
1309
+ }
1310
+ return { tuning, string: index + 1 };
986
1311
  }
987
- function textTabToAlphaTex(text) {
988
- const systems = systemsOf(text);
989
- const first = systems[0];
990
- if (!first)
991
- return null;
992
- let tuning = first.kind === "strings" ? tuningOf(first.names) : null;
993
- const placed = tuning ? placedOnGuitar(tuning) : null;
994
- if (placed)
995
- tuning = placed.tuning;
996
- const rows = [];
997
- if (first.kind === "drums") {
998
- for (const s of systems)
999
- if (s.kind === "drums")
1000
- rows.push(rowOf(s.lines, barsOf(s.lines, drumBeatAt(s.drums)), s.texts, false));
1001
- } else {
1002
- const same = JSON.stringify(tuningOf(first.names));
1003
- const strings = placed?.strings ?? [];
1004
- for (const s of systems) {
1005
- if (s.kind !== "strings" || JSON.stringify(tuningOf(s.names)) !== same)
1006
- continue;
1007
- const beatAt = stringBeatAt(s.lines.map(techniquesOf), s.muted, strings);
1008
- rows.push(rowOf(s.lines, barsOf(s.lines, beatAt), s.texts, s.openStart));
1009
- }
1312
+ function placedOnGuitar(tuning) {
1313
+ if (tuning.length === 1) {
1314
+ const { tuning: six, string } = onGuitar(tuning[0]);
1315
+ return { tuning: six, strings: [string] };
1010
1316
  }
1011
- const typical = typicalWidth(rows);
1012
- const meter = meterOf(rows, typical);
1013
- const bars = splitUnbarred(measuresOf(rows, typical), meter).map((m) => ({
1014
- beats: m.beats.map((b) => b.notes),
1015
- rhythm: rhythmOf(m, typical ?? 0, meter),
1016
- text: m.text,
1017
- pickup: m.pickup
1018
- }));
1019
- if (!bars.length)
1317
+ const standard = BY_COUNT[6];
1318
+ if (tuning.length > 5)
1020
1319
  return null;
1021
- const ts = meter === COMMON ? [] : [`\\ts ${meter.ts.join(" ")}`];
1022
- if (first.kind === "drums")
1023
- return [
1024
- "\\instrument percussion",
1025
- "\\articulation defaults",
1026
- ...ts,
1027
- texOf(bars, meter)
1028
- ].join(`
1029
- `);
1030
- const standard = tuning?.join(" ") === BY_COUNT[6].join(" ");
1031
- const header = tuning && !standard ? [`\\tuning (${tuning.map((m) => noteOf(m)).join(" ")})`] : [];
1032
- return [...header, ...ts, texOf(bars, meter)].join(`
1033
- `);
1034
- }
1035
- // src/theory/note-set.ts
1036
- import { Chord, Interval, Scale as Scale2 } from "tonal";
1037
-
1038
- // src/theory/suffix.ts
1039
- var CANONICAL = new Map([
1040
- ["M", ""],
1041
- ["maj", ""],
1042
- ["min", "m"],
1043
- ["-", "m"],
1044
- ["M7", "maj7"],
1045
- ["Δ", "maj7"],
1046
- ["Δ7", "maj7"],
1047
- ["M9", "maj9"],
1048
- ["Δ9", "maj9"],
1049
- ["min6", "m6"],
1050
- ["-6", "m6"],
1051
- ["min7", "m7"],
1052
- ["-7", "m7"],
1053
- ["min9", "m9"],
1054
- ["-9", "m9"],
1055
- ["ø", "m7b5"],
1056
- ["ø7", "m7b5"],
1057
- ["m7-5", "m7b5"],
1058
- ["mmaj7", "mMaj7"],
1059
- ["mM7", "mMaj7"],
1060
- ["m(maj7)", "mMaj7"],
1061
- ["-(maj7)", "mMaj7"],
1062
- ["°", "dim"],
1063
- ["°7", "dim7"],
1064
- ["+", "aug"],
1065
- ["sus", "sus4"],
1066
- ["add2", "add9"],
1067
- ["69", "6/9"],
1068
- ["alt", "7alt"],
1069
- ["-5", "Mb5"],
1070
- ["#5", "aug"],
1071
- ["b5", "Mb5"],
1072
- ["maj7b5", "M7b5"],
1073
- ["mmaj9", "mMaj9"],
1074
- ["m6/9", "m69"],
1075
- ["m6add9", "m69"],
1076
- ["sus2sus4", "sus24"]
1077
- ]);
1078
- function withoutParentheses(suffix) {
1079
- if (!/[(),]/.test(suffix))
1080
- return suffix;
1081
- if (!/^[^(),]*(?:\([^(),]+(?:,[^(),]+)*\)[^(),]*)+$/.test(suffix))
1320
+ const at = tuning.map((m) => standard.indexOf(m));
1321
+ if (at[0] < 0 || at.some((i, k) => i !== at[0] + k))
1082
1322
  return null;
1083
- return suffix.replace(/[(),\s]/g, "");
1323
+ return { tuning: [...standard], strings: at.map((i) => i + 1) };
1084
1324
  }
1085
- function canonicalSuffix(suffix) {
1086
- const direct = CANONICAL.get(suffix);
1087
- if (direct !== undefined)
1088
- return direct;
1089
- const flat = withoutParentheses(suffix);
1090
- if (flat === null || flat === suffix)
1091
- return suffix;
1092
- return CANONICAL.get(flat) ?? flat;
1325
+ var drumBeatAt = (drums) => (padded, col) => {
1326
+ const beat = [];
1327
+ padded.forEach((line, i) => {
1328
+ const hit = line[col];
1329
+ if (!/[xXoOgfdb#@*+]/.test(hit))
1330
+ return;
1331
+ const name = articulationOf(drums[i], hit);
1332
+ if (!beat.some((n) => n.tex === name))
1333
+ beat.push({ tex: name, effects: effectOf(hit) });
1334
+ });
1335
+ return { beat, skip: 0 };
1336
+ };
1337
+ var VALUES = [
1338
+ [24, 1, true],
1339
+ [16, 1, false],
1340
+ [12, 2, true],
1341
+ [8, 2, false],
1342
+ [6, 4, true],
1343
+ [4, 4, false],
1344
+ [3, 8, true],
1345
+ [2, 8, false],
1346
+ [1, 16, false]
1347
+ ];
1348
+ function valuesOf(sixteenths) {
1349
+ const out = [];
1350
+ for (let left = sixteenths;left > 0; ) {
1351
+ const [length, duration, dotted] = VALUES.find(([n]) => n <= left);
1352
+ out.push({ duration, dotted });
1353
+ left -= length;
1354
+ }
1355
+ return out;
1093
1356
  }
1094
-
1095
- // src/theory/scales.ts
1096
- import { Note, Scale } from "tonal";
1097
- var ALIASES = new Map([
1098
- ["natural minor", "minor"],
1099
- ["blues", "minor blues"],
1100
- ["whole-tone", "whole tone"],
1101
- ["pentatonic major", "major pentatonic"],
1102
- ["pentatonic minor", "minor pentatonic"]
1103
- ]);
1104
- function scaleName(text) {
1105
- const m = /^\s*([A-Ga-g](?:#|b|♯|♭)?)\s+(.+?)\s*$/.exec(text);
1106
- const [tonic, type] = m ? [m[1], m[2]] : ["", text.trim()];
1107
- const lower = type.toLowerCase().replace(/\s+/g, " ");
1108
- const name = ALIASES.get(lower) ?? lower;
1109
- return tonic ? `${tonic[0].toUpperCase()}${tonic.slice(1).replace("♯", "#").replace("♭", "b")} ${name}` : name;
1357
+ var COMMON = { ts: [4, 4], length: 16, beat: 4, grids: [1, 2, 4, 8, 16] };
1358
+ var THREE_FOUR = { ts: [3, 4], length: 12, beat: 4, grids: [1, 3, 6, 12] };
1359
+ var SIX_EIGHT = { ts: [6, 8], length: 12, beat: 6, grids: [1, 2, 6, 12] };
1360
+ var TWELVE_EIGHT = { ts: [12, 8], length: 24, beat: 6, grids: [1, 2, 4, 12, 24] };
1361
+ function keepsSpacing(cols, at) {
1362
+ const lengths = new Map;
1363
+ for (let i = 1;i < cols.length; i++) {
1364
+ const gap = cols[i] - cols[i - 1];
1365
+ const length = at[i] - at[i - 1];
1366
+ if ((lengths.get(gap) ?? length) !== length)
1367
+ return false;
1368
+ lengths.set(gap, length);
1369
+ }
1370
+ const sorted = [...lengths].sort((a, b) => a[0] - b[0]);
1371
+ return sorted.every(([, length], i) => i === 0 || length >= sorted[i - 1][1]);
1110
1372
  }
1111
- var isScaleWithoutRoot = (text) => {
1112
- const scale = Scale.get(scaleName(text));
1113
- return !scale.empty && !scale.tonic;
1114
- };
1115
- var CHARACTERISTIC = {
1116
- lydian: ["4A"],
1117
- dorian: ["6M"],
1118
- mixolydian: ["7m"],
1119
- phrygian: ["2m"],
1120
- locrian: ["5d"],
1121
- minor: ["6m"],
1122
- "minor blues": ["5d"],
1123
- "major blues": ["3m"],
1124
- "harmonic minor": ["7M"],
1125
- "melodic minor": ["6M", "7M"],
1126
- "phrygian dominant": ["2m", "3M"]
1127
- };
1128
- var MODE_WORDS = /\b(dorian|phrygian|lydian|mixolydian|aeolian|locrian|blues)\b/i;
1129
- var characteristicIntervals = (type) => CHARACTERISTIC[type] ?? [];
1130
- var marksByDefault = (written) => MODE_WORDS.test(written);
1131
- function modesOf(text) {
1132
- const scale = Scale.get(scaleName(text));
1133
- if (scale.empty || !scale.tonic)
1373
+ var PLAIN = new Set(VALUES.map(([n]) => n));
1374
+ function fit(cols, n, [origin, span], slack, ties, bar) {
1375
+ const step = span / n;
1376
+ if (step < 1 || ties && !Number.isInteger(step))
1134
1377
  return null;
1135
- const modes = Scale.modeNames(scale.name);
1136
- if (new Set(modes.map(([, mode]) => mode)).size < 2)
1378
+ const at = [];
1379
+ let error = 0;
1380
+ for (const col of cols) {
1381
+ const exact = (col - origin) / step;
1382
+ const k = Math.round(exact);
1383
+ const off = Math.abs(exact - k) * step;
1384
+ if (k < 0 || k >= n || off > slack + 0.000000001 || at.length && k * (bar / n) <= at.at(-1))
1385
+ return null;
1386
+ error = Math.max(error, off);
1387
+ at.push(k * (bar / n));
1388
+ }
1389
+ if (!ties && at.some((p, i) => !PLAIN.has((at[i + 1] ?? bar) - p)))
1137
1390
  return null;
1138
- return modes.map(([tonic, mode]) => `${tonic} ${mode}`);
1391
+ return keepsSpacing(cols, at) ? { at, error } : null;
1392
+ }
1393
+ function positionsOf(cols, width, pad, meter = COMMON) {
1394
+ if (!cols.length)
1395
+ return [];
1396
+ const spans = [
1397
+ [pad, width - pad],
1398
+ [pad, width]
1399
+ ];
1400
+ for (let start = 1;start < pad; start++)
1401
+ spans.push([start, width - start]);
1402
+ if (cols[0] > pad)
1403
+ spans.push([0, width]);
1404
+ for (const [slack, ties] of [
1405
+ [0.4, false],
1406
+ [1, false],
1407
+ [0.4, true]
1408
+ ])
1409
+ for (const n of meter.grids) {
1410
+ const fits = spans.map((span) => fit(cols, n, span, slack, ties, meter.length)).filter((f) => f !== null);
1411
+ if (fits.length)
1412
+ return fits.reduce((a, b) => b.error < a.error ? b : a).at;
1413
+ }
1414
+ return null;
1415
+ }
1416
+ function restsFrom(at, meter, end = meter.length) {
1417
+ const out = [];
1418
+ const { beat, length: bar } = meter;
1419
+ for (let p = at;p < end; ) {
1420
+ const half = bar === 4 * beat && p % (2 * beat) === 0 && p <= bar / 2 ? [2 * beat] : [];
1421
+ const lengths = p % 2 ? [1] : p % beat ? [2, 1] : [...half, beat, 2, 1];
1422
+ const length = lengths.find((n) => n <= end - p);
1423
+ out.push({ beat: -1, sixteenths: length });
1424
+ p += length;
1425
+ }
1426
+ return out;
1427
+ }
1428
+ function sketchRhythmOf(cols, meter = COMMON, legato = []) {
1429
+ const gaps = cols.slice(1).map((c, i) => c - cols[i]);
1430
+ const counts = new Map;
1431
+ for (const g of gaps)
1432
+ counts.set(g, (counts.get(g) ?? 0) + 1);
1433
+ const unit = [...counts].reduce((best, e) => !best || e[1] > best[1] || e[1] === best[1] && e[0] < best[0] ? e : best, null)?.[0];
1434
+ for (const eighth of [2, 1]) {
1435
+ const lengths = cols.map((_, i) => eighth * (i < gaps.length ? Math.max(1, Math.round(gaps[i] / unit)) : 1));
1436
+ let total = lengths.reduce((a, b) => a + b, 0);
1437
+ if (eighth === 2)
1438
+ for (const i of legato) {
1439
+ if (total <= meter.length)
1440
+ break;
1441
+ if (i + 1 >= lengths.length || lengths[i] !== 2)
1442
+ continue;
1443
+ const next = Math.max(1, lengths[i + 1] - 1);
1444
+ total -= 1 + lengths[i + 1] - next;
1445
+ lengths[i] = 1;
1446
+ lengths[i + 1] = next;
1447
+ }
1448
+ if (total > meter.length)
1449
+ continue;
1450
+ return [
1451
+ ...lengths.map((sixteenths, beat) => ({ beat, sixteenths })),
1452
+ ...restsFrom(total, meter)
1453
+ ];
1454
+ }
1455
+ return cols.map((_, beat) => ({ beat, sixteenths: 1 }));
1139
1456
  }
1140
- var DOUBLE_ACCIDENTAL = /^[A-G](##|bb)/;
1141
- var SUPERLOCRIAN = ["1P", "2m", "3m", "4d", "5d", "6m", "7m"];
1142
- function scaleSpelling(scale) {
1143
- const hasDouble = (notes) => notes.some((n) => DOUBLE_ACCIDENTAL.test(n));
1144
- if (!hasDouble(scale.notes))
1145
- return { notes: scale.notes, intervals: scale.intervals };
1146
- if (scale.type === "altered" && scale.tonic) {
1147
- const notes = SUPERLOCRIAN.map((interval) => Note.transpose(scale.tonic, interval));
1148
- if (!hasDouble(notes))
1149
- return { notes, intervals: SUPERLOCRIAN };
1457
+ var LEGATO = new Set(["h", "sl"]);
1458
+ var legatoOf = (beats) => beats.flatMap((b, i) => b.notes.some((n) => n.effects.some((e) => LEGATO.has(e))) ? [i] : []);
1459
+ function rhythmOf(m, typical, meter) {
1460
+ const bar = meter.length;
1461
+ const span = m.part === "whole" ? m.width : typical;
1462
+ const shift = m.part === "end" ? typical - m.width : 0;
1463
+ const cols = m.beats.map((b) => b.col + shift);
1464
+ if (m.part === "start" && cols.length) {
1465
+ const at = positionsOf([...cols, m.width], span, m.pad, meter);
1466
+ if (at) {
1467
+ const end = at.pop();
1468
+ const out = at[0] > 0 ? [{ beat: -1, sixteenths: at[0] }] : [];
1469
+ at.forEach((p, beat) => out.push({ beat, sixteenths: (at[beat + 1] ?? end) - p }));
1470
+ return [...out, ...restsFrom(end, meter)];
1471
+ }
1150
1472
  }
1151
- return { notes: scale.notes, intervals: scale.intervals };
1473
+ const at = positionsOf(cols, span, m.pad, meter);
1474
+ if (!at) {
1475
+ const sketch = sketchRhythmOf(m.beats.map((b) => b.col), meter, legatoOf(m.beats));
1476
+ if (m.part !== "end")
1477
+ return sketch;
1478
+ const notes = sketch.filter((e) => e.beat >= 0);
1479
+ const total = notes.reduce((sum, e) => sum + e.sixteenths, 0);
1480
+ return m.pickup ? notes : [...restsFrom(0, meter, bar - total), ...notes];
1481
+ }
1482
+ const first = at[0];
1483
+ const out = first === 0 || m.pickup ? [] : m.part === "end" ? restsFrom(0, meter, first) : [{ beat: -1, sixteenths: first }];
1484
+ at.forEach((p, beat) => out.push({ beat, sixteenths: (at[beat + 1] ?? bar) - p }));
1485
+ return out;
1152
1486
  }
1153
- var scaleTypes = () => Scale.names();
1154
-
1155
- // src/theory/note-set.ts
1156
- function markClasses(set, chroma, marks = {}) {
1157
- const classes = [];
1158
- if (set.root === chroma)
1159
- classes.push("mn-root");
1160
- else if (marks.characteristic?.has(chroma))
1161
- classes.push("mn-char");
1162
- if (marks.different?.has(chroma))
1163
- classes.push("mn-diff");
1164
- if (marks.chordTones)
1165
- classes.push(marks.chordTones.has(chroma) ? "mn-tone" : "mn-passing");
1166
- return classes.length ? ` ${classes.join(" ")}` : "";
1487
+ var padOf = (bars) => bars.reduce((pad, b) => b.beats.length ? Math.min(pad, b.beats[0].col - b.start) : pad, 3);
1488
+ function rowOf(lines, bars, texts, openStart) {
1489
+ const width = Math.max(...lines.map((l) => l.length));
1490
+ return {
1491
+ bars,
1492
+ pad: padOf(bars),
1493
+ texts,
1494
+ openStart: openStart && bars[0]?.start === 0,
1495
+ openEnd: bars.at(-1)?.end === width
1496
+ };
1167
1497
  }
1168
- function describeMarks(set, marks = {}) {
1169
- const names = (chromas) => set.members.filter((m) => chromas?.has(m.chroma)).map((m) => m.name);
1170
- const characteristic = names(marks.characteristic);
1171
- const different = names(marks.different);
1172
- const tones = names(marks.chordTones);
1173
- return (characteristic.length ? `, characteristic notes: ${characteristic.join(" ")}` : "") + (different.length ? `, different from the compared scale: ${different.join(" ")}` : "") + (tones.length ? `, chord tones: ${tones.join(" ")}` : "");
1498
+ function typicalWidth(rows) {
1499
+ const widths = [];
1500
+ for (const row of rows)
1501
+ row.bars.forEach((bar, i) => {
1502
+ const closed = (i > 0 || !row.openStart) && (i < row.bars.length - 1 || !row.openEnd);
1503
+ if (closed && bar.beats.length)
1504
+ widths.push(bar.end - bar.start);
1505
+ });
1506
+ if (widths.length < 2)
1507
+ return null;
1508
+ widths.sort((a, b) => a - b);
1509
+ return widths[widths.length >> 1];
1174
1510
  }
1175
- var memberFor = (set, chroma) => set.members.find((m) => m.chroma === chroma);
1176
- var memberOf = (set, midi) => set.pitches && !set.pitches.includes(midi) ? undefined : memberFor(set, (midi % 12 + 12) % 12);
1177
- function intervalLabel(interval) {
1178
- const m = /^(\d+)([PMmdA]+)$/.exec(interval);
1179
- if (!m)
1180
- return interval;
1181
- const [, number, quality] = m;
1182
- if (number === "1" && quality === "P")
1183
- return "R";
1184
- const perfect = ["1", "4", "5", "8", "11", "12"].includes(String((Number(number) - 1) % 7 + 1));
1185
- if (quality === "P" || quality === "M")
1186
- return number;
1187
- if (quality === "m")
1188
- return `b${number}`;
1189
- if (quality.startsWith("A"))
1190
- return `${"#".repeat(quality.length)}${number}`;
1191
- return `${"b".repeat(quality.length + (perfect ? 0 : 1))}${number}`;
1511
+ function mostFrequent(values) {
1512
+ const counts = new Map;
1513
+ for (const v of values)
1514
+ counts.set(v, (counts.get(v) ?? 0) + 1);
1515
+ let best;
1516
+ for (const [value, count] of counts)
1517
+ if (!best || count > best.count || count === best.count && value < best.value)
1518
+ best = { value, count };
1519
+ return best;
1192
1520
  }
1193
- function labelOf(member, label, finger) {
1194
- switch (label) {
1195
- case "none":
1196
- return "";
1197
- case "degrees":
1198
- return member.degree === null ? member.name : String(member.degree);
1199
- case "intervals":
1200
- return member.interval === null ? member.name : intervalLabel(member.interval);
1201
- case "fingers":
1202
- return finger ?? "";
1203
- default:
1204
- return member.name;
1521
+ function meterOf(rows, typical) {
1522
+ if (typical === null)
1523
+ return COMMON;
1524
+ const bars = [];
1525
+ for (const row of rows)
1526
+ row.bars.forEach((bar, i) => {
1527
+ const closed = (i > 0 || !row.openStart) && (i < row.bars.length - 1 || !row.openEnd);
1528
+ const width = bar.end - bar.start;
1529
+ if (closed && bar.beats.length && Math.abs(width - typical) <= 1)
1530
+ bars.push({ bar, pad: row.pad });
1531
+ });
1532
+ const gaps = new Map;
1533
+ for (const { bar } of bars)
1534
+ for (let i = 1;i < bar.beats.length; i++) {
1535
+ const gap = bar.beats[i].col - bar.beats[i - 1].col;
1536
+ gaps.set(gap, (gaps.get(gap) ?? 0) + 1);
1537
+ }
1538
+ const top = Math.max(0, ...gaps.values());
1539
+ const unit = Math.min(...[...gaps].filter(([, n]) => n * 2 >= top).map(([gap]) => gap));
1540
+ if (bars.length < 2 || !Number.isFinite(unit))
1541
+ return COMMON;
1542
+ const counts = [];
1543
+ let twos = 0;
1544
+ let threes = 0;
1545
+ for (const { bar, pad } of bars) {
1546
+ const exact = bar.beats.map((b) => (b.col - bar.start - pad) / unit);
1547
+ if (exact.some((u) => Math.abs(u - Math.round(u)) * unit > 0.4 + 0.000000001)) {
1548
+ counts.push(0);
1549
+ continue;
1550
+ }
1551
+ const at = exact.map(Math.round);
1552
+ const count = Math.max(Math.ceil((bar.end - bar.start - pad) / unit - 0.5), at.at(-1) + 1);
1553
+ counts.push(count);
1554
+ if (count !== 6)
1555
+ continue;
1556
+ const lowest = bar.beats.reduce((low, b) => b.notes.reduce((l, n) => Math.max(l, n.string ?? 0), low), 0);
1557
+ const bass = at.filter((_, i) => bar.beats[i].notes.some((n) => n.string === lowest));
1558
+ for (const group of [at, bass.length < at.length ? bass : []]) {
1559
+ if (group.some((u) => u !== 0 && u % 2 === 0) && group.every((u) => u % 2 === 0))
1560
+ twos++;
1561
+ else if (group.includes(3) && group.every((u) => u % 3 === 0))
1562
+ threes++;
1563
+ }
1205
1564
  }
1565
+ const most = mostFrequent(counts);
1566
+ if (most.count * 3 < bars.length * 2)
1567
+ return COMMON;
1568
+ if (most.value === 3)
1569
+ return THREE_FOUR;
1570
+ if (most.value === 6)
1571
+ return twos > threes ? THREE_FOUR : SIX_EIGHT;
1572
+ return most.value === 12 ? TWELVE_EIGHT : COMMON;
1206
1573
  }
1207
- var fromNames = (title, names, intervals, chord = false) => {
1208
- const members = [];
1209
- names.forEach((name, i) => {
1210
- const chroma = chromaOf(name);
1211
- if (chroma === null || members.some((m) => m.chroma === chroma))
1212
- return;
1213
- members.push({
1214
- chroma,
1215
- name,
1216
- degree: intervals ? chord ? Number(/^\d+/.exec(intervals[i] ?? "")?.[0] ?? i + 1) : i + 1 : null,
1217
- interval: intervals?.[i] ?? null
1574
+ function measuresOf(rows, typical) {
1575
+ const short = (width) => typical !== null && width <= typical * 2 / 3;
1576
+ const out = [];
1577
+ let carry = null;
1578
+ rows.forEach((row, r) => {
1579
+ const before = out.length;
1580
+ const next = rows[r + 1];
1581
+ row.bars.forEach((bar, i) => {
1582
+ const beats = bar.beats.map((b) => ({ notes: b.notes, col: b.col - bar.start }));
1583
+ let m = {
1584
+ beats,
1585
+ width: bar.end - bar.start,
1586
+ pad: row.pad,
1587
+ part: "whole",
1588
+ pickup: false,
1589
+ text: null
1590
+ };
1591
+ const joined = i === 0 && carry !== null;
1592
+ if (carry && i === 0) {
1593
+ const shift = carry.width - row.pad;
1594
+ m = {
1595
+ ...carry,
1596
+ beats: [
1597
+ ...carry.beats,
1598
+ ...beats.map((b) => ({ notes: b.notes, col: b.col + shift }))
1599
+ ],
1600
+ width: carry.width + m.width - row.pad
1601
+ };
1602
+ carry = null;
1603
+ }
1604
+ if (i === row.bars.length - 1 && short(m.width)) {
1605
+ const after = next?.bars[0];
1606
+ const together = after ? m.width + after.end - after.start - next.pad : 0;
1607
+ if (after && (row.openEnd || short(after.end - after.start) && (next.openStart || together <= typical * 1.25))) {
1608
+ if (m.beats.length || !row.openEnd)
1609
+ carry = m;
1610
+ return;
1611
+ }
1612
+ if (row.openEnd && !joined) {
1613
+ if (!m.beats.length)
1614
+ return;
1615
+ m.part = "start";
1616
+ }
1617
+ }
1618
+ const first = !out.length;
1619
+ if (i === 0 && !joined && m.part === "whole" && short(m.width) && m.beats.length) {
1620
+ if (first || row.openStart) {
1621
+ m.part = "end";
1622
+ m.pickup = first;
1623
+ }
1624
+ }
1625
+ out.push(m);
1626
+ });
1627
+ const target = carry ?? (out.length > before ? out.at(-1) : null);
1628
+ if (row.texts.length && target) {
1629
+ const text = row.texts.join(" / ");
1630
+ target.text = target.text ? `${target.text} / ${text}` : text;
1631
+ }
1632
+ });
1633
+ return out;
1634
+ }
1635
+ function splitUnbarred(measures, meter) {
1636
+ return measures.flatMap((m) => {
1637
+ if (m.part !== "whole" || m.beats.length < 2)
1638
+ return [m];
1639
+ const cols = m.beats.map((b) => b.col);
1640
+ if (positionsOf(cols, m.width, m.pad, meter))
1641
+ return [m];
1642
+ const gaps = cols.slice(1).map((c, i) => c - cols[i]);
1643
+ const unit = mostFrequent(gaps).value;
1644
+ const eighths = gaps.reduce((sum, g) => sum + Math.max(1, Math.round(g / unit)), 1);
1645
+ const perBar = meter.length / 2;
1646
+ const span = unit * perBar;
1647
+ if (eighths <= perBar || m.width - m.pad < span * 1.5)
1648
+ return [m];
1649
+ const count = Math.floor((cols.at(-1) - m.pad) / span) + 1;
1650
+ const pieces = Array.from({ length: count }, () => []);
1651
+ for (const b of m.beats) {
1652
+ let k = Math.min(count - 1, Math.max(0, Math.floor((b.col - m.pad) / span)));
1653
+ while (k < count - 1 && b.col >= m.pad + (k + 1) * span)
1654
+ k++;
1655
+ while (k > 0 && b.col < m.pad + k * span)
1656
+ k--;
1657
+ pieces[k].push({ notes: b.notes, col: b.col - k * span });
1658
+ }
1659
+ return pieces.map((beats, k) => {
1660
+ return {
1661
+ beats,
1662
+ width: m.pad + span,
1663
+ pad: m.pad,
1664
+ part: "whole",
1665
+ pickup: false,
1666
+ text: k === count - 1 ? m.text : null
1667
+ };
1218
1668
  });
1219
1669
  });
1220
- if (!members.length)
1221
- return null;
1222
- return {
1223
- title,
1224
- members,
1225
- root: intervals ? members[0].chroma : null,
1226
- pitches: null,
1227
- preferFlats: names.some(isFlat)
1228
- };
1229
- };
1230
- function chordNoteSet(symbol) {
1231
- const parts = splitChordSymbol(symbol);
1232
- if (!parts)
1233
- return null;
1234
- const chord = Chord.getChord(canonicalSuffix(parts.suffix), parts.root);
1235
- if (chord.empty)
1236
- return null;
1237
- const bass = parts.bass;
1238
- const set = fromNames(symbol.trim(), chord.notes, chord.intervals, true);
1239
- const bassChroma = bass ? chromaOf(bass) : null;
1240
- if (set && bass && bassChroma !== null && !memberFor(set, bassChroma)) {
1241
- set.members.push({ chroma: bassChroma, name: bass, degree: null, interval: null });
1242
- }
1243
- return set;
1244
- }
1245
- function respell(set, chord) {
1246
- set.root = chord.root;
1247
- for (const member of set.members) {
1248
- const own = memberFor(chord, member.chroma);
1249
- if (own)
1250
- member.name = own.name;
1251
- }
1252
- }
1253
- function scaleNoteSet(name) {
1254
- const scale = Scale2.get(scaleName(name));
1255
- if (scale.empty || !scale.tonic)
1256
- return null;
1257
- const { notes, intervals } = scaleSpelling(scale);
1258
- const set = fromNames(name.trim(), notes, intervals);
1259
- if (set)
1260
- set.scaleType = scale.type;
1261
- return set;
1262
1670
  }
1263
- function rootNameOf(text) {
1264
- const name = text.trim().replace(/-?\d$/, "").replace(/♯/g, "#").replace(/♭/g, "b");
1265
- if (chromaOf(name) === null)
1266
- return null;
1267
- return name[0].toUpperCase() + name.slice(1);
1671
+ var quoted = (text) => `"${text.replace(/[\\"]/g, (c) => `\\${c}`)}"`;
1672
+ var withEffects = (tex, effects) => effects.length ? `${tex}{${effects.join(" ")}}` : tex;
1673
+ function beatTex(notes, effects) {
1674
+ if (!notes.length)
1675
+ return withEffects("r", effects);
1676
+ if (notes.length === 1)
1677
+ return withEffects(notes[0].tex, [...notes[0].effects, ...effects]);
1678
+ return withEffects(`(${notes.map((n) => withEffects(n.tex, n.effects)).join(" ")})`, effects);
1268
1679
  }
1269
- var PLAIN_INTERVALS = ["1P", "2m", "2M", "3m", "3M", "4P", "5d", "5P", "6m", "6M", "7m", "7M"];
1270
- function intervalFrom(root, name) {
1271
- const from = rootNameOf(root);
1272
- const to = rootNameOf(name);
1273
- if (from === null || to === null)
1274
- return null;
1275
- const semitones = (chromaOf(to) - chromaOf(from) + 12) % 12;
1276
- if (semitones === 0)
1277
- return "1P";
1278
- const spelled = Interval.distance(from, to);
1279
- const m = /^(\d+)([PMmdA]+)$/.exec(spelled);
1280
- return m && m[1] !== "1" && m[1] !== "8" ? spelled : PLAIN_INTERVALS[semitones];
1680
+ var LINKS = new Set(["h", "sl", "sou", "sod"]);
1681
+ function tied(notes, pieces) {
1682
+ if (pieces === 1)
1683
+ return [notes];
1684
+ const out = [notes.map((n) => ({ ...n, effects: n.effects.filter((e) => !LINKS.has(e)) }))];
1685
+ for (let piece = 1;piece < pieces; piece++)
1686
+ out.push(notes.filter((n) => n.string !== undefined).map((n) => ({
1687
+ tex: `-.${n.string}`,
1688
+ effects: n.effects.filter((e) => e === "pm" || piece === pieces - 1 && LINKS.has(e))
1689
+ })));
1690
+ return out;
1281
1691
  }
1282
- function listNoteSet(text, root) {
1283
- const tokens = text.split(/[\s,]+/).filter(Boolean);
1284
- if (!tokens.length)
1285
- return null;
1286
- const withOctaves = tokens.every((t) => midiOf(t) !== null);
1287
- const names = withOctaves ? tokens.map((t) => t.replace(/-?\d$/, "")) : tokens;
1288
- if (!withOctaves && names.some((n) => chromaOf(n) === null))
1289
- return null;
1290
- const set = fromNames(tokens.join(" "), names, null);
1291
- if (!set)
1292
- return null;
1293
- set.list = true;
1294
- if (withOctaves)
1295
- set.pitches = tokens.map((t) => midiOf(t));
1296
- if (root === undefined)
1297
- return set;
1298
- const rootName = rootNameOf(root);
1299
- if (rootName === null)
1300
- return null;
1301
- set.root = chromaOf(rootName);
1302
- for (const member of set.members) {
1303
- member.interval = intervalFrom(rootName, member.name);
1304
- member.degree = Number(/^\d+/.exec(member.interval ?? "")?.[0] ?? 1);
1305
- }
1306
- return set;
1692
+ function texOf(bars, meter) {
1693
+ let duration = 0;
1694
+ const out = bars.map(({ beats, rhythm, text, pickup }) => {
1695
+ const items = [];
1696
+ if (!beats.length)
1697
+ for (const value of meter === COMMON ? [{ duration: 1, dotted: false }] : valuesOf(meter.length))
1698
+ items.push({ notes: [], ...value });
1699
+ for (const { beat, sixteenths } of rhythm) {
1700
+ const values = valuesOf(sixteenths);
1701
+ const notes = tied(beat >= 0 ? beats[beat] : [], values.length);
1702
+ values.forEach((value, i) => items.push({ notes: notes[i], ...value }));
1703
+ }
1704
+ let annotated = items.length - 1;
1705
+ while (annotated > 0 && !items[annotated].notes.length)
1706
+ annotated--;
1707
+ if (!items[annotated].notes.length)
1708
+ annotated = items.length - 1;
1709
+ const tex = items.map((item, i) => {
1710
+ const effects = item.dotted ? ["d"] : [];
1711
+ if (text && i === annotated)
1712
+ effects.push(`txt ${quoted(text)}`);
1713
+ const head = item.duration === duration ? "" : `:${item.duration} `;
1714
+ duration = item.duration;
1715
+ return head + beatTex(item.notes, effects);
1716
+ }).join(" ");
1717
+ return pickup ? `\\ac ${tex}` : tex;
1718
+ });
1719
+ return out.join(` |
1720
+ `);
1307
1721
  }
1308
-
1309
- // src/theory/chord-symbol.ts
1310
- var QUALITY_SUFFIXES = [
1311
- [/^(m7b5|m7-5|ø7?)$/, "Minor 7 flat 5"],
1312
- [/^(dim7|°7)$/, "Diminished 7"],
1313
- [/^(maj9|M9|Δ9)$/, "Major 9"],
1314
- [/^(maj7|M7|Δ7?)$/, "Major 7"],
1315
- [/^(7sus4)$/, "7sus4"],
1316
- [/^(m9|min9|-9)$/, "Minor 9"],
1317
- [/^(m7|min7|-7)$/, "Minor 7"],
1318
- [/^(m6|min6|-6)$/, "Minor 6"],
1319
- [/^(m|min|-)$/, "Minor"],
1320
- [/^(dim|°)$/, "Diminished"],
1321
- [/^(aug|\+|\+5|#5)$/, "Augmented"],
1322
- [/^(sus2)$/, "Sus2"],
1323
- [/^(sus4|sus)$/, "Sus4"],
1324
- [/^(add9|add2)$/, "Add9"],
1325
- [/^5$/, "5 (Power)"],
1326
- [/^(6\/9|69)$/, "6/9"],
1327
- [/^(m6\/9|m69|m6add9)$/, "Minor 6/9"],
1328
- [/^(Mb5|b5|-5)$/, "Major flat 5"],
1329
- [/^(mM7|mMaj7|mmaj7|m\(maj7\)|-\(maj7\))$/, "Minor major 7"],
1330
- [/^(13|11|9|7|6)$/, "$1"],
1331
- [/^(maj|M)?$/, "Major"]
1332
- ];
1333
- var ACCIDENTAL_WORDS = {
1334
- "#": " Sharp",
1335
- "##": " Double Sharp",
1336
- b: " Flat",
1337
- bb: " Double Flat"
1338
- };
1339
- var spellNote = (note) => note[0] + (ACCIDENTAL_WORDS[note.slice(1)] ?? "");
1340
- var plain = (quality) => quality.replace(/\s*\([^)]*\)/g, "").trim();
1341
- function parseChord(symbol) {
1342
- const parts = splitChordSymbol(symbol);
1343
- if (!parts)
1722
+ function textTabToAlphaTex(text) {
1723
+ const systems = systemsOf(text);
1724
+ const first = systems[0];
1725
+ if (!first)
1344
1726
  return null;
1345
- const trimmed = symbol.trim();
1346
- const { root, bass } = parts;
1347
- const suffix = withoutParentheses(parts.suffix);
1348
- let quality = null;
1349
- for (const written of suffix === null || suffix === parts.suffix ? [parts.suffix] : [parts.suffix, suffix]) {
1350
- for (const [re, label] of QUALITY_SUFFIXES) {
1351
- const hit = re.exec(written);
1352
- if (hit) {
1353
- quality = label.replace("$1", hit[1] ?? "");
1354
- break;
1355
- }
1727
+ let tuning = first.kind === "strings" ? tuningOf(first.names) : null;
1728
+ const placed = tuning ? placedOnGuitar(tuning) : null;
1729
+ if (placed)
1730
+ tuning = placed.tuning;
1731
+ const rows = [];
1732
+ if (first.kind === "drums") {
1733
+ for (const s of systems)
1734
+ if (s.kind === "drums")
1735
+ rows.push(rowOf(s.lines, barsOf(s.lines, drumBeatAt(s.drums)), s.texts, false));
1736
+ } else {
1737
+ const same = JSON.stringify(tuningOf(first.names));
1738
+ const strings = placed?.strings ?? [];
1739
+ for (const s of systems) {
1740
+ if (s.kind !== "strings" || JSON.stringify(tuningOf(s.names)) !== same)
1741
+ continue;
1742
+ const beatAt = stringBeatAt(s.lines.map(techniquesOf), s.muted, strings);
1743
+ rows.push(rowOf(s.lines, barsOf(s.lines, beatAt), s.texts, s.openStart));
1356
1744
  }
1357
- if (quality)
1358
- break;
1359
1745
  }
1360
- if (suffix === null && !quality)
1361
- return null;
1362
- if (!quality && suffix !== null && chordNoteSet(trimmed))
1363
- quality = suffix;
1364
- if (!quality)
1746
+ const typical = typicalWidth(rows);
1747
+ const meter = meterOf(rows, typical);
1748
+ const bars = splitUnbarred(measuresOf(rows, typical), meter).map((m) => ({
1749
+ beats: m.beats.map((b) => b.notes),
1750
+ rhythm: rhythmOf(m, typical ?? 0, meter),
1751
+ text: m.text,
1752
+ pickup: m.pickup
1753
+ }));
1754
+ if (!bars.length)
1365
1755
  return null;
1366
- return {
1367
- symbol: trimmed,
1368
- root,
1369
- quality,
1370
- bass,
1371
- name: `${spellNote(root)} ${plain(quality)}${bass ? ` over ${spellNote(bass)}` : ""}`
1372
- };
1756
+ const ts = meter === COMMON ? [] : [`\\ts ${meter.ts.join(" ")}`];
1757
+ if (first.kind === "drums")
1758
+ return [
1759
+ "\\instrument percussion",
1760
+ "\\articulation defaults",
1761
+ ...ts,
1762
+ texOf(bars, meter)
1763
+ ].join(`
1764
+ `);
1765
+ const standard = tuning?.join(" ") === BY_COUNT[6].join(" ");
1766
+ const header = tuning && !standard ? [`\\tuning (${tuning.map((m) => noteOf(m)).join(" ")})`] : [];
1767
+ return [...header, ...ts, texOf(bars, meter)].join(`
1768
+ `);
1373
1769
  }
1374
-
1375
1770
  // src/convert/chord-sheet.ts
1376
1771
  function chordsOf(line) {
1377
1772
  const found = [];
@@ -2106,5 +2501,5 @@ export {
2106
2501
  textTabToAlphaTex
2107
2502
  };
2108
2503
 
2109
- //# debugId=88C605D20363676064756E2164756E21
2504
+ //# debugId=793BC5718CFFD45C64756E2164756E21
2110
2505
  //# sourceMappingURL=index.js.map