@dsebastien/music-notation 0.8.0 → 0.10.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.
Files changed (40) hide show
  1. package/README.md +37 -5
  2. package/dist/chord/generate.d.ts +45 -9
  3. package/dist/chord/guitar.d.ts +23 -0
  4. package/dist/circle/circle.d.ts +8 -2
  5. package/dist/cli.js +1 -1
  6. package/dist/convert/text-tab.d.ts +61 -0
  7. package/dist/index.d.ts +9 -8
  8. package/dist/index.js +6427 -4316
  9. package/dist/index.js.map +34 -32
  10. package/dist/keyboard/keyboard.d.ts +17 -2
  11. package/dist/keyboard/piano-chord.d.ts +28 -3
  12. package/dist/keyboard/play-voicing.d.ts +10 -0
  13. package/dist/keyboard/scale-fingering.d.ts +41 -0
  14. package/dist/keyboard/voice-leading.d.ts +55 -4
  15. package/dist/music-notation.css +78 -5
  16. package/dist/music-notation.publish.min.js +101 -28
  17. package/dist/music-notation.tab.min.js +85 -9
  18. package/dist/playback/controls.d.ts +19 -2
  19. package/dist/playback/player.d.ts +69 -5
  20. package/dist/publish/index.js +4849 -3334
  21. package/dist/publish/index.js.map +33 -31
  22. package/dist/render/dom.d.ts +30 -1
  23. package/dist/strum/pattern.d.ts +31 -0
  24. package/dist/strum/play.d.ts +46 -5
  25. package/dist/strum/render.d.ts +5 -2
  26. package/dist/tab/index.d.ts +47 -2
  27. package/dist/tab/index.js +766 -77
  28. package/dist/tab/index.js.map +7 -7
  29. package/dist/tab/load.d.ts +10 -0
  30. package/dist/theory/detect.d.ts +6 -2
  31. package/dist/theory/find.d.ts +35 -7
  32. package/dist/theory/keys.d.ts +8 -2
  33. package/dist/theory/note-set.d.ts +5 -0
  34. package/dist/theory/numerals.d.ts +34 -7
  35. package/dist/voicings/check.d.ts +24 -0
  36. package/dist/voicings/curated.d.ts +10 -0
  37. package/dist/voicings/index.d.ts +1 -1
  38. package/dist/voicings/index.js +519 -111
  39. package/dist/voicings/index.js.map +10 -8
  40. package/package.json +1 -1
package/dist/tab/index.js CHANGED
@@ -22,6 +22,15 @@ function svgText(doc, text, attrs = {}) {
22
22
  function svgLabel(doc, text, [x, y], cls, anchor = "middle") {
23
23
  return svgText(doc, text, { class: cls, x, y: y + 4, "text-anchor": anchor });
24
24
  }
25
+ function dotLabel(doc, text, point, r) {
26
+ const label = svgLabel(doc, text, point, "mn-dot-text");
27
+ if ([...text].length >= 3) {
28
+ label.classList.add("mn-dot-text-long");
29
+ label.setAttribute("textLength", String(2 * r - 2));
30
+ label.setAttribute("lengthAdjust", "spacingAndGlyphs");
31
+ }
32
+ return label;
33
+ }
25
34
  function svgLine(doc, [x1, y1], [x2, y2], cls) {
26
35
  return svg(doc, "line", { class: cls, x1, y1, x2, y2 });
27
36
  }
@@ -33,15 +42,55 @@ function html(doc, tag, cls, text) {
33
42
  el.textContent = text;
34
43
  return el;
35
44
  }
45
+ var NAME_PREFIX = `mn-name-${Math.random().toString(36).slice(2, 8)}-`;
46
+ var names = 0;
36
47
  function svgRoot(doc, width, height, cls, label) {
48
+ const id = `${NAME_PREFIX}${++names}`;
49
+ const title = svg(doc, "title", { class: "mn-name", id });
50
+ title.textContent = label;
37
51
  return svg(doc, "svg", {
38
52
  xmlns: SVG_NS,
39
53
  viewBox: `0 0 ${width} ${height}`,
40
54
  width,
41
55
  class: `mn-svg ${cls}`,
42
56
  role: "img",
43
- "aria-label": label
57
+ "aria-labelledby": id
58
+ }, [svg(doc, "defs", {}, [title])]);
59
+ }
60
+ var nameElement = (el) => {
61
+ const id = el.getAttribute("aria-labelledby");
62
+ if (!id)
63
+ return null;
64
+ for (const candidate of el.querySelectorAll("[id]")) {
65
+ if (candidate.getAttribute("id") === id)
66
+ return candidate;
67
+ }
68
+ return el.ownerDocument.getElementById(id);
69
+ };
70
+ function accessibleName(el) {
71
+ const named = nameElement(el);
72
+ if (named)
73
+ return named.textContent;
74
+ return el.getAttribute("aria-label");
75
+ }
76
+ function setAccessibleName(el, name) {
77
+ const named = nameElement(el);
78
+ if (named)
79
+ named.textContent = name;
80
+ else
81
+ el.setAttribute("aria-label", name);
82
+ }
83
+ function playableMark(doc, area, ...children) {
84
+ const hit = svg(doc, "rect", {
85
+ class: "mn-hit",
86
+ x: area.x,
87
+ y: area.y,
88
+ width: area.width,
89
+ height: area.height,
90
+ fill: "transparent",
91
+ "pointer-events": "all"
44
92
  });
93
+ return svg(doc, "g", { class: "mn-mark" }, [hit, ...children]);
45
94
  }
46
95
 
47
96
  // src/theory/pitch.ts
@@ -95,11 +144,20 @@ var isFlat = (name) => /^[A-Ga-g][b♭]/.test(name.trim());
95
144
  var NAMED = new Map(Object.entries({
96
145
  standard: "E2 A2 D3 G3 B3 E4",
97
146
  "drop d": "D2 A2 D3 G3 B3 E4",
147
+ "drop c": "C2 G2 C3 F3 A3 D4",
148
+ "drop b": "B1 F#2 B2 E3 G#3 C#4",
149
+ "drop a": "A1 E2 A2 D3 F#3 B3",
150
+ "double drop d": "D2 A2 D3 G3 B3 D4",
98
151
  dadgad: "D2 A2 D3 G3 A3 D4",
99
152
  "open g": "D2 G2 D3 G3 B3 D4",
100
153
  "open d": "D2 A2 D3 F#3 A3 D4",
101
154
  "open e": "E2 B2 E3 G#3 B3 E4",
155
+ "open c": "C2 G2 C3 G3 C4 E4",
156
+ "open a": "E2 A2 E3 A3 C#4 E4",
102
157
  "half step down": "Eb2 Ab2 Db3 Gb3 Bb3 Eb4",
158
+ "whole step down": "D2 G2 C3 F3 A3 D4",
159
+ "modal c6": "C2 A2 C3 G3 C4 E4",
160
+ c6: "C2 A2 C3 G3 C4 E4",
103
161
  bass: "E1 A1 D2 G2",
104
162
  ukulele: "G4 C4 E4 A4"
105
163
  }));
@@ -190,7 +248,7 @@ function articulationOf(drum, hit) {
190
248
  return "KickHit";
191
249
  }
192
250
  }
