vexflow 5.2.0 → 5.3.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 (114) hide show
  1. package/build/cjs/vexflow-bravura.js +2 -2
  2. package/build/cjs/vexflow-bravura.js.map +1 -1
  3. package/build/cjs/vexflow-core.js +2 -2
  4. package/build/cjs/vexflow-core.js.map +1 -1
  5. package/build/cjs/vexflow-debug-with-tests.js +2759 -1382
  6. package/build/cjs/vexflow-debug-with-tests.js.map +1 -1
  7. package/build/cjs/vexflow-debug.js +1814 -1227
  8. package/build/cjs/vexflow-debug.js.map +1 -1
  9. package/build/cjs/vexflow.js +2 -2
  10. package/build/cjs/vexflow.js.map +1 -1
  11. package/build/esm/src/accidental.js +10 -3
  12. package/build/esm/src/articulation.js +24 -6
  13. package/build/esm/src/beam.js +158 -28
  14. package/build/esm/src/bend.js +24 -19
  15. package/build/esm/src/curve.js +27 -53
  16. package/build/esm/src/dot.js +13 -4
  17. package/build/esm/src/easyscore/composition.js +40 -1
  18. package/build/esm/src/easyscore/policies.js +34 -6
  19. package/build/esm/src/element.js +4 -0
  20. package/build/esm/src/engravinggeometry.js +150 -0
  21. package/build/esm/src/engravingprofile.js +44 -0
  22. package/build/esm/src/factory.js +15 -7
  23. package/build/esm/src/formatter.js +9 -1
  24. package/build/esm/src/gracenote.js +43 -38
  25. package/build/esm/src/gracenotegroup.js +53 -56
  26. package/build/esm/src/index.js +2 -0
  27. package/build/esm/src/keysignature.js +1 -1
  28. package/build/esm/src/modifiercontext.js +11 -0
  29. package/build/esm/src/notehead.js +11 -6
  30. package/build/esm/src/ornament.js +38 -18
  31. package/build/esm/src/proportionalformatter.js +54 -6
  32. package/build/esm/src/stavenote.js +128 -115
  33. package/build/esm/src/stavetie.js +39 -7
  34. package/build/esm/src/stem.js +26 -11
  35. package/build/esm/src/tickcontext.js +19 -0
  36. package/build/esm/src/timesignature.js +5 -0
  37. package/build/esm/src/tuplet.js +57 -17
  38. package/build/esm/src/version.js +3 -3
  39. package/build/esm/src/vexflow.js +4 -0
  40. package/build/esm/tests/bend_tests.js +14 -1
  41. package/build/esm/tests/curve_tests.js +14 -4
  42. package/build/esm/tests/demo_repertoire_tests.js +27 -0
  43. package/build/esm/tests/demos/drums.js +54 -0
  44. package/build/esm/tests/demos/electric.js +63 -0
  45. package/build/esm/tests/demos/greensleeves.js +90 -0
  46. package/build/esm/tests/demos/joy.js +61 -0
  47. package/build/esm/tests/demos/kesh.js +80 -0
  48. package/build/esm/tests/demos/prelude.js +59 -0
  49. package/build/esm/tests/demos/quartertones.js +50 -0
  50. package/build/esm/tests/demos/saints.js +65 -0
  51. package/build/esm/tests/engraving/score-layout.mjs +75 -0
  52. package/build/esm/tests/engraving/score-persistence.mjs +262 -0
  53. package/build/esm/tests/engraving/studies.mjs +279 -0
  54. package/build/esm/tests/formatter_tests.js +10 -1
  55. package/build/esm/tests/index.js +1 -0
  56. package/build/esm/tests/node/audit-dependencies-tests.mjs +42 -0
  57. package/build/esm/tests/node/easyscore-tests.mjs +71 -0
  58. package/build/esm/tests/node/engraving-layout-tests.mjs +449 -0
  59. package/build/esm/tests/node/local-engraving-tests.mjs +128 -0
  60. package/build/esm/tests/node/proportional-spacing-tests.mjs +64 -0
  61. package/build/esm/tests/node/rendering-tests.mjs +6 -2
  62. package/build/esm/tests/threevoice_tests.js +11 -1
  63. package/build/esm/tests/vexflow_test_helpers.js +19 -10
  64. package/build/esm/tools/audit-dependencies.mjs +61 -0
  65. package/build/esm/tools/score-fixtures.mjs +23 -6
  66. package/build/types/src/accidental.d.ts +4 -0
  67. package/build/types/src/articulation.d.ts +6 -1
  68. package/build/types/src/beam.d.ts +14 -0
  69. package/build/types/src/curve.d.ts +9 -0
  70. package/build/types/src/dot.d.ts +5 -0
  71. package/build/types/src/easyscore/composition.d.ts +19 -0
  72. package/build/types/src/easyscore/policies.d.ts +1 -1
  73. package/build/types/src/element.d.ts +2 -0
  74. package/build/types/src/engravinggeometry.d.ts +31 -0
  75. package/build/types/src/engravingprofile.d.ts +20 -0
  76. package/build/types/src/factory.d.ts +6 -1
  77. package/build/types/src/formatter.d.ts +3 -3
  78. package/build/types/src/gracenote.d.ts +7 -0
  79. package/build/types/src/gracenotegroup.d.ts +7 -2
  80. package/build/types/src/index.d.ts +2 -0
  81. package/build/types/src/modifiercontext.d.ts +4 -0
  82. package/build/types/src/notehead.d.ts +5 -0
  83. package/build/types/src/ornament.d.ts +7 -0
  84. package/build/types/src/proportionalformatter.d.ts +11 -2
  85. package/build/types/src/stavenote.d.ts +20 -2
  86. package/build/types/src/stavetie.d.ts +4 -0
  87. package/build/types/src/stem.d.ts +10 -1
  88. package/build/types/src/tickcontext.d.ts +5 -0
  89. package/build/types/src/timesignature.d.ts +2 -0
  90. package/build/types/src/tuplet.d.ts +5 -48
  91. package/build/types/src/vexflow.d.ts +4 -0
  92. package/changelog/CHANGELOG.md +17 -0
  93. package/package.json +7 -2
  94. package/tests/all.html +277 -0
  95. package/tests/demo_petzold_tests.ts +435 -0
  96. package/tests/demos/drums.ts +55 -0
  97. package/tests/demos/drums.webp +0 -0
  98. package/tests/demos/electric.ts +70 -0
  99. package/tests/demos/electric.webp +0 -0
  100. package/tests/demos/greensleeves.ts +97 -0
  101. package/tests/demos/greensleeves.webp +0 -0
  102. package/tests/demos/joy.ts +65 -0
  103. package/tests/demos/joy.webp +0 -0
  104. package/tests/demos/kesh.ts +86 -0
  105. package/tests/demos/kesh.webp +0 -0
  106. package/tests/demos/prelude.ts +65 -0
  107. package/tests/demos/prelude.webp +0 -0
  108. package/tests/demos/quartertones.ts +51 -0
  109. package/tests/demos/quartertones.webp +0 -0
  110. package/tests/demos/saints.ts +70 -0
  111. package/tests/demos/saints.webp +0 -0
  112. package/tests/flow.html +550 -239
  113. package/tests/fonts.css +493 -0
  114. package/tests/minuet.webp +0 -0
