@dsebastien/music-notation 0.11.0 → 0.12.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));
@@ -4074,6 +4169,28 @@ function playStrum(pattern, options = {}) {
4074
4169
 
4075
4170
  // src/playback/progression.ts
4076
4171
  var PROGRESSION_STRUMS = ["beats", "bar", "arpeggio"];
4172
+ function spansOf(chords, beatsPerBar) {
4173
+ const spans = [];
4174
+ const chordAt = [];
4175
+ let at = 0;
4176
+ chords.forEach((chord, i) => {
4177
+ const given = chord.beats;
4178
+ const length = given === undefined || !Number.isFinite(given) ? beatsPerBar : Math.max(1, Math.round(given));
4179
+ spans.push({ start: at, length });
4180
+ for (let k = 0;k < length; k++)
4181
+ chordAt.push(i);
4182
+ at += length;
4183
+ });
4184
+ const bars = Math.max(1, Math.ceil(at / beatsPerBar));
4185
+ const last = spans[spans.length - 1];
4186
+ if (last) {
4187
+ const end = bars * beatsPerBar;
4188
+ last.length += end - at;
4189
+ while (chordAt.length < end)
4190
+ chordAt.push(spans.length - 1);
4191
+ }
4192
+ return { spans, chordAt, bars };
4193
+ }
4077
4194
  var CLICK2 = { first: 88, beat: 84, other: 81, duration: 0.05 };
4078
4195
  var CLICK_VELOCITY = { first: 92, beat: 76, other: 62 };
4079
4196
  function patternBars(pattern) {
@@ -4083,8 +4200,10 @@ function patternBars(pattern) {
4083
4200
  bars.push(pattern.slots.slice(i, i + perBar));
4084
4201
  return bars.length ? bars : [[]];
4085
4202
  }
4086
- function strumScoreOf(bars, beatsPerBar, perPulse, strum, pattern) {
4203
+ function strumScoreOf(chords, timeline, beatsPerBar, perPulse, strum, pattern) {
4087
4204
  const plain = { accent: false, ghost: false };
4205
+ const pitchesAt = (beat) => [...chords[timeline.chordAt[beat] ?? 0].pitches];
4206
+ const bars = Array.from({ length: timeline.bars }, (_, b) => b);
4088
4207
  if (pattern) {
4089
4208
  const own = patternBars(pattern);
4090
4209
  return {
@@ -4092,24 +4211,29 @@ function strumScoreOf(bars, beatsPerBar, perPulse, strum, pattern) {
4092
4211
  beatsPerBar: pattern.beatsPerBar,
4093
4212
  slotsPerPulse: pattern.slotsPerPulse,
4094
4213
  swing: pattern.swing,
4095
- slots: bars.flatMap((bar, b) => own[b % own.length].map((s) => ({
4214
+ slots: bars.flatMap((b) => own[b % own.length].map((s, k) => ({
4096
4215
  stroke: s.stroke,
4097
4216
  accent: s.accent,
4098
4217
  ghost: s.ghost,
4099
- pitches: [...bar.pitches]
4218
+ pitches: pitchesAt(b * beatsPerBar + Math.floor(k / pattern.slotsPerBeat))
4100
4219
  })))
4101
4220
  };
4102
4221
  }
4222
+ const starts = new Set(timeline.spans.map((s) => s.start));
4103
4223
  return {
4104
4224
  slotsPerBeat: 1,
4105
4225
  beatsPerBar,
4106
4226
  slotsPerPulse: perPulse,
4107
4227
  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
- })))
4228
+ slots: bars.flatMap((b) => Array.from({ length: beatsPerBar }, (_, beat) => {
4229
+ const at = b * beatsPerBar + beat;
4230
+ const struck = strum === "bar" ? beat === 0 || starts.has(at) : beat % perPulse === 0;
4231
+ return {
4232
+ ...plain,
4233
+ stroke: struck ? "down" : "rest",
4234
+ pitches: pitchesAt(at)
4235
+ };
4236
+ }))
4113
4237
  };
4114
4238
  }
4115
4239
  function arpeggioOrder(pitches) {
@@ -4138,6 +4262,7 @@ function progressionEvents(bars, options = {}) {
4138
4262
  const bpm = tempoOf(options.bpm, compound);
4139
4263
  const tail = Math.max(0, options.tail ?? 1);
4140
4264
  const spread = options.spread;
4265
+ const timeline = spansOf(bars, beatsPerBar);
4141
4266
  let beat;
4142
4267
  let events;
4143
4268
  if (strum === "arpeggio" && !pattern) {
@@ -4145,29 +4270,38 @@ function progressionEvents(bars, options = {}) {
4145
4270
  const start = options.countIn ? beatsPerBar * beat : 0;
4146
4271
  const slotsPerBeat = beatUnit >= 8 ? 1 : 8 / beatUnit;
4147
4272
  const slot = beat / slotsPerBeat;
4148
- const end = start + bars.length * beatsPerBar * beat;
4273
+ const end = start + timeline.bars * beatsPerBar * beat;
4149
4274
  events = [];
4150
- bars.forEach((bar, b) => {
4151
- const order = arpeggioOrder(bar.pitches);
4275
+ const slots = Math.max(1, Math.round(beatsPerBar * slotsPerBeat));
4276
+ for (let b = 0;b < timeline.bars; b++) {
4152
4277
  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++) {
4278
+ const barEnd = barStart + beatsPerBar * beat;
4279
+ for (let k = 0;k < slots; k++) {
4280
+ const at = b * beatsPerBar + Math.floor(k / slotsPerBeat);
4281
+ const index = timeline.chordAt[at] ?? 0;
4282
+ const span = timeline.spans[index];
4283
+ const order = arpeggioOrder(bars[index].pitches);
4284
+ if (!order.length)
4285
+ continue;
4286
+ const from = Math.max(span.start * slotsPerBeat, b * slots);
4287
+ const n = b * slots + k - from;
4156
4288
  const time = barStart + k * slot;
4289
+ const spanEnd = start + (span.start + span.length) * beat;
4290
+ const ring = Math.min(barEnd, spanEnd);
4157
4291
  const counted = k % (slotsPerBeat * perPulse) === 0;
4158
4292
  events.push({
4159
- midi: order[k % order.length],
4293
+ midi: order[n % order.length],
4160
4294
  time,
4161
- duration: Math.max(0.06, barEnd - time),
4295
+ duration: Math.max(0.06, (ring >= end ? end + tail : ring) - time),
4162
4296
  velocity: k === 0 ? 92 : counted ? 80 : 72
4163
4297
  });
4164
4298
  }
4165
- });
4299
+ }
4166
4300
  if (options.countIn)
4167
4301
  for (let i = 0;i < beatsPerBar; i++)
4168
4302
  events.push(clickAt(i * beat, i, perPulse, true));
4169
4303
  } else {
4170
- const score = strumScoreOf(bars, beatsPerBar, perPulse, strum === "arpeggio" ? "beats" : strum, pattern);
4304
+ const score = strumScoreOf(bars, timeline, beatsPerBar, perPulse, strum === "arpeggio" ? "beats" : strum, pattern);
4171
4305
  const pulse = score.slotsPerPulse ?? score.slotsPerBeat;
4172
4306
  beat = 60 / bpm / pulse * score.slotsPerBeat;
4173
4307
  events = strumEvents(score, {
@@ -4181,17 +4315,26 @@ function progressionEvents(bars, options = {}) {
4181
4315
  const start = options.countIn ? beatsPerBar * beat : 0;
4182
4316
  const barLength = beatsPerBar * beat;
4183
4317
  if (options.click ?? true)
4184
- bars.forEach((_, b) => {
4318
+ for (let b = 0;b < timeline.bars; b++)
4185
4319
  for (let i = 0;i < beatsPerBar; i += perPulse)
4186
4320
  events.push(clickAt(start + b * barLength + i * beat, i, perPulse, false));
4187
- });
4188
4321
  events.sort((a, b) => a.time - b.time);
4189
- const strums = bars.map((_, b) => ({
4322
+ const strums = timeline.spans.map((span, i) => ({
4323
+ slot: i,
4324
+ time: start + span.start * beat,
4325
+ duration: span.length * beat
4326
+ }));
4327
+ const barTimes = Array.from({ length: timeline.bars }, (_, b) => ({
4190
4328
  slot: b,
4191
4329
  time: start + b * barLength,
4192
4330
  duration: barLength
4193
4331
  }));
4194
- return { events, length: start + bars.length * barLength, strums, bars: strums };
4332
+ return { events, length: start + timeline.bars * barLength, strums, bars: barTimes };
4333
+ }
4334
+ function chordOfBars(bars, beatsPerBar) {
4335
+ const perBar = Math.min(16, Math.max(1, Math.round(beatsPerBar) || 4));
4336
+ const timeline = spansOf(bars, perBar);
4337
+ return Array.from({ length: timeline.bars }, (_, b) => timeline.chordAt[b * perBar] ?? 0);
4195
4338
  }
4196
4339
  var MAX_PROGRESSION_BARS = 256;
4197
4340
  function progressionPitches(chord, sound = "guitar", tuning = STANDARD_TUNING, voicings) {
@@ -4243,7 +4386,7 @@ function runProgression(bars, options, player, settings, timers, onEnd, follow)
4243
4386
  return runPasses((s, first, id) => {
4244
4387
  pass = id;
4245
4388
  return make(s, first, id);
4246
- }, player, settings, timers, onEnd, follow ? (strums, current) => follow(strums, current, pass) : undefined);
4389
+ }, player, settings, timers, onEnd, follow ? (strums, current, made) => follow(strums, current, pass, made) : undefined);
4247
4390
  }
4248
4391
  function playProgression(chords, options = {}) {
4249
4392
  const sound = options.sound === "piano" ? "piano" : "guitar";
@@ -4254,14 +4397,18 @@ function playProgression(chords, options = {}) {
4254
4397
  if (!chords.length)
4255
4398
  throw new Error("playProgression needs at least one chord");
4256
4399
  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);
4400
+ const name = typeof c === "string" ? c : c.chord ?? null;
4401
+ const beats = typeof c === "string" ? undefined : c.beats;
4402
+ const timed = beats === undefined ? {} : { beats };
4403
+ if (typeof c !== "string" && c.pitches)
4404
+ return { chord: name, pitches: [...c.pitches], ...timed };
4405
+ const read = name ? readChord(name) : null;
4260
4406
  if (!read)
4261
- throw new Error(`Didn't recognize the chord "${c}"`);
4407
+ throw new Error(`Didn't recognize the chord "${name ?? ""}"`);
4262
4408
  return {
4263
- chord: c,
4264
- pitches: progressionPitches(read.symbol, sound, tuning, options.voicings)
4409
+ chord: name,
4410
+ pitches: progressionPitches(read.symbol, sound, tuning, options.voicings),
4411
+ ...timed
4265
4412
  };
4266
4413
  });
4267
4414
  const pattern = typeof options.pattern === "string" ? parseStrum(options.pattern) : options.pattern ?? null;
@@ -4279,13 +4426,29 @@ function playProgression(chords, options = {}) {
4279
4426
  volume: Number.isFinite(options.volume) ? Math.min(1, Math.max(0, options.volume)) : 0.8
4280
4427
  };
4281
4428
  const timers = win ?? globalThis;
4282
- const onBar = options.onBar;
4429
+ const { onBar, onChord } = options;
4430
+ const perBar = pattern ? pattern.beatsPerBar : options.beatsPerBar ?? 4;
4431
+ const barChords = chordOfBars(bars, perBar);
4283
4432
  const handle = runProgression(bars, {
4284
4433
  ...options.beatsPerBar === undefined ? {} : { beatsPerBar: options.beatsPerBar },
4285
4434
  ...options.beatUnit === undefined ? {} : { beatUnit: options.beatUnit },
4286
4435
  ...options.strum ? { strum: options.strum } : {},
4287
4436
  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);
4437
+ }, () => player, () => settings, timers, options.onEnd, onBar || onChord ? (timings, current, pass, made) => {
4438
+ const wait = startsReported(current) ? Infinity : START_WAIT;
4439
+ const followers = [
4440
+ ...onChord ? [
4441
+ followTimes(timers, timings, (t) => onChord(t.slot, bars[t.slot]?.chord ?? null, pass), wait)
4442
+ ] : [],
4443
+ ...onBar ? [
4444
+ followTimes(timers, made.bars ?? timings, (t) => onBar(t.slot, bars[barChords[t.slot] ?? 0]?.chord ?? null, pass), wait)
4445
+ ] : []
4446
+ ];
4447
+ return {
4448
+ heard: () => followers.forEach((f) => f.heard()),
4449
+ stop: () => followers.forEach((f) => f.stop())
4450
+ };
4451
+ } : undefined);
4289
4452
  return {
4290
4453
  stop: () => handle.stop(),
4291
4454
  update(changes) {
@@ -4712,6 +4875,59 @@ function renderChordsUsed(doc, song, options) {
4712
4875
 
4713
4876
  // src/chords/chart.ts
4714
4877
  var PLACEMENTS = new Set(["top", "bottom", "off"]);
4878
+ function lineBeats(segments, playable, beatsPerBar, perPulse) {
4879
+ if (!segments.some((s) => s.text.includes("|")))
4880
+ return { measured: false, steps: [] };
4881
+ const steps = [];
4882
+ const counted = Math.max(1, Math.round(beatsPerBar / perPulse));
4883
+ let bar = [];
4884
+ let silent = null;
4885
+ let opened = false;
4886
+ const close = (ended) => {
4887
+ if (bar.length) {
4888
+ const n = bar.length;
4889
+ const slashed = bar.reduce((sum, c) => sum + 1 + c.slashes, 0);
4890
+ const dotted = bar.reduce((sum, c) => sum + c.dots, 0);
4891
+ let lengths;
4892
+ if (bar.every((c) => c.dots) && dotted === counted)
4893
+ lengths = bar.map((c) => c.dots * perPulse);
4894
+ else if (bar.some((c) => c.slashes) && slashed === counted)
4895
+ lengths = bar.map((c) => (1 + c.slashes) * perPulse);
4896
+ else {
4897
+ const [whole, unit] = n <= counted ? [counted, perPulse] : [beatsPerBar, 1];
4898
+ const base = Math.floor(whole / n);
4899
+ const extra = whole % n;
4900
+ lengths = bar.map((_, i) => Math.max(1, (base + (i < extra ? 1 : 0)) * unit));
4901
+ }
4902
+ bar.forEach((c, i) => steps.push({ segment: c.segment, beats: lengths[i] }));
4903
+ } else if (silent !== null)
4904
+ steps.push({ rest: beatsPerBar, segment: silent });
4905
+ else if (ended && opened)
4906
+ steps.push({ hold: beatsPerBar });
4907
+ bar = [];
4908
+ silent = null;
4909
+ opened = ended || opened;
4910
+ };
4911
+ segments.forEach((segment, i) => {
4912
+ if (segment.chord !== null) {
4913
+ if (playable(segment.chord))
4914
+ bar.push({ segment: i, slashes: 0, dots: 0 });
4915
+ else
4916
+ silent ??= i;
4917
+ }
4918
+ for (const ch of segment.text) {
4919
+ if (ch === "|")
4920
+ close(true);
4921
+ else if (ch === "/" && bar.length)
4922
+ bar[bar.length - 1].slashes++;
4923
+ else if (ch === "." && bar.length)
4924
+ bar[bar.length - 1].dots++;
4925
+ }
4926
+ });
4927
+ if (bar.length || silent !== null)
4928
+ close(false);
4929
+ return { measured: true, steps };
4930
+ }
4715
4931
  function timeOf(text) {
4716
4932
  if (!text)
4717
4933
  return null;
@@ -4733,15 +4949,75 @@ function guessedKey(song) {
4733
4949
  const found = chords.length ? findKey(chords) : null;
4734
4950
  return found ? `${found.tonic}${found.mode === "minor" ? "m" : ""}` : null;
4735
4951
  }
4736
- function renderChart(doc, song, options = {}) {
4737
- const extra = options.transpose ?? 0;
4952
+ function transposerOf(song, extra) {
4738
4953
  const semitones = song.transpose + (Number.isFinite(extra) ? Math.round(extra) : 0);
4739
4954
  const key = song.key ? transposeKey(song.key, semitones) : null;
4740
4955
  const flats = key ? keyPrefersFlats(key) : undefined;
4741
4956
  const from = song.key ?? (semitones % 12 ? guessedKey(song) : null);
4742
4957
  const move = from ? keyMove(from, semitones) : null;
4743
4958
  const spelling = move ?? flats;
4744
- const chord = (symbol) => transposeChord(symbol, semitones, spelling);
4959
+ return {
4960
+ semitones,
4961
+ key,
4962
+ spelling,
4963
+ chord: (symbol) => transposeChord(symbol, semitones, spelling)
4964
+ };
4965
+ }
4966
+ function meterOf(song) {
4967
+ let beatsPerBar = 4;
4968
+ let beatUnit = 4;
4969
+ const time = timeOf(song.time);
4970
+ if (time)
4971
+ ({ beatsPerBar, beatUnit } = parseTime(time));
4972
+ return { beatsPerBar, beatUnit, perPulse: isCompound(beatsPerBar, beatUnit) ? 3 : 1 };
4973
+ }
4974
+ function chartChords(song, options = {}) {
4975
+ const { chord } = transposerOf(song, options.transpose);
4976
+ const { beatsPerBar, beatUnit, perPulse } = meterOf(song);
4977
+ const playable = (written) => {
4978
+ const shown = chord(written);
4979
+ return Boolean(findDefinition(song.definitions, written)?.diagram || parseChord(shown) && chordNoteSet(shown));
4980
+ };
4981
+ const chords = [];
4982
+ const hold = (beats) => {
4983
+ const last = chords[chords.length - 1];
4984
+ if (last)
4985
+ last.beats = (last.beats ?? beatsPerBar) + beats;
4986
+ };
4987
+ for (const section of song.sections)
4988
+ for (const line of section.lines) {
4989
+ if (line.kind !== "lyrics")
4990
+ continue;
4991
+ const { measured, steps } = lineBeats(line.segments, playable, beatsPerBar, perPulse);
4992
+ if (!measured) {
4993
+ for (const s of line.segments)
4994
+ if (s.chord !== null && playable(s.chord))
4995
+ chords.push({ chord: chord(s.chord) });
4996
+ continue;
4997
+ }
4998
+ for (const step of steps) {
4999
+ if ("hold" in step)
5000
+ hold(step.hold);
5001
+ else if ("rest" in step)
5002
+ chords.push({ chord: null, pitches: [], beats: step.rest });
5003
+ else
5004
+ chords.push({
5005
+ chord: chord(line.segments[step.segment].chord),
5006
+ beats: step.beats
5007
+ });
5008
+ }
5009
+ }
5010
+ const tempo = Number(song.tempo);
5011
+ return {
5012
+ chords,
5013
+ beatsPerBar,
5014
+ beatUnit,
5015
+ tempo: song.tempo && Number.isFinite(tempo) && tempo >= 20 && tempo <= 240 ? tempo : null
5016
+ };
5017
+ }
5018
+ function renderChart(doc, song, options = {}) {
5019
+ const { semitones, key, spelling, chord } = transposerOf(song, options.transpose);
5020
+ const meter = meterOf(song);
4745
5021
  const drawing = {
4746
5022
  instrument: song.instrument ?? (options.instrument === "piano" ? "piano" : "guitar"),
4747
5023
  ...options.voicings ? { voicings: options.voicings } : {},
@@ -4765,6 +5041,11 @@ function renderChart(doc, song, options = {}) {
4765
5041
  if (song.tempo && Number.isFinite(tempo) && tempo >= 20 && tempo <= 240)
4766
5042
  root.setAttribute("data-mn-tempo", String(Math.round(tempo)));
4767
5043
  let bars = 0;
5044
+ let last = null;
5045
+ const setBeats = (mark, beats) => {
5046
+ mark.setAttribute("data-mn-beats", String(beats));
5047
+ last = { mark, beats };
5048
+ };
4768
5049
  const sounds = new Map;
4769
5050
  const soundOf = (written, shown) => {
4770
5051
  const known = sounds.get(shown);
@@ -4851,7 +5132,13 @@ function renderChart(doc, song, options = {}) {
4851
5132
  const chordsOnly = line.segments.every((s) => !s.text.trim());
4852
5133
  if (chordsOnly)
4853
5134
  row.classList.add("mn-chords-only");
4854
- for (const segment of line.segments) {
5135
+ const timing = lineBeats(line.segments, (written) => soundOf(written, chord(written)) !== null, meter.beatsPerBar, meter.perPulse);
5136
+ const marks = new Map;
5137
+ const rests = new Map;
5138
+ for (const step of timing.steps)
5139
+ if ("rest" in step)
5140
+ rests.set(step.segment, step.rest);
5141
+ line.segments.forEach((segment, index) => {
4855
5142
  const seg = html(doc, "span", "mn-seg");
4856
5143
  const mark = html(doc, "span", "mn-chord", segment.chord === null ? "" : chord(segment.chord));
4857
5144
  if (segment.chord !== null) {
@@ -4861,11 +5148,33 @@ function renderChart(doc, song, options = {}) {
4861
5148
  mark.setAttribute("data-mn-bar", String(bars++));
4862
5149
  mark.setAttribute("data-mn-chord", shown);
4863
5150
  mark.setAttribute("data-mn-voicing", voicing);
5151
+ marks.set(index, mark);
5152
+ if (!timing.measured)
5153
+ last = { mark, beats: null };
5154
+ } else if (rests.has(index)) {
5155
+ mark.setAttribute("data-mn-bar", String(bars++));
5156
+ mark.setAttribute("data-mn-rest", "");
5157
+ marks.set(index, mark);
4864
5158
  }
4865
5159
  }
4866
5160
  seg.appendChild(mark);
4867
5161
  seg.appendChild(html(doc, "span", "mn-lyric", segment.text || (chordsOnly ? "" : " ")));
4868
5162
  row.appendChild(seg);
5163
+ });
5164
+ for (const step of timing.steps) {
5165
+ const held = last;
5166
+ if ("hold" in step) {
5167
+ if (held)
5168
+ setBeats(held.mark, (held.beats ?? meter.beatsPerBar) + step.hold);
5169
+ } else if ("rest" in step) {
5170
+ const mark = marks.get(step.segment);
5171
+ if (mark)
5172
+ setBeats(mark, step.rest);
5173
+ } else {
5174
+ const mark = marks.get(step.segment);
5175
+ if (mark)
5176
+ setBeats(mark, step.beats);
5177
+ }
4869
5178
  }
4870
5179
  el.appendChild(row);
4871
5180
  }
@@ -4908,7 +5217,7 @@ function renderFretboard(doc, set, options = {}) {
4908
5217
  const vertical = orientation === "vertical";
4909
5218
  const openW = from === 0 ? OPEN_W : 0;
4910
5219
  const acrossLength = (strings - 1) * STRING_GAP;
4911
- const frame = neckFrame({
5220
+ const layout = {
4912
5221
  orientation,
4913
5222
  hand: options.hand ?? "right",
4914
5223
  across: acrossLength,
@@ -4917,8 +5226,13 @@ function renderFretboard(doc, set, options = {}) {
4917
5226
  after: 8,
4918
5227
  low: NUMBERS,
4919
5228
  high: 12,
4920
- top: options.title ? TITLE3 : 0,
4921
- minWidth: Math.max(titleWidth(options.title), titleWidth(caption))
5229
+ top: 0,
5230
+ minWidth: titleWidth(caption)
5231
+ };
5232
+ const lines = options.title ? titleLines(options.title, neckFrame(layout).width) : [];
5233
+ const frame = neckFrame({
5234
+ ...layout,
5235
+ top: lines.length ? TITLE3 + (lines.length - 1) * TITLE_LINE : 0
4922
5236
  });
4923
5237
  const across = (string) => string * STRING_GAP;
4924
5238
  const wire = (fret) => openW + (fret - first + 1) * FRET_W;
@@ -4935,14 +5249,8 @@ function renderFretboard(doc, set, options = {}) {
4935
5249
  root.setAttribute("data-mn-capo", String(capo));
4936
5250
  root.setAttribute("data-mn-frets-from", fromNut ? "nut" : "capo");
4937
5251
  }
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
- }
5252
+ if (lines.length)
5253
+ drawTitle(doc, root, lines, frame.width / 2, 15);
4946
5254
  const markOf = (s, fret) => {
4947
5255
  const pitch = tuning[s] + fret;
4948
5256
  const member = memberOf(set, pitch);
@@ -5629,6 +5937,7 @@ function exerciseTex(run, tuning, options = {}) {
5629
5937
  ...standard ? [] : [
5630
5938
  `\\tuning (${[...tuning].reverse().map((m) => noteOf(m)).join(" ")})`
5631
5939
  ],
5940
+ ...options.capo ? [`\\capo ${options.capo}`] : [],
5632
5941
  "\\ts 4 4",
5633
5942
  `${DURATION[rhythm]} ${bars.join(` |
5634
5943
  `)}`
@@ -5675,12 +5984,18 @@ function exerciseTab(notes, options = {}) {
5675
5984
  const tuning = typeof options.tuning === "string" ? parseTuning(options.tuning) : options.tuning ?? STANDARD_TUNING;
5676
5985
  if (!tuning || tuning.length < 2)
5677
5986
  throw new Error(`Unknown tuning "${String(options.tuning)}"`);
5987
+ const capo = options.capo ?? 0;
5988
+ if (!Number.isInteger(capo) || capo < 0 || capo > 12) {
5989
+ throw new Error(`capo: use a fret from 1 to 12 (0 for none), got ${String(options.capo)}`);
5990
+ }
5991
+ const sounding = capo ? capoTuning(tuning, capo) : tuning;
5678
5992
  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, {
5993
+ const cells = exercisePosition(set, sounding, at, options);
5994
+ return exerciseTex(exerciseRun(cells, sounding, set.root, options.direction ?? "both"), tuning, {
5681
5995
  ...options.rhythm ? { rhythm: options.rhythm } : {},
5682
5996
  ...options.tempo !== undefined ? { tempo: options.tempo } : {},
5683
- ...options.title ? { title: options.title } : {}
5997
+ ...options.title ? { title: options.title } : {},
5998
+ ...capo ? { capo } : {}
5684
5999
  });
5685
6000
  }
5686
6001
 
@@ -8427,7 +8742,7 @@ var renderFretboardBlock = (doc, block, options) => {
8427
8742
  const stringsText = field2(block, "strings");
8428
8743
  const count = (tuning ?? STANDARD_TUNING).length;
8429
8744
  const strings = stringsText ? parseStrings(stringsText, count).map((n) => count - n) : undefined;
8430
- const exercise = exerciseOf(block, options, set, tuning ?? STANDARD_TUNING, cells, capo, strings);
8745
+ const exercise = exerciseOf(block, options, set, tuning ?? STANDARD_TUNING, cells, capo, fromNut, strings);
8431
8746
  const shapeTitle = at ? positionTitle(set, at, arpeggio, field2(block, "numbering")) : undefined;
8432
8747
  const diagram = renderFretboard(doc, set, {
8433
8748
  title: field2(block, "title") ?? shapeTitle,
@@ -8449,11 +8764,13 @@ var renderFretboardBlock = (doc, block, options) => {
8449
8764
  pre.setAttribute("data-mn-rhythm", exercise.rhythm);
8450
8765
  pre.setAttribute("data-mn-tempo", String(exercise.tempo));
8451
8766
  pre.setAttribute("data-mn-notes", exercise.notes.join(" "));
8767
+ if (exercise.capo)
8768
+ pre.setAttribute("data-mn-capo", String(exercise.capo));
8452
8769
  pre.appendChild(html(doc, "code", "language-tab", exercise.tex));
8453
8770
  wrap.append(diagram, pre);
8454
8771
  return wrap;
8455
8772
  };
8456
- function exerciseOf(block, options, set, open, cells, capo, strings) {
8773
+ function exerciseOf(block, options, set, open, cells, capo, fromNut, strings) {
8457
8774
  const text = field2(block, "exercise");
8458
8775
  const rhythmText = field2(block, "rhythm");
8459
8776
  if (text === undefined) {
@@ -8466,9 +8783,6 @@ function exerciseOf(block, options, set, open, cells, capo, strings) {
8466
8783
  const rhythm = rhythmText === undefined ? "8ths" : parseRhythm(rhythmText);
8467
8784
  if (!cells)
8468
8785
  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
8786
  const tempoText = field2(block, "tempo", "bpm");
8473
8787
  let tempo = typeof options.play === "object" ? options.play.bpm : undefined;
8474
8788
  if (tempoText !== undefined) {
@@ -8480,13 +8794,15 @@ function exerciseOf(block, options, set, open, cells, capo, strings) {
8480
8794
  tempo = tempo === undefined || !Number.isFinite(tempo) ? DEFAULT_EXERCISE_TEMPO : tempo;
8481
8795
  tempo = Math.min(240, Math.max(20, Math.round(tempo)));
8482
8796
  const shown = strings ? cells.filter((c) => strings.includes(c.string)) : cells;
8483
- const run = exerciseRun(shown, open, set.root, direction);
8797
+ const fromCapo = capo > 0 && !fromNut;
8798
+ const run = exerciseRun(shown, fromCapo ? capoTuning(open, capo) : open, set.root, direction);
8484
8799
  return {
8485
8800
  direction,
8486
8801
  rhythm,
8487
8802
  tempo,
8803
+ capo: fromCapo ? capo : 0,
8488
8804
  notes: run.map((c) => `${c.fret}.${open.length - c.string}`),
8489
- tex: exerciseTex(run, open, { rhythm, tempo })
8805
+ tex: exerciseTex(run, open, { rhythm, tempo, ...fromCapo ? { capo } : {} })
8490
8806
  };
8491
8807
  }
8492
8808
  function positionTitle(set, at, arpeggio, numbering) {
@@ -8523,6 +8839,53 @@ var RENDERERS = {
8523
8839
  circle: renderCircleBlock
8524
8840
  };
8525
8841
 
8842
+ // src/playback/app-bar.ts
8843
+ var NONE = { tempoChanged() {}, free() {} };
8844
+ function handToApp(options, bar, info) {
8845
+ const hook = options.timedBar;
8846
+ if (!hook)
8847
+ return NONE;
8848
+ const listeners = new Set;
8849
+ let slot = null;
8850
+ const timed = {
8851
+ ...info,
8852
+ element: bar,
8853
+ onTempo(listener) {
8854
+ listeners.add(listener);
8855
+ return () => listeners.delete(listener);
8856
+ },
8857
+ add(control) {
8858
+ if (!slot) {
8859
+ slot = html(bar.ownerDocument, "span", "mn-play-app");
8860
+ bar.appendChild(slot);
8861
+ }
8862
+ slot.appendChild(control);
8863
+ }
8864
+ };
8865
+ let free = null;
8866
+ try {
8867
+ const given = hook(timed);
8868
+ if (typeof given === "function")
8869
+ free = given;
8870
+ } catch {}
8871
+ return {
8872
+ tempoChanged(bpm) {
8873
+ for (const listener of [...listeners]) {
8874
+ try {
8875
+ listener(bpm);
8876
+ } catch {}
8877
+ }
8878
+ },
8879
+ free() {
8880
+ listeners.clear();
8881
+ try {
8882
+ free?.();
8883
+ } catch {}
8884
+ free = null;
8885
+ }
8886
+ };
8887
+ }
8888
+
8526
8889
  // src/playback/strum-bar.ts
8527
8890
  var STROKES2 = new Set(["down", "up", "mute", "rest"]);
8528
8891
  var pitchesOf = (text) => {
@@ -8592,6 +8955,7 @@ function strumBarFor(doc, win, drawing, options) {
8592
8955
  if (!score)
8593
8956
  return () => {};
8594
8957
  return timedBarFor(doc, win, drawing, options, {
8958
+ kind: "strum",
8595
8959
  cls: "mn-strum-playable",
8596
8960
  label: "Play the strumming pattern",
8597
8961
  compound: (score.slotsPerPulse ?? score.slotsPerBeat) > score.slotsPerBeat,
@@ -8716,7 +9080,10 @@ function timedBarFor(doc, win, drawing, options, piece) {
8716
9080
  field.append(tag, input);
8717
9081
  bar.appendChild(field);
8718
9082
  };
8719
- slider("Tempo (BPM)", 20, 240, settings.bpm, (n) => settings.bpm = tempoOf(n), compound ? "♩." : "♩");
9083
+ slider("Tempo (BPM)", 20, 240, settings.bpm, (n) => {
9084
+ settings.bpm = tempoOf(n);
9085
+ app.tempoChanged(settings.bpm);
9086
+ }, compound ? "♩." : "♩");
8720
9087
  slider("Volume", 0, 100, Math.round(settings.volume * 100), (n) => settings.volume = n / 100, icon(doc, "volume"));
8721
9088
  const sound = html(doc, "select", "mn-play-sound");
8722
9089
  sound.setAttribute("aria-label", "Sound");
@@ -8735,7 +9102,16 @@ function timedBarFor(doc, win, drawing, options, piece) {
8735
9102
  return;
8736
9103
  wrap.classList.toggle("mn-play-open");
8737
9104
  });
8738
- return stop;
9105
+ const app = handToApp(options, bar, {
9106
+ kind: piece.kind,
9107
+ drawing,
9108
+ compound,
9109
+ tempo: () => settings.bpm
9110
+ });
9111
+ return () => {
9112
+ stop();
9113
+ app.free();
9114
+ };
8739
9115
  }
8740
9116
 
8741
9117
  // src/playback/progression-bar.ts
@@ -8756,9 +9132,15 @@ function barsFromDrawing(drawing) {
8756
9132
  for (const index of order) {
8757
9133
  const els = byBar.get(index);
8758
9134
  const pitches = pitchesOf2(els[0].getAttribute("data-mn-voicing"));
8759
- if (!pitches.length)
9135
+ const rest = els[0].hasAttribute("data-mn-rest");
9136
+ if (!pitches.length && !rest)
8760
9137
  continue;
8761
- bars.push({ chord: els[0].getAttribute("data-mn-chord"), pitches });
9138
+ const beats = Number(els[0].getAttribute("data-mn-beats"));
9139
+ bars.push({
9140
+ chord: rest ? null : els[0].getAttribute("data-mn-chord"),
9141
+ pitches,
9142
+ ...els[0].hasAttribute("data-mn-beats") && beats > 0 ? { beats } : {}
9143
+ });
8762
9144
  marks.push(els);
8763
9145
  }
8764
9146
  return { bars, marks };
@@ -8899,7 +9281,10 @@ function progressionBarFor(doc, win, drawing, options) {
8899
9281
  field.append(tag, input);
8900
9282
  bar.appendChild(field);
8901
9283
  };
8902
- slider("Tempo (BPM)", 20, 240, settings.bpm, (n) => settings.bpm = tempoOf(n), compound ? "♩." : "♩");
9284
+ slider("Tempo (BPM)", 20, 240, settings.bpm, (n) => {
9285
+ settings.bpm = tempoOf(n);
9286
+ app.tempoChanged(settings.bpm);
9287
+ }, compound ? "♩." : "♩");
8903
9288
  slider("Volume", 0, 100, Math.round(settings.volume * 100), (n) => settings.volume = n / 100, icon(doc, "volume"));
8904
9289
  const select = (cls, label, values, chosen, names, set) => {
8905
9290
  const el = html(doc, "select", cls);
@@ -8924,7 +9309,16 @@ function progressionBarFor(doc, win, drawing, options) {
8924
9309
  start();
8925
9310
  });
8926
9311
  select("mn-play-sound", "Sound", ["guitar", "piano"], settings.sound, { guitar: "Guitar", piano: "Piano" }, (value) => settings.sound = value === "piano" ? "piano" : "guitar");
8927
- return stop;
9312
+ const app = handToApp(options, bar, {
9313
+ kind: drawing.classList.contains("mn-chart") ? "chart" : "progression",
9314
+ drawing,
9315
+ compound,
9316
+ tempo: () => settings.bpm
9317
+ });
9318
+ return () => {
9319
+ stop();
9320
+ app.free();
9321
+ };
8928
9322
  }
8929
9323
 
8930
9324
  // src/playback/picking-bar.ts
@@ -8970,6 +9364,7 @@ function pickingBarFor(doc, win, drawing, options) {
8970
9364
  if (!score)
8971
9365
  return () => {};
8972
9366
  return timedBarFor(doc, win, drawing, options, {
9367
+ kind: "picking",
8973
9368
  cls: "mn-strum-playable mn-picking-playable",
8974
9369
  label: "Play the picking pattern",
8975
9370
  compound: score.slotsPerPulse > score.slotsPerBeat,
@@ -9670,6 +10065,7 @@ function renderBlock(language, source, host, given = {}) {
9670
10065
  } catch (e) {
9671
10066
  return failed(el, host, language, messageOf(e));
9672
10067
  }
10068
+ alignTitleLines(el.querySelectorAll("svg.mn-guitar-chord, svg.mn-fretboard"));
9673
10069
  host.appendChild(el);
9674
10070
  const freeTabs = [];
9675
10071
  if (options.tab) {
@@ -10463,5 +10859,5 @@ export {
10463
10859
  renderAll
10464
10860
  };
10465
10861
 
10466
- //# debugId=AD49A0DBEFB46A3A64756E2164756E21
10862
+ //# debugId=FDD304C0A12A289A64756E2164756E21
10467
10863
  //# sourceMappingURL=index.js.map