vexflow 5.0.0 → 5.1.1

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 (130) hide show
  1. package/LICENSE +3 -3
  2. package/README.md +46 -53
  3. package/build/cjs/vexflow-bravura.js +2 -2
  4. package/build/cjs/vexflow-bravura.js.map +1 -1
  5. package/build/cjs/vexflow-core.js +2 -2
  6. package/build/cjs/vexflow-core.js.map +1 -1
  7. package/build/cjs/vexflow-debug-with-tests.js +3825 -1396
  8. package/build/cjs/vexflow-debug-with-tests.js.map +1 -1
  9. package/build/cjs/vexflow-debug.js +2577 -984
  10. package/build/cjs/vexflow-debug.js.map +1 -1
  11. package/build/cjs/vexflow.js +2 -2
  12. package/build/cjs/vexflow.js.map +1 -1
  13. package/build/esm/src/accidental.js +1 -0
  14. package/build/esm/src/annotation.js +31 -8
  15. package/build/esm/src/beam.js +4 -2
  16. package/build/esm/src/chordsymbol.js +3 -1
  17. package/build/esm/src/clef.js +3 -1
  18. package/build/esm/src/curve.js +68 -11
  19. package/build/esm/src/easyscore.js +40 -1
  20. package/build/esm/src/element.js +49 -11
  21. package/build/esm/src/factory.js +46 -9
  22. package/build/esm/src/flag.js +3 -1
  23. package/build/esm/src/font.js +20 -1
  24. package/build/esm/src/formatter.js +34 -36
  25. package/build/esm/src/fraction.js +4 -1
  26. package/build/esm/src/glyphnote.js +3 -1
  27. package/build/esm/src/gracenotegroup.js +18 -1
  28. package/build/esm/src/index.js +2 -0
  29. package/build/esm/src/keysignature.js +3 -1
  30. package/build/esm/src/metrics.js +58 -3
  31. package/build/esm/src/modifiercontext.js +15 -1
  32. package/build/esm/src/note.js +2 -2
  33. package/build/esm/src/notehead.js +3 -1
  34. package/build/esm/src/ornament.js +3 -1
  35. package/build/esm/src/pedalmarking.js +44 -5
  36. package/build/esm/src/registry.js +16 -6
  37. package/build/esm/src/rendercontext.js +10 -0
  38. package/build/esm/src/sheet.js +117 -0
  39. package/build/esm/src/stave.js +13 -8
  40. package/build/esm/src/stavebarline.js +53 -1
  41. package/build/esm/src/staveline.js +2 -0
  42. package/build/esm/src/stavenote.js +54 -19
  43. package/build/esm/src/stavetie.js +3 -1
  44. package/build/esm/src/stem.js +2 -1
  45. package/build/esm/src/stemmablenote.js +9 -0
  46. package/build/esm/src/stringnumber.js +0 -1
  47. package/build/esm/src/strokes.js +10 -0
  48. package/build/esm/src/svgcontext.js +14 -4
  49. package/build/esm/src/svgexport.js +68 -0
  50. package/build/esm/src/system.js +14 -0
  51. package/build/esm/src/tables.js +69 -37
  52. package/build/esm/src/tabnote.js +20 -1
  53. package/build/esm/src/textbracket.js +5 -4
  54. package/build/esm/src/textdynamics.js +5 -0
  55. package/build/esm/src/textmetricscache.js +93 -0
  56. package/build/esm/src/textnote.js +3 -3
  57. package/build/esm/src/tickable.js +56 -22
  58. package/build/esm/src/timesignature.js +30 -9
  59. package/build/esm/src/timesignote.js +3 -1
  60. package/build/esm/src/tuning.js +2 -2
  61. package/build/esm/src/tuplet.js +79 -29
  62. package/build/esm/src/util.js +1 -0
  63. package/build/esm/src/version.js +3 -3
  64. package/build/esm/src/vexflow.js +14 -2
  65. package/build/esm/src/voice.js +44 -8
  66. package/build/esm/tests/accidental_tests.js +52 -0
  67. package/build/esm/tests/annotation_tests.js +38 -0
  68. package/build/esm/tests/articulation_tests.js +34 -0
  69. package/build/esm/tests/beam_tests.js +17 -0
  70. package/build/esm/tests/curve_tests.js +81 -0
  71. package/build/esm/tests/font_tests.js +32 -1
  72. package/build/esm/tests/formatter_tests.js +58 -23
  73. package/build/esm/tests/gracenote_tests.js +58 -0
  74. package/build/esm/tests/gracetabnote_tests.js +40 -0
  75. package/build/esm/tests/keysignature_tests.js +14 -3
  76. package/build/esm/tests/node/metrics-tests.mjs +278 -0
  77. package/build/esm/tests/node/package-input-tests.mjs +149 -0
  78. package/build/esm/tests/node/render-metrics-tests.mjs +78 -0
  79. package/build/esm/tests/node/rendering-tests.mjs +75 -0
  80. package/build/esm/tests/node/sheet-tests.mjs +202 -0
  81. package/build/esm/tests/node/svg-export-tests.mjs +182 -0
  82. package/build/esm/tests/pedalmarking_tests.js +25 -0
  83. package/build/esm/tests/rests_tests.js +6 -0
  84. package/build/esm/tests/stave_tests.js +6 -3
  85. package/build/esm/tests/stavenote_tests.js +100 -55
  86. package/build/esm/tests/strokes_tests.js +19 -5
  87. package/build/esm/tests/timesignature_tests.js +19 -0
  88. package/build/esm/tests/tuplet_tests.js +273 -12
  89. package/build/esm/tests/unison_tests.js +13 -13
  90. package/build/esm/tests/voice_tests.js +34 -0
  91. package/build/esm/tools/render-metrics.mjs +49 -0
  92. package/build/esm/tools/score-fixtures.mjs +94 -0
  93. package/build/esm/tools/sheet-fixture.mjs +90 -0
  94. package/build/esm/tools/visual-regression.mjs +106 -0
  95. package/build/types/src/annotation.d.ts +17 -1
  96. package/build/types/src/curve.d.ts +24 -7
  97. package/build/types/src/easyscore.d.ts +8 -0
  98. package/build/types/src/element.d.ts +7 -0
  99. package/build/types/src/factory.d.ts +18 -1
  100. package/build/types/src/font.d.ts +2 -0
  101. package/build/types/src/formatter.d.ts +23 -14
  102. package/build/types/src/gracenotegroup.d.ts +5 -0
  103. package/build/types/src/index.d.ts +2 -0
  104. package/build/types/src/metrics.d.ts +2 -0
  105. package/build/types/src/modifiercontext.d.ts +4 -0
  106. package/build/types/src/pedalmarking.d.ts +4 -1
  107. package/build/types/src/registry.d.ts +2 -0
  108. package/build/types/src/rendercontext.d.ts +12 -0
  109. package/build/types/src/sheet.d.ts +49 -0
  110. package/build/types/src/stave.d.ts +4 -4
  111. package/build/types/src/stavebarline.d.ts +10 -0
  112. package/build/types/src/stavenote.d.ts +11 -0
  113. package/build/types/src/strokes.d.ts +4 -0
  114. package/build/types/src/svgcontext.d.ts +5 -0
  115. package/build/types/src/svgexport.d.ts +22 -0
  116. package/build/types/src/system.d.ts +4 -0
  117. package/build/types/src/tables.d.ts +9 -0
  118. package/build/types/src/tabnote.d.ts +4 -0
  119. package/build/types/src/textbracket.d.ts +1 -1
  120. package/build/types/src/textdynamics.d.ts +3 -0
  121. package/build/types/src/textmetricscache.d.ts +21 -0
  122. package/build/types/src/tickable.d.ts +27 -10
  123. package/build/types/src/timesignature.d.ts +4 -0
  124. package/build/types/src/tuplet.d.ts +8 -0
  125. package/build/types/src/util.d.ts +1 -0
  126. package/build/types/src/vexflow.d.ts +8 -1
  127. package/build/types/src/voice.d.ts +6 -0
  128. package/changelog/CHANGELOG.md +109 -0
  129. package/package.json +44 -26
  130. package/tests/flow.html +15 -7
