@dsebastien/music-notation 0.11.0 → 0.13.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.
@@ -135,6 +135,102 @@ function titleWidth(title) {
135
135
  }
136
136
  return Math.ceil(width);
137
137
  }
138
+ var MAX_TITLE_LINES = 3;
139
+ var TITLE_LINE = 17;
140
+ function titleLineWidth(text) {
141
+ if (!text)
142
+ return 0;
143
+ let width = 8;
144
+ for (const ch of text) {
145
+ const code = ch.codePointAt(0);
146
+ width += code > 591 ? 15 : ch === " " || ".,:;'!|".includes(ch) ? 4 : "()[]-/".includes(ch) || "iljfrt".includes(ch) ? 5 : "mwMW".includes(ch) ? 12 : /[A-Z0-9#♯♭]/.test(ch) ? 9.5 : 7.8;
147
+ }
148
+ return Math.ceil(width);
149
+ }
150
+ function titleLines(title, width) {
151
+ const fits = (text) => titleLineWidth(text) <= width;
152
+ const squeeze = (text) => ({
153
+ text,
154
+ textLength: fits(text) ? null : Math.max(1, width - 8)
155
+ });
156
+ if (fits(title))
157
+ return [{ text: title, textLength: null }];
158
+ const phrases = title.split(/(?<=,)\s+|\s+(?=\()/).flatMap((phrase) => fits(phrase) ? [phrase] : phrase.split(/\s+/)).filter(Boolean);
159
+ const lines = [];
160
+ let line = "";
161
+ for (const phrase of phrases) {
162
+ const next = line ? `${line} ${phrase}` : phrase;
163
+ if (!line || fits(next))
164
+ line = next;
165
+ else {
166
+ lines.push(line);
167
+ line = phrase;
168
+ }
169
+ }
170
+ if (line)
171
+ lines.push(line);
172
+ if (lines.length > MAX_TITLE_LINES) {
173
+ const kept = lines.slice(0, MAX_TITLE_LINES - 1);
174
+ kept.push(lines.slice(MAX_TITLE_LINES - 1).join(" "));
175
+ return kept.map(squeeze);
176
+ }
177
+ return lines.map(squeeze);
178
+ }
179
+ function drawTitle(doc, root, lines, x, y) {
180
+ const NS = "http://www.w3.org/2000/svg";
181
+ const text = doc.createElementNS(NS, "text");
182
+ text.setAttribute("class", "mn-title");
183
+ text.setAttribute("x", String(x));
184
+ text.setAttribute("y", String(y));
185
+ text.setAttribute("text-anchor", "middle");
186
+ const squeeze = (el, line) => {
187
+ if (line.textLength === null)
188
+ return;
189
+ el.setAttribute("textLength", String(line.textLength));
190
+ el.setAttribute("lengthAdjust", "spacingAndGlyphs");
191
+ };
192
+ if (lines.length === 1) {
193
+ text.textContent = lines[0].text;
194
+ squeeze(text, lines[0]);
195
+ } else {
196
+ lines.forEach((line, i) => {
197
+ const span = doc.createElementNS(NS, "tspan");
198
+ span.setAttribute("x", String(x));
199
+ if (i > 0)
200
+ span.setAttribute("dy", String(TITLE_LINE));
201
+ span.textContent = i > 0 ? ` ${line.text}` : line.text;
202
+ squeeze(span, line);
203
+ text.appendChild(span);
204
+ });
205
+ }
206
+ root.setAttribute("data-mn-title-lines", String(lines.length));
207
+ root.appendChild(text);
208
+ return text;
209
+ }
210
+ function alignTitleLines(diagrams) {
211
+ const list = [...diagrams].filter((d) => d.hasAttribute("data-mn-title-lines"));
212
+ const most = Math.max(0, ...list.map((d) => Number(d.getAttribute("data-mn-title-lines"))));
213
+ for (const d of list) {
214
+ const missing = most - Number(d.getAttribute("data-mn-title-lines"));
215
+ if (missing <= 0)
216
+ continue;
217
+ const shift = missing * TITLE_LINE;
218
+ const doc = d.ownerDocument;
219
+ const g = doc.createElementNS("http://www.w3.org/2000/svg", "g");
220
+ g.setAttribute("class", "mn-title-pad");
221
+ g.setAttribute("transform", `translate(0 ${shift})`);
222
+ for (const child of [...d.children]) {
223
+ if (child.tagName.toLowerCase() !== "defs")
224
+ g.appendChild(child);
225
+ }
226
+ d.appendChild(g);
227
+ const [x, y, w, h] = (d.getAttribute("viewBox") ?? "0 0 0 0").split(/\s+/).map(Number);
228
+ d.setAttribute("viewBox", `${x} ${y} ${w} ${h + shift}`);
229
+ if (d.hasAttribute("height"))
230
+ d.setAttribute("height", String(Number(d.getAttribute("height")) + shift));
231
+ d.setAttribute("data-mn-title-lines", String(most));
232
+ }
233
+ }
138
234
  function neckFrame(n) {
139
235
  const vertical = n.orientation === "vertical";
140
236
  const left = n.hand === "left";
@@ -286,7 +382,7 @@ function renderGuitarDiagram(doc, voicing, options = {}) {
286
382
  const fromNut = capo > 0 && options.fretsFrom === "nut";
287
383
  const capoFret = fromNut ? capo : null;
288
384
  const caption = capo && options.caption !== false ? capoCaption(capo, options.sounds) : undefined;
289
- const frame = neckFrame({
385
+ const layout = {
290
386
  orientation,
291
387
  hand: options.hand ?? "right",
292
388
  across: (strings - 1) * SPACING,
@@ -295,8 +391,13 @@ function renderGuitarDiagram(doc, voicing, options = {}) {
295
391
  after: 10,
296
392
  low: vertical || base > 1 ? BASE : 10,
297
393
  high: vertical ? 14 : 10,
298
- top: options.title ? TITLE : 4,
299
- minWidth: Math.max(titleWidth(options.title), titleWidth(caption))
394
+ top: 4,
395
+ minWidth: titleWidth(caption)
396
+ };
397
+ const lines = options.title ? titleLines(options.title, neckFrame(layout).width) : [];
398
+ const frame = neckFrame({
399
+ ...layout,
400
+ top: lines.length ? TITLE + (lines.length - 1) * TITLE_LINE : 4
300
401
  });
301
402
  const across = (string) => string * SPACING;
302
403
  const along = (row) => row * ROW;
@@ -319,14 +420,8 @@ function renderGuitarDiagram(doc, voicing, options = {}) {
319
420
  root.setAttribute("data-mn-capo", String(capo));
320
421
  root.setAttribute("data-mn-frets-from", fromNut ? "nut" : "capo");
321
422
  }
322
- if (options.title) {
323
- root.appendChild(svgText(doc, options.title, {
324
- class: "mn-title",
325
- x: frame.width / 2,
326
- y: 15,
327
- "text-anchor": "middle"
328
- }));
329
- }
423
+ if (lines.length)
424
+ drawTitle(doc, root, lines, frame.width / 2, 15);
330
425
  for (let row = 0;row <= rows; row++) {
331
426
  const cls = row === 0 && base === 1 && (!capo || fromNut) ? "mn-nut" : "mn-fret";
332
427
  root.appendChild(svgLine(doc, at(0, row), at(strings - 1, row), cls));
@@ -1806,6 +1901,21 @@ function parseTuning(text) {
1806
1901
  }
1807
1902
  return midis;
1808
1903
  }
1904
+ function tuningNames(text) {
1905
+ const trimmed = text.trim();
1906
+ const named = NAMED.get(trimmed.toLowerCase().replace(/\s*\(.*\)$/, ""));
1907
+ if (named)
1908
+ return tuningNames(named);
1909
+ if (!parseTuning(trimmed))
1910
+ return null;
1911
+ const spaced = trimmed.split(/[\s,]+/).filter(Boolean);
1912
+ const names = spaced.length > 1 ? spaced : trimmed.match(/[A-G][#♯b♭]?|[a-g][#♯♭]?/g) ?? [];
1913
+ return names.map((n) => {
1914
+ const letter = n.charAt(0).toUpperCase();
1915
+ const accidental = n.slice(1).replace(/-?\d+$/, "").replace("♯", "#").replace("♭", "b");
1916
+ return letter + accidental;
1917
+ });
1918
+ }
1809
1919
 
1810
1920
  // src/keyboard/piano-chord.ts
1811
1921
  import { Note as Note4 } from "tonal";
@@ -2154,6 +2264,11 @@ function triadFingering(voicing) {
2154
2264
  ][inversion];
2155
2265
  return withBass(fingers);
2156
2266
  }
2267
+ function autoVoicingHand(voicing) {
2268
+ if (voicing.hands || voicing.style !== "rootless" && voicing.style !== "shell")
2269
+ return null;
2270
+ return voicing.pitches[0] < 60 ? "left" : "right";
2271
+ }
2157
2272
  function jazzFingering(voicing) {
2158
2273
  const both = voicing.hands === "left+right";
2159
2274
  const chord = both ? voicing.right : voicing.pitches;
@@ -4074,6 +4189,28 @@ function playStrum(pattern, options = {}) {
4074
4189
 
4075
4190
  // src/playback/progression.ts
4076
4191
  var PROGRESSION_STRUMS = ["beats", "bar", "arpeggio"];
4192
+ function spansOf(chords, beatsPerBar) {
4193
+ const spans = [];
4194
+ const chordAt = [];
4195
+ let at = 0;
4196
+ chords.forEach((chord, i) => {
4197
+ const given = chord.beats;
4198
+ const length = given === undefined || !Number.isFinite(given) ? beatsPerBar : Math.max(1, Math.round(given));
4199
+ spans.push({ start: at, length });
4200
+ for (let k = 0;k < length; k++)
4201
+ chordAt.push(i);
4202
+ at += length;
4203
+ });
4204
+ const bars = Math.max(1, Math.ceil(at / beatsPerBar));
4205
+ const last = spans[spans.length - 1];
4206
+ if (last) {
4207
+ const end = bars * beatsPerBar;
4208
+ last.length += end - at;
4209
+ while (chordAt.length < end)
4210
+ chordAt.push(spans.length - 1);
4211
+ }
4212
+ return { spans, chordAt, bars };
4213
+ }
4077
4214
  var CLICK2 = { first: 88, beat: 84, other: 81, duration: 0.05 };
4078
4215
  var CLICK_VELOCITY = { first: 92, beat: 76, other: 62 };
4079
4216
  function patternBars(pattern) {
@@ -4083,8 +4220,10 @@ function patternBars(pattern) {
4083
4220
  bars.push(pattern.slots.slice(i, i + perBar));
4084
4221
  return bars.length ? bars : [[]];
4085
4222
  }
4086
- function strumScoreOf(bars, beatsPerBar, perPulse, strum, pattern) {
4223
+ function strumScoreOf(chords, timeline, beatsPerBar, perPulse, strum, pattern) {
4087
4224
  const plain = { accent: false, ghost: false };
4225
+ const pitchesAt = (beat) => [...chords[timeline.chordAt[beat] ?? 0].pitches];
4226
+ const bars = Array.from({ length: timeline.bars }, (_, b) => b);
4088
4227
  if (pattern) {
4089
4228
  const own = patternBars(pattern);
4090
4229
  return {
@@ -4092,24 +4231,29 @@ function strumScoreOf(bars, beatsPerBar, perPulse, strum, pattern) {
4092
4231
  beatsPerBar: pattern.beatsPerBar,
4093
4232
  slotsPerPulse: pattern.slotsPerPulse,
4094
4233
  swing: pattern.swing,
4095
- slots: bars.flatMap((bar, b) => own[b % own.length].map((s) => ({
4234
+ slots: bars.flatMap((b) => own[b % own.length].map((s, k) => ({
4096
4235
  stroke: s.stroke,
4097
4236
  accent: s.accent,
4098
4237
  ghost: s.ghost,
4099
- pitches: [...bar.pitches]
4238
+ pitches: pitchesAt(b * beatsPerBar + Math.floor(k / pattern.slotsPerBeat))
4100
4239
  })))
4101
4240
  };
4102
4241
  }
4242
+ const starts = new Set(timeline.spans.map((s) => s.start));
4103
4243
  return {
4104
4244
  slotsPerBeat: 1,
4105
4245
  beatsPerBar,
4106
4246
  slotsPerPulse: perPulse,
4107
4247
  swing: null,
4108
- slots: bars.flatMap((bar) => Array.from({ length: beatsPerBar }, (_, beat) => ({
4109
- ...plain,
4110
- stroke: strum === "bar" && beat > 0 || beat % perPulse ? "rest" : "down",
4111
- pitches: [...bar.pitches]
4112
- })))
4248
+ slots: bars.flatMap((b) => Array.from({ length: beatsPerBar }, (_, beat) => {
4249
+ const at = b * beatsPerBar + beat;
4250
+ const struck = strum === "bar" ? beat === 0 || starts.has(at) : beat % perPulse === 0;
4251
+ return {
4252
+ ...plain,
4253
+ stroke: struck ? "down" : "rest",
4254
+ pitches: pitchesAt(at)
4255
+ };
4256
+ }))
4113
4257
  };
4114
4258
  }
4115
4259
  function arpeggioOrder(pitches) {
@@ -4138,6 +4282,7 @@ function progressionEvents(bars, options = {}) {
4138
4282
  const bpm = tempoOf(options.bpm, compound);
4139
4283
  const tail = Math.max(0, options.tail ?? 1);
4140
4284
  const spread = options.spread;
4285
+ const timeline = spansOf(bars, beatsPerBar);
4141
4286
  let beat;
4142
4287
  let events;
4143
4288
  if (strum === "arpeggio" && !pattern) {
@@ -4145,29 +4290,38 @@ function progressionEvents(bars, options = {}) {
4145
4290
  const start = options.countIn ? beatsPerBar * beat : 0;
4146
4291
  const slotsPerBeat = beatUnit >= 8 ? 1 : 8 / beatUnit;
4147
4292
  const slot = beat / slotsPerBeat;
4148
- const end = start + bars.length * beatsPerBar * beat;
4293
+ const end = start + timeline.bars * beatsPerBar * beat;
4149
4294
  events = [];
4150
- bars.forEach((bar, b) => {
4151
- const order = arpeggioOrder(bar.pitches);
4295
+ const slots = Math.max(1, Math.round(beatsPerBar * slotsPerBeat));
4296
+ for (let b = 0;b < timeline.bars; b++) {
4152
4297
  const barStart = start + b * beatsPerBar * beat;
4153
- const barEnd = b === bars.length - 1 ? end + tail : barStart + beatsPerBar * beat;
4154
- const slots = Math.max(1, Math.round(beatsPerBar * slotsPerBeat));
4155
- for (let k = 0;k < slots && order.length; k++) {
4298
+ const barEnd = barStart + beatsPerBar * beat;
4299
+ for (let k = 0;k < slots; k++) {
4300
+ const at = b * beatsPerBar + Math.floor(k / slotsPerBeat);
4301
+ const index = timeline.chordAt[at] ?? 0;
4302
+ const span = timeline.spans[index];
4303
+ const order = arpeggioOrder(bars[index].pitches);
4304
+ if (!order.length)
4305
+ continue;
4306
+ const from = Math.max(span.start * slotsPerBeat, b * slots);
4307
+ const n = b * slots + k - from;
4156
4308
  const time = barStart + k * slot;
4309
+ const spanEnd = start + (span.start + span.length) * beat;
4310
+ const ring = Math.min(barEnd, spanEnd);
4157
4311
  const counted = k % (slotsPerBeat * perPulse) === 0;
4158
4312
  events.push({
4159
- midi: order[k % order.length],
4313
+ midi: order[n % order.length],
4160
4314
  time,
4161
- duration: Math.max(0.06, barEnd - time),
4315
+ duration: Math.max(0.06, (ring >= end ? end + tail : ring) - time),
4162
4316
  velocity: k === 0 ? 92 : counted ? 80 : 72
4163
4317
  });
4164
4318
  }
4165
- });
4319
+ }
4166
4320
  if (options.countIn)
4167
4321
  for (let i = 0;i < beatsPerBar; i++)
4168
4322
  events.push(clickAt(i * beat, i, perPulse, true));
4169
4323
  } else {
4170
- const score = strumScoreOf(bars, beatsPerBar, perPulse, strum === "arpeggio" ? "beats" : strum, pattern);
4324
+ const score = strumScoreOf(bars, timeline, beatsPerBar, perPulse, strum === "arpeggio" ? "beats" : strum, pattern);
4171
4325
  const pulse = score.slotsPerPulse ?? score.slotsPerBeat;
4172
4326
  beat = 60 / bpm / pulse * score.slotsPerBeat;
4173
4327
  events = strumEvents(score, {
@@ -4181,17 +4335,26 @@ function progressionEvents(bars, options = {}) {
4181
4335
  const start = options.countIn ? beatsPerBar * beat : 0;
4182
4336
  const barLength = beatsPerBar * beat;
4183
4337
  if (options.click ?? true)
4184
- bars.forEach((_, b) => {
4338
+ for (let b = 0;b < timeline.bars; b++)
4185
4339
  for (let i = 0;i < beatsPerBar; i += perPulse)
4186
4340
  events.push(clickAt(start + b * barLength + i * beat, i, perPulse, false));
4187
- });
4188
4341
  events.sort((a, b) => a.time - b.time);
4189
- const strums = bars.map((_, b) => ({
4342
+ const strums = timeline.spans.map((span, i) => ({
4343
+ slot: i,
4344
+ time: start + span.start * beat,
4345
+ duration: span.length * beat
4346
+ }));
4347
+ const barTimes = Array.from({ length: timeline.bars }, (_, b) => ({
4190
4348
  slot: b,
4191
4349
  time: start + b * barLength,
4192
4350
  duration: barLength
4193
4351
  }));
4194
- return { events, length: start + bars.length * barLength, strums, bars: strums };
4352
+ return { events, length: start + timeline.bars * barLength, strums, bars: barTimes };
4353
+ }
4354
+ function chordOfBars(bars, beatsPerBar) {
4355
+ const perBar = Math.min(16, Math.max(1, Math.round(beatsPerBar) || 4));
4356
+ const timeline = spansOf(bars, perBar);
4357
+ return Array.from({ length: timeline.bars }, (_, b) => timeline.chordAt[b * perBar] ?? 0);
4195
4358
  }
4196
4359
  var MAX_PROGRESSION_BARS = 256;
4197
4360
  function progressionPitches(chord, sound = "guitar", tuning = STANDARD_TUNING, voicings) {
@@ -4243,7 +4406,7 @@ function runProgression(bars, options, player, settings, timers, onEnd, follow)
4243
4406
  return runPasses((s, first, id) => {
4244
4407
  pass = id;
4245
4408
  return make(s, first, id);
4246
- }, player, settings, timers, onEnd, follow ? (strums, current) => follow(strums, current, pass) : undefined);
4409
+ }, player, settings, timers, onEnd, follow ? (strums, current, made) => follow(strums, current, pass, made) : undefined);
4247
4410
  }
4248
4411
  function playProgression(chords, options = {}) {
4249
4412
  const sound = options.sound === "piano" ? "piano" : "guitar";
@@ -4254,14 +4417,18 @@ function playProgression(chords, options = {}) {
4254
4417
  if (!chords.length)
4255
4418
  throw new Error("playProgression needs at least one chord");
4256
4419
  const bars = chords.slice(0, MAX_PROGRESSION_BARS).map((c) => {
4257
- if (typeof c !== "string")
4258
- return { chord: c.chord ?? null, pitches: [...c.pitches] };
4259
- const read = readChord(c);
4420
+ const name = typeof c === "string" ? c : c.chord ?? null;
4421
+ const beats = typeof c === "string" ? undefined : c.beats;
4422
+ const timed = beats === undefined ? {} : { beats };
4423
+ if (typeof c !== "string" && c.pitches)
4424
+ return { chord: name, pitches: [...c.pitches], ...timed };
4425
+ const read = name ? readChord(name) : null;
4260
4426
  if (!read)
4261
- throw new Error(`Didn't recognize the chord "${c}"`);
4427
+ throw new Error(`Didn't recognize the chord "${name ?? ""}"`);
4262
4428
  return {
4263
- chord: c,
4264
- pitches: progressionPitches(read.symbol, sound, tuning, options.voicings)
4429
+ chord: name,
4430
+ pitches: progressionPitches(read.symbol, sound, tuning, options.voicings),
4431
+ ...timed
4265
4432
  };
4266
4433
  });
4267
4434
  const pattern = typeof options.pattern === "string" ? parseStrum(options.pattern) : options.pattern ?? null;
@@ -4279,13 +4446,29 @@ function playProgression(chords, options = {}) {
4279
4446
  volume: Number.isFinite(options.volume) ? Math.min(1, Math.max(0, options.volume)) : 0.8
4280
4447
  };
4281
4448
  const timers = win ?? globalThis;
4282
- const onBar = options.onBar;
4449
+ const { onBar, onChord } = options;
4450
+ const perBar = pattern ? pattern.beatsPerBar : options.beatsPerBar ?? 4;
4451
+ const barChords = chordOfBars(bars, perBar);
4283
4452
  const handle = runProgression(bars, {
4284
4453
  ...options.beatsPerBar === undefined ? {} : { beatsPerBar: options.beatsPerBar },
4285
4454
  ...options.beatUnit === undefined ? {} : { beatUnit: options.beatUnit },
4286
4455
  ...options.strum ? { strum: options.strum } : {},
4287
4456
  pattern
4288
- }, () => player, () => settings, timers, options.onEnd, onBar ? (timings, current, pass) => followTimes(timers, timings, (t) => onBar(t.slot, bars[t.slot]?.chord ?? null, pass), startsReported(current) ? Infinity : START_WAIT) : undefined);
4457
+ }, () => player, () => settings, timers, options.onEnd, onBar || onChord ? (timings, current, pass, made) => {
4458
+ const wait = startsReported(current) ? Infinity : START_WAIT;
4459
+ const followers = [
4460
+ ...onChord ? [
4461
+ followTimes(timers, timings, (t) => onChord(t.slot, bars[t.slot]?.chord ?? null, pass), wait)
4462
+ ] : [],
4463
+ ...onBar ? [
4464
+ followTimes(timers, made.bars ?? timings, (t) => onBar(t.slot, bars[barChords[t.slot] ?? 0]?.chord ?? null, pass), wait)
4465
+ ] : []
4466
+ ];
4467
+ return {
4468
+ heard: () => followers.forEach((f) => f.heard()),
4469
+ stop: () => followers.forEach((f) => f.stop())
4470
+ };
4471
+ } : undefined);
4289
4472
  return {
4290
4473
  stop: () => handle.stop(),
4291
4474
  update(changes) {
@@ -4712,6 +4895,59 @@ function renderChordsUsed(doc, song, options) {
4712
4895
 
4713
4896
  // src/chords/chart.ts
4714
4897
  var PLACEMENTS = new Set(["top", "bottom", "off"]);
4898
+ function lineBeats(segments, playable, beatsPerBar, perPulse) {
4899
+ if (!segments.some((s) => s.text.includes("|")))
4900
+ return { measured: false, steps: [] };
4901
+ const steps = [];
4902
+ const counted = Math.max(1, Math.round(beatsPerBar / perPulse));
4903
+ let bar = [];
4904
+ let silent = null;
4905
+ let opened = false;
4906
+ const close = (ended) => {
4907
+ if (bar.length) {
4908
+ const n = bar.length;
4909
+ const slashed = bar.reduce((sum, c) => sum + 1 + c.slashes, 0);
4910
+ const dotted = bar.reduce((sum, c) => sum + c.dots, 0);
4911
+ let lengths;
4912
+ if (bar.every((c) => c.dots) && dotted === counted)
4913
+ lengths = bar.map((c) => c.dots * perPulse);
4914
+ else if (bar.some((c) => c.slashes) && slashed === counted)
4915
+ lengths = bar.map((c) => (1 + c.slashes) * perPulse);
4916
+ else {
4917
+ const [whole, unit] = n <= counted ? [counted, perPulse] : [beatsPerBar, 1];
4918
+ const base = Math.floor(whole / n);
4919
+ const extra = whole % n;
4920
+ lengths = bar.map((_, i) => Math.max(1, (base + (i < extra ? 1 : 0)) * unit));
4921
+ }
4922
+ bar.forEach((c, i) => steps.push({ segment: c.segment, beats: lengths[i] }));
4923
+ } else if (silent !== null)
4924
+ steps.push({ rest: beatsPerBar, segment: silent });
4925
+ else if (ended && opened)
4926
+ steps.push({ hold: beatsPerBar });
4927
+ bar = [];
4928
+ silent = null;
4929
+ opened = ended || opened;
4930
+ };
4931
+ segments.forEach((segment, i) => {
4932
+ if (segment.chord !== null) {
4933
+ if (playable(segment.chord))
4934
+ bar.push({ segment: i, slashes: 0, dots: 0 });
4935
+ else
4936
+ silent ??= i;
4937
+ }
4938
+ for (const ch of segment.text) {
4939
+ if (ch === "|")
4940
+ close(true);
4941
+ else if (ch === "/" && bar.length)
4942
+ bar[bar.length - 1].slashes++;
4943
+ else if (ch === "." && bar.length)
4944
+ bar[bar.length - 1].dots++;
4945
+ }
4946
+ });
4947
+ if (bar.length || silent !== null)
4948
+ close(false);
4949
+ return { measured: true, steps };
4950
+ }
4715
4951
  function timeOf(text) {
4716
4952
  if (!text)
4717
4953
  return null;
@@ -4733,15 +4969,75 @@ function guessedKey(song) {
4733
4969
  const found = chords.length ? findKey(chords) : null;
4734
4970
  return found ? `${found.tonic}${found.mode === "minor" ? "m" : ""}` : null;
4735
4971
  }
4736
- function renderChart(doc, song, options = {}) {
4737
- const extra = options.transpose ?? 0;
4972
+ function transposerOf(song, extra) {
4738
4973
  const semitones = song.transpose + (Number.isFinite(extra) ? Math.round(extra) : 0);
4739
4974
  const key = song.key ? transposeKey(song.key, semitones) : null;
4740
4975
  const flats = key ? keyPrefersFlats(key) : undefined;
4741
4976
  const from = song.key ?? (semitones % 12 ? guessedKey(song) : null);
4742
4977
  const move = from ? keyMove(from, semitones) : null;
4743
4978
  const spelling = move ?? flats;
4744
- const chord = (symbol) => transposeChord(symbol, semitones, spelling);
4979
+ return {
4980
+ semitones,
4981
+ key,
4982
+ spelling,
4983
+ chord: (symbol) => transposeChord(symbol, semitones, spelling)
4984
+ };
4985
+ }
4986
+ function meterOf(song) {
4987
+ let beatsPerBar = 4;
4988
+ let beatUnit = 4;
4989
+ const time = timeOf(song.time);
4990
+ if (time)
4991
+ ({ beatsPerBar, beatUnit } = parseTime(time));
4992
+ return { beatsPerBar, beatUnit, perPulse: isCompound(beatsPerBar, beatUnit) ? 3 : 1 };
4993
+ }
4994
+ function chartChords(song, options = {}) {
4995
+ const { chord } = transposerOf(song, options.transpose);
4996
+ const { beatsPerBar, beatUnit, perPulse } = meterOf(song);
4997
+ const playable = (written) => {
4998
+ const shown = chord(written);
4999
+ return Boolean(findDefinition(song.definitions, written)?.diagram || parseChord(shown) && chordNoteSet(shown));
5000
+ };
5001
+ const chords = [];
5002
+ const hold = (beats) => {
5003
+ const last = chords[chords.length - 1];
5004
+ if (last)
5005
+ last.beats = (last.beats ?? beatsPerBar) + beats;
5006
+ };
5007
+ for (const section of song.sections)
5008
+ for (const line of section.lines) {
5009
+ if (line.kind !== "lyrics")
5010
+ continue;
5011
+ const { measured, steps } = lineBeats(line.segments, playable, beatsPerBar, perPulse);
5012
+ if (!measured) {
5013
+ for (const s of line.segments)
5014
+ if (s.chord !== null && playable(s.chord))
5015
+ chords.push({ chord: chord(s.chord) });
5016
+ continue;
5017
+ }
5018
+ for (const step of steps) {
5019
+ if ("hold" in step)
5020
+ hold(step.hold);
5021
+ else if ("rest" in step)
5022
+ chords.push({ chord: null, pitches: [], beats: step.rest });
5023
+ else
5024
+ chords.push({
5025
+ chord: chord(line.segments[step.segment].chord),
5026
+ beats: step.beats
5027
+ });
5028
+ }
5029
+ }
5030
+ const tempo = Number(song.tempo);
5031
+ return {
5032
+ chords,
5033
+ beatsPerBar,
5034
+ beatUnit,
5035
+ tempo: song.tempo && Number.isFinite(tempo) && tempo >= 20 && tempo <= 240 ? tempo : null
5036
+ };
5037
+ }
5038
+ function renderChart(doc, song, options = {}) {
5039
+ const { semitones, key, spelling, chord } = transposerOf(song, options.transpose);
5040
+ const meter = meterOf(song);
4745
5041
  const drawing = {
4746
5042
  instrument: song.instrument ?? (options.instrument === "piano" ? "piano" : "guitar"),
4747
5043
  ...options.voicings ? { voicings: options.voicings } : {},
@@ -4765,6 +5061,11 @@ function renderChart(doc, song, options = {}) {
4765
5061
  if (song.tempo && Number.isFinite(tempo) && tempo >= 20 && tempo <= 240)
4766
5062
  root.setAttribute("data-mn-tempo", String(Math.round(tempo)));
4767
5063
  let bars = 0;
5064
+ let last = null;
5065
+ const setBeats = (mark, beats) => {
5066
+ mark.setAttribute("data-mn-beats", String(beats));
5067
+ last = { mark, beats };
5068
+ };
4768
5069
  const sounds = new Map;
4769
5070
  const soundOf = (written, shown) => {
4770
5071
  const known = sounds.get(shown);
@@ -4851,7 +5152,13 @@ function renderChart(doc, song, options = {}) {
4851
5152
  const chordsOnly = line.segments.every((s) => !s.text.trim());
4852
5153
  if (chordsOnly)
4853
5154
  row.classList.add("mn-chords-only");
4854
- for (const segment of line.segments) {
5155
+ const timing = lineBeats(line.segments, (written) => soundOf(written, chord(written)) !== null, meter.beatsPerBar, meter.perPulse);
5156
+ const marks = new Map;
5157
+ const rests = new Map;
5158
+ for (const step of timing.steps)
5159
+ if ("rest" in step)
5160
+ rests.set(step.segment, step.rest);
5161
+ line.segments.forEach((segment, index) => {
4855
5162
  const seg = html(doc, "span", "mn-seg");
4856
5163
  const mark = html(doc, "span", "mn-chord", segment.chord === null ? "" : chord(segment.chord));
4857
5164
  if (segment.chord !== null) {
@@ -4861,11 +5168,33 @@ function renderChart(doc, song, options = {}) {
4861
5168
  mark.setAttribute("data-mn-bar", String(bars++));
4862
5169
  mark.setAttribute("data-mn-chord", shown);
4863
5170
  mark.setAttribute("data-mn-voicing", voicing);
5171
+ marks.set(index, mark);
5172
+ if (!timing.measured)
5173
+ last = { mark, beats: null };
5174
+ } else if (rests.has(index)) {
5175
+ mark.setAttribute("data-mn-bar", String(bars++));
5176
+ mark.setAttribute("data-mn-rest", "");
5177
+ marks.set(index, mark);
4864
5178
  }
4865
5179
  }
4866
5180
  seg.appendChild(mark);
4867
5181
  seg.appendChild(html(doc, "span", "mn-lyric", segment.text || (chordsOnly ? "" : " ")));
4868
5182
  row.appendChild(seg);
5183
+ });
5184
+ for (const step of timing.steps) {
5185
+ const held = last;
5186
+ if ("hold" in step) {
5187
+ if (held)
5188
+ setBeats(held.mark, (held.beats ?? meter.beatsPerBar) + step.hold);
5189
+ } else if ("rest" in step) {
5190
+ const mark = marks.get(step.segment);
5191
+ if (mark)
5192
+ setBeats(mark, step.rest);
5193
+ } else {
5194
+ const mark = marks.get(step.segment);
5195
+ if (mark)
5196
+ setBeats(mark, step.beats);
5197
+ }
4869
5198
  }
4870
5199
  el.appendChild(row);
4871
5200
  }
@@ -4908,7 +5237,7 @@ function renderFretboard(doc, set, options = {}) {
4908
5237
  const vertical = orientation === "vertical";
4909
5238
  const openW = from === 0 ? OPEN_W : 0;
4910
5239
  const acrossLength = (strings - 1) * STRING_GAP;
4911
- const frame = neckFrame({
5240
+ const layout = {
4912
5241
  orientation,
4913
5242
  hand: options.hand ?? "right",
4914
5243
  across: acrossLength,
@@ -4917,8 +5246,13 @@ function renderFretboard(doc, set, options = {}) {
4917
5246
  after: 8,
4918
5247
  low: NUMBERS,
4919
5248
  high: 12,
4920
- top: options.title ? TITLE3 : 0,
4921
- minWidth: Math.max(titleWidth(options.title), titleWidth(caption))
5249
+ top: 0,
5250
+ minWidth: titleWidth(caption)
5251
+ };
5252
+ const lines = options.title ? titleLines(options.title, neckFrame(layout).width) : [];
5253
+ const frame = neckFrame({
5254
+ ...layout,
5255
+ top: lines.length ? TITLE3 + (lines.length - 1) * TITLE_LINE : 0
4922
5256
  });
4923
5257
  const across = (string) => string * STRING_GAP;
4924
5258
  const wire = (fret) => openW + (fret - first + 1) * FRET_W;
@@ -4935,14 +5269,8 @@ function renderFretboard(doc, set, options = {}) {
4935
5269
  root.setAttribute("data-mn-capo", String(capo));
4936
5270
  root.setAttribute("data-mn-frets-from", fromNut ? "nut" : "capo");
4937
5271
  }
4938
- if (options.title) {
4939
- root.appendChild(svgText(doc, options.title, {
4940
- class: "mn-title",
4941
- x: frame.width / 2,
4942
- y: 15,
4943
- "text-anchor": "middle"
4944
- }));
4945
- }
5272
+ if (lines.length)
5273
+ drawTitle(doc, root, lines, frame.width / 2, 15);
4946
5274
  const markOf = (s, fret) => {
4947
5275
  const pitch = tuning[s] + fret;
4948
5276
  const member = memberOf(set, pitch);
@@ -5153,6 +5481,11 @@ function parseFingerList(text) {
5153
5481
  }
5154
5482
  return fingers;
5155
5483
  }
5484
+ function isBothHandsFingering(text) {
5485
+ return /^(auto)?[\s:(,-]*both(?:[\s-]*hands?)?\)?$/.test(text.trim().toLowerCase());
5486
+ }
5487
+ var AUTO_FINGERING_NEEDS_SCALE = "fingering: auto goes with a major or minor scale (scale: G major): write one finger per note, e.g. fingering: 1 2 3 4 5";
5488
+ var autoFingeringUnknown = (scale) => `fingering: auto knows the major, natural minor, harmonic minor and melodic minor scales: write the fingers for ${scale}, root to root, e.g. fingering: 1 2 3 1 2 3 4 5`;
5156
5489
  function autoFingeringHand(text) {
5157
5490
  const m = /^(auto)?[\s:(,-]*(?:(left|right)(?:[\s-]*hand)?)?\)?$/.exec(text.trim().toLowerCase());
5158
5491
  if (!m || !m[1] && !m[2])
@@ -5345,6 +5678,165 @@ function detectChordFromFrets(frets, tuning = STANDARD) {
5345
5678
  return detectChordFromPitches(pitches);
5346
5679
  }
5347
5680
 
5681
+ // src/chord/fingering-words.ts
5682
+ import { Note as Note5 } from "tonal";
5683
+ var ordinal = (n) => `${n}${n % 100 >= 11 && n % 100 <= 13 ? "th" : ["th", "st", "nd", "rd"][n % 10] ?? "th"}`;
5684
+ var GUITAR_FINGERS = {
5685
+ "1": "Index",
5686
+ "2": "Middle",
5687
+ "3": "Ring",
5688
+ "4": "Pinky",
5689
+ T: "Thumb"
5690
+ };
5691
+ var PIANO_FINGERS = {
5692
+ "1": "thumb",
5693
+ "2": "index finger",
5694
+ "3": "middle finger",
5695
+ "4": "ring finger",
5696
+ "5": "little finger"
5697
+ };
5698
+ var capitalized = (s) => s.charAt(0).toUpperCase() + s.slice(1);
5699
+ var andList = (items) => items.length < 2 ? items[0] ?? "" : `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`;
5700
+ var letter = (midi) => noteOf(midi).replace(/-?\d+$/, "");
5701
+ function stringNames(tuning, count, spelled) {
5702
+ const letters = tuning?.map((p, s) => spelled?.[s] ?? letter(p)) ?? [];
5703
+ const repeated = letters.filter((name, i) => letters.indexOf(name) !== i);
5704
+ const byName = tuning !== null && (repeated.length === 0 || repeated.length === 1 && letters[0] === letters[count - 1] && count > 2);
5705
+ return Array.from({ length: count }, (_, s) => {
5706
+ if (!byName)
5707
+ return numbered(tuning, count, s, spelled);
5708
+ const name = letters[s];
5709
+ if (repeated.length && s === 0)
5710
+ return `the low ${name} string`;
5711
+ if (repeated.length && s === count - 1)
5712
+ return `the high ${name} string`;
5713
+ return `the ${name} string`;
5714
+ });
5715
+ }
5716
+ function numbered(tuning, count, s, spelled) {
5717
+ const name = tuning ? spelled?.[s] ?? letter(tuning[s]) : null;
5718
+ return `the ${ordinal(count - s)} string${name ? ` (${name})` : ""}`;
5719
+ }
5720
+ var range = (from, to) => Array.from({ length: to - from + 1 }, (_, i) => from + i);
5721
+ var together = (names) => names.every((n) => /^the [^(]+ string$/.test(n)) ? `the ${andList(names.map((n) => n.slice(4, -7)))} strings` : andList(names);
5722
+ function guitarWords(input) {
5723
+ const { frets } = input;
5724
+ const count = frets.length;
5725
+ const tuning = input.tuning ?? (count === 6 ? STANDARD_TUNING : null);
5726
+ const spelled = input.tuningNames?.length === count ? input.tuningNames : undefined;
5727
+ const names = stringNames(tuning, count, spelled);
5728
+ const capo = input.capo ?? 0;
5729
+ const fromNut = capo > 0 && input.fretsFrom === "nut";
5730
+ const shape = frets.map((f) => f === null ? null : fromNut ? Math.max(0, f - capo) : f);
5731
+ const fingers = input.fingers?.some((f) => f) ? input.fingers : fingerVoicing(shape) ?? frets.map(() => null);
5732
+ const sentences = [];
5733
+ if (capo) {
5734
+ sentences.push(`Capo on the ${ordinal(capo)} fret${fromNut ? "" : ": frets count from the capo"}.`);
5735
+ }
5736
+ const sounding = frets.flatMap((f, s) => f !== null ? [s] : []);
5737
+ if (!sounding.length)
5738
+ return [...sentences, "Every string is muted: no note sounds."];
5739
+ const low = sounding[0];
5740
+ const high = sounding.at(-1);
5741
+ if (low === 0 && high === count - 1) {
5742
+ sentences.push(count === 6 ? "Strum all six strings." : "Strum every string.");
5743
+ } else if (high === count - 1) {
5744
+ sentences.push(`Strum from ${numbered(tuning, count, low, spelled)}.`);
5745
+ } else {
5746
+ sentences.push(`Strum from ${numbered(tuning, count, low, spelled)} to ${numbered(tuning, count, high, spelled)}.`);
5747
+ }
5748
+ const barred = new Set;
5749
+ const byFinger = new Map;
5750
+ shape.forEach((f, s) => {
5751
+ const finger = fingers[s];
5752
+ if (f !== null && f > 0 && finger)
5753
+ byFinger.set(finger, [...byFinger.get(finger) ?? [], s]);
5754
+ });
5755
+ const said = new Set;
5756
+ const fingerName = (finger) => GUITAR_FINGERS[finger] ?? `Finger ${finger}`;
5757
+ frets.forEach((fret, s) => {
5758
+ if (fret === null || shape[s] === 0)
5759
+ return;
5760
+ const finger = fingers[s];
5761
+ if (!finger) {
5762
+ sentences.push(`Press ${names[s]} at the ${ordinal(fret)} fret.`);
5763
+ return;
5764
+ }
5765
+ if (said.has(finger))
5766
+ return;
5767
+ said.add(finger);
5768
+ const strings = byFinger.get(finger).filter((t) => frets[t] === fret);
5769
+ const between = strings.length > 1 ? range(strings[0], strings.at(-1)) : [];
5770
+ const flat = between.every((t) => shape[t] === null || shape[t] >= shape[s]);
5771
+ if (strings.length > 1 && !flat) {
5772
+ sentences.push(`${fingerName(finger)} on ${together(strings.map((t) => names[t]))}, ${ordinal(fret)} fret.`);
5773
+ } else if (strings.length > 1) {
5774
+ const from = count - strings.at(-1);
5775
+ const to = count - strings[0];
5776
+ for (const t of strings)
5777
+ barred.add(t);
5778
+ sentences.push(`${fingerName(finger)} bars the ${ordinal(fret)} fret, strings ${from} to ${to}.`);
5779
+ } else {
5780
+ sentences.push(`${fingerName(finger)} on ${names[s]}, ${ordinal(fret)} fret.`);
5781
+ }
5782
+ for (const t of byFinger.get(finger)) {
5783
+ if (frets[t] !== fret) {
5784
+ sentences.push(`${fingerName(finger)} also on ${names[t]}, ${ordinal(frets[t])} fret.`);
5785
+ }
5786
+ }
5787
+ });
5788
+ const muted = frets.flatMap((f, s) => f === null && s > low && s < high ? [names[s]] : []);
5789
+ if (muted.length) {
5790
+ sentences.push(`Mute ${andList(muted)}: let a fretting finger touch ${muted.length > 1 ? "them" : "it"} lightly.`);
5791
+ }
5792
+ const open = shape.flatMap((f, s) => f === 0 && !barred.has(s) ? [names[s]] : []);
5793
+ if (open.length) {
5794
+ const where = capo ? " at the capo" : " open";
5795
+ const plural = open.length > 1;
5796
+ sentences.push(open.every((n) => /^the [^(]+ string$/.test(n)) ? `The ${andList(open.map((n) => n.slice(4, -7)))} ${plural ? "strings ring" : "string rings"}${where}.` : `${capitalized(andList(open))} ${plural ? "ring" : "rings"}${where}.`);
5797
+ }
5798
+ return sentences;
5799
+ }
5800
+ function pianoWords(input) {
5801
+ const keys = [...input.keys].sort((a, b) => a - b);
5802
+ if (!keys.length)
5803
+ return [];
5804
+ const plain = (midi) => input.names?.get(midi % 12) ?? letter(midi);
5805
+ const octaves = new Set(keys.map(plain)).size < keys.length;
5806
+ const keyName = (midi) => {
5807
+ const name = plain(midi);
5808
+ if (!octaves)
5809
+ return name;
5810
+ return `${name}${Math.floor((midi - (Note5.get(name).alt || 0)) / 12) - 1}`;
5811
+ };
5812
+ const part = (group) => {
5813
+ const withFinger = group.filter((k) => input.fingers?.has(k));
5814
+ const without = group.filter((k) => !input.fingers?.has(k)).map(keyName);
5815
+ const fingered = withFinger.map((k) => {
5816
+ const finger = input.fingers.get(k);
5817
+ return `${PIANO_FINGERS[finger] ?? `finger ${finger}`} on ${keyName(k)}`;
5818
+ });
5819
+ if (!fingered.length)
5820
+ return andList(without);
5821
+ if (!without.length)
5822
+ return fingered.join(", ");
5823
+ return `${fingered.join(", ")}, and also play ${andList(without)}`;
5824
+ };
5825
+ const hands = input.hands;
5826
+ if (!hands?.size) {
5827
+ return [
5828
+ keys.some((k) => input.fingers?.has(k)) ? `${capitalized(part(keys))}.` : `Play ${part(keys)}.`
5829
+ ];
5830
+ }
5831
+ return ["left", "right"].flatMap((hand) => {
5832
+ const group = keys.filter((k) => (hands.get(k) ?? "right") === hand);
5833
+ return group.length ? [`${capitalized(hand)} hand: ${part(group)}.`] : [];
5834
+ });
5835
+ }
5836
+ function fingeringInWords(chord) {
5837
+ return "frets" in chord ? guitarWords(chord) : pianoWords(chord);
5838
+ }
5839
+
5348
5840
  // src/blocks/block-source.ts
5349
5841
  var FIELD2 = /^([A-Za-z][\w-]*)\s*:\s*(.*)$/;
5350
5842
  function parseBlockSource(source) {
@@ -5629,6 +6121,7 @@ function exerciseTex(run, tuning, options = {}) {
5629
6121
  ...standard ? [] : [
5630
6122
  `\\tuning (${[...tuning].reverse().map((m) => noteOf(m)).join(" ")})`
5631
6123
  ],
6124
+ ...options.capo ? [`\\capo ${options.capo}`] : [],
5632
6125
  "\\ts 4 4",
5633
6126
  `${DURATION[rhythm]} ${bars.join(` |
5634
6127
  `)}`
@@ -5675,12 +6168,18 @@ function exerciseTab(notes, options = {}) {
5675
6168
  const tuning = typeof options.tuning === "string" ? parseTuning(options.tuning) : options.tuning ?? STANDARD_TUNING;
5676
6169
  if (!tuning || tuning.length < 2)
5677
6170
  throw new Error(`Unknown tuning "${String(options.tuning)}"`);
6171
+ const capo = options.capo ?? 0;
6172
+ if (!Number.isInteger(capo) || capo < 0 || capo > 12) {
6173
+ throw new Error(`capo: use a fret from 1 to 12 (0 for none), got ${String(options.capo)}`);
6174
+ }
6175
+ const sounding = capo ? capoTuning(tuning, capo) : tuning;
5678
6176
  const at = positionOf(options.position === undefined ? undefined : String(options.position), options.shape) ?? { system: "box", n: 1 };
5679
- const cells = exercisePosition(set, tuning, at, options);
5680
- return exerciseTex(exerciseRun(cells, tuning, set.root, options.direction ?? "both"), tuning, {
6177
+ const cells = exercisePosition(set, sounding, at, options);
6178
+ return exerciseTex(exerciseRun(cells, sounding, set.root, options.direction ?? "both"), tuning, {
5681
6179
  ...options.rhythm ? { rhythm: options.rhythm } : {},
5682
6180
  ...options.tempo !== undefined ? { tempo: options.tempo } : {},
5683
- ...options.title ? { title: options.title } : {}
6181
+ ...options.title ? { title: options.title } : {},
6182
+ ...capo ? { capo } : {}
5684
6183
  });
5685
6184
  }
5686
6185
 
@@ -5745,7 +6244,7 @@ var FINGER_NAMES = {
5745
6244
  "4": "pinky",
5746
6245
  T: "thumb"
5747
6246
  };
5748
- var ordinal = (n) => `${n}${n % 100 >= 11 && n % 100 <= 13 ? "th" : ["th", "st", "nd", "rd"][n % 10] ?? "th"}`;
6247
+ var ordinal2 = (n) => `${n}${n % 100 >= 11 && n % 100 <= 13 ? "th" : ["th", "st", "nd", "rd"][n % 10] ?? "th"}`;
5749
6248
  var MAX_SLIDE = 3;
5750
6249
  function stringName(tuning, s) {
5751
6250
  const name = noteOf(tuning[s]).replace(/-?\d+$/, "");
@@ -5753,7 +6252,7 @@ function stringName(tuning, s) {
5753
6252
  if (same < 2)
5754
6253
  return `the ${name} string`;
5755
6254
  if (same > 2)
5756
- return `the ${ordinal(tuning.length - s)} string (${name})`;
6255
+ return `the ${ordinal2(tuning.length - s)} string (${name})`;
5757
6256
  const lowest = tuning.findIndex((p) => noteOf(p).replace(/-?\d+$/, "") === name);
5758
6257
  return `the ${s === lowest ? "low" : "high"} ${name} string`;
5759
6258
  }
@@ -5794,7 +6293,7 @@ function move(from, fromFingers, to, tuning) {
5794
6293
  if (seen.has(f))
5795
6294
  continue;
5796
6295
  seen.add(f);
5797
- tips.push(`Keep your ${fingerName(f)} on ${stringName(tuning, s)}'s ${ordinal(to.frets[s])} fret.`);
6296
+ tips.push(`Keep your ${fingerName(f)} on ${stringName(tuning, s)}'s ${ordinal2(to.frets[s])} fret.`);
5798
6297
  }
5799
6298
  for (const s of guides) {
5800
6299
  const f = to.fingers[s];
@@ -6126,7 +6625,7 @@ function voiceLeadVoicings(symbols, options) {
6126
6625
  }
6127
6626
 
6128
6627
  // src/theory/numerals.ts
6129
- import { Note as Note5 } from "tonal";
6628
+ import { Note as Note6 } from "tonal";
6130
6629
  var MAJOR2 = ["1P", "2M", "3M", "4P", "5P", "6M", "7M"];
6131
6630
  var NATURAL_MINOR = ["1P", "2M", "3m", "4P", "5P", "6m", "7m"];
6132
6631
  var ROMAN_NUMBERS = { i: 1, ii: 2, iii: 3, iv: 4, v: 5, vi: 6, vii: 7 };
@@ -6134,13 +6633,16 @@ var keyOf = (key) => typeof key === "string" ? readKey(key) : key;
6134
6633
  function noteOn(key, degree, accidental, diminished) {
6135
6634
  const minor = key.mode === "minor" || key.mode === "aeolian";
6136
6635
  let interval = MAJOR2[degree - 1];
6137
- let shift = accidental === "#" ? 1 : accidental === "b" ? -1 : 0;
6636
+ const steps = { "##": 2, "#": 1, b: -1, bb: -2 };
6637
+ let shift = steps[accidental] ?? 0;
6138
6638
  if (minor && [3, 6, 7].includes(degree)) {
6139
6639
  interval = NATURAL_MINOR[degree - 1];
6140
- shift = accidental === "#" || !accidental && degree === 7 && diminished ? 1 : 0;
6640
+ shift = accidental === "bb" ? -1 : accidental === "#" || !accidental && degree === 7 && diminished ? 1 : accidental === "##" ? 2 : 0;
6141
6641
  }
6142
- const note = Note5.transpose(key.tonic, interval);
6143
- return shift === 0 ? note : Note5.transpose(note, shift > 0 ? "1A" : "-1A");
6642
+ let note = Note6.transpose(key.tonic, interval);
6643
+ for (let i = 0;i < Math.abs(shift); i++)
6644
+ note = Note6.transpose(note, shift > 0 ? "1A" : "-1A");
6645
+ return note;
6144
6646
  }
6145
6647
  function suffixOf(mark, lower) {
6146
6648
  let s = mark.replace(/♭/g, "b").replace(/♯/g, "#");
@@ -6171,14 +6673,14 @@ function chordFrom(root, suffix) {
6171
6673
  return parseChord(symbol) && chordNoteSet(symbol) ? symbol : null;
6172
6674
  }
6173
6675
  function bassOf(key, text) {
6174
- const m = /^([b#♭♯]?)([1-7])$/.exec(text);
6676
+ const m = /^(bb|##|[b#♭♯]?)([1-7])$/.exec(text);
6175
6677
  if (!m)
6176
6678
  return null;
6177
6679
  const accidental = m[1].replace("♭", "b").replace("♯", "#");
6178
6680
  return noteOn(key, Number(m[2]), accidental, false);
6179
6681
  }
6180
- var ROMAN2 = /^([b#♭♯]?)(VII|VI|V|IV|III|II|I|vii|vi|v|iv|iii|ii|i)(.*)$/;
6181
- var NASHVILLE = /^([b#♭♯]?)([1-7])(.*)$/;
6682
+ var ROMAN2 = /^(bb|##|[b#♭♯]?)(VII|VI|V|IV|III|II|I|vii|vi|v|iv|iii|ii|i)(.*)$/;
6683
+ var NASHVILLE = /^(bb|##|[b#♭♯]?)([1-7])(.*)$/;
6182
6684
  function readOne(key, text) {
6183
6685
  const roman = ROMAN2.exec(text);
6184
6686
  const nashville = roman ? null : NASHVILLE.exec(text);
@@ -6256,7 +6758,7 @@ function keySpelling(note, key) {
6256
6758
  const chroma = chromaOf(note);
6257
6759
  const notes = keyNotes(key);
6258
6760
  if (isMinorMode(key.mode) && notes.length === 7)
6259
- notes.push(Note5.transpose(notes[6], "1A"));
6761
+ notes.push(Note6.transpose(notes[6], "1A"));
6260
6762
  if (notes.includes(note))
6261
6763
  return note;
6262
6764
  return notes.find((n) => chromaOf(n) === chroma) ?? note;
@@ -6308,13 +6810,13 @@ function secondaryTarget(symbol, key) {
6308
6810
  if (has("3m") && has("5d")) {
6309
6811
  if (has("7M"))
6310
6812
  return null;
6311
- target = Note5.transpose(parts.root, "2m");
6813
+ target = Note6.transpose(parts.root, "2m");
6312
6814
  } else {
6313
6815
  if (!has("3M"))
6314
6816
  return null;
6315
6817
  if (set.members.some((m) => ["5d", "5A", "7M"].includes(m.interval ?? "")))
6316
6818
  return null;
6317
- target = Note5.transpose(parts.root, "-5P");
6819
+ target = Note6.transpose(parts.root, "-5P");
6318
6820
  }
6319
6821
  if (chromaOf(target) === chromaOf(key.tonic))
6320
6822
  return null;
@@ -6529,7 +7031,115 @@ function progressionChord(written, key, options = {}) {
6529
7031
  };
6530
7032
  }
6531
7033
 
7034
+ // src/theory/harmonize.ts
7035
+ import { Interval as Interval6, Key as Key2, Note as Note7, Scale as Scale6 } from "tonal";
7036
+ var HARMONIZE_KINDS = ["triads", "sevenths", "sus", "power"];
7037
+ var MAJOR_FUNCTIONS2 = [
7038
+ "tonic",
7039
+ "subdominant",
7040
+ "tonic",
7041
+ "subdominant",
7042
+ "dominant",
7043
+ "tonic",
7044
+ "dominant"
7045
+ ];
7046
+ var MINOR_FUNCTIONS2 = [
7047
+ "tonic",
7048
+ "subdominant",
7049
+ "tonic",
7050
+ "subdominant",
7051
+ "dominant",
7052
+ "subdominant",
7053
+ "dominant"
7054
+ ];
7055
+ var DIATONIC = ["tonic", "subdominant", "dominant"];
7056
+ var unknown = (text) => `Unknown scale "${text.trim()}": use e.g. key: G major, key: A harmonic minor or key: D dorian`;
7057
+ function readHarmonyScale(text) {
7058
+ const name = scaleName(text);
7059
+ const asKey = readKey(name);
7060
+ if (asKey) {
7061
+ const mode = asKey.mode === "ionian" ? "major" : asKey.mode === "aeolian" ? "minor" : asKey.mode;
7062
+ const key = { tonic: asKey.tonic, mode, name: `${asKey.tonic} ${mode}` };
7063
+ const problem = keyProblem(key);
7064
+ if (problem)
7065
+ return { error: problem };
7066
+ return { name: key.name, notes: Scale6.get(key.name).notes, key };
7067
+ }
7068
+ const scale = Scale6.get(name);
7069
+ if (scale.empty || !scale.tonic)
7070
+ return { error: unknown(text) };
7071
+ if (scale.notes.length !== 7) {
7072
+ return {
7073
+ error: `harmonize needs a scale of 7 notes: ${scale.name} has ${scale.notes.length}`
7074
+ };
7075
+ }
7076
+ const tonic = scale.tonic;
7077
+ const notes = scaleSpelling(scale).notes;
7078
+ const minor = Interval6.distance(tonic, notes[2]) === "3m";
7079
+ const key = {
7080
+ tonic,
7081
+ mode: minor ? "minor" : "major",
7082
+ name: `${tonic} ${minor ? "minor" : "major"}`
7083
+ };
7084
+ const count = minor ? Key2.minorKey(tonic).alteration : Key2.majorKey(tonic).alteration;
7085
+ if (Math.abs(count) > MAX_SIGNATURE) {
7086
+ return {
7087
+ error: `${scale.name} needs ${Math.abs(count)} ${count > 0 ? "sharps" : "flats"}: write ${Note7.enharmonic(tonic)} ${scale.type}`
7088
+ };
7089
+ }
7090
+ return { name: scale.name, notes, key };
7091
+ }
7092
+ function chordOn(notes, i, kind) {
7093
+ const root = notes[i];
7094
+ const above = (step) => Interval6.distance(root, notes[(i + step) % 7]);
7095
+ if (kind === "triads" || kind === "sevenths") {
7096
+ const symbol = stackedChord(notes, i, kind === "sevenths");
7097
+ return symbol ? { symbol } : { reason: "not a named chord" };
7098
+ }
7099
+ if (above(4) !== "5P")
7100
+ return { reason: "no perfect fifth" };
7101
+ if (kind === "power")
7102
+ return { symbol: `${root}5` };
7103
+ if (above(3) === "4P")
7104
+ return { symbol: `${root}sus4` };
7105
+ if (above(1) === "2M")
7106
+ return { symbol: `${root}sus2` };
7107
+ return { reason: "no perfect fourth or major second" };
7108
+ }
7109
+ function harmonize(scale, options = {}) {
7110
+ const kind = options.kind ?? "triads";
7111
+ if (!HARMONIZE_KINDS.includes(kind))
7112
+ return null;
7113
+ const read = readHarmonyScale(scale);
7114
+ if ("error" in read)
7115
+ return null;
7116
+ const { notes, key } = read;
7117
+ const byDegree = isMinorMode(key.mode) ? MINOR_FUNCTIONS2 : MAJOR_FUNCTIONS2;
7118
+ const chords = [];
7119
+ const skipped = [];
7120
+ notes.forEach((note, i) => {
7121
+ const made = chordOn(notes, i, kind);
7122
+ if ("reason" in made) {
7123
+ skipped.push({ degree: i + 1, note, reason: made.reason });
7124
+ return;
7125
+ }
7126
+ const { symbol } = made;
7127
+ const fn = harmonicFunction(symbol, key);
7128
+ const shown = (text) => text.replace(/Mb5$/, "(b5)").replace(/Mb⁵$/, "(b⁵)");
7129
+ chords.push({
7130
+ degree: i + 1,
7131
+ note,
7132
+ symbol: shown(symbol),
7133
+ numeral: shown(numeralOf(symbol, key, "roman", { byDegree: true }) ?? symbol),
7134
+ nashville: shown(numeralOf(symbol, key, "nashville", { byDegree: true }) ?? symbol),
7135
+ function: fn && DIATONIC.includes(fn) ? fn : byDegree[i]
7136
+ });
7137
+ });
7138
+ return { ...read, kind, chords, skipped };
7139
+ }
7140
+
6532
7141
  // src/blocks/progression.ts
7142
+ import { Note as Note8 } from "tonal";
6533
7143
  var MAX_CHORDS = 32;
6534
7144
  var MAX_SHARED_OCTAVES = 3;
6535
7145
  var SHARED = [
@@ -6551,8 +7161,22 @@ var SHARED = [
6551
7161
  "time",
6552
7162
  "tempo",
6553
7163
  "bpm",
6554
- "strum"
7164
+ "strum",
7165
+ "harmonize"
6555
7166
  ];
7167
+ var KIND_WORDS = {
7168
+ triad: "triads",
7169
+ triads: "triads",
7170
+ seventh: "sevenths",
7171
+ sevenths: "sevenths",
7172
+ "7th": "sevenths",
7173
+ "7ths": "sevenths",
7174
+ "7": "sevenths",
7175
+ sus: "sus",
7176
+ power: "power",
7177
+ "5": "power"
7178
+ };
7179
+ var HARMONIZED_CHORDS = 7;
6556
7180
  var yes = (text, key, fallback) => {
6557
7181
  if (text === undefined || text === "")
6558
7182
  return fallback;
@@ -6610,7 +7234,69 @@ function sourceOf(part) {
6610
7234
  return { head: lines.length ? lines.join(" ") : null, fields };
6611
7235
  }
6612
7236
  var chordsText = (block) => block.head ?? field(block, "progression") ?? field(block, "chords");
7237
+ function harmonizedSectionOf(block, kindText) {
7238
+ const kind = KIND_WORDS[kindText.toLowerCase()];
7239
+ if (!kind || !HARMONIZE_KINDS.includes(kind)) {
7240
+ throw new Error(`harmonize: write triads, sevenths, sus or power, got "${kindText}"`);
7241
+ }
7242
+ const written = chordsText(block);
7243
+ if (written) {
7244
+ throw new Error(`harmonize draws the chords of the scale: leave out the chords (${written})`);
7245
+ }
7246
+ const keyText = field(block, "key");
7247
+ if (!keyText)
7248
+ throw new Error("Add the scale: e.g. key: A harmonic minor");
7249
+ const shift = Number(field(block, "transpose") ?? 0);
7250
+ if (!Number.isInteger(shift)) {
7251
+ throw new Error(`transpose must be a whole number of semitones, e.g. transpose: -2`);
7252
+ }
7253
+ let scale = readHarmonyScale(keyText);
7254
+ if ("error" in scale)
7255
+ throw new Error(scale.error);
7256
+ if (shift) {
7257
+ const { tonic, mode } = scale.key;
7258
+ const moved = transposeKey(`${tonic}${isMinorMode(mode) ? "m" : ""}`, shift).replace(/m$/, "");
7259
+ const type = scale.name.slice(tonic.length).trim();
7260
+ const spellings = [...new Set([moved, Note8.enharmonic(moved)])].map((t) => readHarmonyScale(`${t} ${type}`));
7261
+ const valid = spellings.filter((sp) => !("error" in sp));
7262
+ const accidentals = (sp) => sp.notes.join("").replace(/[^#b]/g, "").length;
7263
+ const best = valid.sort((a, b) => accidentals(a) - accidentals(b))[0];
7264
+ if (!best)
7265
+ throw new Error(spellings[0].error);
7266
+ scale = best;
7267
+ }
7268
+ const harmonized = harmonize(scale.name, { kind });
7269
+ const chords = harmonized.chords.map((c) => ({
7270
+ written: c.numeral,
7271
+ symbol: c.symbol,
7272
+ numeral: c.numeral,
7273
+ nashville: c.nashville,
7274
+ function: c.function
7275
+ }));
7276
+ const left = harmonized.skipped.map((s) => `degree ${s.degree} (${s.note}), ${s.reason}`);
7277
+ return {
7278
+ key: harmonized.key,
7279
+ others: [],
7280
+ chords,
7281
+ blues: false,
7282
+ block,
7283
+ name: harmonized.name,
7284
+ ...left.length ? { note: `Left out: ${left.join("; ")}` } : {}
7285
+ };
7286
+ }
7287
+ function harmonizeText(block) {
7288
+ if (!block.fields.has("harmonize"))
7289
+ return;
7290
+ const text = field(block, "harmonize");
7291
+ if (text === undefined) {
7292
+ throw new Error("harmonize: write triads, sevenths, sus or power, got nothing");
7293
+ }
7294
+ return text.toLowerCase() === "none" ? undefined : text;
7295
+ }
6613
7296
  function sectionOf(block) {
7297
+ const kindText = harmonizeText(block);
7298
+ if (kindText)
7299
+ return harmonizedSectionOf(block, kindText);
6614
7300
  const text = chordsText(block);
6615
7301
  if (!text) {
6616
7302
  throw new Error("Add the chords: e.g. I V vi IV with key: G, 1 5 6m 4, or G D Em C");
@@ -6753,7 +7439,9 @@ function renderSection(doc, section, options, renderChord) {
6753
7439
  const el = html(doc, "div", "mn-progression-section");
6754
7440
  const others = section.others.length ? ` (or ${section.others.join(", ")})` : "";
6755
7441
  const blues = section.blues ? " (blues)" : "";
6756
- el.appendChild(html(doc, "div", "mn-progression-key", `Key: ${section.key.name}${blues}${others}`));
7442
+ el.appendChild(html(doc, "div", "mn-progression-key", `Key: ${section.name ?? section.key.name}${blues}${others}`));
7443
+ if (section.note)
7444
+ el.appendChild(html(doc, "div", "mn-progression-note", section.note));
6757
7445
  const instrument = (field(block, "instrument") ?? options.instrument ?? "guitar").toLowerCase();
6758
7446
  if (!["guitar", "piano", "keyboard"].includes(instrument)) {
6759
7447
  throw new Error(`Unknown instrument "${instrument}": use guitar or piano`);
@@ -6873,13 +7561,14 @@ function renderProgression(doc, source, options, renderChord) {
6873
7561
  const parts = splitParts(source) ?? [source];
6874
7562
  const blocks = parts.map(sourceOf);
6875
7563
  const first = blocks[0];
6876
- const sharedOnly = blocks.length > 1 && first !== undefined && first.head === null && !first.fields.has("progression") && !first.fields.has("chords") && [...first.fields.keys()].every((k) => SHARED.includes(k));
7564
+ const harmonizedFirst = first !== undefined && first.fields.has("harmonize") && field(first, "key") !== undefined;
7565
+ const sharedOnly = blocks.length > 1 && first !== undefined && first.head === null && !harmonizedFirst && !first.fields.has("progression") && !first.fields.has("chords") && [...first.fields.keys()].every((k) => SHARED.includes(k));
6877
7566
  const shared = sharedOnly ? first.fields : new Map;
6878
7567
  const own = sharedOnly ? blocks.slice(1) : blocks;
6879
7568
  if (!own.length)
6880
7569
  throw new Error('Add the chords after the shared settings, after a "---" line');
6881
7570
  const merged = own.map((b) => ({ head: b.head, fields: new Map([...shared, ...b.fields]) }));
6882
- const count = merged.reduce((n, b) => n + progressionTokens(chordsText(b) ?? "").length, 0);
7571
+ const count = merged.reduce((n, b) => n + (harmonizeText(b) ? HARMONIZED_CHORDS : progressionTokens(chordsText(b) ?? "").length), 0);
6883
7572
  if (count > MAX_CHORDS)
6884
7573
  throw new Error(`At most ${MAX_CHORDS} chords per block, found ${count}`);
6885
7574
  const sections = merged.map(sectionOf);
@@ -6903,7 +7592,7 @@ function renderProgression(doc, source, options, renderChord) {
6903
7592
  }
6904
7593
 
6905
7594
  // src/circle/circle.ts
6906
- import { Key as Key2 } from "tonal";
7595
+ import { Key as Key3 } from "tonal";
6907
7596
  var MAJORS = ["C", "G", "D", "A", "E", "B", "F#/Gb", "Db", "Ab", "Eb", "Bb", "F"];
6908
7597
  var MINORS = ["Am", "Em", "Bm", "F#m", "C#m", "G#m", "D#m/Ebm", "Bbm", "Fm", "Cm", "Gm", "Dm"];
6909
7598
  var DIMINISHED = ["B°", "F#°", "C#°", "G#°", "D#°", "A#°", "E#°", "C°", "G°", "D°", "A°", "E°"];
@@ -7060,7 +7749,7 @@ function renderCircle(doc, options = {}) {
7060
7749
  }
7061
7750
  for (let position = 0;position < 12; position++) {
7062
7751
  const chord = at("major", position);
7063
- const count = chord ? Key2.majorKey(splitChordSymbol(chord.symbol).root).alteration : 0;
7752
+ const count = chord ? Key3.majorKey(splitChordSymbol(chord.symbol).root).alteration : 0;
7064
7753
  const own = chord !== undefined && Math.abs(count) <= MAX_SIGNATURE;
7065
7754
  const text = own ? signatureText(count).replace("no ♯ or ♭", "0") : SIGNATURES[position];
7066
7755
  const [x, y] = point((R.sig + R.major) / 2, position * 30, top);
@@ -7971,7 +8660,8 @@ var SHARED_KEYS = {
7971
8660
  "inversion",
7972
8661
  "octave",
7973
8662
  "hands",
7974
- "fingering"
8663
+ "fingering",
8664
+ "caption"
7975
8665
  ],
7976
8666
  keyboard: ["orientation", "hand", "labels", "range", "highlight", "compare"],
7977
8667
  fretboard: [
@@ -8067,6 +8757,7 @@ var renderChord = (doc, block, options) => {
8067
8757
  const voicingOptions = pianoOptionsOf((key) => field2(block, key));
8068
8758
  const fingering = field2(block, "fingering", "fingers");
8069
8759
  let auto = null;
8760
+ let captionHands;
8070
8761
  let hands;
8071
8762
  let set;
8072
8763
  if (pitchesText) {
@@ -8124,6 +8815,9 @@ var renderChord = (doc, block, options) => {
8124
8815
  }
8125
8816
  if (fingering?.trim().toLowerCase() === "auto") {
8126
8817
  auto = triadFingering(voiced);
8818
+ if (autoVoicingHand(voiced) === "left") {
8819
+ captionHands = new Map(voiced.pitches.map((p) => [p, "left"]));
8820
+ }
8127
8821
  if (!auto) {
8128
8822
  throw new Error("fingering: auto covers triads and four-note chords (sevenths, sixths) in close position, and rootless and shell voicings one hand can reach: write the fingers, e.g. fingering: 1 2 3 4 5");
8129
8823
  }
@@ -8134,7 +8828,8 @@ var renderChord = (doc, block, options) => {
8134
8828
  const fingers = auto ?? (fingering ? fingersFor(set.pitches, fingering) : new Map);
8135
8829
  const range = field2(block, "range");
8136
8830
  handOf(block, options);
8137
- return named(renderKeyboard(doc, set, {
8831
+ const caption = captionOf(block);
8832
+ const keyboard = named(renderKeyboard(doc, set, {
8138
8833
  playAs: "chord",
8139
8834
  title,
8140
8835
  label: labelField(block, fingers.size ? "fingers" : "notes", fingers.size > 0),
@@ -8143,6 +8838,15 @@ var renderChord = (doc, block, options) => {
8143
8838
  range: keyRange(range ? rangeOf(range) : keyRangeOf(set)),
8144
8839
  orientation: orientationOf(block, options.orientation?.keyboard)
8145
8840
  }), symbol);
8841
+ if (!caption)
8842
+ return keyboard;
8843
+ const names = new Map(set.members.map((m) => [m.chroma, m.name]));
8844
+ return captioned(doc, keyboard, fingeringInWords({
8845
+ keys: set.pitches,
8846
+ fingers,
8847
+ ...hands ? { hands } : captionHands ? { hands: captionHands } : {},
8848
+ names
8849
+ }));
8146
8850
  }
8147
8851
  if (instrument && instrument !== "guitar" && !field2(block, "tuning")) {
8148
8852
  throw new Error(`Unknown instrument "${instrument}": use guitar or piano, or give a tuning`);
@@ -8226,8 +8930,30 @@ var renderChord = (doc, block, options) => {
8226
8930
  }), symbol);
8227
8931
  if (capo && sounding && sounding !== symbol)
8228
8932
  diagram.setAttribute("data-mn-sounds", sounding);
8229
- return diagram;
8933
+ if (!captionOf(block))
8934
+ return diagram;
8935
+ return captioned(doc, diagram, fingeringInWords({
8936
+ frets: voicing.frets,
8937
+ fingers: voicing.fingers,
8938
+ ...strings ? { tuning: strings } : {},
8939
+ ...tuningText && tuning ? { tuningNames: tuningNames(tuningText) ?? [] } : {},
8940
+ ...capo ? { capo, fretsFrom: fromNut ? "nut" : "capo" } : {}
8941
+ }));
8230
8942
  };
8943
+ function captionOf(block) {
8944
+ const written = field2(block, "caption")?.trim();
8945
+ const text = written?.toLowerCase();
8946
+ if (!text || ["none", "no", "off", "false"].includes(text))
8947
+ return null;
8948
+ if (text === "fingering")
8949
+ return "fingering";
8950
+ throw new Error(`caption: use fingering (the fingering in words) or none, got "${written}"`);
8951
+ }
8952
+ function captioned(doc, diagram, sentences) {
8953
+ const figure = html(doc, "figure", "mn-captioned");
8954
+ figure.append(diagram, html(doc, "figcaption", "mn-fingering", sentences.join(" ")));
8955
+ return figure;
8956
+ }
8231
8957
  function soundsField(text, shape, capo) {
8232
8958
  const value = text?.trim();
8233
8959
  if (!value || /^(no|false|off)$/i.test(value))
@@ -8297,8 +9023,11 @@ var renderKeyboardBlock = (doc, block, options) => {
8297
9023
  let fingers;
8298
9024
  let title = field2(block, "title");
8299
9025
  const autoHand = fingering ? autoFingeringHand(fingering) : null;
9026
+ if (fingering && isBothHandsFingering(fingering)) {
9027
+ throw new Error("fingering: auto both draws two keyboards: put it in a block of its own, not in a --- row");
9028
+ }
8300
9029
  if (autoHand && (set.root === null || set.list || set.pitches || !set.scaleType)) {
8301
- throw new Error("fingering: auto goes with a major or minor scale (scale: G major): write one finger per note, e.g. fingering: 1 2 3 4 5");
9030
+ throw new Error(AUTO_FINGERING_NEEDS_SCALE);
8302
9031
  }
8303
9032
  if (fingering && set.scaleType && set.root !== null && !set.list && !set.pitches) {
8304
9033
  const chromas = set.members.map((m) => m.chroma);
@@ -8306,7 +9035,7 @@ var renderKeyboardBlock = (doc, block, options) => {
8306
9035
  if (autoHand) {
8307
9036
  const standard = standardScaleFingering(set.root, set.scaleType, autoHand);
8308
9037
  if (!standard) {
8309
- throw new Error(`fingering: auto knows the major, natural minor, harmonic minor and melodic minor scales: write the fingers for ${set.title}, root to root, e.g. fingering: 1 2 3 1 2 3 4 5`);
9038
+ throw new Error(autoFingeringUnknown(set.title));
8310
9039
  }
8311
9040
  octave = standard;
8312
9041
  title ??= `${set.title}, ${autoHand} hand`;
@@ -8427,7 +9156,7 @@ var renderFretboardBlock = (doc, block, options) => {
8427
9156
  const stringsText = field2(block, "strings");
8428
9157
  const count = (tuning ?? STANDARD_TUNING).length;
8429
9158
  const strings = stringsText ? parseStrings(stringsText, count).map((n) => count - n) : undefined;
8430
- const exercise = exerciseOf(block, options, set, tuning ?? STANDARD_TUNING, cells, capo, strings);
9159
+ const exercise = exerciseOf(block, options, set, tuning ?? STANDARD_TUNING, cells, capo, fromNut, strings);
8431
9160
  const shapeTitle = at ? positionTitle(set, at, arpeggio, field2(block, "numbering")) : undefined;
8432
9161
  const diagram = renderFretboard(doc, set, {
8433
9162
  title: field2(block, "title") ?? shapeTitle,
@@ -8449,11 +9178,13 @@ var renderFretboardBlock = (doc, block, options) => {
8449
9178
  pre.setAttribute("data-mn-rhythm", exercise.rhythm);
8450
9179
  pre.setAttribute("data-mn-tempo", String(exercise.tempo));
8451
9180
  pre.setAttribute("data-mn-notes", exercise.notes.join(" "));
9181
+ if (exercise.capo)
9182
+ pre.setAttribute("data-mn-capo", String(exercise.capo));
8452
9183
  pre.appendChild(html(doc, "code", "language-tab", exercise.tex));
8453
9184
  wrap.append(diagram, pre);
8454
9185
  return wrap;
8455
9186
  };
8456
- function exerciseOf(block, options, set, open, cells, capo, strings) {
9187
+ function exerciseOf(block, options, set, open, cells, capo, fromNut, strings) {
8457
9188
  const text = field2(block, "exercise");
8458
9189
  const rhythmText = field2(block, "rhythm");
8459
9190
  if (text === undefined) {
@@ -8466,9 +9197,6 @@ function exerciseOf(block, options, set, open, cells, capo, strings) {
8466
9197
  const rhythm = rhythmText === undefined ? "8ths" : parseRhythm(rhythmText);
8467
9198
  if (!cells)
8468
9199
  throw new Error("exercise plays one position: add position: 1 (or shape: E)");
8469
- if (capo) {
8470
- throw new Error("exercise does not go with capo yet: leave capo out (the shape is the same)");
8471
- }
8472
9200
  const tempoText = field2(block, "tempo", "bpm");
8473
9201
  let tempo = typeof options.play === "object" ? options.play.bpm : undefined;
8474
9202
  if (tempoText !== undefined) {
@@ -8480,13 +9208,15 @@ function exerciseOf(block, options, set, open, cells, capo, strings) {
8480
9208
  tempo = tempo === undefined || !Number.isFinite(tempo) ? DEFAULT_EXERCISE_TEMPO : tempo;
8481
9209
  tempo = Math.min(240, Math.max(20, Math.round(tempo)));
8482
9210
  const shown = strings ? cells.filter((c) => strings.includes(c.string)) : cells;
8483
- const run = exerciseRun(shown, open, set.root, direction);
9211
+ const fromCapo = capo > 0 && !fromNut;
9212
+ const run = exerciseRun(shown, fromCapo ? capoTuning(open, capo) : open, set.root, direction);
8484
9213
  return {
8485
9214
  direction,
8486
9215
  rhythm,
8487
9216
  tempo,
9217
+ capo: fromCapo ? capo : 0,
8488
9218
  notes: run.map((c) => `${c.fret}.${open.length - c.string}`),
8489
- tex: exerciseTex(run, open, { rhythm, tempo })
9219
+ tex: exerciseTex(run, open, { rhythm, tempo, ...fromCapo ? { capo } : {} })
8490
9220
  };
8491
9221
  }
8492
9222
  function positionTitle(set, at, arpeggio, numbering) {
@@ -8523,6 +9253,53 @@ var RENDERERS = {
8523
9253
  circle: renderCircleBlock
8524
9254
  };
8525
9255
 
9256
+ // src/playback/app-bar.ts
9257
+ var NONE = { tempoChanged() {}, free() {} };
9258
+ function handToApp(options, bar, info) {
9259
+ const hook = options.timedBar;
9260
+ if (!hook)
9261
+ return NONE;
9262
+ const listeners = new Set;
9263
+ let slot = null;
9264
+ const timed = {
9265
+ ...info,
9266
+ element: bar,
9267
+ onTempo(listener) {
9268
+ listeners.add(listener);
9269
+ return () => listeners.delete(listener);
9270
+ },
9271
+ add(control) {
9272
+ if (!slot) {
9273
+ slot = html(bar.ownerDocument, "span", "mn-play-app");
9274
+ bar.appendChild(slot);
9275
+ }
9276
+ slot.appendChild(control);
9277
+ }
9278
+ };
9279
+ let free = null;
9280
+ try {
9281
+ const given = hook(timed);
9282
+ if (typeof given === "function")
9283
+ free = given;
9284
+ } catch {}
9285
+ return {
9286
+ tempoChanged(bpm) {
9287
+ for (const listener of [...listeners]) {
9288
+ try {
9289
+ listener(bpm);
9290
+ } catch {}
9291
+ }
9292
+ },
9293
+ free() {
9294
+ listeners.clear();
9295
+ try {
9296
+ free?.();
9297
+ } catch {}
9298
+ free = null;
9299
+ }
9300
+ };
9301
+ }
9302
+
8526
9303
  // src/playback/strum-bar.ts
8527
9304
  var STROKES2 = new Set(["down", "up", "mute", "rest"]);
8528
9305
  var pitchesOf = (text) => {
@@ -8592,6 +9369,7 @@ function strumBarFor(doc, win, drawing, options) {
8592
9369
  if (!score)
8593
9370
  return () => {};
8594
9371
  return timedBarFor(doc, win, drawing, options, {
9372
+ kind: "strum",
8595
9373
  cls: "mn-strum-playable",
8596
9374
  label: "Play the strumming pattern",
8597
9375
  compound: (score.slotsPerPulse ?? score.slotsPerBeat) > score.slotsPerBeat,
@@ -8716,7 +9494,10 @@ function timedBarFor(doc, win, drawing, options, piece) {
8716
9494
  field.append(tag, input);
8717
9495
  bar.appendChild(field);
8718
9496
  };
8719
- slider("Tempo (BPM)", 20, 240, settings.bpm, (n) => settings.bpm = tempoOf(n), compound ? "♩." : "♩");
9497
+ slider("Tempo (BPM)", 20, 240, settings.bpm, (n) => {
9498
+ settings.bpm = tempoOf(n);
9499
+ app.tempoChanged(settings.bpm);
9500
+ }, compound ? "♩." : "♩");
8720
9501
  slider("Volume", 0, 100, Math.round(settings.volume * 100), (n) => settings.volume = n / 100, icon(doc, "volume"));
8721
9502
  const sound = html(doc, "select", "mn-play-sound");
8722
9503
  sound.setAttribute("aria-label", "Sound");
@@ -8735,7 +9516,16 @@ function timedBarFor(doc, win, drawing, options, piece) {
8735
9516
  return;
8736
9517
  wrap.classList.toggle("mn-play-open");
8737
9518
  });
8738
- return stop;
9519
+ const app = handToApp(options, bar, {
9520
+ kind: piece.kind,
9521
+ drawing,
9522
+ compound,
9523
+ tempo: () => settings.bpm
9524
+ });
9525
+ return () => {
9526
+ stop();
9527
+ app.free();
9528
+ };
8739
9529
  }
8740
9530
 
8741
9531
  // src/playback/progression-bar.ts
@@ -8756,9 +9546,15 @@ function barsFromDrawing(drawing) {
8756
9546
  for (const index of order) {
8757
9547
  const els = byBar.get(index);
8758
9548
  const pitches = pitchesOf2(els[0].getAttribute("data-mn-voicing"));
8759
- if (!pitches.length)
9549
+ const rest = els[0].hasAttribute("data-mn-rest");
9550
+ if (!pitches.length && !rest)
8760
9551
  continue;
8761
- bars.push({ chord: els[0].getAttribute("data-mn-chord"), pitches });
9552
+ const beats = Number(els[0].getAttribute("data-mn-beats"));
9553
+ bars.push({
9554
+ chord: rest ? null : els[0].getAttribute("data-mn-chord"),
9555
+ pitches,
9556
+ ...els[0].hasAttribute("data-mn-beats") && beats > 0 ? { beats } : {}
9557
+ });
8762
9558
  marks.push(els);
8763
9559
  }
8764
9560
  return { bars, marks };
@@ -8899,7 +9695,10 @@ function progressionBarFor(doc, win, drawing, options) {
8899
9695
  field.append(tag, input);
8900
9696
  bar.appendChild(field);
8901
9697
  };
8902
- slider("Tempo (BPM)", 20, 240, settings.bpm, (n) => settings.bpm = tempoOf(n), compound ? "♩." : "♩");
9698
+ slider("Tempo (BPM)", 20, 240, settings.bpm, (n) => {
9699
+ settings.bpm = tempoOf(n);
9700
+ app.tempoChanged(settings.bpm);
9701
+ }, compound ? "♩." : "♩");
8903
9702
  slider("Volume", 0, 100, Math.round(settings.volume * 100), (n) => settings.volume = n / 100, icon(doc, "volume"));
8904
9703
  const select = (cls, label, values, chosen, names, set) => {
8905
9704
  const el = html(doc, "select", cls);
@@ -8924,7 +9723,16 @@ function progressionBarFor(doc, win, drawing, options) {
8924
9723
  start();
8925
9724
  });
8926
9725
  select("mn-play-sound", "Sound", ["guitar", "piano"], settings.sound, { guitar: "Guitar", piano: "Piano" }, (value) => settings.sound = value === "piano" ? "piano" : "guitar");
8927
- return stop;
9726
+ const app = handToApp(options, bar, {
9727
+ kind: drawing.classList.contains("mn-chart") ? "chart" : "progression",
9728
+ drawing,
9729
+ compound,
9730
+ tempo: () => settings.bpm
9731
+ });
9732
+ return () => {
9733
+ stop();
9734
+ app.free();
9735
+ };
8928
9736
  }
8929
9737
 
8930
9738
  // src/playback/picking-bar.ts
@@ -8970,6 +9778,7 @@ function pickingBarFor(doc, win, drawing, options) {
8970
9778
  if (!score)
8971
9779
  return () => {};
8972
9780
  return timedBarFor(doc, win, drawing, options, {
9781
+ kind: "picking",
8973
9782
  cls: "mn-strum-playable mn-picking-playable",
8974
9783
  label: "Play the picking pattern",
8975
9784
  compound: score.slotsPerPulse > score.slotsPerBeat,
@@ -9296,6 +10105,8 @@ function barFor(doc, win, diagram, data, options) {
9296
10105
  }
9297
10106
  let other;
9298
10107
  const redraws = diagram.getAttribute("data-mn-redraw") !== "no";
10108
+ const figure = wrap.parentElement;
10109
+ const caption = figure?.classList.contains("mn-captioned") ? [...figure.children].find((c) => c.classList.contains("mn-fingering")) : undefined;
9299
10110
  const drawFor = () => {
9300
10111
  if (!redraws)
9301
10112
  return;
@@ -9306,6 +10117,8 @@ function barFor(doc, win, diagram, data, options) {
9306
10117
  wrap.replaceChild(next, shown);
9307
10118
  shown = next;
9308
10119
  }
10120
+ if (caption)
10121
+ caption.hidden = shown !== diagram;
9309
10122
  };
9310
10123
  sound.addEventListener("change", () => {
9311
10124
  stop();
@@ -9536,7 +10349,7 @@ function blockFromProperties(language, properties, options = {}) {
9536
10349
  }
9537
10350
 
9538
10351
  // src/chord/triads.ts
9539
- import { Key as Key3 } from "tonal";
10352
+ import { Key as Key4 } from "tonal";
9540
10353
  var inversionName = (inversion) => inversion === 0 ? "root position" : inversion === 1 ? "1st inversion" : "2nd inversion";
9541
10354
  function triadVoicings(symbol, options) {
9542
10355
  const tuning = options.tuning ?? STANDARD_TUNING;
@@ -9589,7 +10402,7 @@ function keyTriads(key, options) {
9589
10402
  const parsed = parseKey(key);
9590
10403
  if (!parsed)
9591
10404
  return null;
9592
- const scale = parsed.minor ? Key3.minorKey(parsed.tonic).natural : Key3.majorKey(parsed.tonic);
10405
+ const scale = parsed.minor ? Key4.minorKey(parsed.tonic).natural : Key4.majorKey(parsed.tonic);
9593
10406
  if (!scale.triads.length)
9594
10407
  return null;
9595
10408
  const inversion = options.inversion ?? 0;
@@ -9647,7 +10460,7 @@ function renderBlock(language, source, host, given = {}) {
9647
10460
  try {
9648
10461
  if ((language === "fretboard" || language === "keyboard") && !splitParts(text))
9649
10462
  text = resolveScalesFor(text);
9650
- parts = isDiagramLanguage(language) ? splitParts(text) ?? modeParts(language, text) ?? positionParts(language, text) ?? transitionParts(language, text, options.voicings) ?? triadParts(language, text) ?? voicingParts(language, text) : null;
10463
+ parts = isDiagramLanguage(language) ? splitParts(text) ?? modeParts(language, text) ?? positionParts(language, text) ?? handParts(language, text) ?? transitionParts(language, text, options.voicings) ?? triadParts(language, text) ?? voicingParts(language, text) : null;
9651
10464
  } catch (e) {
9652
10465
  return failed(el, host, language, messageOf(e));
9653
10466
  }
@@ -9670,6 +10483,7 @@ function renderBlock(language, source, host, given = {}) {
9670
10483
  } catch (e) {
9671
10484
  return failed(el, host, language, messageOf(e));
9672
10485
  }
10486
+ alignTitleLines(el.querySelectorAll("svg.mn-guitar-chord, svg.mn-fretboard"));
9673
10487
  host.appendChild(el);
9674
10488
  const freeTabs = [];
9675
10489
  if (options.tab) {
@@ -9821,6 +10635,39 @@ function positionParts(language, source) {
9821
10635
  return [...header.length ? [header.join(`
9822
10636
  `)] : [], ...diagrams];
9823
10637
  }
10638
+ function handParts(language, source) {
10639
+ if (language !== "keyboard")
10640
+ return null;
10641
+ let block;
10642
+ try {
10643
+ block = parseBlockSource(source);
10644
+ } catch {
10645
+ return null;
10646
+ }
10647
+ const fingering = block.fields.get("fingering");
10648
+ if (fingering === undefined || !isBothHandsFingering(fingering))
10649
+ return null;
10650
+ block = scalesForBlock(block);
10651
+ const set = noteSetOf(block);
10652
+ if (set.root === null || set.list || set.pitches || !set.scaleType) {
10653
+ throw new Error(AUTO_FINGERING_NEEDS_SCALE);
10654
+ }
10655
+ if (!standardScaleFingering(set.root, set.scaleType, "right")) {
10656
+ throw new Error(autoFingeringUnknown(set.title));
10657
+ }
10658
+ const title = block.fields.get("title")?.trim();
10659
+ const others = [...block.fields].filter(([key]) => !["fingering", "title", "columns"].includes(key)).map(([key, value]) => `${key}: ${value}`);
10660
+ const head = block.head ? [block.head] : [];
10661
+ const hand = (side) => [
10662
+ ...head,
10663
+ ...others,
10664
+ `fingering: auto ${side}`,
10665
+ ...title ? [`title: ${title}, ${side} hand`] : []
10666
+ ].join(`
10667
+ `);
10668
+ const columns = block.fields.get("columns")?.trim() || "1";
10669
+ return [`columns: ${columns}`, hand("right"), hand("left")];
10670
+ }
9824
10671
  function capoIn(block) {
9825
10672
  const text = block.fields.get("capo");
9826
10673
  if (!text?.trim())
@@ -10463,5 +11310,5 @@ export {
10463
11310
  renderAll
10464
11311
  };
10465
11312
 
10466
- //# debugId=AD49A0DBEFB46A3A64756E2164756E21
11313
+ //# debugId=A62ED8A359C490EB64756E2164756E21
10467
11314
  //# sourceMappingURL=index.js.map