193
- var effectOf = (hit) => hit === "X" || hit === "O" ? "{ac}" : hit === "g" ? "{g}" : "";
251
+ var effectOf = (hit) => hit === "X" || hit === "O" ? ["ac"] : hit === "g" ? ["g"] : [];
194
252
  var NOT_TAB = /[^-0-9xXoOgfdbhprsvt/\\~^().*<>#@+|:\s]|<(?!\d)/;
195
253
  var COUNT = /^\s*(?:[xX]\s*\d{1,3}|\d{1,3}\s*[xX])\s*$/;
196
254
  function splitText(line) {
@@ -210,7 +268,7 @@ function tabLineOf(raw) {
210
268
  const m = STRING_PREFIX.exec(line);
211
269
  const body = line.slice(m[0].length);
212
270
  if (STRING_BODY.test(body) && (line.match(/-/g)?.length ?? 0) >= 4 && (line.includes("|") || /^\s*[A-Ga-g][#b]?\s*[-|:]/.test(line)))
213
- string = { name: m[1] ?? null, body };
271
+ string = { name: m[1] ?? null, body, offset: m[0].length, barred: /[|:]$/.test(m[0]) };
214
272
  let drum = null;
215
273
  const d = DRUM_LINE.exec(line);
216
274
  const name = d ? d[1].toLowerCase().replace(/[ .-]/g, "") : "";
@@ -248,16 +306,39 @@ function splitDrums(run) {
248
306
  out.push(current);
249
307
  return out;
250
308
  }
251
- function stringSystems(run) {
252
- return splitStrings(run).flatMap((part) => {
309
+ var PM_LINE = /^[\sPpMm.\-_|=~]*$/;
310
+ var PM_MARK = /P\.?M/i;
311
+ function palmMutesOf(line) {
312
+ if (!PM_LINE.test(line) || !PM_MARK.test(line))
313
+ return [];
314
+ const ranges = [];
315
+ for (let i = 0;i < line.length; i++) {
316
+ const c = line[i];
317
+ const mark = (c === "P" || c === "p") && /^\.?[Mm]/.test(line.slice(i + 1, i + 3));
318
+ if (mark)
319
+ ranges.push([i, i]);
320
+ else if (c !== " " && ranges.length)
321
+ ranges[ranges.length - 1][1] = i;
322
+ }
323
+ return ranges;
324
+ }
325
+ function stringSystems(run, above = null) {
326
+ return splitStrings(run).flatMap((part, index) => {
253
327
  const names = part.map((l) => l.string.name);
254
328
  if (part.length < 3 && names.some((n) => n === null))
255
329
  return [];
256
330
  const lines = part.map((l) => l.string.body);
257
- return [{ kind: "strings", names, lines, texts: textsOf(part) }];
331
+ const offset = part[0].string.offset;
332
+ const muted = new Set;
333
+ if (index === 0 && above !== null)
334
+ for (const [a, b] of palmMutesOf(above))
335
+ for (let col = Math.max(a, offset);col <= b; col++)
336
+ muted.add(col - offset);
337
+ const openStart = part.some((l) => !l.string.barred);
338
+ return [{ kind: "strings", names, lines, texts: textsOf(part), muted, openStart }];
258
339
  });
259
340
  }
260
- function systemsOfRun(run) {
341
+ function systemsOfRun(run, above) {
261
342
  if (!run.length)
262
343
  return [];
263
344
  if (run.every((l) => l.drum) && run.some((l) => !l.string || !l.drum.lettered || /[xXoOgfdb#@*+]/.test(l.drum.body)))
@@ -268,7 +349,7 @@ function systemsOfRun(run) {
268
349
  texts: textsOf(part)
269
350
  }));
270
351
  if (run.every((l) => l.string))
271
- return stringSystems(run);
352
+ return stringSystems(run, above);
272
353
  const out = [];
273
354
  let stretch = [];
274
355
  for (const l of [...run, null]) {
@@ -276,7 +357,7 @@ function systemsOfRun(run) {
276
357
  stretch.push(l);
277
358
  else {
278
359
  if (stretch.length)
279
- out.push(...stringSystems(stretch));
360
+ out.push(...stringSystems(stretch, out.length ? null : above));
280
361
  stretch = [];
281
362
  }
282
363
  }
@@ -285,16 +366,21 @@ function systemsOfRun(run) {
285
366
  function systemsOf(text) {
286
367
  const systems = [];
287
368
  let run = [];
369
+ let above = null;
370
+ let previous = null;
288
371
  for (const raw of text.split(/\r?\n/)) {
289
372
  const line = tabLineOf(raw);
290
- if (line)
373
+ if (line) {
374
+ if (!run.length)
375
+ above = previous;
291
376
  run.push(line);
292
- else {
293
- systems.push(...systemsOfRun(run));
377
+ } else {
378
+ systems.push(...systemsOfRun(run, above));
294
379
  run = [];
295
380
  }
381
+ previous = raw;
296
382
  }
297
- systems.push(...systemsOfRun(run));
383
+ systems.push(...systemsOfRun(run, above));
298
384
  return systems;
299
385
  }
300
386
  function barsOf(lines, beatAt) {
@@ -303,49 +389,131 @@ function barsOf(lines, beatAt) {
303
389
  const bars = [];
304
390
  let beats = [];
305
391
  let filled = false;
392
+ let start = 0;
306
393
  for (let col = 0;col < width; col++) {
307
394
  if (padded.every((l) => l[col] === "|" || l[col] === ":")) {
308
395
  if (filled)
309
- bars.push(beats);
396
+ bars.push({ beats, start, end: col });
310
397
  beats = [];
311
398
  filled = false;
399
+ start = col + 1;
312
400
  continue;
313
401
  }
314
402
  if (padded.some((l) => l[col] !== " "))
315
403
  filled = true;
316
- const { beat, skip } = beatAt(padded, col);
404
+ const { beat, skip, at } = beatAt(padded, col);
317
405
  if (beat.length)
318
- beats.push(beat);
406
+ beats.push({ notes: beat, col: at ?? col });
319
407
  col += skip;
320
408
  }
321
409
  if (filled)
322
- bars.push(beats);
410
+ bars.push({ beats, start, end: width });
323
411
  return bars;
324
412
  }
325
- function stringBeatAt(padded, col) {
413
+ var isDigit = (c) => c !== undefined && c >= "0" && c <= "9";
414
+ var twoDigits = (a, b) => (a === "1" || a === "2") && isDigit(b) && Number(a + b) <= 24;
415
+ function techniquesOf(body) {
416
+ const frets = new Map;
417
+ const effects = new Map;
418
+ const hidden = new Set;
419
+ const target = (at) => {
420
+ let j = at;
421
+ const open = body[j] === "(";
422
+ if (open)
423
+ j++;
424
+ if (!isDigit(body[j]))
425
+ return { fret: null, next: at };
426
+ const width = twoDigits(body[j], body[j + 1]) ? 2 : 1;
427
+ const fret = Number(body.slice(j, j + width));
428
+ for (let w = 0;w < width; w++)
429
+ hidden.add(j + w);
430
+ j += width;
431
+ if (open && body[j] === ")")
432
+ j++;
433
+ return { fret, next: j };
434
+ };
435
+ for (let i = 0;i < body.length; ) {
436
+ if (!isDigit(body[i]) || hidden.has(i)) {
437
+ i++;
438
+ continue;
439
+ }
440
+ const width = twoDigits(body[i], body[i + 1]) ? 2 : 1;
441
+ const fret = Number(body.slice(i, i + width));
442
+ frets.set(i, { fret, width });
443
+ const fx = [];
444
+ const before = body[i - 1];
445
+ let k = i + width;
446
+ if (before === "<" && body[k] === ">") {
447
+ fx.push("nh");
448
+ k++;
449
+ } else if ((before === "/" || before === "\\") && !/[\d)>]/.test(body[i - 2] ?? "-"))
450
+ fx.push(before === "/" ? "sib" : "sia");
451
+ if (body[k] === "b" || body[k] === "^") {
452
+ const up = target(k + 1);
453
+ k = up.next;
454
+ const semitones = up.fret !== null && up.fret > fret ? Math.min(up.fret - fret, 4) : 2;
455
+ const points = [0, semitones * 2];
456
+ if (body[k] === "r") {
457
+ const down = target(k + 1);
458
+ k = down.next;
459
+ const back = down.fret === null ? 0 : (down.fret - fret) * 2;
460
+ points.push(Math.min(points[1], Math.max(0, back)));
461
+ }
462
+ fx.push(`b (${points.join(" ")})`);
463
+ }
464
+ if (body[k] === "~" || body[k] === "v") {
465
+ fx.push("v");
466
+ while (body[k] === "~" || body[k] === "v")
467
+ k++;
468
+ }
469
+ const next = body[k];
470
+ const onto = isDigit(body[k + 1]) || body[k + 1] === "(" && isDigit(body[k + 2]);
471
+ if ((next === "h" || next === "p") && onto)
472
+ fx.push("h");
473
+ else if (next === "/" || next === "\\" || next === "s") {
474
+ if (onto)
475
+ fx.push("sl");
476
+ else if (next !== "s")
477
+ fx.push(next === "/" ? "sou" : "sod");
478
+ }
479
+ if (fx.length)
480
+ effects.set(i, fx);
481
+ i += width;
482
+ }
483
+ return { frets, effects };
484
+ }
485
+ var stringBeatAt = (lines, muted, numbers = []) => (padded, col) => {
326
486
  const beat = [];
487
+ const strings = new Set;
488
+ let start = col;
327
489
  let wide = false;
328
- padded.forEach((line, i) => {
329
- const c = line[col];
330
- if (!/\d/.test(c) || /\d/.test(line[col - 1] ?? ""))
490
+ const read = (i, at) => {
491
+ const c = padded[i][at];
492
+ const pm = muted.has(at) ? ["pm"] : [];
493
+ if (c === "x" || c === "X") {
494
+ beat.push({ tex: `x.${numbers[i] ?? i + 1}`, effects: pm });
495
+ strings.add(i);
496
+ return;
497
+ }
498
+ const note = lines[i].frets.get(at);
499
+ if (!note)
331
500
  return;
332
- const two = /\d/.test(line[col + 1] ?? "") ? line.slice(col, col + 2) : c;
333
- if (two.length === 2)
501
+ if (note.width === 2 && at === col)
334
502
  wide = true;
335
- beat.push({ fret: Number(two), string: i + 1 });
336
- });
337
- if (wide)
338
- padded.forEach((line, i) => {
339
- if (beat.some((n) => n.string === i + 1))
340
- return;
341
- const c = line[col + 1] ?? "";
342
- if (!/\d/.test(c) || /\d/.test(line[col] ?? ""))
343
- return;
344
- const two = /\d/.test(line[col + 2] ?? "") ? line.slice(col + 1, col + 3) : c;
345
- beat.push({ fret: Number(two), string: i + 1 });
503
+ if (padded[i][at - 1] === "<")
504
+ start = Math.min(start, at - 1);
505
+ beat.push({
506
+ tex: `${note.fret}.${numbers[i] ?? i + 1}`,
507
+ effects: [...lines[i].effects.get(at) ?? [], ...pm],
508
+ string: numbers[i] ?? i + 1
346
509
  });
347
- return { beat, skip: wide ? 1 : 0 };
348
- }
510
+ strings.add(i);
511
+ };
512
+ padded.forEach((_, i) => read(i, col));
513
+ if (wide)
514
+ padded.forEach((_, i) => strings.has(i) || read(i, col + 1));
515
+ return { beat, skip: wide ? 1 : 0, at: start };
516
+ };
349
517
  var BY_COUNT = {
350
518
  3: [64, 59, 55],
351
519
  4: [43, 38, 33, 28],
@@ -381,6 +549,28 @@ function tuningOf(names) {
381
549
  }
382
550
  return BY_COUNT[strings] ?? null;
383
551
  }
552
+ function onGuitar(midi) {
553
+ const tuning = [...BY_COUNT[6]];
554
+ let index = tuning.indexOf(midi);
555
+ if (index < 0) {
556
+ index = tuning.reduce((best, m, i) => Math.abs(m - midi) < Math.abs(tuning[best] - midi) ? i : best, 0);
557
+ tuning[index] = midi;
558
+ }
559
+ return { tuning, string: index + 1 };
560
+ }
561
+ function placedOnGuitar(tuning) {
562
+ if (tuning.length === 1) {
563
+ const { tuning: six, string } = onGuitar(tuning[0]);
564
+ return { tuning: six, strings: [string] };
565
+ }
566
+ const standard = BY_COUNT[6];
567
+ if (tuning.length > 5)
568
+ return null;
569
+ const at = tuning.map((m) => standard.indexOf(m));
570
+ if (at[0] < 0 || at.some((i, k) => i !== at[0] + k))
571
+ return null;
572
+ return { tuning: [...standard], strings: at.map((i) => i + 1) };
573
+ }
384
574
  var drumBeatAt = (drums) => (padded, col) => {
385
575
  const beat = [];
386
576
  padded.forEach((line, i) => {
@@ -388,22 +578,385 @@ var drumBeatAt = (drums) => (padded, col) => {
388
578
  if (!/[xXoOgfdb#@*+]/.test(hit))
389
579
  return;
390
580
  const name = articulationOf(drums[i], hit);
391
- if (!beat.some((n) => n.startsWith(name + "{") || n === name))
392
- beat.push(name + effectOf(hit));
581
+ if (!beat.some((n) => n.tex === name))
582
+ beat.push({ tex: name, effects: effectOf(hit) });
393
583
  });
394
584
  return { beat, skip: 0 };
395
585
  };
586
+ var VALUES = [
587
+ [24, 1, true],
588
+ [16, 1, false],
589
+ [12, 2, true],
590
+ [8, 2, false],
591
+ [6, 4, true],
592
+ [4, 4, false],
593
+ [3, 8, true],
594
+ [2, 8, false],
595
+ [1, 16, false]
596
+ ];
597
+ function valuesOf(sixteenths) {
598
+ const out = [];
599
+ for (let left = sixteenths;left > 0; ) {
600
+ const [length, duration, dotted] = VALUES.find(([n]) => n <= left);
601
+ out.push({ duration, dotted });
602
+ left -= length;
603
+ }
604
+ return out;
605
+ }
606
+ var COMMON = { ts: [4, 4], length: 16, beat: 4, grids: [1, 2, 4, 8, 16] };
607
+ var THREE_FOUR = { ts: [3, 4], length: 12, beat: 4, grids: [1, 3, 6, 12] };
608
+ var SIX_EIGHT = { ts: [6, 8], length: 12, beat: 6, grids: [1, 2, 6, 12] };
609
+ var TWELVE_EIGHT = { ts: [12, 8], length: 24, beat: 6, grids: [1, 2, 4, 12, 24] };
610
+ function keepsSpacing(cols, at) {
611
+ const lengths = new Map;
612
+ for (let i = 1;i < cols.length; i++) {
613
+ const gap = cols[i] - cols[i - 1];
614
+ const length = at[i] - at[i - 1];
615
+ if ((lengths.get(gap) ?? length) !== length)
616
+ return false;
617
+ lengths.set(gap, length);
618
+ }
619
+ const sorted = [...lengths].sort((a, b) => a[0] - b[0]);
620
+ return sorted.every(([, length], i) => i === 0 || length >= sorted[i - 1][1]);
621
+ }
622
+ var PLAIN = new Set(VALUES.map(([n]) => n));
623
+ function fit(cols, n, [origin, span], slack, ties, bar) {
624
+ const step = span / n;
625
+ if (step < 1 || ties && !Number.isInteger(step))
626
+ return null;
627
+ const at = [];
628
+ let error = 0;
629
+ for (const col of cols) {
630
+ const exact = (col - origin) / step;
631
+ const k = Math.round(exact);
632
+ const off = Math.abs(exact - k) * step;
633
+ if (k < 0 || k >= n || off > slack + 0.000000001 || at.length && k * (bar / n) <= at.at(-1))
634
+ return null;
635
+ error = Math.max(error, off);
636
+ at.push(k * (bar / n));
637
+ }
638
+ if (!ties && at.some((p, i) => !PLAIN.has((at[i + 1] ?? bar) - p)))
639
+ return null;
640
+ return keepsSpacing(cols, at) ? { at, error } : null;
641
+ }
642
+ function positionsOf(cols, width, pad, meter = COMMON) {
643
+ if (!cols.length)
644
+ return [];
645
+ const spans = [
646
+ [pad, width - pad],
647
+ [pad, width]
648
+ ];
649
+ for (let start = 1;start < pad; start++)
650
+ spans.push([start, width - start]);
651
+ if (cols[0] > pad)
652
+ spans.push([0, width]);
653
+ for (const [slack, ties] of [
654
+ [0.4, false],
655
+ [1, false],
656
+ [0.4, true]
657
+ ])
658
+ for (const n of meter.grids) {
659
+ const fits = spans.map((span) => fit(cols, n, span, slack, ties, meter.length)).filter((f) => f !== null);
660
+ if (fits.length)
661
+ return fits.reduce((a, b) => b.error < a.error ? b : a).at;
662
+ }
663
+ return null;
664
+ }
665
+ function restsFrom(at, meter, end = meter.length) {
666
+ const out = [];
667
+ const { beat, length: bar } = meter;
668
+ for (let p = at;p < end; ) {
669
+ const half = bar === 4 * beat && p % (2 * beat) === 0 && p <= bar / 2 ? [2 * beat] : [];
670
+ const lengths = p % 2 ? [1] : p % beat ? [2, 1] : [...half, beat, 2, 1];
671
+ const length = lengths.find((n) => n <= end - p);
672
+ out.push({ beat: -1, sixteenths: length });
673
+ p += length;
674
+ }
675
+ return out;
676
+ }
677
+ function sketchRhythmOf(cols, meter = COMMON, legato = []) {
678
+ const gaps = cols.slice(1).map((c, i) => c - cols[i]);
679
+ const counts = new Map;
680
+ for (const g of gaps)
681
+ counts.set(g, (counts.get(g) ?? 0) + 1);
682
+ const unit = [...counts].reduce((best, e) => !best || e[1] > best[1] || e[1] === best[1] && e[0] < best[0] ? e : best, null)?.[0];
683
+ for (const eighth of [2, 1]) {
684
+ const lengths = cols.map((_, i) => eighth * (i < gaps.length ? Math.max(1, Math.round(gaps[i] / unit)) : 1));
685
+ let total = lengths.reduce((a, b) => a + b, 0);
686
+ if (eighth === 2)
687
+ for (const i of legato) {
688
+ if (total <= meter.length)
689
+ break;
690
+ if (i + 1 >= lengths.length || lengths[i] !== 2)
691
+ continue;
692
+ const next = Math.max(1, lengths[i + 1] - 1);
693
+ total -= 1 + lengths[i + 1] - next;
694
+ lengths[i] = 1;
695
+ lengths[i + 1] = next;
696
+ }
697
+ if (total > meter.length)
698
+ continue;
699
+ return [
700
+ ...lengths.map((sixteenths, beat) => ({ beat, sixteenths })),
701
+ ...restsFrom(total, meter)
702
+ ];
703
+ }
704
+ return cols.map((_, beat) => ({ beat, sixteenths: 1 }));
705
+ }
706
+ var LEGATO = new Set(["h", "sl"]);
707
+ var legatoOf = (beats) => beats.flatMap((b, i) => b.notes.some((n) => n.effects.some((e) => LEGATO.has(e))) ? [i] : []);
708
+ function rhythmOf(m, typical, meter) {
709
+ const bar = meter.length;
710
+ const span = m.part === "whole" ? m.width : typical;
711
+ const shift = m.part === "end" ? typical - m.width : 0;
712
+ const cols = m.beats.map((b) => b.col + shift);
713
+ if (m.part === "start" && cols.length) {
714
+ const at = positionsOf([...cols, m.width], span, m.pad, meter);
715
+ if (at) {
716
+ const end = at.pop();
717
+ const out = at[0] > 0 ? [{ beat: -1, sixteenths: at[0] }] : [];
718
+ at.forEach((p, beat) => out.push({ beat, sixteenths: (at[beat + 1] ?? end) - p }));
719
+ return [...out, ...restsFrom(end, meter)];
720
+ }
721
+ }
722
+ const at = positionsOf(cols, span, m.pad, meter);
723
+ if (!at) {
724
+ const sketch = sketchRhythmOf(m.beats.map((b) => b.col), meter, legatoOf(m.beats));
725
+ if (m.part !== "end")
726
+ return sketch;
727
+ const notes = sketch.filter((e) => e.beat >= 0);
728
+ const total = notes.reduce((sum, e) => sum + e.sixteenths, 0);
729
+ return m.pickup ? notes : [...restsFrom(0, meter, bar - total), ...notes];
730
+ }
731
+ const first = at[0];
732
+ const out = first === 0 || m.pickup ? [] : m.part === "end" ? restsFrom(0, meter, first) : [{ beat: -1, sixteenths: first }];
733
+ at.forEach((p, beat) => out.push({ beat, sixteenths: (at[beat + 1] ?? bar) - p }));
734
+ return out;
735
+ }
736
+ var padOf = (bars) => bars.reduce((pad, b) => b.beats.length ? Math.min(pad, b.beats[0].col - b.start) : pad, 3);
737
+ function rowOf(lines, bars, texts, openStart) {
738
+ const width = Math.max(...lines.map((l) => l.length));
739
+ return {
740
+ bars,
741
+ pad: padOf(bars),
742
+ texts,
743
+ openStart: openStart && bars[0]?.start === 0,
744
+ openEnd: bars.at(-1)?.end === width
745
+ };
746
+ }
747
+ function typicalWidth(rows) {
748
+ const widths = [];
749
+ for (const row of rows)
750
+ row.bars.forEach((bar, i) => {
751
+ const closed = (i > 0 || !row.openStart) && (i < row.bars.length - 1 || !row.openEnd);
752
+ if (closed && bar.beats.length)
753
+ widths.push(bar.end - bar.start);
754
+ });
755
+ if (widths.length < 2)
756
+ return null;
757
+ widths.sort((a, b) => a - b);
758
+ return widths[widths.length >> 1];
759
+ }
760
+ function mostFrequent(values) {
761
+ const counts = new Map;
762
+ for (const v of values)
763
+ counts.set(v, (counts.get(v) ?? 0) + 1);
764
+ let best;
765
+ for (const [value, count] of counts)
766
+ if (!best || count > best.count || count === best.count && value < best.value)
767
+ best = { value, count };
768
+ return best;
769
+ }
770
+ function meterOf(rows, typical) {
771
+ if (typical === null)
772
+ return COMMON;
773
+ const bars = [];
774
+ for (const row of rows)
775
+ row.bars.forEach((bar, i) => {
776
+ const closed = (i > 0 || !row.openStart) && (i < row.bars.length - 1 || !row.openEnd);
777
+ const width = bar.end - bar.start;
778
+ if (closed && bar.beats.length && Math.abs(width - typical) <= 1)
779
+ bars.push({ bar, pad: row.pad });
780
+ });
781
+ const gaps = new Map;
782
+ for (const { bar } of bars)
783
+ for (let i = 1;i < bar.beats.length; i++) {
784
+ const gap = bar.beats[i].col - bar.beats[i - 1].col;
785
+ gaps.set(gap, (gaps.get(gap) ?? 0) + 1);
786
+ }
787
+ const top = Math.max(0, ...gaps.values());
788
+ const unit = Math.min(...[...gaps].filter(([, n]) => n * 2 >= top).map(([gap]) => gap));
789
+ if (bars.length < 2 || !Number.isFinite(unit))
790
+ return COMMON;
791
+ const counts = [];
792
+ let twos = 0;
793
+ let threes = 0;
794
+ for (const { bar, pad } of bars) {
795
+ const exact = bar.beats.map((b) => (b.col - bar.start - pad) / unit);
796
+ if (exact.some((u) => Math.abs(u - Math.round(u)) * unit > 0.4 + 0.000000001)) {
797
+ counts.push(0);
798
+ continue;
799
+ }
800
+ const at = exact.map(Math.round);
801
+ const count = Math.max(Math.ceil((bar.end - bar.start - pad) / unit - 0.5), at.at(-1) + 1);
802
+ counts.push(count);
803
+ if (count !== 6)
804
+ continue;
805
+ const lowest = bar.beats.reduce((low, b) => b.notes.reduce((l, n) => Math.max(l, n.string ?? 0), low), 0);
806
+ const bass = at.filter((_, i) => bar.beats[i].notes.some((n) => n.string === lowest));
807
+ for (const group of [at, bass.length < at.length ? bass : []]) {
808
+ if (group.some((u) => u !== 0 && u % 2 === 0) && group.every((u) => u % 2 === 0))
809
+ twos++;
810
+ else if (group.includes(3) && group.every((u) => u % 3 === 0))
811
+ threes++;
812
+ }
813
+ }
814
+ const most = mostFrequent(counts);
815
+ if (most.count * 3 < bars.length * 2)
816
+ return COMMON;
817
+ if (most.value === 3)
818
+ return THREE_FOUR;
819
+ if (most.value === 6)
820
+ return twos > threes ? THREE_FOUR : SIX_EIGHT;
821
+ return most.value === 12 ? TWELVE_EIGHT : COMMON;
822
+ }
823
+ function measuresOf(rows, typical) {
824
+ const short = (width) => typical !== null && width <= typical * 2 / 3;
825
+ const out = [];
826
+ let carry = null;
827
+ rows.forEach((row, r) => {
828
+ const before = out.length;
829
+ const next = rows[r + 1];
830
+ row.bars.forEach((bar, i) => {
831
+ const beats = bar.beats.map((b) => ({ notes: b.notes, col: b.col - bar.start }));
832
+ let m = {
833
+ beats,
834
+ width: bar.end - bar.start,
835
+ pad: row.pad,
836
+ part: "whole",
837
+ pickup: false,
838
+ text: null
839
+ };
840
+ const joined = i === 0 && carry !== null;
841
+ if (carry && i === 0) {
842
+ const shift = carry.width - row.pad;
843
+ m = {
844
+ ...carry,
845
+ beats: [
846
+ ...carry.beats,
847
+ ...beats.map((b) => ({ notes: b.notes, col: b.col + shift }))
848
+ ],
849
+ width: carry.width + m.width - row.pad
850
+ };
851
+ carry = null;
852
+ }
853
+ if (i === row.bars.length - 1 && short(m.width)) {
854
+ const after = next?.bars[0];
855
+ const together = after ? m.width + after.end - after.start - next.pad : 0;
856
+ if (after && (row.openEnd || short(after.end - after.start) && (next.openStart || together <= typical * 1.25))) {
857
+ if (m.beats.length || !row.openEnd)
858
+ carry = m;
859
+ return;
860
+ }
861
+ if (row.openEnd && !joined) {
862
+ if (!m.beats.length)
863
+ return;
864
+ m.part = "start";
865
+ }
866
+ }
867
+ const first = !out.length;
868
+ if (i === 0 && !joined && m.part === "whole" && short(m.width) && m.beats.length) {
869
+ if (first || row.openStart) {
870
+ m.part = "end";
871
+ m.pickup = first;
872
+ }
873
+ }
874
+ out.push(m);
875
+ });
876
+ const target = carry ?? (out.length > before ? out.at(-1) : null);
877
+ if (row.texts.length && target) {
878
+ const text = row.texts.join(" / ");
879
+ target.text = target.text ? `${target.text} / ${text}` : text;
880
+ }
881
+ });
882
+ return out;
883
+ }
884
+ function splitUnbarred(measures, meter) {
885
+ return measures.flatMap((m) => {
886
+ if (m.part !== "whole" || m.beats.length < 2)
887
+ return [m];
888
+ const cols = m.beats.map((b) => b.col);
889
+ if (positionsOf(cols, m.width, m.pad, meter))
890
+ return [m];
891
+ const gaps = cols.slice(1).map((c, i) => c - cols[i]);
892
+ const unit = mostFrequent(gaps).value;
893
+ const eighths = gaps.reduce((sum, g) => sum + Math.max(1, Math.round(g / unit)), 1);
894
+ const perBar = meter.length / 2;
895
+ const span = unit * perBar;
896
+ if (eighths <= perBar || m.width - m.pad < span * 1.5)
897
+ return [m];
898
+ const count = Math.floor((cols.at(-1) - m.pad) / span) + 1;
899
+ return Array.from({ length: count }, (_, k) => {
900
+ const from = m.pad + k * span;
901
+ const beats = m.beats.filter((b) => (k === 0 || b.col >= from) && (k === count - 1 || b.col < from + span)).map((b) => ({ notes: b.notes, col: b.col - k * span }));
902
+ return {
903
+ beats,
904
+ width: m.pad + span,
905
+ pad: m.pad,
906
+ part: "whole",
907
+ pickup: false,
908
+ text: k === count - 1 ? m.text : null
909
+ };
910
+ });
911
+ });
912
+ }
396
913
  var quoted = (text) => `"${text.replace(/[\\"]/g, (c) => `\\${c}`)}"`;
397
- function texOf(bars) {
914
+ var withEffects = (tex, effects) => effects.length ? `${tex}{${effects.join(" ")}}` : tex;
915
+ function beatTex(notes, effects) {
916
+ if (!notes.length)
917
+ return withEffects("r", effects);
918
+ if (notes.length === 1)
919
+ return withEffects(notes[0].tex, [...notes[0].effects, ...effects]);
920
+ return withEffects(`(${notes.map((n) => withEffects(n.tex, n.effects)).join(" ")})`, effects);
921
+ }
922
+ var LINKS = new Set(["h", "sl", "sou", "sod"]);
923
+ function tied(notes, pieces) {
924
+ if (pieces === 1)
925
+ return [notes];
926
+ const out = [notes.map((n) => ({ ...n, effects: n.effects.filter((e) => !LINKS.has(e)) }))];
927
+ for (let piece = 1;piece < pieces; piece++)
928
+ out.push(notes.filter((n) => n.string !== undefined).map((n) => ({
929
+ tex: `-.${n.string}`,
930
+ effects: n.effects.filter((e) => e === "pm" || piece === pieces - 1 && LINKS.has(e))
931
+ })));
932
+ return out;
933
+ }
934
+ function texOf(bars, meter) {
398
935
  let duration = 0;
399
- const out = bars.map(({ beats, text }) => {
400
- const wanted = beats.length ? 8 : 1;
401
- const items = beats.length ? [...beats] : ["r"];
402
- if (text)
403
- items[items.length - 1] += `{txt ${quoted(text)}}`;
404
- const head = wanted === duration ? "" : `:${wanted} `;
405
- duration = wanted;
406
- return head + items.join(" ");
936
+ const out = bars.map(({ beats, rhythm, text, pickup }) => {
937
+ const items = [];
938
+ if (!beats.length)
939
+ for (const value of meter === COMMON ? [{ duration: 1, dotted: false }] : valuesOf(meter.length))
940
+ items.push({ notes: [], ...value });
941
+ for (const { beat, sixteenths } of rhythm) {
942
+ const values = valuesOf(sixteenths);
943
+ const notes = tied(beat >= 0 ? beats[beat] : [], values.length);
944
+ values.forEach((value, i) => items.push({ notes: notes[i], ...value }));
945
+ }
946
+ let annotated = items.length - 1;
947
+ while (annotated > 0 && !items[annotated].notes.length)
948
+ annotated--;
949
+ if (!items[annotated].notes.length)
950
+ annotated = items.length - 1;
951
+ const tex = items.map((item, i) => {
952
+ const effects = item.dotted ? ["d"] : [];
953
+ if (text && i === annotated)
954
+ effects.push(`txt ${quoted(text)}`);
955
+ const head = item.duration === duration ? "" : `:${item.duration} `;
956
+ duration = item.duration;
957
+ return head + beatTex(item.notes, effects);
958
+ }).join(" ");
959
+ return pickup ? `\\ac ${tex}` : tex;
407
960
  });
408
961
  return out.join(` |
409
962
  `);
@@ -413,36 +966,47 @@ function textTabToAlphaTex(text) {
413
966
  const first = systems[0];
414
967
  if (!first)
415
968
  return null;
416
- const bars = [];
417
- const add = (systemBars, texts) => {
418
- const at = bars.length;
419
- bars.push(...systemBars.map((b) => ({ beats: b.map(chord), text: null })));
420
- if (texts.length && bars.length > at)
421
- bars[bars.length - 1].text = texts.join(" / ");
422
- };
423
- const chord = (notes) => notes.length === 1 ? notes[0] : `(${notes.join(" ")})`;
969
+ let tuning = first.kind === "strings" ? tuningOf(first.names) : null;
970
+ const placed = tuning ? placedOnGuitar(tuning) : null;
971
+ if (placed)
972
+ tuning = placed.tuning;
973
+ const rows = [];
424
974
  if (first.kind === "drums") {
425
975
  for (const s of systems)
426
976
  if (s.kind === "drums")
427
- add(barsOf(s.lines, drumBeatAt(s.drums)), s.texts);
428
- if (!bars.length)
429
- return null;
430
- return ["\\instrument percussion", "\\articulation defaults", texOf(bars)].join(`
431
- `);
432
- }
433
- const tuning = tuningOf(first.names);
434
- const same = JSON.stringify(tuning);
435
- for (const s of systems) {
436
- if (s.kind !== "strings" || JSON.stringify(tuningOf(s.names)) !== same)
437
- continue;
438
- const noteBars = barsOf(s.lines, stringBeatAt);
439
- add(noteBars.map((bar) => bar.map((beat) => beat.map((n) => `${n.fret}.${n.string}`))), s.texts);
977
+ rows.push(rowOf(s.lines, barsOf(s.lines, drumBeatAt(s.drums)), s.texts, false));
978
+ } else {
979
+ const same = JSON.stringify(tuningOf(first.names));
980
+ const strings = placed?.strings ?? [];
981
+ for (const s of systems) {
982
+ if (s.kind !== "strings" || JSON.stringify(tuningOf(s.names)) !== same)
983
+ continue;
984
+ const beatAt = stringBeatAt(s.lines.map(techniquesOf), s.muted, strings);
985
+ rows.push(rowOf(s.lines, barsOf(s.lines, beatAt), s.texts, s.openStart));
986
+ }
440
987
  }
988
+ const typical = typicalWidth(rows);
989
+ const meter = meterOf(rows, typical);
990
+ const bars = splitUnbarred(measuresOf(rows, typical), meter).map((m) => ({
991
+ beats: m.beats.map((b) => b.notes),
992
+ rhythm: rhythmOf(m, typical ?? 0, meter),
993
+ text: m.text,
994
+ pickup: m.pickup
995
+ }));
441
996
  if (!bars.length)
442
997
  return null;
998
+ const ts = meter === COMMON ? [] : [`\\ts ${meter.ts.join(" ")}`];
999
+ if (first.kind === "drums")
1000
+ return [
1001
+ "\\instrument percussion",
1002
+ "\\articulation defaults",
1003
+ ...ts,
1004
+ texOf(bars, meter)
1005
+ ].join(`
1006
+ `);
443
1007
  const standard = tuning?.join(" ") === BY_COUNT[6].join(" ");
444
1008
  const header = tuning && !standard ? [`\\tuning (${tuning.map((m) => noteOf(m)).join(" ")})`] : [];
445
- return [...header, texOf(bars)].join(`
1009
+ return [...header, ...ts, texOf(bars, meter)].join(`
446
1010
  `);
447
1011
  }
448
1012
  // src/theory/note-set.ts
@@ -655,6 +1219,14 @@ function chordNoteSet(symbol) {
655
1219
  }
656
1220
  return set;
657
1221
  }
1222
+ function respell(set, chord) {
1223
+ set.root = chord.root;
1224
+ for (const member of set.members) {
1225
+ const own = memberFor(chord, member.chroma);
1226
+ if (own)
1227
+ member.name = own.name;
1228
+ }
1229
+ }
658
1230
  function scaleNoteSet(name) {
659
1231
  const scale = Scale2.get(scaleName(name));
660
1232
  if (scale.empty || !scale.tonic)
@@ -852,7 +1424,15 @@ var alphaTabCdn = (version = ALPHATAB_VERSION) => {
852
1424
  var SETTING = /^\s*(staves|file|tracks?)\s*:\s*(.*)$/i;
853
1425
  function parseTabSource(language, source) {
854
1426
  const lines = source.split(/\r?\n/);
855
- const out = { staves: language, file: null, tracks: null, tex: "", texLine: 0 };
1427
+ const out = {
1428
+ staves: language,
1429
+ stavesWritten: false,
1430
+ file: null,
1431
+ tracks: null,
1432
+ tex: "",
1433
+ texLine: 0,
1434
+ fromText: false
1435
+ };
856
1436
  let i = 0;
857
1437
  for (;i < lines.length; i++) {
858
1438
  const line = lines[i];
@@ -869,6 +1449,7 @@ function parseTabSource(language, source) {
869
1449
  throw new Error(`staves: use tab, score or both, got "${value}"`);
870
1450
  }
871
1451
  out.staves = v;
1452
+ out.stavesWritten = true;
872
1453
  } else if (key === "file") {
873
1454
  out.file = value.replace(/^!?\[\[|\]\]$/g, "").split(/[|#]/)[0].trim() || null;
874
1455
  } else {
@@ -886,6 +1467,11 @@ function parseTabSource(language, source) {
886
1467
  `).trimEnd();
887
1468
  if (!out.file && !out.tex)
888
1469
  throw new Error("Write the music in alphaTex, or give a file: [[Song.gp]]");
1470
+ const converted = out.file ? null : textTabToAlphaTex(out.tex);
1471
+ if (converted !== null) {
1472
+ out.tex = converted;
1473
+ out.fromText = true;
1474
+ }
889
1475
  return out;
890
1476
  }
891
1477
  function messageOf(error, lineOffset) {
@@ -896,7 +1482,7 @@ function messageOf(error, lineOffset) {
896
1482
  continue;
897
1483
  const first = items.find((d) => d.severity === 2 && d.message);
898
1484
  if (first) {
899
- const at = first.start ? `line ${first.start.line + lineOffset}, column ${first.start.col}: ` : "";
1485
+ const at = first.start && lineOffset !== null ? `line ${first.start.line + lineOffset}, column ${first.start.col}: ` : "";
900
1486
  return `${at}${first.message}`;
901
1487
  }
902
1488
  }
@@ -922,6 +1508,26 @@ function chooseStaves(staves, score) {
922
1508
  }
923
1509
  }
924
1510
  }
1511
+ var DEFAULT_DYNAMIC = 5;
1512
+ function hideDefaultDynamics(score, tex) {
1513
+ if (tex !== null && /\bdy\b|\\showdynamics/i.test(tex))
1514
+ return;
1515
+ const written = score.tracks.some((track) => track.staves.some((staff) => staff.bars.some((bar) => bar.voices.some((voice) => voice.beats.some((beat) => !beat.isRest && beat.dynamics !== DEFAULT_DYNAMIC)))));
1516
+ if (!written)
1517
+ score.stylesheet.hideDynamics = true;
1518
+ }
1519
+ var CREDIT = "rendered by alphaTab";
1520
+ function hideCredit(api, surface) {
1521
+ const renderer = api.renderer;
1522
+ renderer?.partialRenderFinished?.on((e) => {
1523
+ for (const part of surface.querySelectorAll(".at-surface > div")) {
1524
+ if (part.layoutResultId !== e.id)
1525
+ continue;
1526
+ const credit = typeof e.renderResult === "string" && e.renderResult.includes(CREDIT);
1527
+ part.style.visibility = credit ? "hidden" : "";
1528
+ }
1529
+ });
1530
+ }
925
1531
  function rgbaOf(doc, color, alpha = 1) {
926
1532
  const canvas = doc.createElement("canvas");
927
1533
  canvas.width = 1;
@@ -1002,6 +1608,7 @@ var time = (ms) => {
1002
1608
  };
1003
1609
  function playerBar(doc, api, alphaTab, assets) {
1004
1610
  const bar = html(doc, "div", "mn-play mn-tab-bar");
1611
+ bar.addEventListener("mousedown", (event) => event.stopPropagation());
1005
1612
  bar.setAttribute("role", "group");
1006
1613
  bar.setAttribute("aria-label", "Playback");
1007
1614
  const state = { loop: false, metronome: false, countIn: false, speed: 1, volume: 1 };
@@ -1115,6 +1722,55 @@ function playerBar(doc, api, alphaTab, assets) {
1115
1722
  }
1116
1723
  };
1117
1724
  }
1725
+ function hasTablature(score, tracks) {
1726
+ return score.tracks.some((track, i) => (!tracks || tracks.includes(i + 1)) && track.staves.some((staff) => !staff.isPercussion && staff.tuning.length > 0));
1727
+ }
1728
+ var VIEWS = [
1729
+ { staves: "tab", label: "Tab", what: "tablature" },
1730
+ { staves: "score", label: "Score", what: "standard notation" },
1731
+ { staves: "both", label: "Both", what: "standard notation and tablature" }
1732
+ ];
1733
+ function viewControl(doc, own, choose, keep) {
1734
+ const group = html(doc, "span", "mn-tab-views");
1735
+ group.setAttribute("role", "group");
1736
+ group.setAttribute("aria-label", "View");
1737
+ let current = own.staves;
1738
+ const keepButton = keep ? html(doc, "button", "mn-tab-keep", "Keep this view") : null;
1739
+ const buttons = VIEWS.map(({ staves, label, what }) => {
1740
+ const b = html(doc, "button", "mn-tab-view", label);
1741
+ b.type = "button";
1742
+ b.dataset["staves"] = staves;
1743
+ const mine = staves !== own.staves ? "" : own.written ? ` (this block's staves: line)` : " (the default: the block has no staves: line)";
1744
+ b.title = `Draw as ${what}${mine}`;
1745
+ b.addEventListener("click", () => {
1746
+ if (staves === current)
1747
+ return;
1748
+ current = staves;
1749
+ show();
1750
+ choose(staves);
1751
+ });
1752
+ group.appendChild(b);
1753
+ return b;
1754
+ });
1755
+ const show = () => {
1756
+ for (const b of buttons) {
1757
+ const on = b.dataset["staves"] === current;
1758
+ b.classList.toggle("mn-on", on);
1759
+ b.setAttribute("aria-pressed", String(on));
1760
+ }
1761
+ if (keepButton) {
1762
+ keepButton.hidden = current === own.staves;
1763
+ keepButton.title = `Write staves: ${current} at the top of the block`;
1764
+ }
1765
+ };
1766
+ if (keepButton && keep) {
1767
+ keepButton.type = "button";
1768
+ keepButton.addEventListener("click", () => keep(current));
1769
+ group.appendChild(keepButton);
1770
+ }
1771
+ show();
1772
+ return group;
1773
+ }
1118
1774
  function renderTab(language, source, host, options) {
1119
1775
  const doc = host.ownerDocument;
1120
1776
  const el = html(doc, "div", `mn-block mn-block-${language} mn-tab`);
@@ -1143,6 +1799,12 @@ function renderTab(language, source, host, options) {
1143
1799
  (async () => {
1144
1800
  await Promise.resolve();
1145
1801
  const parsed = parseTabSource(language, source);
1802
+ const own = {
1803
+ staves: parsed.stavesWritten ? parsed.staves : options.defaultStaves ?? parsed.staves,
1804
+ written: parsed.stavesWritten
1805
+ };
1806
+ let view = own.staves;
1807
+ let tablature = false;
1146
1808
  const at = options.alphaTab;
1147
1809
  if (!at?.AlphaTabApi)
1148
1810
  throw new Error("alphaTab isn't loaded");
@@ -1155,7 +1817,8 @@ function renderTab(language, source, host, options) {
1155
1817
  useWorkers: Boolean(assets.scriptFile),
1156
1818
  ...assets.scriptFile ? { scriptFile: assets.scriptFile } : {},
1157
1819
  smuflFontSources: made.map([[at.FontFileFormat.Woff2, assets.font]]),
1158
- logLevel: at.LogLevel.Warning
1820
+ logLevel: at.LogLevel.Warning,
1821
+ enableLazyLoading: false
1159
1822
  },
1160
1823
  display: {
1161
1824
  staveProfile: "Default",
@@ -1170,9 +1833,14 @@ function renderTab(language, source, host, options) {
1170
1833
  return;
1171
1834
  }
1172
1835
  options.onApi?.(current);
1836
+ let written = [];
1173
1837
  current.scoreLoaded.on((score) => {
1174
- chooseStaves(parsed.staves, score);
1838
+ written = score.tracks.flatMap((t) => t.staves.map((s) => ({ showSlash: s.showSlash, showNumbered: s.showNumbered })));
1839
+ chooseStaves(view, score);
1840
+ tablature = hasTablature(score, parsed.tracks);
1841
+ hideDefaultDynamics(score, parsed.file ? null : parsed.tex);
1175
1842
  });
1843
+ hideCredit(current, surface);
1176
1844
  let bar = null;
1177
1845
  current.renderFinished.on(() => {
1178
1846
  if (settled || gone)
@@ -1180,6 +1848,17 @@ function renderTab(language, source, host, options) {
1180
1848
  if (options.player !== false) {
1181
1849
  bar = playerBar(doc, current, at, assets);
1182
1850
  el.appendChild(bar.bar);
1851
+ if (options.views !== false && tablature)
1852
+ bar.bar.appendChild(viewControl(doc, own, (staves) => {
1853
+ view = staves;
1854
+ const score = current.score;
1855
+ if (gone || !score)
1856
+ return;
1857
+ const all = score.tracks.flatMap((t) => t.staves);
1858
+ all.forEach((staff, i) => Object.assign(staff, written[i]));
1859
+ chooseStaves(staves, score);
1860
+ current.render();
1861
+ }, options.onKeepView));
1183
1862
  el.addEventListener("pointerdown", (event) => {
1184
1863
  if (event.pointerType !== "touch" || bar?.bar.contains(event.target))
1185
1864
  return;
@@ -1189,7 +1868,7 @@ function renderTab(language, source, host, options) {
1189
1868
  settle({ ok: true, error: null });
1190
1869
  });
1191
1870
  current.error.on((e) => {
1192
- const message = messageOf(e, parsed.texLine);
1871
+ const message = parsed.fromText ? `Couldn't draw this text tab: ${messageOf(e, null)}` : messageOf(e, parsed.texLine);
1193
1872
  if (settled)
1194
1873
  bar?.failed(message);
1195
1874
  else
@@ -1235,6 +1914,9 @@ function renderTab(language, source, host, options) {
1235
1914
  };
1236
1915
  }
1237
1916
  var PROGRAMS = { guitar: 25, piano: 0 };
1917
+ var MUTED = { channel: 1, program: 28 };
1918
+ var CLICK = { channel: 9, key: 33 };
1919
+ var SOUNDFONT_TAIL = 0.5;
1238
1920
  function soundfontPlayer(alphaTab, api) {
1239
1921
  return {
1240
1922
  reportsStart: true,
@@ -1248,13 +1930,19 @@ function soundfontPlayer(alphaTab, api) {
1248
1930
  const ticks = (seconds) => Math.round(seconds * midi.division);
1249
1931
  handler.addTempo(0, 60);
1250
1932
  handler.addProgramChange(0, 0, 0, PROGRAMS[sound]);
1933
+ if (sound === "guitar" && events.some((e) => e.kind === "muted"))
1934
+ handler.addProgramChange(0, 0, MUTED.channel, MUTED.program);
1935
+ if (events.some((e) => e.kind === "click"))
1936
+ handler.addProgramChange(0, 0, CLICK.channel, 0);
1251
1937
  const level = Number.isFinite(volume) ? Math.min(1, Math.max(0, volume)) : 0.8;
1252
1938
  current.masterVolume = level;
1253
1939
  for (const e of events) {
1254
1940
  const velocity = e.velocity === undefined || !Number.isFinite(e.velocity) ? 100 : Math.round(Math.min(127, Math.max(1, e.velocity)));
1255
- handler.addNote(0, ticks(e.time), Math.max(1, ticks(e.duration)), e.midi, velocity, 0);
1941
+ const channel = e.kind === "click" ? CLICK.channel : e.kind === "muted" && sound === "guitar" ? MUTED.channel : 0;
1942
+ handler.addNote(0, ticks(e.time), Math.max(1, ticks(e.duration)), e.kind === "click" ? CLICK.key : e.midi, velocity, channel);
1256
1943
  }
1257
1944
  const end = Math.max(...events.map((e) => e.time + e.duration), 0);
1945
+ handler.addControlChange(0, ticks(end + SOUNDFONT_TAIL), 0, alphaTab.midi.ControllerType.HoldPedal, 0);
1258
1946
  current.playbackSpeed = 1;
1259
1947
  player.playOneTimeMidiFile(midi);
1260
1948
  let stopped = false;
@@ -1319,7 +2007,7 @@ function createSoundfontPlayer(alphaTab, assets, doc, fallback) {
1319
2007
  });
1320
2008
  if (assets.soundFont instanceof Uint8Array)
1321
2009
  current.loadSoundFont(made.bytes(assets.soundFont), false);
1322
- current.tex(`\\track "Guitar" \\instrument ${PROGRAMS.guitar} r \\track "Piano" \\instrument ${PROGRAMS.piano} r`);
2010
+ current.tex(`\\track "Guitar" \\instrument ${PROGRAMS.guitar} r \\track "Piano" \\instrument ${PROGRAMS.piano} r \\track "Muted" \\instrument ${MUTED.program} r`);
1323
2011
  return ready;
1324
2012
  };
1325
2013
  const inner = soundfontPlayer(alphaTab, () => api);
@@ -1382,6 +2070,7 @@ export {
1382
2070
  createSoundfontPlayer,
1383
2071
  exportGp7,
1384
2072
  exportMidi,
2073
+ hideDefaultDynamics,
1385
2074
  parseTabSource,
1386
2075
  printTab,
1387
2076
  renderTab,
@@ -1390,5 +2079,5 @@ export {
1390
2079
  textTabToAlphaTex
1391
2080
  };
1392
2081
 
1393
- //# debugId=38E7EB39910B180864756E2164756E21
2082
+ //# debugId=676F0DA21BF6D94464756E2164756E21
1394
2083
  //# sourceMappingURL=index.js.map