@@ -0,0 +1,90 @@
1
+ var __rest = (this && this.__rest) || function (s, e) {
2
+ var t = {};
3
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
4
+ t[p] = s[p];
5
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
6
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
7
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
8
+ t[p[i]] = s[p[i]];
9
+ }
10
+ return t;
11
+ };
12
+ export function renderSheetStudy({ width = 680, backend = 'svg', font = 'Bravura', theme = '#e7edf5', widths = [], } = {}) {
13
+ const VF = globalThis.VexFlow;
14
+ VF.setFonts(font, font === 'Petaluma' ? 'Petaluma Script' : 'Academico');
15
+ const host = document.getElementById('score');
16
+ host.replaceChildren();
17
+ host.style.background = '#17283c';
18
+ const target = backend === 'canvas' ? host.appendChild(document.createElement('canvas')) : host;
19
+ target.id = backend === 'canvas' ? 'score-canvas' : 'score';
20
+ const factory = new VF.Factory({ renderer: { elementId: target.id, width: width + 40, height: 1000 } });
21
+ const ctx = factory.getContext();
22
+ factory.setStyle({ fillStyle: theme, strokeStyle: theme });
23
+ const sheet = factory.Sheet({ width, x: 20, y: 35, rowGap: 45 });
24
+ const score = factory.EasyScore();
25
+ const upper = score.measures('C6/8, D6, E6, F6, G5/q, C5 | (C5 E5)/h, G4 | E5/q, D5, C5, G4 | C5/w');
26
+ const lower = score.measures('C3/h, G2 | C3, G2 | C3, G2 | C3/w', { clef: 'bass' });
27
+ const systems = upper.map((notes, i) => {
28
+ const system = sheet.addSystem({ spaceBetweenStaves: 10 });
29
+ system.addStave({ voices: [score.voice(notes)] }).addClef('treble');
30
+ system.addStave({ voices: [score.voice(lower[i])] }).addClef('bass');
31
+ system.addConnector('brace');
32
+ if (i === 0) {
33
+ score.beam(notes.slice(0, 4));
34
+ notes[4].setStyle({ fillStyle: '#ed9b40', strokeStyle: '#ed9b40' });
35
+ factory.TextBracket({
36
+ from: notes[0],
37
+ to: notes[3],
38
+ text: '8',
39
+ options: { superscript: 'va', position: 'top', line: 3 },
40
+ });
41
+ factory.PedalMarking({ notes: [lower[i][0], lower[i][1]] });
42
+ }
43
+ return system;
44
+ });
45
+ const snapshots = [];
46
+ for (const nextWidth of [width, ...widths]) {
47
+ sheet.setWidth(nextWidth).format();
48
+ ctx.resize(nextWidth + 40, sheet.getHeight() + 40);
49
+ ctx.clear();
50
+ factory.draw({ retain: true });
51
+ const rows = sheet.getRows().map((_a) => {
52
+ var { systems: rowSystems } = _a, row = __rest(_a, ["systems"]);
53
+ return (Object.assign(Object.assign({}, row), { count: rowSystems.length }));
54
+ });
55
+ const boxes = [];
56
+ systems.forEach((system, s) => {
57
+ const box = system.getBoundingBox();
58
+ boxes.push({
59
+ id: `measure-${s}`,
60
+ group: 'measures',
61
+ x: box.getX(),
62
+ y: box.getY(),
63
+ width: box.getW(),
64
+ height: box.getH(),
65
+ });
66
+ system.getVoices().forEach((voice, v) => voice.getTickables().forEach((note, n) => {
67
+ const b = note.getBoundingBox();
68
+ boxes.push({
69
+ id: `note-${s}-${v}-${n}`,
70
+ group: `voice-${s}-${v}`,
71
+ x: b.getX(),
72
+ y: b.getY(),
73
+ width: b.getW(),
74
+ height: b.getH(),
75
+ });
76
+ }));
77
+ });
78
+ snapshots.push({ width: nextWidth, height: sheet.getHeight(), rows, boxes });
79
+ }
80
+ const svg = host.querySelector('svg');
81
+ const colors = svg
82
+ ? [...svg.querySelectorAll('path,text,rect')]
83
+ .filter((node) => node.getAttribute('fill') !== 'none' || node.getAttribute('stroke') !== 'none')
84
+ .map((node) => {
85
+ const style = getComputedStyle(node);
86
+ return { tag: node.tagName, fill: style.fill, stroke: style.stroke };
87
+ })
88
+ : [];
89
+ return { snapshots, colors, svg: svg === null || svg === void 0 ? void 0 : svg.outerHTML, cssWidth: svg === null || svg === void 0 ? void 0 : svg.style.width };
90
+ }
@@ -0,0 +1,106 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { copyFile, mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
11
+ import { join, resolve } from 'node:path';
12
+ import { pathToFileURL } from 'node:url';
13
+ import { createCanvas, loadImage } from 'canvas';
14
+ import { comparePixels } from './render-metrics.mjs';
15
+ function pixels(path) {
16
+ return __awaiter(this, void 0, void 0, function* () {
17
+ const image = yield loadImage(yield readFile(path));
18
+ const canvas = createCanvas(image.width, image.height);
19
+ const context = canvas.getContext('2d');
20
+ context.drawImage(image, 0, 0);
21
+ return { width: image.width, height: image.height, data: context.getImageData(0, 0, image.width, image.height).data };
22
+ });
23
+ }
24
+ export function compareDirectories(reference_1, current_1, output_1) {
25
+ return __awaiter(this, arguments, void 0, function* (reference, current, output, prefix = '') {
26
+ const list = (directory) => __awaiter(this, void 0, void 0, function* () { return (yield readdir(directory)).filter((name) => name.endsWith('.png') && name.startsWith(prefix)); });
27
+ const before = yield list(reference);
28
+ const after = yield list(current);
29
+ if (!before.length || !after.length)
30
+ throw new Error('Both image suites must contain matching PNG files.');
31
+ yield mkdir(output, { recursive: true });
32
+ const results = [];
33
+ for (const name of [...new Set([...before, ...after])].sort()) {
34
+ const result = { name, status: 'passed' };
35
+ if (!before.includes(name) || !after.includes(name)) {
36
+ result.status = 'missing';
37
+ }
38
+ else {
39
+ try {
40
+ const a = yield pixels(join(reference, name));
41
+ const b = yield pixels(join(current, name));
42
+ if (a.width !== b.width || a.height !== b.height) {
43
+ result.status = 'size changed';
44
+ }
45
+ else {
46
+ const comparison = comparePixels(a.data, b.data);
47
+ Object.assign(result, {
48
+ changedPixels: comparison.changed,
49
+ changedRatio: comparison.ratio,
50
+ maxDelta: comparison.maxDelta,
51
+ });
52
+ if (comparison.changed) {
53
+ result.status = 'changed';
54
+ const canvas = createCanvas(a.width, a.height);
55
+ const ctx = canvas.getContext('2d');
56
+ const image = ctx.createImageData(a.width, a.height);
57
+ image.data.set(comparison.diff);
58
+ ctx.putImageData(image, 0, 0);
59
+ yield writeFile(join(output, `diff-${name}`), canvas.toBuffer('image/png'));
60
+ }
61
+ }
62
+ if (result.status !== 'passed') {
63
+ yield copyFile(join(reference, name), join(output, `before-${name}`));
64
+ yield copyFile(join(current, name), join(output, `after-${name}`));
65
+ }
66
+ }
67
+ catch (error) {
68
+ result.status = 'error';
69
+ result.error = error.message;
70
+ }
71
+ }
72
+ results.push(result);
73
+ }
74
+ const failed = results.filter((result) => result.status !== 'passed');
75
+ yield writeFile(join(output, 'results.json'), JSON.stringify({ total: results.length, failed: failed.length, results }, null, 2));
76
+ yield writeFile(join(output, 'results.txt'), failed.map((result) => `${result.name}: ${result.status}`).join('\n'));
77
+ const escape = (text) => String(text).replace(/[&<>"']/g, (char) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char]);
78
+ const cards = failed
79
+ .map((result) => {
80
+ var _a, _b;
81
+ return `<article><h2>${escape(result.name)}</h2><p>${escape(result.status)} · ${(_a = result.changedPixels) !== null && _a !== void 0 ? _a : 0} changed pixels · ${(((_b = result.changedRatio) !== null && _b !== void 0 ? _b : 0) * 100).toFixed(3)}%</p>${[
82
+ 'before',
83
+ 'after',
84
+ ...(result.status === 'changed' ? ['diff'] : []),
85
+ ]
86
+ .filter(() => !['missing', 'error'].includes(result.status))
87
+ .map((kind) => `<figure><figcaption>${kind}</figcaption><img loading="lazy" src="${encodeURIComponent(`${kind}-${result.name}`)}"></figure>`)
88
+ .join('')}</article>`;
89
+ })
90
+ .join('');
91
+ yield writeFile(join(output, 'index.html'), `<!doctype html><meta charset="utf-8"><title>VexFlow visual comparison</title><style>body{font:15px system-ui;background:#f4f6f9;color:#17283c;margin:32px}article{background:white;padding:20px;margin:20px 0;border:1px solid #dce3ed;border-radius:10px}h2{font-size:17px}figure{display:inline-block;max-width:100%;margin:8px}img{max-width:100%;border:1px solid #ddd}figcaption{padding:6px;color:#52657c}</style><h1>Visual comparison</h1><p>${results.length} images · ${failed.length} need review</p>${cards}`);
92
+ return { total: results.length, failed: failed.length };
93
+ });
94
+ }
95
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
96
+ const [reference = 'reference', prefix = ''] = process.argv.slice(2);
97
+ try {
98
+ const result = await compareDirectories(`build/images/${reference}`, 'build/images/current', 'build/images/diff', prefix);
99
+ console.log(`${result.total} images; ${result.failed} failures. Open build/images/diff/index.html`);
100
+ process.exitCode = result.failed ? 1 : 0;
101
+ }
102
+ catch (error) {
103
+ console.error(error.message);
104
+ process.exitCode = 1;
105
+ }
106
+ }
@@ -33,6 +33,8 @@ export declare class Annotation extends Modifier {
33
33
  static format(annotations: Annotation[], state: ModifierContextState): boolean;
34
34
  protected horizontalJustification: AnnotationHorizontalJustify;
35
35
  protected verticalJustification: AnnotationVerticalJustify;
36
+ /** Optional absolute baseline for lyrics aligned across a stave or system. */
37
+ protected textBaseline?: number;
36
38
  /**
37
39
  * Annotations inherit from `Modifier` and is positioned correctly when
38
40
  * in a `ModifierContext`.
@@ -44,6 +46,8 @@ export declare class Annotation extends Modifier {
44
46
  * @param just value in `AnnotationVerticalJustify`.
45
47
  */
46
48
  setVerticalJustification(just: string | AnnotationVerticalJustify): this;
49
+ /** Get the annotation's position relative to the note. */
50
+ getVerticalJustification(): AnnotationVerticalJustify;
47
51
  /**
48
52
  * Get horizontal justification.
49
53
  */
@@ -53,6 +57,18 @@ export declare class Annotation extends Modifier {
53
57
  * @param just value in `Annotation.Justify`.
54
58
  */
55
59
  setJustification(just: string | AnnotationHorizontalJustify): this;
56
- /** Render text beside the note. */
60
+ /** Use an absolute text baseline. Pass undefined to restore automatic placement. */
61
+ setTextBaseline(y?: number): this;
62
+ /** Compute horizontal placement after formatting, without drawing or changing position. */
63
+ computeX(): {
64
+ x: number;
65
+ textWidth: number;
66
+ };
67
+ /** Compute the text baseline after formatting. Subclasses may override just this axis. */
68
+ computeY(): {
69
+ y: number;
70
+ textHeight: number;
71
+ };
72
+ /** Draw using the same positioning methods available to callers before rendering. */
57
73
  draw(): void;
58
74
  }
@@ -1,3 +1,4 @@
1
+ import { BoundingBox } from './boundingbox';
1
2
  import { Element } from './element';
2
3
  import { Note } from './note';
3
4
  export interface CurveOptions {
@@ -14,6 +15,13 @@ export interface CurveOptions {
14
15
  invert?: boolean;
15
16
  openingDirection?: 'up' | 'down' | 'auto';
16
17
  }
18
+ interface CurveRenderParams {
19
+ firstX: number;
20
+ firstY: number;
21
+ lastX: number;
22
+ lastY: number;
23
+ direction: number;
24
+ }
17
25
  export declare enum CurvePosition {
18
26
  NEAR_HEAD = 1,
19
27
  NEAR_TOP = 2
@@ -31,12 +39,21 @@ export declare class Curve extends Element {
31
39
  * @return {boolean} Returns true if this is a partial bar.
32
40
  */
33
41
  isPartial(): boolean;
34
- renderCurve(params: {
35
- lastY: number;
36
- lastX: number;
37
- firstY: number;
38
- firstX: number;
39
- direction: number;
40
- }): void;
42
+ /**
43
+ * Compute the end points and control points of the bezier curve(s) for `renderCurve()`.
44
+ * The first bezier is the upper edge of the slur, the second one (only drawn for solid lines) goes back
45
+ * from the last to the first point, at a distance of `thickness`.
46
+ */
47
+ private getBezierPoints;
48
+ renderCurve(params: CurveRenderParams): void;
49
+ /** Get the points where the curve starts and ends, and the direction it bulges to. Requires formatted notes. */
50
+ private getRenderParams;
51
+ /**
52
+ * Get the bounding box of the drawn curve, including its thickness but not the stroke width.
53
+ * The notes must be formatted.
54
+ * The box is exact: it is fitted to the extrema of the bezier curves, not to their control points.
55
+ */
56
+ getBoundingBox(): BoundingBox;
41
57
  draw(): boolean;
42
58
  }
59
+ export {};
@@ -71,6 +71,8 @@ export interface BuilderElements {
71
71
  export interface BuilderOptions extends Record<string, any> {
72
72
  stem?: string;
73
73
  clef?: string;
74
+ /** Initial duration for notes that omit one. Defaults to an eighth note. */
75
+ duration?: string;
74
76
  }
75
77
  export declare class Builder {
76
78
  factory: Factory;
@@ -142,6 +144,12 @@ export declare class EasyScore {
142
144
  }): StemmableNote[];
143
145
  tuplet(notes: StemmableNote[], options?: TupletOptions): StemmableNote[];
144
146
  notes(line: string, options?: BuilderOptions): StemmableNote[];
147
+ /**
148
+ * Parse bar-separated measures. Durations carry across bars; notes() is unchanged.
149
+ * A bar may have adjacent commas. Quoted option values may contain literal bars.
150
+ * Empty measures and invalid notation throw, rather than returning partial music.
151
+ */
152
+ measures(line: string, options?: BuilderOptions): StemmableNote[][];
145
153
  voice(notes: Note[], options?: {
146
154
  time?: string;
147
155
  options?: {
@@ -73,11 +73,16 @@ export declare class Element {
73
73
  /** Canvas used to measure text. See measureText(): TextMetrics. */
74
74
  private static txtCanvas?;
75
75
  static setTextMeasurementCanvas(canvas: HTMLCanvasElement | OffscreenCanvas): void;
76
+ /** Clear shared measurements after external font registration or custom context changes. */
77
+ static clearTextMeasurementCache(): void;
76
78
  static getTextMeasurementCanvas(): HTMLCanvasElement | OffscreenCanvas | undefined;
77
79
  private context?;
78
80
  protected attrs: ElementAttributes;
81
+ protected shouldDrawPointerRect: boolean;
79
82
  protected rendered: boolean;
80
83
  protected style: ElementStyle;
84
+ /** Distinguishes caller overrides from built-in metric colors. */
85
+ protected styleExplicit: boolean;
81
86
  protected registry?: Registry;
82
87
  protected _fontInfo: Required<FontInfo>;
83
88
  protected fontScale: number;
@@ -162,6 +167,8 @@ export declare class Element {
162
167
  getBoundingBox(): BoundingBox;
163
168
  /** Return the context, such as an SVGContext or CanvasContext object. */
164
169
  getContext(): RenderContext | undefined;
170
+ /** Draw pointer rect. This allows mouse interaction with the element */
171
+ drawPointerRect(): void;
165
172
  /** Set the context to an SVGContext or CanvasContext object */
166
173
  setContext(context?: RenderContext): this;
167
174
  /** Validate and return the rendering context. */
@@ -24,6 +24,7 @@ import { Ornament } from './ornament';
24
24
  import { PedalMarking } from './pedalmarking';
25
25
  import { RenderContext } from './rendercontext';
26
26
  import { RepeatNote } from './repeatnote';
27
+ import { Sheet, SheetOptions } from './sheet';
27
28
  import { Stave, StaveOptions } from './stave';
28
29
  import { BarlineType } from './stavebarline';
29
30
  import { StaveConnector, StaveConnectorType } from './staveconnector';
@@ -78,6 +79,13 @@ export declare class Factory {
78
79
  protected voices: Voice[];
79
80
  protected renderQ: Element[];
80
81
  protected systems: System[];
82
+ protected sheets: Sheet[];
83
+ private retained;
84
+ /** Foreground defaults survive reset(), like renderer options. */
85
+ protected style: {
86
+ fillStyle?: string;
87
+ strokeStyle?: string;
88
+ };
81
89
  /**
82
90
  * Example:
83
91
  *
@@ -93,6 +101,13 @@ export declare class Factory {
93
101
  setContext(context: RenderContext): this;
94
102
  getStave(): Stave | undefined;
95
103
  getVoices(): Voice[];
104
+ /** Set score colors. Explicit element styles override these defaults. */
105
+ setStyle(style: {
106
+ fillStyle?: string;
107
+ strokeStyle?: string;
108
+ }): this;
109
+ /** Create an optional continuous sheet from measure-sized Systems. */
110
+ Sheet(options?: Omit<SheetOptions, 'factory'>): Sheet;
96
111
  /** Return pixels from current stave spacing. */
97
112
  Stave(params?: {
98
113
  x?: number;
@@ -269,5 +284,7 @@ export declare class Factory {
269
284
  notes?: Note[];
270
285
  }): NoteSubGroup;
271
286
  /** Render the score. */
272
- draw(): void;
287
+ draw(options?: {
288
+ retain?: boolean;
289
+ }): void;
273
290
  }
@@ -20,6 +20,8 @@ export declare enum FontStyle {
20
20
  ITALIC = "italic"
21
21
  }
22
22
  export declare class Font {
23
+ /** Known text faces. Custom faces can be selected with VexFlow.setTextFonts(). */
24
+ static TEXT_FONT_NAMES: string[];
23
25
  /** Given a length (for units: pt, px, em, %, in, mm, cm) what is the scale factor to convert it to px? */
24
26
  static scaleToPxFrom: Record<string, number>;
25
27
  /**
@@ -16,16 +16,21 @@ export interface FormatterOptions {
16
16
  /** Defaults to 5. */
17
17
  maxIterations?: number;
18
18
  }
19
+ /** An interface for passing options to various formatters **/
19
20
  export interface FormatParams {
21
+ /** Should rests align vertically with neighboring notes (default false) **/
20
22
  alignRests?: boolean;
23
+ /** Should notes be automatically beamed **/
24
+ autoBeam?: boolean;
25
+ /** Stave object to render to **/
21
26
  stave?: Stave;
27
+ /** The RenderContext **/
22
28
  context?: RenderContext;
23
- autoBeam?: boolean;
24
29
  }
25
- export interface AlignmentContexts<T> {
30
+ export interface AlignmentTickContexts {
26
31
  list: number[];
27
- map: Record<number, T>;
28
- array: T[];
32
+ map: Record<number, TickContext>;
33
+ array: TickContext[];
29
34
  resolutionMultiplier: number;
30
35
  }
31
36
  export interface AlignmentModifierContexts {
@@ -43,7 +48,7 @@ export interface AlignmentModifierContexts {
43
48
  * to each tick based on the widths of the notes and modifiers in that tick. This
44
49
  * establishes the smallest amount of space required for each tick.
45
50
  *
46
- * Finally, the formatter distributes the left over space proportionally to
51
+ * Finally, the formatter distributes the leftover space proportionally to
47
52
  * all the ticks, setting the `x` values of the notes in each tick.
48
53
  *
49
54
  * See `tests/formatter_tests.ts` for usage examples. The helper functions included
@@ -63,7 +68,7 @@ export declare class Formatter {
63
68
  protected justifyWidth: number;
64
69
  protected totalCost: number;
65
70
  protected totalShift: number;
66
- protected tickContexts: AlignmentContexts<TickContext>;
71
+ protected tickContexts: AlignmentTickContexts;
67
72
  protected formatterOptions: Required<FormatterOptions>;
68
73
  protected modifierContexts: AlignmentModifierContexts[];
69
74
  protected voices: Voice[];
@@ -109,16 +114,18 @@ export declare class Formatter {
109
114
  * @param notes array of `Note` instances for the stave (`Note`, `BarNote`, etc.)
110
115
  * @param tabnotes array of `Note` instances for the tab stave (`TabNote`, `BarNote`, etc.)
111
116
  * @param autoBeam automatically generate beams.
112
- * @param params a configuration object:
113
- * * `autoBeam` automatically generates beams for the notes.
114
- * * `alignRests` aligns rests with nearby notes.
117
+ * @param params a FormatParams configuration object:
118
+ * * `autoBeam` automatically generates beams for the notes. (overrides autoBeam setting above)
119
+ * * `alignRests` aligns rests with nearby notes. (default false)
115
120
  */
116
121
  static FormatAndDrawTab(ctx: RenderContext, tabstave: TabStave, stave: Stave, tabnotes: TabNote[], notes: Tickable[], autoBeam: boolean, params: FormatParams): void;
117
122
  /**
118
123
  * Automatically set the vertical position of rests based on previous/next note positions.
124
+ * Useful for multiple voices on the same staff or for rests within beam groups.
125
+ * Ignores rests that have already been set to a line other than 3 (middle line).
119
126
  * @param tickables an array of Tickables.
120
127
  * @param alignAllNotes If `false`, only align rests that are within a group of beamed notes.
121
- * @param alignTuplets If `false`, ignores tuplets.
128
+ * @param alignTuplets If `false` (default), ignores tuplets.
122
129
  */
123
130
  static AlignRestsToNotes(tickables: Tickable[], alignAllNotes: boolean, alignTuplets?: boolean): void;
124
131
  constructor(options?: FormatterOptions);
@@ -155,7 +162,8 @@ export declare class Formatter {
155
162
  * `preCalculateMinTotalWidth` must be called before this method.
156
163
  */
157
164
  getMinTotalWidth(): number;
158
- /** Calculate the resolution multiplier for `voices`. */
165
+ /** Calculate the resolution multiplier for `voices`, which is the
166
+ * least common multiple of all the voices' getResolutionMultiplier() results. */
159
167
  static getResolutionMultiplier(voices: Voice[]): number;
160
168
  /** Create a `ModifierContext` for each tick in `voices`. */
161
169
  createModifierContexts(voices: Voice[]): void;
@@ -163,12 +171,12 @@ export declare class Formatter {
163
171
  * Create a `TickContext` for each tick in `voices`. Also calculate the
164
172
  * total number of ticks in voices.
165
173
  */
166
- createTickContexts(voices: Voice[]): AlignmentContexts<TickContext>;
174
+ createTickContexts(voices: Voice[]): AlignmentTickContexts;
167
175
  /**
168
- * Get the AlignmentContexts of TickContexts that were created by createTickContexts.
176
+ * Get the AlignmentTickContexts of TickContexts that were created by createTickContexts.
169
177
  * Returns undefined if createTickContexts has not yet been run.
170
178
  */
171
- getTickContexts(): AlignmentContexts<TickContext> | undefined;
179
+ getTickContexts(): AlignmentTickContexts | undefined;
172
180
  /**
173
181
  * This is the core formatter logic. Format voices and justify them
174
182
  * to `justifyWidth` pixels. `renderingContext` is required to justify elements
@@ -194,6 +202,7 @@ export declare class Formatter {
194
202
  * This is the top-level call for all formatting logic completed
195
203
  * after `x` *and* `y` values have been computed for the notes
196
204
  * in the voices.
205
+ * Calls postFormat on each ModifierContext and TickContext.
197
206
  */
198
207
  postFormat(): this;
199
208
  /**
@@ -1,4 +1,5 @@
1
1
  import { Beam } from './beam';
2
+ import { BoundingBox } from './boundingbox';
2
3
  import { Formatter } from './formatter';
3
4
  import { Modifier } from './modifier';
4
5
  import { ModifierContextState } from './modifiercontext';
@@ -29,5 +30,9 @@ export declare class GraceNoteGroup extends Modifier {
29
30
  setWidth(width: number): this;
30
31
  getWidth(): number;
31
32
  getGraceNotes(): Note[];
33
+ /** Position grace notes after the parent has been formatted and assigned a stave. */
34
+ private positionGraceNotes;
35
+ /** Enclose the positioned grace notes (not the slur). Drawing is not required. */
36
+ getBoundingBox(): BoundingBox;
32
37
  draw(): void;
33
38
  }
@@ -44,6 +44,7 @@ export * from './registry';
44
44
  export * from './rendercontext';
45
45
  export * from './renderer';
46
46
  export * from './repeatnote';
47
+ export * from './sheet';
47
48
  export * from './stave';
48
49
  export * from './stavebarline';
49
50
  export * from './staveconnector';
@@ -62,6 +63,7 @@ export * from './stemmablenote';
62
63
  export * from './stringnumber';
63
64
  export * from './strokes';
64
65
  export * from './svgcontext';
66
+ export * from './svgexport';
65
67
  export * from './system';
66
68
  export * from './tabnote';
67
69
  export * from './tabslide';
@@ -6,6 +6,8 @@ export declare class Metrics {
6
6
  /** Use the provided key to look up a FontInfo in CommonMetrics. **/
7
7
  static clear(key?: string): void;
8
8
  static getFontInfo(key: string): Required<FontInfo>;
9
+ /** Keep text spaces in the text font while honoring class-specific font overrides. */
10
+ private static getFontFamily;
9
11
  static getStyle(key: string): ElementStyle;
10
12
  /**
11
13
  * Use the provided key to look up a value in CommonMetrics.
@@ -22,6 +22,8 @@ export declare class ModifierContext {
22
22
  protected formatted: boolean;
23
23
  protected width: number;
24
24
  protected spacing: number;
25
+ /** Horizontal space added only for annotations above or below the note. */
26
+ protected annotationRightShift: number;
25
27
  addModifier(member: ModifierContextMember): this;
26
28
  /**
27
29
  * this.members maps CATEGORY strings to arrays of Tickable | Modifier | StaveNote | TabNote.
@@ -41,6 +43,8 @@ export declare class ModifierContext {
41
43
  getWidth(): number;
42
44
  getLeftShift(): number;
43
45
  getRightShift(): number;
46
+ /** Ties clear nearby modifiers, but must not start beyond a lyric's text box. */
47
+ getRightShiftForTie(): number;
44
48
  getState(): ModifierContextState;
45
49
  getMetrics(): ModifierContextMetrics;
46
50
  preFormat(): void;
@@ -1,4 +1,5 @@
1
1
  import { Element } from './element';
2
+ import { Stave } from './stave';
2
3
  import { StaveNote } from './stavenote';
3
4
  /**
4
5
  * PedalMarking implements different types of pedal markings. These notation
@@ -16,7 +17,7 @@ export declare class PedalMarking extends Element {
16
17
  protected depressText: string;
17
18
  protected releaseText: string;
18
19
  renderOptions: {
19
- color: string;
20
+ color?: string;
20
21
  bracketHeight: number;
21
22
  textMarginRight: number;
22
23
  bracketLineWidth: number;
@@ -51,6 +52,8 @@ export declare class PedalMarking extends Element {
51
52
  setCustomText(depress: string, release?: string): this;
52
53
  /** Set the staff line to render the markings on. */
53
54
  setLine(line: number): this;
55
+ /** Compute a baseline below annotations in participating voices on this stave. */
56
+ getYForStave(stave: Stave): number;
54
57
  /** Draw the bracket based pedal markings. */
55
58
  drawBracketed(): void;
56
59
  /**
@@ -6,6 +6,8 @@ declare class Index {
6
6
  };
7
7
  };
8
8
  constructor();
9
+ /** Only these attributes may select an index, even when called directly. */
10
+ static isValidName(name: string): boolean;
9
11
  }
10
12
  export interface RegistryUpdate {
11
13
  id: string;
@@ -6,6 +6,18 @@ export interface TextMeasure {
6
6
  height: number;
7
7
  }
8
8
  export declare abstract class RenderContext {
9
+ /** Drawing defaults supplied by a score. Explicit element colors take precedence. */
10
+ private defaultStyle;
11
+ /** Set foreground defaults. Factory scopes these to a single draw. */
12
+ setDefaultStyle(style: {
13
+ fillStyle?: string;
14
+ strokeStyle?: string;
15
+ }): this;
16
+ /** Return the current score defaults, without exposing mutable state. */
17
+ getDefaultStyle(): {
18
+ fillStyle?: string;
19
+ strokeStyle?: string;
20
+ };
9
21
  static get CATEGORY(): string;
10
22
  abstract clear(): void;
11
23
  abstract setFillStyle(style: string): this;
@@ -0,0 +1,49 @@
1
+ import { Factory } from './factory';
2
+ import { System, SystemOptions } from './system';
3
+ /** Dimensions are in rendering units (normally pixels). */
4
+ export interface SheetOptions {
5
+ factory: Factory;
6
+ width?: number;
7
+ x?: number;
8
+ y?: number;
9
+ rowGap?: number;
10
+ measureGap?: number;
11
+ measurePadding?: number;
12
+ justify?: boolean;
13
+ }
14
+ /** Layout result. Oversized measures occupy their own row and remain readable. */
15
+ export interface SheetRow {
16
+ systems: System[];
17
+ x: number;
18
+ y: number;
19
+ width: number;
20
+ height: number;
21
+ overflow: number;
22
+ }
23
+ /** Arrange measure-sized Systems left to right, wrapping at a requested width. */
24
+ export declare class Sheet {
25
+ private options;
26
+ private systems;
27
+ private rows;
28
+ constructor(options: SheetOptions);
29
+ /** Create a measure. Add its staves and voices with the existing System API. */
30
+ addSystem(options?: Omit<SystemOptions, 'factory' | 'width' | 'autoWidth' | 'noJustification'>): System;
31
+ /** Update the available row width. Call format() or Factory.draw() to reflow. */
32
+ setWidth(width: number): this;
33
+ /** Access the measures without exposing the membership array. */
34
+ getSystems(): System[];
35
+ /** Inspect row bounds and overflow after formatting. */
36
+ getRows(): SheetRow[];
37
+ /** Required drawing height, including the top inset. */
38
+ getHeight(): number;
39
+ /** Measure and pack rows. Always recompute, so repeated resize is deterministic. */
40
+ format(): this;
41
+ /** Measure intrinsic widths without carrying coordinates over from a prior layout. */
42
+ private measureSystems;
43
+ /** Greedy packing keeps measure order and gives oversized measures their own rows. */
44
+ private packRows;
45
+ /** Include staff envelopes and note bounds in the ordinary vertical layout. */
46
+ private verticalBounds;
47
+ /** Justify a row horizontally, then place every measure on a shared baseline. */
48
+ private formatRow;
49
+ }