@@ -212,3 +212,67 @@ test('unsupported numeric ranges fail before producing infinite coordinates', ()
212
212
  const v = voice();
213
213
  assert.throws(() => proportional(Number.MAX_VALUE).joinVoices([v]).format([v]), /pixel range/);
214
214
  });
215
+ test('optical spacing fits measured obstacles, then stretches rhythmic intervals without moving clefs into notes', () => {
216
+ const stave = new Stave(10, 50, 900);
217
+ const notes = ['q', 'q', '8', '16', '32', '64'].map((duration) => new StaveNote({ keys: ['c/5'], duration }).setStave(stave));
218
+ notes[0].addModifier(new VF.Annotation('crescendo'), 0);
219
+ notes[1].addModifier(new GraceNoteGroup(['d/5', 'e/5', 'f/5'].map((key) => new GraceNote({ keys: [key], duration: '16' }))), 0);
220
+ notes[2].addModifier(new VF.ChordSymbol().addText('Cmaj7/G'), 0);
221
+ notes[3].addModifier(new Accidental('##'), 0);
222
+ const clef = new ClefNote('bass', 'small').setStave(stave);
223
+ const v = new Voice('4/4').setStrict(false).addTickables([notes[0], clef, ...notes.slice(1)]);
224
+ const f = new Formatter({ spacing: { mode: 'optical' } }).joinVoices([v]);
225
+ const minimum = f.preCalculateMinTotalWidth([v]);
226
+ assert.throws(() => f.format([v], minimum - 1), /InsufficientOpticalSpace.*px width/);
227
+ f.format([v], minimum);
228
+ const tight = positions(v);
229
+ for (let i = 1; i < notes.length; ++i) {
230
+ const prev = notes[i - 1].getMetrics(), curr = notes[i].getMetrics();
231
+ assert.ok(tight[i] - curr.modLeftPx - curr.leftDisplacedHeadPx >=
232
+ tight[i - 1] + prev.notePx + prev.rightDisplacedHeadPx + prev.modRightPx + 2 - 1e-7);
233
+ }
234
+ assert.ok(clef.getAbsoluteX() + clef.getWidth() <= notes[1].getAbsoluteX());
235
+ f.format([v], minimum + 200);
236
+ const loose = positions(v);
237
+ const extra = (i) => loose[i] - loose[i - 1] - (tight[i] - tight[i - 1]);
238
+ close(extra(3) / extra(4), Math.sqrt(2));
239
+ f.tune();
240
+ assert.deepEqual(positions(v), loose);
241
+ });
242
+ test('nested 5:4 and 3:2 tuplets preserve every exact onset through reformat', () => {
243
+ const stave = new Stave(10, 50, 900);
244
+ const notes = Array.from({ length: 5 }, () => new StaveNote({ keys: ['c/5'], duration: '8' }).setStave(stave));
245
+ new Tuplet(notes, { numNotes: 5, notesOccupied: 4 });
246
+ new Tuplet(notes.slice(1, 4), { numNotes: 3, notesOccupied: 2 });
247
+ const v = new Voice('4/4').setStrict(false).addTickables(notes);
248
+ const f = proportional(200).joinVoices([v]).format([v]);
249
+ const expected = [0, 6, 10, 14, 18];
250
+ const elapsed = new VF.Fraction(0, 1);
251
+ for (const [i, n] of notes.entries()) {
252
+ assert.ok(elapsed.equals(new VF.Fraction(expected[i] * 4096, 15)));
253
+ elapsed.add(n.getTicks());
254
+ }
255
+ assert.ok(elapsed.equals(new VF.Fraction(24 * 4096, 15)));
256
+ onsets(v, expected.map((value) => (value * 200) / 15));
257
+ f.format([v], 1600);
258
+ onsets(v, expected.map((value) => (value * 200) / 15));
259
+ });
260
+ test('optical and exact policies expose different minima for a very short final attack', () => {
261
+ const makeVoice = () => voice(['h', 'q', '8', '16', '32', '64', '64']);
262
+ const run = (spacing) => {
263
+ const v = makeVoice();
264
+ const f = new Formatter(spacing ? { spacing } : {}).joinVoices([v]);
265
+ const minimum = f.preCalculateMinTotalWidth([v]);
266
+ f.format([v], minimum);
267
+ assert.ok(positions(v).every(Number.isFinite));
268
+ return minimum;
269
+ };
270
+ const optical = run({ mode: 'optical' });
271
+ const exact = run({ mode: 'proportional' });
272
+ const legacy = run();
273
+ assert.ok(optical < exact);
274
+ assert.ok(legacy > 0);
275
+ const constrained = new Formatter({ spacing: { mode: 'proportional' } });
276
+ const v = makeVoice();
277
+ assert.throws(() => constrained.joinVoices([v]).format([v], optical), /InsufficientProportionalSpace/);
278
+ });
@@ -14,7 +14,7 @@ import { join } from 'node:path';
14
14
  import test from 'node:test';
