vexflow 5.0.0-beta.1 → 5.1.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 (127) hide show
  1. package/LICENSE +3 -3
  2. package/README.md +32 -50
  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 +3685 -1386
  8. package/build/cjs/vexflow-debug-with-tests.js.map +1 -1
  9. package/build/cjs/vexflow-debug.js +2443 -980
  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 +42 -9
  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 +17 -0
  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 +55 -1
  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/textnote.js +3 -3
  56. package/build/esm/src/tickable.js +56 -22
  57. package/build/esm/src/timesignature.js +30 -9
  58. package/build/esm/src/timesignote.js +3 -1
  59. package/build/esm/src/tuning.js +2 -2
  60. package/build/esm/src/tuplet.js +79 -29
  61. package/build/esm/src/util.js +1 -0
  62. package/build/esm/src/version.js +3 -3
  63. package/build/esm/src/vexflow.js +14 -2
  64. package/build/esm/src/voice.js +44 -8
  65. package/build/esm/tests/accidental_tests.js +52 -0
  66. package/build/esm/tests/annotation_tests.js +38 -0
  67. package/build/esm/tests/articulation_tests.js +34 -0
  68. package/build/esm/tests/beam_tests.js +17 -0
  69. package/build/esm/tests/curve_tests.js +81 -0
  70. package/build/esm/tests/font_tests.js +32 -1
  71. package/build/esm/tests/formatter_tests.js +58 -23
  72. package/build/esm/tests/gracenote_tests.js +58 -0
  73. package/build/esm/tests/gracetabnote_tests.js +40 -0
  74. package/build/esm/tests/keysignature_tests.js +14 -3
  75. package/build/esm/tests/node/package-input-tests.mjs +149 -0
  76. package/build/esm/tests/node/render-metrics-tests.mjs +78 -0
  77. package/build/esm/tests/node/rendering-tests.mjs +75 -0
  78. package/build/esm/tests/node/sheet-tests.mjs +202 -0
  79. package/build/esm/tests/node/svg-export-tests.mjs +182 -0
  80. package/build/esm/tests/pedalmarking_tests.js +25 -0
  81. package/build/esm/tests/rests_tests.js +6 -0
  82. package/build/esm/tests/stave_tests.js +6 -3
  83. package/build/esm/tests/stavenote_tests.js +100 -55
  84. package/build/esm/tests/strokes_tests.js +19 -5
  85. package/build/esm/tests/timesignature_tests.js +19 -0
  86. package/build/esm/tests/tuplet_tests.js +273 -12
  87. package/build/esm/tests/unison_tests.js +13 -13
  88. package/build/esm/tests/voice_tests.js +34 -0
  89. package/build/esm/tools/render-metrics.mjs +49 -0
  90. package/build/esm/tools/score-fixtures.mjs +94 -0
  91. package/build/esm/tools/sheet-fixture.mjs +90 -0
  92. package/build/esm/tools/visual-regression.mjs +106 -0
  93. package/build/types/src/annotation.d.ts +17 -1
  94. package/build/types/src/curve.d.ts +24 -7
  95. package/build/types/src/easyscore.d.ts +8 -0
  96. package/build/types/src/element.d.ts +5 -0
  97. package/build/types/src/factory.d.ts +18 -1
  98. package/build/types/src/font.d.ts +2 -0
  99. package/build/types/src/formatter.d.ts +23 -14
  100. package/build/types/src/gracenotegroup.d.ts +5 -0
  101. package/build/types/src/index.d.ts +2 -0
  102. package/build/types/src/metrics.d.ts +2 -0
  103. package/build/types/src/modifiercontext.d.ts +4 -0
  104. package/build/types/src/pedalmarking.d.ts +4 -1
  105. package/build/types/src/registry.d.ts +2 -0
  106. package/build/types/src/rendercontext.d.ts +12 -0
  107. package/build/types/src/sheet.d.ts +49 -0
  108. package/build/types/src/stave.d.ts +4 -4
  109. package/build/types/src/stavebarline.d.ts +10 -0
  110. package/build/types/src/stavenote.d.ts +11 -0
  111. package/build/types/src/strokes.d.ts +4 -0
  112. package/build/types/src/svgcontext.d.ts +5 -0
  113. package/build/types/src/svgexport.d.ts +22 -0
  114. package/build/types/src/system.d.ts +4 -0
  115. package/build/types/src/tables.d.ts +9 -0
  116. package/build/types/src/tabnote.d.ts +4 -0
  117. package/build/types/src/textbracket.d.ts +1 -1
  118. package/build/types/src/textdynamics.d.ts +3 -0
  119. package/build/types/src/tickable.d.ts +27 -10
  120. package/build/types/src/timesignature.d.ts +4 -0
  121. package/build/types/src/tuplet.d.ts +8 -0
  122. package/build/types/src/util.d.ts +1 -0
  123. package/build/types/src/vexflow.d.ts +8 -1
  124. package/build/types/src/voice.d.ts +6 -0
  125. package/changelog/CHANGELOG.md +94 -0
  126. package/package.json +42 -26
  127. package/tests/flow.html +15 -7
@@ -4,6 +4,7 @@ import { Accidental } from '../src/accidental.js';
4
4
  import { Bend } from '../src/bend.js';
5
5
  import { CanvasContext } from '../src/canvascontext.js';
6
6
  import { Font, FontStyle, FontWeight } from '../src/font.js';
7
+ import { Metrics, MetricsDefaults } from '../src/metrics.js';
7
8
  import { PedalMarking } from '../src/pedalmarking.js';