15
15
  import { fileURLToPath } from 'node:url';
16
16
  import puppeteer from 'puppeteer';
17
- import { renderScore } from '../../tools/score-fixtures.mjs';
17
+ import { renderScore, scoreKinds } from '../../tools/score-fixtures.mjs';
18
18
  const root = fileURLToPath(new URL('../../', import.meta.url));
19
19
  test('jsdom registers fonts, renders PNGs, and exports portable SVG', () => {
20
20
  const directory = join(root, 'build/jsdom-smoke');
@@ -56,14 +56,18 @@ test('score benchmark fixtures render', () => __awaiter(void 0, void 0, void 0,
56
56
  yield page.setContent('<div id="score"></div>');
57
57
  yield page.addScriptTag({ path: join(root, 'build/cjs/vexflow-debug.js') });
58
58
  yield page.evaluate(() => __awaiter(void 0, void 0, void 0, function* () {
59
+ yield Promise.all([...document.fonts].map((face) => face.load()));
59
60
  yield document.fonts.ready;
60
61
  }));
61
- for (const kind of ['chorale', 'piano', 'chamber']) {
62
+ for (const kind of scoreKinds) {
62
63
  const result = yield page.evaluate(renderScore, { kind, systems: 1 });
63
64
  const expected = {
64
65
  chorale: { notes: 48, staves: 8 },
65
66
  piano: { notes: 64, staves: 8 },
66
67
  chamber: { notes: 144, staves: 12 },
68
+ 'lead-sheet': { notes: 32, staves: 4 },
69
+ percussion: { notes: 32, staves: 4 },
70
+ tab: { notes: 32, staves: 4 },
67
71
  }[kind];
68
72
  assert.deepEqual({ notes: result.notes, staves: result.staves }, expected);
69
73
  assert.ok(result.svg.includes('<path'));
@@ -12,7 +12,7 @@ const ThreeVoicesTests = {
12
12
  run('Auto Adjust Rest Positions - Three Voices #2', autoRestThreeVoices2);
13
13
  },
14
14
  };
15
- function createThreeVoicesTest(noteGroup1, noteGroup2, noteGroup3, setup) {
15
+ function createThreeVoicesTest(noteGroup1, noteGroup2, noteGroup3, setup, check) {
16
16
  return (options) => {
17
17
  const factory = VexFlowTests.makeFactory(options, 600, 200);
18
18
  const stave = factory.Stave().addClef('treble').addTimeSignature('4/4');
@@ -30,6 +30,7 @@ function createThreeVoicesTest(noteGroup1, noteGroup2, noteGroup3, setup) {
30
30
  for (let i = 0; i < beams.length; i++) {
31
31
  beams[i].setContext(factory.getContext()).drawWithStyle();
32
32
  }
33
+ check === null || check === void 0 ? void 0 : check(noteGroups, options.assert);
33
34
  options.assert.ok(true);
34
35
  };
35
36
  }
@@ -49,6 +50,15 @@ const threeVoices2 = createThreeVoicesTest(['(a4 e5)/16, e5, e5, e5, e5/8, e5, e
49
50
  .getTickables()[0]
50
51
  .addModifier(f.Fingering({ number: '0', position: 'left' }), 0)
51
52
  .addModifier(f.Fingering({ number: '4', position: 'left' }), 1);
53
+ }, (groups, assert) => {
54
+ const beam = groups[1][0].checkBeam();
55
+ const first = beam.getNotes()[0];
56
+ const lower = groups[2][1];
57
+ const headTop = lower.noteHeads[0].getBoundingBox().getY();
58
+ for (const x of [lower.getNoteHeadBeginX(), lower.getNoteHeadEndX()]) {
59
+ const edge = beam.getSlopeY(x, first.getStemX(), beam.getBeamYToDraw(), beam.slope);
60
+ assert.ok(edge < headTop, `Middle beam edge at ${edge} clears lower head at ${headTop} (x=${x})`);
61
+ }
52
62
  });
53
63
  const threeVoices3 = createThreeVoicesTest(['(g4 e5)/4, e5, (g4 e5)/2', { stem: 'up' }], ['c#5/4, b4/8, b4/8/r, a4/4., g4/8', { stem: 'down' }], ['c4/4, b3, a3, g3', { stem: 'down' }], (f, voices) => {
54
64
  voices[0]
@@ -134,10 +134,10 @@ export class VexFlowTests {
134
134
  static generateTestID(prefix) {
135
135
  return prefix + '_' + VexFlowTests.NEXT_TEST_ID++;
136
136
  }
137
- static runTests(name, testFunc, params) {
138
- VexFlowTests.runCanvasTest(name, testFunc, params);
139
- VexFlowTests.runSVGTest(name, testFunc, params);
140
- VexFlowTests.runNodeTest(name, testFunc, params);
137
+ static runTests(name, testFunc, params, fontStacks) {
138
+ VexFlowTests.runCanvasTest(name, testFunc, params, fontStacks);
139
+ VexFlowTests.runSVGTest(name, testFunc, params, fontStacks);
140
+ VexFlowTests.runNodeTest(name, testFunc, params, fontStacks);
141
141
  }
142
142
  static runTextTests(name, testFunc, params) {
143
143
  VexFlowTests.runCanvasText(name, testFunc, params);
@@ -155,10 +155,13 @@ export class VexFlowTests {
155
155
  const { elementId, backend } = options;
156
156
  return new Factory({ renderer: { elementId, backend, width, height } });
157
157
  }
158
- static runCanvasTest(name, testFunc, params) {
158
+ static runCanvasTest(name, testFunc, params, fontStacks) {
159
159
  if (VexFlowTests.RUN_CANVAS_TESTS) {
160
160
  const helper = null;
161
- VexFlowTests.runWithParams(Object.assign(Object.assign({}, CANVAS_TEST_CONFIG), { name, testFunc, params, helper }));
161
+ VexFlowTests.runWithParams(Object.assign(Object.assign({}, CANVAS_TEST_CONFIG), { fontStacks: fontStacks !== null && fontStacks !== void 0 ? fontStacks : CANVAS_TEST_CONFIG.fontStacks, name,
162
+ testFunc,
163
+ params,
164
+ helper }));
162
165
  }
163
166
  }
164
167
  static runCanvasText(name, testFunc, params) {
@@ -167,10 +170,13 @@ export class VexFlowTests {
167
170
  VexFlowTests.runWithParams(Object.assign(Object.assign({}, CANVAS_TEXT_CONFIG), { name, testFunc, params, helper }));
168
171
  }
169
172
  }
170
- static runSVGTest(name, testFunc, params) {
173
+ static runSVGTest(name, testFunc, params, fontStacks) {
171
174
  if (VexFlowTests.RUN_SVG_TESTS) {
172
175
  const helper = null;
173
- VexFlowTests.runWithParams(Object.assign(Object.assign({}, SVG_TEST_CONFIG), { name, testFunc, params, helper }));
176
+ VexFlowTests.runWithParams(Object.assign(Object.assign({}, SVG_TEST_CONFIG), { fontStacks: fontStacks !== null && fontStacks !== void 0 ? fontStacks : SVG_TEST_CONFIG.fontStacks, name,
177
+ testFunc,
178
+ params,
179
+ helper }));
174
180
  }
175
181
  }
176
182
  static runSVGText(name, testFunc, params) {
@@ -179,10 +185,13 @@ export class VexFlowTests {
179
185
  VexFlowTests.runWithParams(Object.assign(Object.assign({}, SVG_TEXT_CONFIG), { name, testFunc, params, helper }));
180
186
  }
181
187
  }
182
- static runNodeTest(name, testFunc, params) {
188
+ static runNodeTest(name, testFunc, params, fontStacks) {
183
189
  if (VexFlowTests.RUN_NODE_TESTS) {
184
190
  const helper = VexFlowTests.runNodeTestHelper;
185
- VexFlowTests.runWithParams(Object.assign(Object.assign({}, NODE_TEST_CONFIG), { name, testFunc, params, helper }));
191
+ VexFlowTests.runWithParams(Object.assign(Object.assign({}, NODE_TEST_CONFIG), { fontStacks: fontStacks !== null && fontStacks !== void 0 ? fontStacks : NODE_TEST_CONFIG.fontStacks, name,
192
+ testFunc,
193
+ params,
194
+ helper }));
186
195
  }
187
196
  }
188
197
  static runNodeTestHelper(fontName, element) {
@@ -0,0 +1,61 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { readFileSync } from 'node:fs';
3
+ const advisory = 'https://github.com/advisories/GHSA-fc5q-39xc-vjpf';
4
+ const reviewedVersions = new Set(['2.3.2', '4.0.5']);
5
+ const expires = Date.parse('2026-12-18T00:00:00Z');
6
+ export function isExcepted(report, packages, now = Date.now()) {
7
+ var _a, _b, _c, _d, _e, _f;
8
+ const findings = Object.entries((_a = report === null || report === void 0 ? void 0 : report.vulnerabilities) !== null && _a !== void 0 ? _a : {});
9
+ if (now >= expires || report.auditReportVersion !== 2 || report.error || !findings.length)
10
+ return false;
11
+ if (((_c = (_b = report.metadata) === null || _b === void 0 ? void 0 : _b.vulnerabilities) === null || _c === void 0 ? void 0 : _c.total) !== findings.length)
12
+ return false;
13
+ const accepted = new Set();
14
+ for (const [name, finding] of findings) {
15
+ if (!((_d = finding.nodes) === null || _d === void 0 ? void 0 : _d.length) || !finding.nodes.every((path) => { var _a; return ((_a = packages[path]) === null || _a === void 0 ? void 0 : _a.dev) === true; }))
16
+ return false;
17
+ if (name === 'picomatch') {
18
+ if (finding.isDirect || finding.fixAvailable === true)
19
+ return false;
20
+ if (!finding.nodes.every((path) => reviewedVersions.has(packages[path].version)))
21
+ return false;
22
+ if (((_e = finding.via) === null || _e === void 0 ? void 0 : _e.length) !== 1 || ((_f = finding.via[0]) === null || _f === void 0 ? void 0 : _f.url) !== advisory)
23
+ return false;
24
+ accepted.add(name);
25
+ }
26
+ }
27
+ let previousSize;
28
+ do {
29
+ previousSize = accepted.size;
30
+ for (const [name, { via }] of findings) {
31
+ if ((via === null || via === void 0 ? void 0 : via.length) && via.every((cause) => accepted.has(cause)))
32
+ accepted.add(name);
33
+ }
34
+ } while (accepted.size > previousSize);
35
+ return accepted.size === findings.length;
36
+ }
37
+ function main() {
38
+ var _a;
39
+ const result = spawnSync(process.execPath, [process.env.npm_execpath, 'audit', '--include=dev', '--audit-level=low', '--json'], {
40
+ encoding: 'utf8',
41
+ stdio: ['ignore', 'pipe', 'inherit'],
42
+ });
43
+ if (result.error)
44
+ throw result.error;
45
+ if (result.status === 0) {
46
+ console.log('npm audit passed.');
47
+ return;
48
+ }
49
+ console.log(result.stdout);
50
+ if (result.status === 1) {
51
+ const report = JSON.parse(result.stdout);
52
+ const lock = JSON.parse(readFileSync(new URL('../package-lock.json', import.meta.url), 'utf8'));
53
+ if (isExcepted(report, lock.packages)) {
54
+ console.log('Accepted the development-only picomatch advisory through 2026-12-17 UTC. See SECURITY.md.');
55
+ return;
56
+ }
57
+ }
58
+ process.exitCode = (_a = result.status) !== null && _a !== void 0 ? _a : 1;
59
+ }
60
+ if (import.meta.main)
61
+ main();
@@ -1,10 +1,12 @@
1
+ export const scoreKinds = ['chorale', 'piano', 'chamber', 'lead-sheet', 'percussion', 'tab'];
1
2
  export function renderScore({ kind = 'chorale', systems = 4, containerId = 'score' } = {}) {
2
3
  var _a;
3
4
  const VF = globalThis.VexFlow;
4
5
  document.documentElement.style.cssText = 'background:white;color:black;color-scheme:light';
5
6
  const container = document.getElementById(containerId);
6
7
  container.replaceChildren();
7
- const staffCount = kind === 'chamber' ? 3 : 2;
8
+ const singleStaff = ['lead-sheet', 'percussion', 'tab'].includes(kind);
9
+ const staffCount = singleStaff ? 1 : kind === 'chamber' ? 3 : 2;
8
10
  const systemHeight = staffCount * 150 + 40;
9
11
  const renderer = new VF.Renderer(container, VF.Renderer.Backends.SVG);
10
12
  renderer.resize(1100, systems * systemHeight);
@@ -16,8 +18,13 @@ export function renderScore({ kind = 'chorale', systems = 4, containerId = 'scor
16
18
  for (let system = 0; system < systems; system++) {
17
19
  for (let bar = 0; bar < 4; bar++) {
18
20
  for (let staff = 0; staff < staffCount; staff++) {
19
- const clef = staff === staffCount - 1 ? 'bass' : 'treble';
20
- const stave = new VF.Stave(15 + bar * 267, system * systemHeight + staff * 150 + 35, 267);
21
+ let clef = !singleStaff && staff === staffCount - 1 ? 'bass' : 'treble';
22
+ if (kind === 'percussion')
23
+ clef = 'percussion';
24
+ if (kind === 'tab')
25
+ clef = 'tab';
26
+ const Staff = kind === 'tab' ? VF.TabStave : VF.Stave;
27
+ const stave = new Staff(15 + bar * 267, system * systemHeight + staff * 150 + 35, 267);
21
28
  if (bar === 0)
22
29
  stave.addClef(clef).addTimeSignature('4/4');
23
30
  const voices = [];
@@ -25,11 +32,21 @@ export function renderScore({ kind = 'chorale', systems = 4, containerId = 'scor
25
32
  const tuplets = [];
26
33
  const ties = [];
27
34
  const notes = [];
28
- const count = kind === 'chorale' ? 4 : kind === 'piano' ? 8 : 12;
35
+ const count = kind === 'chorale' ? 4 : kind === 'chamber' ? 12 : 8;
29
36
  for (let beat = 0; beat < count; beat++) {
30
37
  const key = clef === 'bass' ? ['c/3', 'g/2', 'a/2', 'f/2'][(bar + beat) % 4] : melody[(bar + beat) % 8];
31
38
  const keys = kind === 'piano' && staff === 1 ? [key, 'e/3', 'g/3'] : [key];
32
- const note = new VF.StaveNote({ keys, clef, duration: count === 4 ? 'q' : '8', stemDirection: 1 });
39
+ let note;
40
+ if (kind === 'tab') {
41
+ note = new VF.TabNote({ positions: [{ str: 1 + (beat % 3), fret: (beat + bar) % 8 }], duration: '8' }, true);
42
+ }
43
+ else {
44
+ const pitches = kind === 'percussion' ? (beat % 2 ? ['g/5/x2'] : ['c/5', 'g/5/x2']) : keys;
45
+ note = new VF.StaveNote({ keys: pitches, clef, duration: count === 4 ? 'q' : '8', stemDirection: 1 });
46
+ }
47
+ if (kind === 'lead-sheet' && beat === 0) {
48
+ note.addModifier(new VF.ChordSymbol().addText(['Cmaj7', 'Am7', 'Dm7', 'G7'][bar]), 0);
49
+ }
33
50
  if (kind === 'chorale' && staff === 0) {
34
51
  const lyric = new VF.Annotation(['Sing', 'with', 'gentle', 'voices'][beat]).setVerticalJustification(VF.Annotation.VerticalJustify.BOTTOM);
35
52
  (_a = lyric.setTextBaseline) === null || _a === void 0 ? void 0 : _a.call(lyric, system * systemHeight + 162);
@@ -44,7 +61,7 @@ export function renderScore({ kind = 'chorale', systems = 4, containerId = 'scor
44
61
  }
45
62
  notes[0].addModifier(new VF.Ornament('tr'), 0);
46
63
  }
47
- else if (kind === 'piano') {
64
+ else if (kind === 'piano' || singleStaff) {
48
65
  for (let i = 0; i < notes.length; i += 4)
49
66
  beams.push(new VF.Beam(notes.slice(i, i + 4)));
50
67
  }
@@ -57,6 +57,10 @@ export declare class Accidental extends Modifier {
57
57
  /** Identify explicit cautionary signs without inspecting protected engraving state. */
58
58
  isCautionary(): boolean;
59
59
  /** Render accidental onto canvas. */
60
+ /** Place the glyph using the same coordinates for measurement and drawing. */
61
+ private positionGlyph;
62
+ /** Visible glyph after formatting, including cautionary or authored shifts. */
63
+ getInkBounds(): import("./boundingbox").BoundingBox;
60
64
  draw(): void;
61
65
  }
62
66
  export {};
@@ -1,3 +1,4 @@
1
+ import { BoundingBox } from './boundingbox';
1
2
  import { Builder } from './easyscore';
2
3
  import { Modifier } from './modifier';
3
4
  import { ModifierContextState } from './modifiercontext';
@@ -76,9 +77,13 @@ export declare class Articulation extends Modifier {
76
77
  * - Odd codes will be positioned BELOW
77
78
  */
78
79
  constructor(type: string);
80
+ private betweenLinesOverride?;
79
81
  protected reset(): void;
80
82
  /** Set if articulation should be rendered between lines. */
81
83
  setBetweenLines(betweenLines?: boolean): this;
82
- /** Render articulation in position next to note. */
84
+ /** Resolve the glyph origin after its owner and modifier context have been formatted. */
85
+ private getPlacement;
86
+ /** Get visible glyph ink without mutating its alignment or drawing coordinates. */
87
+ getInkBounds(): BoundingBox;
83
88
  draw(): void;
84
89
  }
@@ -1,3 +1,4 @@
1
+ import { BoundingBox } from './boundingbox';
1
2
  import { Element } from './element';
2
3
  import { Fraction } from './fraction';
3
4
  import { RenderContext } from './rendercontext';
@@ -18,6 +19,8 @@ export declare class Beam extends Element {
18
19
  beamWidth: number;
19
20
  maxSlope: number;
20
21
  minSlope: number;
22
+ /** Keep automatic slope in the endpoint contour and align level in-staff beams to a half-space. */
23
+ contourSlope?: boolean;
21
24
  slopeIterations: number;
22
25
  slopeCost: number;
23
26
  stemletExtension: number;
@@ -30,6 +33,9 @@ export declare class Beam extends Element {
30
33
  private readonly _stemDirection;
31
34
  private readonly _ticks;
32
35
  protected yShift: number;
36
+ /** Derived extensions must be removed before formatting the next width. */
37
+ private fittedStems;
38
+ private flatOffset?;
33
39
  private breakOnIndexes;
34
40
  private _beamCount;
35
41
  private unbeamable?;
@@ -128,6 +134,8 @@ export declare class Beam extends Element {
128
134
  getSlopeY(x: number, firstX: number, firstY: number, slope: number): number;
129
135
  /** Calculate the best possible slope for the provided notes. */
130
136
  calculateSlope(): void;
137
+ /** Shorten stems together when a beam cuts through an outer voice at or between attacks. */
138
+ private clearOtherVoiceHeads;
131
139
  /** Calculate a slope and y-shift for flat beams. */
132
140
  calculateFlatSlope(): void;
133
141
  /** Return the Beam y offset. */
@@ -146,7 +154,13 @@ export declare class Beam extends Element {
146
154
  }[];
147
155
  /** Render the stems for each note. */
148
156
  protected drawStems(ctx: RenderContext): void;
157
+ /** Each filled strip has two sloping edges separated by a signed thickness. */
158
+ private getStrips;
159
+ /** Bounds of the beam strips alone. The note geometry owns the stem segments. */
160
+ getBoundingBox(): BoundingBox;
149
161
  protected drawBeamLines(ctx: RenderContext): void;
162
+ /** Release only the adjustments from the last fit. Preserve intervening native edits. */
163
+ resetLayout(): void;
150
164
  /** Pre-format the beam. */
151
165
  preFormat(): this;
152
166
  /**
@@ -15,6 +15,10 @@ export interface CurveOptions {
15
15
  invert?: boolean;
16
16
  openingDirection?: 'up' | 'down' | 'auto';
17
17
  }
18
+ type Point = {
19
+ x: number;
20
+ y: number;
21
+ };
18
22
  interface CurveRenderParams {
19
23
  firstX: number;
20
24
  firstY: number;
@@ -54,6 +58,11 @@ export declare class Curve extends Element {
54
58
  * The box is exact: it is fitted to the extrema of the bezier curves, not to their control points.
55
59
  */
56
60
  getBoundingBox(): BoundingBox;
61
+ /** Endpoints on the rendered curve after authored shifts. */
62
+ getAnchors(): {
63
+ start: Point;
64
+ end: Point;
65
+ };
57
66
  draw(): boolean;
58
67
  }
59
68
  export {};
@@ -14,6 +14,11 @@ export declare class Dot extends Modifier {
14
14
  static format(dots: Dot[], state: ModifierContextState): boolean;
15
15
  constructor();
16
16
  setNote(note: Note): this;
17
+ private restShiftY;
17
18
  setDotShiftY(y: number): this;
19
+ /** Place the glyph using the same coordinates for measurement and drawing. */
20
+ private positionGlyph;
21
+ /** Visible glyph after formatting, including cautionary or authored shifts. */
22
+ getInkBounds(): import("./boundingbox").BoundingBox;
18
23
  draw(): void;
19
24
  }
@@ -1,6 +1,7 @@
1
1
  import type { EasyScore, EasyScoreVoiceOptions } from '../easyscore';
2
2
  import type { Element } from '../element';
3
3
  import { Factory } from '../factory';
4
+ import { GraceNoteStruct } from '../gracenote';
4
5
  import { Note } from '../note';
5
6
  import { Sheet, SheetOptions } from '../sheet';
6
7
  import { Stave, StaveOptions } from '../stave';
@@ -17,11 +18,26 @@ export interface EasyScoreStaffState {
17
18
  key?: string;
18
19
  time?: string;
19
20
  }
21
+ /** Explicit signs survive key-aware generation, including cautionaries and microtones. */
22
+ interface GracePitchSpec extends GraceNoteStruct {
23
+ accidentals?: readonly {
24
+ index: number;
25
+ type: string;
26
+ cautionary?: boolean;
27
+ }[];
28
+ }
29
+ interface GraceGroupSpec {
30
+ side: 'before' | 'after';
31
+ notes: readonly GracePitchSpec[];
32
+ slur?: boolean;
33
+ beam?: boolean;
34
+ }
20
35
  /** Typed wrappers add IDs and cross-staff assignment without changing native note fields. */
21
36
  export type EasyScoreContent = string | StaveNoteStruct | Tickable | {
22
37
  note: StaveNoteStruct;
23
38
  id?: string;
24
39
  stave?: string;
40
+ grace?: GraceGroupSpec;
25
41
  } | {
26
42
  tab: TabNoteStruct;
27
43
  id?: string;
@@ -82,6 +98,8 @@ export interface EasyScoreCompositionSpec {
82
98
  sheet?: Omit<SheetOptions, 'factory'>;
83
99
  system?: Omit<SystemOptions, 'factory' | 'width' | 'autoWidth' | 'noJustification'>;
84
100
  accidentals?: 'literal' | 'key-aware';
101
+ /** Include written grace pitches in key-aware state at their host onset. */
102
+ graceAccidentals?: 'explicit' | 'ordered';
85
103
  signatures?: 'changes' | 'every-measure';
86
104
  spans?: readonly EasyScoreSpanSpec[];
87
105
  crossMeasureSpans?: 'reject' | 'manual';
@@ -105,3 +123,4 @@ export interface EasyScoreComposition {
105
123
  }
106
124
  /** Compose aligned measure arrays atomically. Formatting and drawing remain explicit native operations. */
107
125
  export declare function compose(score: EasyScore, spec: EasyScoreCompositionSpec): EasyScoreComposition;
126
+ export {};
@@ -9,4 +9,4 @@ export interface KeyChange {
9
9
  key: string;
10
10
  }
11
11
  /** Each onset is evaluated against one prior state, so voice ordering cannot change accidental output. */
12
- export declare function applyCompositionAccidentals(score: EasyScore, voices: Voice[], key: string, changes: KeyChange[], generated: Set<Accidental>, stave: Stave): void;
12
+ export declare function applyCompositionAccidentals(score: EasyScore, voices: Voice[], key: string, changes: KeyChange[], generated: Set<Accidental>, stave: Stave, includeGrace?: boolean): void;
@@ -167,6 +167,8 @@ export declare class Element {
167
167
  onIdChange(validate: (id: string | undefined) => void, changed: () => void): () => void;
168
168
  /** Set an attribute such as 'id', 'class', or 'type'. */
169
169
  setAttribute(name: string, value: string | undefined): this;
170
+ /** Visible text in renderer pixels at a supplied glyph origin. Positive y points down. */
171
+ getTextInk(x: number, y: number): BoundingBox;
170
172
  /** Get the boundingBox. */
171
173
  getBoundingBox(): BoundingBox;
172
174
  /** Return the context, such as an SVGContext or CanvasContext object. */
@@ -0,0 +1,31 @@
1
+ import { BoundingBox, Bounds } from './boundingbox';
2
+ import { Element } from './element';
3
+ /** Enclosing rectangles can be conservative for strokes and curves. */
4
+ export interface EngravingShape {
5
+ parts: Bounds[];
6
+ anchors: Record<string, {
7
+ x: number;
8
+ y: number;
9
+ }>;
10
+ }
11
+ /** Codes are stable. Source IDs come from the native element or its author. */
12
+ export interface GeometryDiagnostic {
13
+ code: 'UnsupportedGeometry' | 'UnformattedGeometry' | 'InvalidGeometry' | 'LayoutOverflow';
14
+ phase: 'measure';
15
+ severity: 'error' | 'warning';
16
+ sourceId: string;
17
+ }
18
+ /** Return undefined from an extension adapter to delegate to the built-in participants. */
19
+ export interface GeometryOptions {
20
+ extension?: (element: Element) => EngravingShape | undefined;
21
+ paddingPx?: number;
22
+ viewport?: Bounds;
23
+ }
24
+ /** Union and layout bounds are absent for empty or invalid geometry. Check diagnostics for partial results. */
25
+ export interface EngravingGeometry extends EngravingShape {
26
+ ink?: BoundingBox;
27
+ layout?: BoundingBox;
28
+ diagnostics: GeometryDiagnostic[];
29
+ }
30
+ /** Measure after formatting and assigning staves. Never calls draw or touches a renderer. */
31
+ export declare function measureEngraving(element: Element, options?: GeometryOptions): EngravingGeometry;
@@ -0,0 +1,20 @@
1
+ /** Metadata may be passed directly from an installed font. All distances are in staff spaces. */
2
+ export interface EngravingProfileOptions {
3
+ musicFont: string;
4
+ metadata?: unknown;
5
+ beamThickness?: number;
6
+ clearance?: number;
7
+ }
8
+ /** Coordinates in a SMuFL font, where positive y points up. */
9
+ type Anchor = readonly [number, number];
10
+ /** Holds a validated copy of the supported metadata. Never changes global Metrics or fonts. */
11
+ export declare class EngravingProfile {
12
+ readonly musicFont: string;
13
+ readonly beamThickness: number;
14
+ readonly clearance: number;
15
+ private readonly anchors;
16
+ constructor(options: EngravingProfileOptions);
17
+ /** Missing or malformed anchors delegate to VF5's native glyph fallback. */
18
+ stemAnchor(glyph: string, direction: 'up' | 'down'): Anchor | undefined;
19
+ }
20
+ export {};
@@ -12,6 +12,7 @@ import { Curve, CurveOptions } from './curve';
12
12
  import { Dot } from './dot';
13
13
  import { EasyScore, EasyScoreOptions } from './easyscore';
14
14
  import { Element } from './element';
15
+ import { EngravingProfile } from './engravingprofile';
15
16
  import { FontInfo } from './font';
16
17
  import { Formatter, FormatterOptions } from './formatter';
17
18
  import { FretHandFinger } from './frethandfinger';
@@ -67,6 +68,8 @@ import { Voice, VoiceTime } from './voice';
67
68
  /** Explicit drawing role for a native extension adopted into a Factory. */
68
69
  export type FactoryElementRole = 'note' | 'modifier' | 'staveModifier' | 'drawable';
69
70
  export interface FactoryOptions {
71
+ /** Optional per-score pitched notation and beam policy. */
72
+ engraving?: EngravingProfile;
70
73
  stave?: {
71
74
  space: number;
72
75
  };
@@ -94,7 +97,7 @@ export declare class Factory {
94
97
  * `const vf: Factory = VexFlow.Factory.newFromElementId('boo', 1200, 600 );`
95
98
  */
96
99
  static newFromElementId(elementId: string | null, width?: number, height?: number): Factory;
97
- protected options: Required<FactoryOptions>;
100
+ protected options: Required<Omit<FactoryOptions, 'engraving'>> & Pick<FactoryOptions, 'engraving'>;
98
101
  protected stave?: Stave;
99
102
  protected context: RenderContext;
100
103
  protected staves: Stave[];
@@ -163,6 +166,8 @@ export declare class Factory {
163
166
  }): TabStave;
164
167
  /** Construct a native Bend with an explicit drawing role. */
165
168
  Bend(...args: ConstructorParameters<typeof Bend>): Bend;
169
+ /** Apply a score's music family to glyph elements while retaining their individual sizes. */
170
+ private musicGlyph;
166
171
  /** Construct a native Clef with an explicit drawing role. */
167
172
  Clef(...args: ConstructorParameters<typeof Clef>): Clef;
168
173
  /** Construct a native KeySignature with an explicit drawing role. */
@@ -1,6 +1,6 @@
1
1
  import { BoundingBox } from './boundingbox';
2
2
  import { ModifierContext } from './modifiercontext';
3
- import { ProportionalSpacing } from './proportionalformatter';
3
+ import { MeasuredSpacing } from './proportionalformatter';
4
4
  import { RenderContext } from './rendercontext';
5
5
  import { Stave } from './stave';
6
6
  import { StemmableNote } from './stemmablenote';
@@ -9,10 +9,10 @@ import { TabStave } from './tabstave';
9
9
  import { Tickable } from './tickable';
10
10
  import { TickContext } from './tickcontext';
11
11
  import { Voice } from './voice';
12
- export type { ProportionalSpacing } from './proportionalformatter';
12
+ export type { MeasuredSpacing, ProportionalSpacing } from './proportionalformatter';
13
13
  export interface FormatterOptions {
14
14
  /** Omit to use the default engraving layout. */
15
- spacing?: ProportionalSpacing;
15
+ spacing?: MeasuredSpacing;
16
16
  /** Defaults to Tables.SOFTMAX_FACTOR. */
17
17
  softmaxFactor?: number;
18
18
  /** Defaults to `false`. */
@@ -9,6 +9,13 @@ export declare class GraceNote extends StaveNote {
9
9
  protected slur: boolean;
10
10
  constructor(noteStruct: GraceNoteStruct);
11
11
  getStemExtension(): number;
12
+ /** Absolute endpoints of the grace slash used by both measurement and drawing. */
13
+ getSlash(): {
14
+ x1: number;
15
+ y1: number;
16
+ x2: number;
17
+ y2: number;
18
+ } | undefined;
12
19
  draw(): void;
13
20
  calcBeamedNotesSlashBBox(slashStemOffset: number, slashBeamOffset: number, protrusions: {
14
21
  beam: number;
@@ -22,8 +22,11 @@ export declare class GraceNoteGroup extends Modifier {
22
22
  };
23
23
  protected slur?: StaveTie | TabTie;
24
24
  protected beams: Beam[];
25
- /** Arranges groups inside a `ModifierContext`. */
26
- static format(gracenoteGroups: GraceNoteGroup[], state: ModifierContextState): boolean;
25
+ /** Right-side material at the same onset must not move a before-grace cluster to the left. */
26
+ private afterWidth;
27
+ private afterOffset;
28
+ /** Opposing groups reserve their own side. Voices with simultaneous before-graces align at the host. */
29
+ static format(groups: GraceNoteGroup[], state: ModifierContextState): boolean;
27
30
  constructor(graceNotes: StemmableNote[], showSlur?: boolean);
28
31
  preFormat(): void;
29
32
  beamNotes(graceNotes?: StemmableNote[]): this;
@@ -34,5 +37,7 @@ export declare class GraceNoteGroup extends Modifier {
34
37
  private positionGraceNotes;
35
38
  /** Enclose the positioned grace notes (not the slur). Drawing is not required. */
36
39
  getBoundingBox(): BoundingBox;
40
+ /** Positioned components, including the optional slur, shared with geometry consumers. */
41
+ getLayoutElements(): (Note | Beam | StaveTie)[];
37
42
  draw(): void;
38
43
  }