8
9
  import { StaveNote } from '../src/stavenote.js';
9
10
  import { TextBracket } from '../src/textbracket.js';
@@ -12,6 +13,7 @@ import { Voice } from '../src/voice.js';
12
13
  const FontTests = {
13
14
  Start() {
14
15
  QUnit.module('Font');
16
+ QUnit.test('textFontDefaults', textFontDefaults);
15
17
  QUnit.test('setFont', setFont);
16
18
  QUnit.test('Parsing', fontParsing);
17
19
  QUnit.test('Sizes', fontSizes);
@@ -49,7 +51,7 @@ function fontParsing(assert) {
49
51
  { type: Bend.DOWN, text: '' },
50
52
  ]);
51
53
  const bFont = b.fontInfo;
52
- assert.equal(bFont === null || bFont === void 0 ? void 0 : bFont.family, 'Bravura,Academico');
54
+ assert.equal(bFont === null || bFont === void 0 ? void 0 : bFont.family, 'Academico,Bravura');
53
55
  assert.equal(bFont === null || bFont === void 0 ? void 0 : bFont.size, 10);
54
56
  assert.equal(bFont === null || bFont === void 0 ? void 0 : bFont.weight, FontWeight.NORMAL);
55
57
  assert.equal(bFont === null || bFont === void 0 ? void 0 : bFont.style, FontStyle.NORMAL);
@@ -132,3 +134,32 @@ function setMusicFontToPetaluma(options) {
132
134
  }
133
135
  VexFlowTests.register(FontTests);
134
136
  export { FontTests };
137
+ function textFontDefaults(assert) {
138
+ const fonts = VexFlow.getFonts();
139
+ const previous = MetricsDefaults.Annotation.fontFamily;
140
+ try {
141
+ VexFlow.setFonts('Bravura', 'Academico');
142
+ const annotation = new VexFlow.Annotation('Sing with gentle voices');
143
+ const ctx = document.createElement('canvas').getContext('2d');
144
+ ctx.font = Font.toCSSString(annotation.fontInfo);
145
+ const actual = ctx.measureText(annotation.getText()).width;
146
+ ctx.font = Font.toCSSString(Object.assign(Object.assign({}, annotation.fontInfo), { family: 'Academico' }));
147
+ assert.equal(actual, ctx.measureText(annotation.getText()).width);
148
+ assert.equal(new Accidental('#').fontInfo.family, 'Bravura,Academico');
149
+ assert.equal(annotation.setFont('Georgia', 12).fontInfo.family, 'Georgia');
150
+ VexFlow.setTextFonts('Courier New');
151
+ assert.ok(new VexFlow.Annotation('Custom').fontInfo.family.startsWith('Courier New'));
152
+ VexFlow.setFonts('Petaluma', 'Bravura', 'Leland');
153
+ assert.equal(new Accidental('#').fontInfo.family, 'Petaluma,Bravura,Leland');
154
+ MetricsDefaults.Annotation.fontFamily = 'Georgia';
155
+ Metrics.clear();
156
+ assert.equal(new VexFlow.Annotation('Class override').fontInfo.family, 'Georgia');
157
+ }
158
+ finally {
159
+ if (previous === undefined)
160
+ delete MetricsDefaults.Annotation.fontFamily;
161
+ else
162
+ MetricsDefaults.Annotation.fontFamily = previous;
163
+ VexFlow.setFonts(...fonts);
164
+ }
165
+ }
@@ -23,9 +23,32 @@ import { StringNumber } from '../src/stringnumber.js';
23
23
  import { Tuplet } from '../src/tuplet.js';
24
24
  import { Voice } from '../src/voice.js';
25
25
  import { MockTickable } from './mocks.js';
26
+ const QUARTER_NOTE_DURATION = VexFlow.RESOLUTION / 4;
27
+ function createTickable(beat) {
28
+ return new MockTickable().setTicks(beat);
29
+ }
30
+ function getTestVoices() {
31
+ const BEAT = VexFlow.RESOLUTION / 4;
32
+ const tickables1 = [
33
+ createTickable(BEAT).setWidth(10),
34
+ createTickable(BEAT * 2).setWidth(20),
35
+ createTickable(BEAT).setWidth(30),
36
+ ];
37
+ const tickables2 = [
38
+ createTickable(BEAT * 2).setWidth(10),
39
+ createTickable(BEAT).setWidth(20),
40
+ createTickable(BEAT).setWidth(30),
41
+ ];
42
+ const voice1 = new Voice(VexFlow.TIME4_4);
43
+ const voice2 = new Voice(VexFlow.TIME4_4);
44
+ voice1.addTickables(tickables1);
45
+ voice2.addTickables(tickables2);
46
+ return [voice1, voice2];
47
+ }
26
48
  const FormatterTests = {
27
49
  Start() {
28
50
  QUnit.module('Formatter');
51
+ QUnit.test('getResolutionMultiplier', getResolutionMultiplier);
29
52
  QUnit.test('TickContext Building', buildTickContexts);
30
53
  const run = VexFlowTests.runTests;
31
54
  run('Penultimate Note Padding', penultimateNote);
@@ -55,25 +78,37 @@ function getGlyphWidth(glyph) {
55
78
  el.setText(glyph);
56
79
  return el.getWidth();
57
80
  }
58
- function buildTickContexts(assert) {
59
- function createTickable(beat) {
60
- return new MockTickable().setTicks(beat);
81
+ function getResolutionMultiplier(assert) {
82
+ const [voice1, voice2] = getTestVoices();
83
+ assert.equal(voice1.getResolutionMultiplier(), voice2.getResolutionMultiplier(), 'Voices with same smallest duration have the same resolution multiplier');
84
+ assert.equal(Formatter.getResolutionMultiplier([voice1, voice2]), voice1.getResolutionMultiplier(), 'LCM of voice1, voice2 is voice1');
85
+ const TIME1_4 = {
86
+ numBeats: 1,
87
+ beatValue: 4,
88
+ resolution: VexFlow.RESOLUTION,
89
+ };
90
+ const tickables3 = [];
91
+ for (let i = 0; i < 3; i++) {
92
+ tickables3.push(new StaveNote({ keys: ['f/4'], duration: '8' }).setWidth(15));
61
93
  }
62
- const BEAT = (1 * VexFlow.RESOLUTION) / 4;
63
- const tickables1 = [
64
- createTickable(BEAT).setWidth(10),
65
- createTickable(BEAT * 2).setWidth(20),
66
- createTickable(BEAT).setWidth(30),
67
- ];
68
- const tickables2 = [
69
- createTickable(BEAT * 2).setWidth(10),
70
- createTickable(BEAT).setWidth(20),
71
- createTickable(BEAT).setWidth(30),
72
- ];
73
- const voice1 = new Voice(VexFlow.TIME4_4);
74
- const voice2 = new Voice(VexFlow.TIME4_4);
75
- voice1.addTickables(tickables1);
76
- voice2.addTickables(tickables2);
94
+ new Tuplet(tickables3, { numNotes: 3, notesOccupied: 2 });
95
+ const voice3 = new Voice(TIME1_4);
96
+ voice3.addTickables(tickables3);
97
+ const tickables4 = [];
98
+ for (let i = 0; i < 5; i++) {
99
+ tickables4.push(new StaveNote({ keys: ['f/4'], duration: '16' }).setWidth(9));
100
+ }
101
+ new Tuplet(tickables4, { numNotes: 5, notesOccupied: 4 });
102
+ const voice4 = new Voice(TIME1_4);
103
+ voice4.addTickables(tickables4);
104
+ assert.notEqual(voice3.getResolutionMultiplier(), voice4.getResolutionMultiplier());
105
+ assert.notEqual(Formatter.getResolutionMultiplier([voice3, voice4]), voice3.getResolutionMultiplier(), 'LCM of RM of voices 3 and 4 is neither RM(3) nor RM(4)');
106
+ assert.notEqual(Formatter.getResolutionMultiplier([voice3, voice4]), voice4.getResolutionMultiplier(), 'LCM of RM of voices 3 and 4 is neither RM(3) nor RM(4)');
107
+ }
108
+ function buildTickContexts(assert) {
109
+ const [voice1, voice2] = getTestVoices();
110
+ const tickables1 = voice1.getTickables();
111
+ const tickables2 = voice2.getTickables();
77
112
  const formatter = new Formatter();
78
113
  const tContexts = formatter.createTickContexts([voice1, voice2]);
79
114
  assert.equal(tContexts.list.length, 4, 'Voices should have four tick contexts');
@@ -105,10 +140,10 @@ function rightJustify(options) {
105
140
  stave.drawWithStyle();
106
141
  voice.draw(f.getContext(), stave);
107
142
  };
108
- renderTest({ numBeats: 4, beatValue: 4, resolution: 4 * 4096 }, 3, '4', '2', 10, 300);
109
- renderTest({ numBeats: 4, beatValue: 4, resolution: 4 * 4096 }, 1, 'w', 'w', 310, 300);
110
- renderTest({ numBeats: 3, beatValue: 4, resolution: 4 * 4096 }, 3, '4', '4', 610, 300);
111
- renderTest({ numBeats: 3, beatValue: 4, resolution: 4 * 4096 }, 6, '8', '8', 910, 300);
143
+ renderTest({ numBeats: 4, beatValue: 4, resolution: 4 * QUARTER_NOTE_DURATION }, 3, '4', '2', 10, 300);
144
+ renderTest({ numBeats: 4, beatValue: 4, resolution: 4 * QUARTER_NOTE_DURATION }, 1, 'w', 'w', 310, 300);
145
+ renderTest({ numBeats: 3, beatValue: 4, resolution: 4 * QUARTER_NOTE_DURATION }, 3, '4', '4', 610, 300);
146
+ renderTest({ numBeats: 3, beatValue: 4, resolution: 4 * QUARTER_NOTE_DURATION }, 6, '8', '8', 910, 300);
112
147
  options.assert.ok(true);
113
148
  }
114
149
  function penultimateNote(options) {
@@ -700,7 +735,7 @@ function annotations(options) {
700
735
  });
701
736
  let notesToBeam = [];
702
737
  notes.forEach((note) => {
703
- if (note.getIntrinsicTicks() < 4096) {
738
+ if (note.getIntrinsicTicks() < QUARTER_NOTE_DURATION) {
704
739
  notesToBeam.push(note);
705
740
  if (notesToBeam.length >= beamGroup) {
706
741
  beams.push(new Beam(notesToBeam));
@@ -1,3 +1,4 @@
1
+ import { VexFlow } from '../src/vexflow.js';
1
2
  import { VexFlowTests } from './vexflow_test_helpers.js';
2
3
  import { ModifierPosition } from '../src.js';
3
4
  import { Accidental } from '../src/accidental.js';
@@ -5,9 +6,13 @@ import { Annotation } from '../src/annotation.js';
5
6
  import { Articulation } from '../src/articulation.js';
6
7
  import { Dot } from '../src/dot.js';
7
8
  import { Formatter } from '../src/formatter.js';
9
+ import { GraceNote } from '../src/gracenote.js';
10
+ import { GraceNoteGroup } from '../src/gracenotegroup.js';
11
+ import { StaveNote } from '../src/stavenote.js';
8
12
  const GraceNoteTests = {
9
13
  Start() {
10
14
  QUnit.module('Grace Notes');
15
+ QUnit.test('boundsBeforeDrawing', boundsBeforeDrawing);
11
16
  const run = VexFlowTests.runTests;
12
17
  run('Grace Note Basic', basic);
13
18
  run('With Articulation and Annotation on Parent Note', graceNoteModifiers);
@@ -35,8 +40,32 @@ const GraceNoteTests = {
35
40
  run('Grace Note Slash with Beams', slashWithBeams);
36
41
  run('Grace Notes Multiple Voices', multipleVoices);
37
42
  run('Grace Notes Multiple Voices Multiple Draws', multipleVoicesMultipleDraws);
43
+ run('Grace Note Group Bounding Box', boundingBox);
38
44
  },
39
45
  };
46
+ function boundingBox(options) {
47
+ const f = VexFlowTests.makeFactory(options, 300, 130);
48
+ const stave = f.Stave({ x: 10, y: 10, width: 250 });
49
+ const graceNotes = [
50
+ { keys: ['e/4'], duration: '16' },
51
+ { keys: ['f/4'], duration: '16' },
52
+ { keys: ['g/5'], duration: '16' },
53
+ ].map(f.GraceNote.bind(f));
54
+ const group = f.GraceNoteGroup({ notes: graceNotes });
55
+ group.beamNotes();
56
+ const note = f.StaveNote({ keys: ['b/4'], duration: 'q' }).addModifier(group, 0);
57
+ const voice = f.Voice().setStrict(false).addTickables([note]);
58
+ f.Formatter().joinVoices([voice]).formatToStave([voice], stave);
59
+ f.draw();
60
+ VexFlowTests.drawBoundingBox(f.getContext(), group);
61
+ const bb = group.getBoundingBox();
62
+ options.assert.ok(bb.getX() > 0 && bb.getY() > 0, 'Group box is not at the origin');
63
+ options.assert.ok(bb.getX() + bb.getW() <= note.getAbsoluteX(), 'Group box ends left of the main note');
64
+ options.assert.ok(bb.getY() < stave.getBottomLineBottomY() && bb.getY() + bb.getH() > stave.getTopLineTopY(), 'Group box overlaps the stave vertically');
65
+ options.assert.ok(bb.getY() > stave.getTopLineTopY() - 40, 'Group box is near the stave');
66
+ options.assert.ok(note.getBoundingBox().getX() >= bb.getX() - 10, 'Main note box is not stretched to the origin');
67
+ options.assert.ok(new GraceNoteGroup([]).getBoundingBox() !== undefined, 'Empty group has a box');
68
+ }
40
69
  function basic(options) {
41
70
  const f = VexFlowTests.makeFactory(options, 700, 130);
42
71
  const stave = f.Stave({ x: 10, y: 10, width: 650 });
@@ -412,3 +441,32 @@ function multipleVoicesMultipleDraws(options) {
412
441
  }
413
442
  VexFlowTests.register(GraceNoteTests);
414
443
  export { GraceNoteTests };
444
+ function boundsBeforeDrawing(assert) {
445
+ for (const beamed of [false, true]) {
446
+ const ctx = new VexFlow.SVGContext(document.createElement('div'));
447
+ const stave = new VexFlow.Stave(80, 75, 550).setContext(ctx);
448
+ const grace = [
449
+ new GraceNote({ keys: ['d/4', 'e/4'], duration: '8', stemDirection: beamed ? -1 : 1 }),
450
+ new GraceNote({ keys: ['g/4'], duration: '8', stemDirection: beamed ? -1 : 1 }),
451
+ ];
452
+ const group = new GraceNoteGroup(grace);
453
+ if (beamed)
454
+ group.beamNotes();
455
+ const parent = new StaveNote({ keys: ['c/5'], duration: 'q' }).setStave(stave).addModifier(group, 0);
456
+ const dynamics = new VexFlow.TextDynamics({ text: 'sfz', duration: 'q', line: 8 }).setStave(stave);
457
+ const voice = new VexFlow.Voice('2/4').addTickables([parent, dynamics]);
458
+ new Formatter().joinVoices([voice]).formatToStave([voice], stave);
459
+ const before = group.getBoundingBox(), dynamicsBefore = dynamics.getBoundingBox();
460
+ assert.deepEqual(group.getBoundingBox(), before);
461
+ assert.notOk(grace.some((note) => note.isRendered()));
462
+ voice.draw(ctx, stave);
463
+ assert.deepEqual(group.getBoundingBox(), before);
464
+ assert.deepEqual(dynamics.getBoundingBox(), dynamicsBefore);
465
+ assert.ok(before.x > stave.getX() && before.w > 0);
466
+ assert.equal(dynamicsBefore.x, dynamics.getAbsoluteX());
467
+ assert.equal(dynamicsBefore.y, stave.getYForLine(5) - dynamics.getTextMetrics().actualBoundingBoxAscent);
468
+ parent.setStave(new VexFlow.Stave(140, 100, 600).setContext(ctx));
469
+ const moved = group.getBoundingBox();
470
+ assert.ok(moved.x > before.x && moved.y > before.y);
471
+ }
472
+ }
@@ -1,14 +1,17 @@
1
1
  import { VexFlow } from '../src/vexflow.js';
2
2
  import { VexFlowTests } from './vexflow_test_helpers.js';
3
+ import { Font } from '../src/font.js';
3
4
  import { Formatter } from '../src/formatter.js';
4
5
  import { GraceNoteGroup } from '../src/gracenotegroup.js';
5
6
  import { GraceTabNote } from '../src/gracetabnote.js';
7
+ import { Metrics, MetricsDefaults } from '../src/metrics.js';
6
8
  import { TabNote } from '../src/tabnote.js';
7
9
  import { TabStave } from '../src/tabstave.js';
8
10
  import { Voice } from '../src/voice.js';
9
11
  const GraceTabNoteTests = {
10
12
  Start() {
11
13
  QUnit.module('Grace Tab Notes');
14
+ QUnit.test('fretSizing', fretSizing);
12
15
  const run = VexFlowTests.runTests;
13
16
  run('Grace Tab Note Simple', simple);
14
17
  run('Grace Tab Note Slurred', slurred);
@@ -77,3 +80,40 @@ function slurred(options, contextBuilder) {
77
80
  }
78
81
  VexFlowTests.register(GraceTabNoteTests);
79
82
  export { GraceTabNoteTests };
83
+ function fretSizing(assert) {
84
+ class InspectableGraceTabNote extends GraceTabNote {
85
+ getFrets() {
86
+ return this.fretElement;
87
+ }
88
+ }
89
+ const scale = MetricsDefaults.GraceTabNote.fontScale;
90
+ try {
91
+ const note = new InspectableGraceTabNote({
92
+ positions: [
93
+ { str: 2, fret: 12 },
94
+ { str: 4, fret: 3 },
95
+ ],
96
+ duration: '8',
97
+ });
98
+ for (const size of [4, 6, '12px', 14]) {
99
+ note.setFontSize(size).preFormat();
100
+ for (const fret of note.getFrets()) {
101
+ assert.equal(Font.convertSizeToPointValue(fret.fontInfo.size), Font.convertSizeToPointValue(size));
102
+ const metrics = fret.getTextMetrics();
103
+ assert.equal(fret.getYShift(), (metrics.actualBoundingBoxAscent - metrics.actualBoundingBoxDescent) / 2);
104
+ }
105
+ }
106
+ note.setFontSize(7).setGhost(true);
107
+ assert.equal(Font.convertSizeToPointValue(note.getFrets()[0].fontInfo.size), 7);
108
+ note.setGhost(false).setFontSize();
109
+ assert.equal(Font.convertSizeToPointValue(note.getFrets()[0].fontInfo.size), 6);
110
+ MetricsDefaults.GraceTabNote.fontScale = 1 / 3;
111
+ Metrics.clear('GraceTabNote');
112
+ const small = new InspectableGraceTabNote({ positions: [{ str: 2, fret: 12 }], duration: '8' });
113
+ assert.equal(Font.convertSizeToPointValue(small.getFrets()[0].fontInfo.size), 3);
114
+ }
115
+ finally {
116
+ MetricsDefaults.GraceTabNote.fontScale = scale;
117
+ Metrics.clear('GraceTabNote');
118
+ }
119
+ }
@@ -28,20 +28,25 @@ const fontWidths = () => {
28
28
  return { sharpWidth, flatWidth, naturalWidth, clefWidth };
29
29
  };
30
30
  function parser(assert) {
31
- assert.expect(11);
31
+ assert.expect(16);
32
32
  function catchError(spec) {
33
33
  assert.throws(() => VexFlow.keySignature(spec), /BadKeySignature/);
34
34
  }
35
35
  catchError('asdf');
36
36
  catchError('D!');
37
37
  catchError('E#');
38
- catchError('D#');
39
38
  catchError('#');
40
39
  catchError('b');
41
40
  catchError('Kb');
42
41
  catchError('Fb');
43
- catchError('Dbm');
44
42
  catchError('B#m');
43
+ catchError('flats_15');
44
+ catchError('sharps_16');
45
+ catchError('flat_1');
46
+ catchError('sharps_-1');
47
+ catchError('sharp_0');
48
+ catchError('sharps_B');
49
+ catchError('flats_c');
45
50
  VexFlow.keySignature('B');
46
51
  VexFlow.keySignature('C');
47
52
  VexFlow.keySignature('Fm');
@@ -49,6 +54,12 @@ function parser(assert) {
49
54
  VexFlow.keySignature('Abm');
50
55
  VexFlow.keySignature('F#');
51
56
  VexFlow.keySignature('G#m');
57
+ VexFlow.keySignature('flats_8');
58
+ VexFlow.keySignature('sharps_14');
59
+ VexFlow.keySignature('flats_10');
60
+ VexFlow.keySignature('sharps_8');
61
+ VexFlow.keySignature('flats_0');
62
+ VexFlow.keySignature('sharps_0');
52
63
  assert.ok(true, 'all pass');
53
64
  }
54
65
  function majorKeys(options, contextBuilder) {
@@ -0,0 +1,149 @@
1
+ import assert from 'node:assert/strict';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import test from 'node:test';
7
+ import { fileURLToPath } from 'node:url';
8
+ const root = fileURLToPath(new URL('../../', import.meta.url));
9
+ const coreURL = new URL('../../build/esm/entry/vexflow-core.js', import.meta.url).href;
10
+ function runIsolated(source) {
11
+ const result = spawnSync(process.execPath, ['--input-type=module', '-e', source], {
12
+ cwd: root,
13
+ timeout: 3000,
14
+ encoding: 'utf8',
15
+ });
16
+ assert.ifError(result.error);
17
+ assert.equal(result.status, 0, result.stderr || result.stdout);
18
+ }
19
+ function checkCore(source) {
20
+ runIsolated(`import assert from 'node:assert/strict';
21
+ import { Element, Registry, Fraction, Voice, GhostNote, Tuning } from ${JSON.stringify(coreURL)};
22
+ ${source}`);
23
+ }
24
+ test('all published ESM entries load', () => {
25
+ const pkg = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url)));
26
+ for (const entry of Object.values(pkg.exports)) {
27
+ runIsolated(`await import(${JSON.stringify(new URL(`../../${entry.import}`, import.meta.url).href)});`);
28
+ }
29
+ });
30
+ test('ESM rewrite preserves packages, URLs, comments, and explicit extensions', () => {
31
+ const directory = mkdtempSync(join(tmpdir(), 'vexflow-esm-'));
32
+ try {
33
+ const input = `import clone from 'structured-clone-es';
34
+ import scoped from '@scope/package';
35
+ import 'node:fs';
36
+ import 'https://example.com/module';
37
+ import './already.js';
38
+ import './data.json';
39
+ import './side-effect';
40
+ import value from "../value";
41
+ export * from './';
42
+ export { default } from '.';
43
+ export * from '@scope/other';
44
+ const lazy = import('./lazy');
45
+ const text = "import './not-an-import';";
46
+ // import './comment';
47
+ `;
48
+ const filename = join(directory, 'fixture.js');
49
+ writeFileSync(filename, input);
50
+ const command = [join(root, 'tools/fix-esm-imports.mjs'), directory];
51
+ assert.equal(spawnSync(process.execPath, command).status, 0);
52
+ const expected = input
53
+ .replace("'./side-effect'", "'./side-effect.js'")
54
+ .replace('"../value"', '"../value.js"')
55
+ .replace("from './'", "from './index.js'")
56
+ .replace("from '.'", "from './index.js'")
57
+ .replace("import('./lazy')", "import('./lazy.js')");
58
+ assert.equal(readFileSync(filename, 'utf8'), expected);
59
+ assert.equal(spawnSync(process.execPath, command).status, 0);
60
+ assert.equal(readFileSync(filename, 'utf8'), expected, 'rewrite is idempotent');
61
+ }
62
+ finally {
63
+ rmSync(directory, { recursive: true, force: true });
64
+ }
65
+ });
66
+ test('registry treats prototype-related IDs and classes as ordinary data', () => {
67
+ checkCore(`
68
+ const before = Object.getOwnPropertyDescriptors(Object.prototype);
69
+ const registry = new Registry();
70
+ for (const id of ['reviewProbe', '__proto__', 'constructor', 'toString']) {
71
+ const element = registry.register(new Element(), id).getElementById(id);
72
+ assert.ok(element);
73
+ for (const name of ['__proto__', 'constructor', 'toString']) {
74
+ element.addClass(name);
75
+ assert.ok(registry.getElementsByClass(name).includes(element));
76
+ element.removeClass(name);
77
+ assert.ok(!registry.getElementsByClass(name).includes(element));
78
+ }
79
+ }
80
+ for (const name of ['__proto__', 'constructor', 'toString', 'missing']) {
81
+ assert.throws(() => registry.setIndexValue(name, 'value', 'id', new Element()), /BadArgument/);
82
+ assert.throws(() => registry.updateIndex({id:'reviewProbe', name, value:'value'}), /BadArgument/);
83
+ assert.deepEqual(registry.getElementsByAttribute(name, 'value'), []);
84
+ }
85
+ assert.deepEqual(Object.getOwnPropertyDescriptors(Object.prototype), before);
86
+ registry.clear();
87
+ assert.equal(registry.getElementById('__proto__'), undefined);
88
+ `);
89
+ });
90
+ for (const duration of ["'9'.repeat(10000) + 'X'", "'4' + 'd'.repeat(100000)", "'prefix4'", "'4junk'"]) {
91
+ test(`reject malformed duration: ${duration}`, () => checkCore(`assert.throws(() => new GhostNote(${duration}));`));
92
+ }
93
+ test('valid durations and tuning still work', () => {
94
+ checkCore(`
95
+ for (const duration of ['1/2', 'w', 'h', 'q', '4', '8d', '16dd', '4r', '4n', '4h', '4m', '4s']) {
96
+ assert.ok(new GhostNote(duration).getTicks().value() > 0, duration);
97
+ }
98
+ assert.equal(new Tuning(' E/5 , B/4 , G/4 ').getValueForString(2), new Tuning('standard').getValueForString(2));
99
+ assert.throws(() => new Tuning('constructor'));
100
+ assert.throws(() => new Tuning(' '.repeat(100000) + 'X'));
101
+ `);
102
+ });
103
+ for (const meter of [
104
+ "'9'.repeat(100000)",
105
+ "'9'.repeat(400) + '/4'",
106
+ "'4/0'",
107
+ "'0/4'",
108
+ "'prefix4/4'",
109
+ "'4/4suffix'",
110
+ "''",
111
+ '{numBeats:Infinity,beatValue:4}',
112
+ '{numBeats:4,beatValue:NaN}',
113
+ '{numBeats:4,beatValue:0}',
114
+ '{numBeats:-1,beatValue:4}',
115
+ '{numBeats:1.5,beatValue:4}',
116
+ '{numBeats:4,beatValue:4,resolution:0}',
117
+ '{numBeats:4,beatValue:4,resolution:Infinity}',
118
+ '{numBeats:Number.MAX_SAFE_INTEGER,beatValue:1}',
119
+ ]) {
120
+ test(`reject invalid meter: ${meter}`, () => checkCore(`assert.throws(() => new Voice(${meter}).isComplete(), /BadArgument/);`));
121
+ }
122
+ test('valid meters preserve tick counts', () => {
123
+ checkCore(`
124
+ assert.equal(new Voice().getTotalTicks().value(), new Voice('4/4').getTotalTicks().value());
125
+ assert.equal(new Voice('3/8').getTotalTicks().value(), 6144);
126
+ assert.equal(new Voice({numBeats:3,beatValue:8,resolution:480}).getTotalTicks().value(), 180);
127
+ `);
128
+ });
129
+ for (const value of ['Infinity', '-Infinity', 'NaN']) {
130
+ test(`fraction rejects ${value} in both operands`, () => checkCore(`
131
+ assert.throws(() => Fraction.GCD(${value}, 1), /BadArgument/);
132
+ assert.throws(() => Fraction.GCD(1, ${value}), /BadArgument/);
133
+ assert.throws(() => new Fraction(${value}, 1), /BadArgument/);
134
+ assert.throws(() => new Fraction(1, ${value}), /BadArgument/);
135
+ `));
136
+ }
137
+ test('fraction rejects zero denominators and overflow without changing its value', () => {
138
+ checkCore(`
139
+ assert.throws(() => new Fraction(1, 0), /BadArgument/);
140
+ const fraction = new Fraction(1, 2);
141
+ assert.throws(() => fraction.divide(0), /BadArgument/);
142
+ assert.equal(fraction.value(), 0.5);
143
+ assert.throws(() => new Fraction(Number.MAX_VALUE).multiply(2), /BadArgument/);
144
+ assert.equal(new Fraction(0, 2).simplify().value(), 0);
145
+ assert.equal(new Fraction(1, -2).simplify().value(), -0.5);
146
+ assert.equal(new Fraction(0.5, 1).simplify().toString(), '1/2');
147
+ assert.equal(Fraction.GCD(0, 0), 0);
148
+ `);
149
+ });
@@ -0,0 +1,78 @@
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 assert from 'node:assert/strict';
11
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
12
+ import { tmpdir } from 'node:os';
13
+ import { join } from 'node:path';
14
+ import test from 'node:test';
15
+ import { createCanvas } from 'canvas';
16
+ import { analyzeLayout, comparePixels } from '../../tools/render-metrics.mjs';
17
+ import { compareDirectories } from '../../tools/visual-regression.mjs';
18
+ test('layout diagnostics detect moved notes, clipping, and non-finite bounds', () => {
19
+ const boxes = [
20
+ { id: 'a', group: 'voice', x: 5, y: 5, width: 10, height: 10 },
21
+ { id: 'b', group: 'voice', x: 20, y: 5, width: 10, height: 10 },
22
+ ];
23
+ const viewport = { width: 40, height: 30 };
24
+ assert.deepEqual(analyzeLayout(boxes, viewport), { invalid: [], overflow: [], collisions: [] });
25
+ boxes[1].x = 10;
26
+ assert.equal(analyzeLayout(boxes, viewport).collisions[0].area, 50);
27
+ boxes[1].x = 35;
28
+ assert.equal(analyzeLayout(boxes, viewport).overflow[0].excess, 5);
29
+ boxes[1].x = NaN;
30
+ assert.deepEqual(analyzeLayout(boxes, viewport).invalid, ['b']);
31
+ boxes[1] = Object.assign(Object.assign({}, boxes[0]), { id: 'intentional overlap', group: 'other voice' });
32
+ assert.deepEqual(analyzeLayout(boxes, viewport).collisions, []);
33
+ });
34
+ test('pixel metrics detect color and alpha changes', () => {
35
+ const a = new Uint8Array([255, 255, 255, 255, 0, 0, 0, 255]);
36
+ assert.equal(comparePixels(a, a).changed, 0);
37
+ const b = a.slice();
38
+ b[0] = 250;
39
+ b[7] = 0;
40
+ assert.equal(comparePixels(a, b).changed, 2);
41
+ assert.equal(comparePixels(a, b, 5).changed, 1);
42
+ });
43
+ test('visual comparison reports changed, missing, resized, and corrupt images', () => __awaiter(void 0, void 0, void 0, function* () {
44
+ const root = yield mkdtemp(join(tmpdir(), 'vexflow-visual-'));
45
+ const before = join(root, 'before');
46
+ const after = join(root, 'after');
47
+ const output = join(root, 'report');
48
+ try {
49
+ yield mkdir(before);
50
+ yield mkdir(after);
51
+ yield assert.rejects(compareDirectories(before, after, output), /must contain/);
52
+ const canvas = createCanvas(20, 20);
53
+ const ctx = canvas.getContext('2d');
54
+ ctx.fillStyle = 'white';
55
+ ctx.fillRect(0, 0, 20, 20);
56
+ const white = canvas.toBuffer('image/png');
57
+ yield writeFile(join(before, 'same.png'), white);
58
+ yield writeFile(join(after, 'same.png'), white);
59
+ assert.deepEqual(yield compareDirectories(before, after, output), { total: 1, failed: 0 });
60
+ ctx.fillStyle = 'black';
61
+ ctx.fillRect(5, 5, 2, 2);
62
+ yield writeFile(join(before, 'changed.png'), white);
63
+ yield writeFile(join(after, 'changed.png'), canvas.toBuffer('image/png'));
64
+ yield writeFile(join(before, 'missing.png'), white);
65
+ yield writeFile(join(after, 'new.png'), white);
66
+ yield writeFile(join(before, 'size.png'), white);
67
+ yield writeFile(join(after, 'size.png'), createCanvas(10, 10).toBuffer('image/png'));
68
+ yield writeFile(join(before, 'broken.png'), white);
69
+ yield writeFile(join(after, 'broken.png'), 'not a PNG');
70
+ assert.deepEqual(yield compareDirectories(before, after, output), { total: 6, failed: 5 });
71
+ const report = JSON.parse(yield readFile(join(output, 'results.json'), 'utf8'));
72
+ assert.equal(report.results.find((r) => r.name === 'changed.png').changedPixels, 4);
73
+ assert.ok((yield readFile(join(output, 'index.html'), 'utf8')).includes('diff-changed.png'));
74
+ }
75
+ finally {
76
+ yield rm(root, { recursive: true, force: true });
77
+ }
78
+ }));
@@ -0,0 +1,75 @@
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 assert from 'node:assert/strict';
11
+ import { spawnSync } from 'node:child_process';
12
+ import { mkdirSync, readdirSync, readFileSync } from 'node:fs';
13
+ import { join } from 'node:path';
14
+ import test from 'node:test';
15
+ import { fileURLToPath } from 'node:url';
16
+ import puppeteer from 'puppeteer';
17
+ import { renderScore } from '../../tools/score-fixtures.mjs';
18
+ const root = fileURLToPath(new URL('../../', import.meta.url));
19
+ test('jsdom registers fonts, renders PNGs, and exports portable SVG', () => {
20
+ const directory = join(root, 'build/jsdom-smoke');
21
+ mkdirSync(directory, { recursive: true });
22
+ const script = `
23
+ const assert=require('node:assert/strict');const fs=require('node:fs');
24
+ const {JSDOM}=require('jsdom');const {registerFont}=require('canvas');const opentype=require('opentype.js');
25
+ const dom=new JSDOM('<div id="score"></div>');global.window=dom.window;global.document=dom.window.document;
26
+ const fonts=['bravura/bravura','academico/academico'].map((name,i)=>{
27
+ const file='node_modules/@vexflow-fonts/'+name+'.otf';const family=i?'Academico':'Bravura';
28
+ registerFont(file,{family});return {family,font:opentype.loadSync(file)};
29
+ });
30
+ const VF=require('./build/cjs/vexflow-debug.js');VF.setFonts('Bravura','Academico');
31
+ const renderer=new VF.Renderer(document.getElementById('score'),VF.Renderer.Backends.SVG);renderer.resize(400,200);
32
+ const ctx=renderer.getContext();new VF.Stave(10,40,350).addClef('treble').addTimeSignature('4/4').setContext(ctx).draw();
33
+ ctx.setFont('Academico',12).fillText('Font-aware jsdom export',20,150);
34
+ const svg=ctx.toSVG(fonts);assert.ok(!svg.includes('<text'));assert.ok(svg.includes('<path'));
35
+ fs.writeFileSync(${JSON.stringify(join(directory, 'score.svg'))},svg);dom.window.close();
36
+ `;
37
+ const run = (args) => {
38
+ const r = spawnSync(process.execPath, args, { cwd: root, timeout: 30000, encoding: 'utf8' });
39
+ assert.ifError(r.error);
40
+ assert.equal(r.status, 0, r.stderr + r.stdout);
41
+ };
42
+ run(['-e', script]);
43
+ run(['tools/generate_images_jsdom.js', 'build', directory, '--fonts=bravura', '--module=Clef']);
44
+ const pngs = readdirSync(directory).filter((file) => file.endsWith('.png'));
45
+ assert.equal(pngs.length, 7);
46
+ for (const file of pngs)
47
+ assert.equal(readFileSync(join(directory, file)).subarray(1, 4).toString(), 'PNG');
48
+ });
49
+ test('score benchmark fixtures render', () => __awaiter(void 0, void 0, void 0, function* () {
50
+ const browser = yield puppeteer.launch({
51
+ headless: true,
52
+ args: process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : [],
53
+ });
54
+ try {
55
+ const page = yield browser.newPage();
56
+ yield page.setContent('<div id="score"></div>');
57
+ yield page.addScriptTag({ path: join(root, 'build/cjs/vexflow-debug.js') });
58
+ yield page.evaluate(() => __awaiter(void 0, void 0, void 0, function* () {
59
+ yield document.fonts.ready;
60
+ }));
61
+ for (const kind of ['chorale', 'piano', 'chamber']) {
62
+ const result = yield page.evaluate(renderScore, { kind, systems: 1 });
63
+ const expected = {
64
+ chorale: { notes: 48, staves: 8 },
65
+ piano: { notes: 64, staves: 8 },
66
+ chamber: { notes: 144, staves: 12 },
67
+ }[kind];
68
+ assert.deepEqual({ notes: result.notes, staves: result.staves }, expected);
69
+ assert.ok(result.svg.includes('<path'));
70
+ }
71
+ }
72
+ finally {
73
+ yield browser.close();
74
+ }
75
+ }));