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
@@ -21,8 +21,10 @@ export class TimeSigNote extends Note {
21
21
  const stave = this.checkStave();
22
22
  const ctx = this.checkContext();
23
23
  this.setRendered();
24
- ctx.openGroup('timesignote', this.getAttribute('id'));
24
+ const clsAttribute = this.getAttribute('class');
25
+ ctx.openGroup('timesignote' + (clsAttribute ? ' ' + clsAttribute : ''), this.getAttribute('id'));
25
26
  this.timeSig.drawAt(ctx, stave, this.getAbsoluteX());
27
+ this.drawPointerRect();
26
28
  ctx.closeGroup();
27
29
  }
28
30
  }
@@ -19,11 +19,11 @@ export class Tuning {
19
19
  return (_a = Tables.keyProperties(noteString).intValue) !== null && _a !== void 0 ? _a : -1;
20
20
  }
21
21
  setTuning(tuningString) {
22
- if (Tuning.names[tuningString]) {
22
+ if (Object.prototype.hasOwnProperty.call(Tuning.names, tuningString)) {
23
23
  tuningString = Tuning.names[tuningString];
24
24
  }
25
25
  this.tuningValues = [];
26
- const keys = tuningString.split(/\s*,\s*/);
26
+ const keys = tuningString.split(',').map((key) => key.trim());
27
27
  if (keys.length === 0) {
28
28
  throw new RuntimeError('BadArguments', `Invalid tuning string: ${tuningString}`);
29
29
  }
@@ -1,3 +1,4 @@
1
+ import { BoundingBox } from './boundingbox.js';
1
2
  import { Element } from './element.js';
2
3
  import { Formatter } from './formatter.js';
3
4
  import { Glyphs } from './glyphs.js';
@@ -31,6 +32,7 @@ export class Tuplet extends Element {
31
32
  const location = options.location || Tuplet.LOCATION_TOP;
32
33
  const yOffset = options.yOffset || Metrics.get('Tuplet.yOffset');
33
34
  const textYOffset = options.textYOffset || Metrics.get('Tuplet.textYOffset');
35
+ const suffix = options.suffix || '';
34
36
  this.options = {
35
37
  bracketed,
36
38
  location,
@@ -39,8 +41,10 @@ export class Tuplet extends Element {
39
41
  ratioed,
40
42
  yOffset,
41
43
  textYOffset,
44
+ suffix,
42
45
  };
43
46
  this.textElement = new Element('Tuplet');
47
+ this.suffixElement = new Element('Tuplet.suffix');
44
48
  this.setTupletLocation(location || Tuplet.LOCATION_TOP);
45
49
  Formatter.AlignRestsToNotes(notes, true, true);
46
50
  this.resolveGlyphs();
@@ -49,13 +53,15 @@ export class Tuplet extends Element {
49
53
  attach() {
50
54
  for (let i = 0; i < this.notes.length; i++) {
51
55
  const note = this.notes[i];
52
- note.setTuplet(this);
56
+ if (!note.getTupletStack().includes(this)) {
57
+ note.addTuplet(this);
58
+ }
53
59
  }
54
60
  }
55
61
  detach() {
56
62
  for (let i = 0; i < this.notes.length; i++) {
57
63
  const note = this.notes[i];
58
- note.resetTuplet(this);
64
+ note.removeTuplet(this);
59
65
  }
60
66
  }
61
67
  setBracketed(bracketed) {
@@ -106,21 +112,23 @@ export class Tuplet extends Element {
106
112
  denominator = Glyphs.tupletColon + denominator;
107
113
  }
108
114
  this.textElement.setText(numerator + denominator);
115
+ if (this.options.suffix) {
116
+ this.suffixElement.setText(this.options.suffix);
117
+ }
109
118
  }
110
119
  getNestedTupletCount() {
111
120
  const { location } = this.options;
112
- const firstNote = this.notes[0];
113
- let maxTupletCount = countTuplets(firstNote, location);
114
- let minTupletCount = countTuplets(firstNote, location);
115
- function countTuplets(note, location) {
116
- return note.getTupletStack().filter((tuplet) => tuplet.options.location === location).length;
117
- }
118
- this.notes.forEach((note) => {
119
- const tupletCount = countTuplets(note, location);
120
- maxTupletCount = tupletCount > maxTupletCount ? tupletCount : maxTupletCount;
121
- minTupletCount = tupletCount < minTupletCount ? tupletCount : minTupletCount;
122
- });
123
- return maxTupletCount - minTupletCount;
121
+ let maxOffset = 0;
122
+ for (const note of this.notes) {
123
+ const stack = note
124
+ .getTupletStack()
125
+ .filter((tuplet) => tuplet.options.location === location);
126
+ const index = stack.indexOf(this);
127
+ if (index >= 0 && index > maxOffset) {
128
+ maxOffset = index;
129
+ }
130
+ }
131
+ return maxOffset;
124
132
  }
125
133
  getYPosition() {
126
134
  var _a;
@@ -172,37 +180,79 @@ export class Tuplet extends Element {
172
180
  return yPosition + nestedTupletYOffset + yOffset;
173
181
  }
174
182
  draw() {
175
- const { location, bracketed, textYOffset } = this.options;
183
+ const { location, bracketed, textYOffset, suffix } = this.options;
184
+ const bracketPadding = Metrics.get('Tuplet.bracket.padding');
185
+ const bracketThickness = Metrics.get('Tuplet.bracket.lineWidth');
186
+ const bracketLegLength = Metrics.get('Tuplet.bracket.legLength');
187
+ const extraSpacing = Metrics.get('Tuplet.suffix.extraSpacing');
188
+ const suffixOffsetY = Metrics.get('Tuplet.suffix.suffixOffsetY');
176
189
  const ctx = this.checkContext();
177
190
  let xPos = 0;
178
191
  let yPos = 0;
179
192
  const firstNote = this.notes[0];
180
193
  const lastNote = this.notes[this.notes.length - 1];
194
+ let bodyWidth = 0;
181
195
  if (!bracketed) {
182
196
  xPos = firstNote.getStemX();
183
- this.width = lastNote.getStemX() - xPos;
197
+ bodyWidth = lastNote.getStemX() - xPos;
198
+ this.setWidth(bodyWidth);
184
199
  }
185
200
  else {
186
- xPos = firstNote.getTieLeftX() - 5;
187
- this.width = lastNote.getTieRightX() - xPos + 5;
201
+ xPos = firstNote.getTieLeftX() - bracketPadding;
202
+ bodyWidth = lastNote.getTieRightX() - xPos + bracketPadding;
203
+ this.setWidth(bodyWidth + bracketThickness);
188
204
  }
205
+ this.setX(xPos);
189
206
  yPos = this.getYPosition();
190
- const notationCenterX = xPos + this.width / 2;
191
- const notationStartX = notationCenterX - this.textElement.getWidth() / 2;
192
- ctx.openGroup('tuplet', this.getAttribute('id'));
207
+ this.setY(location === 1 ? yPos : yPos - bracketLegLength + bracketThickness);
208
+ this.height = bracketLegLength;
209
+ const ratioWidth = this.textElement.getWidth();
210
+ let totalTextWidth = ratioWidth;
211
+ let noteWidth = 0;
212
+ if (suffix) {
213
+ noteWidth = this.suffixElement.getWidth();
214
+ totalTextWidth = ratioWidth + extraSpacing + noteWidth;
215
+ }
216
+ const notationCenterX = xPos + bodyWidth / 2;
217
+ const notationStartX = notationCenterX - totalTextWidth / 2;
218
+ const commonTextY = yPos + this.textElement.getHeight() / 2 + (location === Tuplet.LOCATION_TOP ? -1 : 1) * textYOffset;
219
+ const clsAttribute = this.getAttribute('class');
220
+ ctx.openGroup('tuplet' + (clsAttribute ? ' ' + clsAttribute : ''), this.getAttribute('id'));
193
221
  if (bracketed) {
194
- const lineWidth = this.width / 2 - this.textElement.getWidth() / 2 - 5;
222
+ const lineWidth = bodyWidth / 2 - totalTextWidth / 2 - bracketPadding;
223
+ const isTupletBottom = location === Tuplet.LOCATION_BOTTOM;
195
224
  if (lineWidth > 0) {
196
- ctx.fillRect(xPos, yPos, lineWidth, 1);
197
- ctx.fillRect(xPos + this.width / 2 + this.textElement.getWidth() / 2 + 5, yPos, lineWidth, 1);
198
- ctx.fillRect(xPos, yPos + (location === Tuplet.LOCATION_BOTTOM ? 1 : 0), 1, location * 10);
199
- ctx.fillRect(xPos + this.width, yPos + (location === Tuplet.LOCATION_BOTTOM ? 1 : 0), 1, location * 10);
225
+ ctx.fillRect(xPos, yPos, lineWidth, bracketThickness);
226
+ ctx.fillRect(xPos + bodyWidth / 2 + totalTextWidth / 2 + bracketPadding, yPos, lineWidth, bracketThickness);
227
+ ctx.fillRect(xPos, yPos + (isTupletBottom ? 1 : 0), bracketThickness, location * bracketLegLength);
228
+ ctx.fillRect(xPos + bodyWidth, yPos + (isTupletBottom ? 1 : 0), bracketThickness, location * bracketLegLength);
200
229
  }
201
230
  }
202
- this.textElement.renderText(ctx, notationStartX, yPos + this.textElement.getHeight() / 2 + (location === Tuplet.LOCATION_TOP ? -1 : 1) * textYOffset);
203
- const bb = this.getBoundingBox();
204
- ctx.pointerRect(bb.getX(), bb.getY(), bb.getW(), bb.getH());
231
+ let currentX = notationStartX;
232
+ this.textElement.setX(currentX);
233
+ this.textElement.setY(commonTextY);
234
+ this.textElement.renderText(ctx, 0, 0);
235
+ currentX += ratioWidth + extraSpacing;
236
+ if (suffix) {
237
+ const suffixY = commonTextY + suffixOffsetY;
238
+ this.suffixElement.setX(currentX);
239
+ this.suffixElement.setY(suffixY);
240
+ this.suffixElement.renderText(ctx, 0, 0);
241
+ currentX += noteWidth;
242
+ }
243
+ this.drawPointerRect();
205
244
  ctx.closeGroup();
206
245
  this.setRendered();
207
246
  }
247
+ getBoundingBox() {
248
+ const { bracketed, suffix } = this.options;
249
+ const ratioBounding = this.textElement.getBoundingBox();
250
+ const suffixBounding = this.suffixElement.getBoundingBox();
251
+ const mergedText = suffix ? ratioBounding.mergeWith(suffixBounding) : ratioBounding;
252
+ if (!bracketed) {
253
+ return mergedText;
254
+ }
255
+ const bracketBounding = new BoundingBox(this.x, this.y, this.width, this.height);
256
+ return bracketBounding.mergeWith(mergedText);
257
+ }
208
258
  }
@@ -1,3 +1,4 @@
1
+ export { structuredClone } from 'structured-clone-es';
1
2
  export class RuntimeError extends Error {
2
3
  constructor(code, message = '') {
3
4
  super('[RuntimeError] ' + code + ': ' + message);
@@ -1,3 +1,3 @@
1
- export const VERSION = '5.0.0';
2
- export const ID = '0ca6f889545c33cce851b420c24945f6eb685aeb';
3
- export const DATE = '2025-03-05T17:05:43.991Z';
1
+ export const VERSION = '5.1.1';
2
+ export const ID = '271f9428354588de1f6c83a065428c8a5c442513';
3
+ export const DATE = '2026-11-16T03:47:09.194Z';
@@ -53,8 +53,9 @@ import { Registry } from './registry.js';
53
53
  import { RenderContext } from './rendercontext.js';
54
54
  import { Renderer, RendererBackends, RendererLineEndType } from './renderer.js';
55
55
  import { RepeatNote } from './repeatnote.js';
56
+ import { Sheet } from './sheet.js';
56
57
  import { Stave } from './stave.js';
57
- import { Barline, BarlineType } from './stavebarline.js';
58
+ import { Barline, BarlineType, RepeatBracketType } from './stavebarline.js';
58
59
  import { StaveConnector } from './staveconnector.js';
59
60
  import { StaveHairpin } from './stavehairpin.js';
60
61
  import { StaveLine } from './staveline.js';
@@ -103,9 +104,18 @@ export class VexFlow {
103
104
  });
104
105
  }
105
106
  static setFonts(...fontNames) {
106
- MetricsDefaults.fontFamily = fontNames.join(',');
107
+ const names = fontNames.flatMap((name) => name.split(',').map((part) => part.trim())).filter(Boolean);
108
+ MetricsDefaults.fontFamily = names.join(',');
109
+ const textNames = names.filter((name) => Font.TEXT_FONT_NAMES.includes(name));
110
+ VexFlow.setTextFonts(...(textNames.length ? textNames : ['Academico']));
111
+ }
112
+ static setTextFonts(...fontNames) {
113
+ MetricsDefaults.textFontFamily = [...new Set([...fontNames, ...VexFlow.getFonts()])].join(',');
107
114
  Metrics.clear();
108
115
  }
116
+ static getTextFonts() {
117
+ return Metrics.get('textFontFamily').split(',');
118
+ }
109
119
  static getFonts() {
110
120
  return Metrics.get('fontFamily').split(',');
111
121
  }
@@ -269,6 +279,7 @@ VexFlow.StringNumber = StringNumber;
269
279
  VexFlow.Stroke = Stroke;
270
280
  VexFlow.SVGContext = SVGContext;
271
281
  VexFlow.System = System;
282
+ VexFlow.Sheet = Sheet;
272
283
  VexFlow.TabNote = TabNote;
273
284
  VexFlow.TabSlide = TabSlide;
274
285
  VexFlow.TabStave = TabStave;
@@ -301,6 +312,7 @@ VexFlow.ModifierPosition = ModifierPosition;
301
312
  VexFlow.RendererBackends = RendererBackends;
302
313
  VexFlow.RendererLineEndType = RendererLineEndType;
303
314
  VexFlow.BarlineType = BarlineType;
315
+ VexFlow.RepeatBracketType = RepeatBracketType;
304
316
  VexFlow.StaveModifierPosition = StaveModifierPosition;
305
317
  VexFlow.VoltaType = VoltaType;
306
318
  VexFlow.TextBracketPosition = TextBracketPosition;
@@ -20,6 +20,7 @@ export class Voice extends Element {
20
20
  this.resolutionMultiplier = 1;
21
21
  this.mode = VoiceMode.STRICT;
22
22
  this.preFormatted = false;
23
+ this.ticksDirty = false;
23
24
  this.ticksUsed = new Fraction(0, 1);
24
25
  this.largestTickWidth = 0;
25
26
  this.tickables = [];
@@ -28,31 +29,40 @@ export class Voice extends Element {
28
29
  };
29
30
  let voiceTime;
30
31
  if (typeof time === 'string') {
31
- const match = time.match(/(\d+)\/(\d+)/);
32
- if (match) {
33
- voiceTime = {
34
- numBeats: parseInt(match[1]),
35
- beatValue: parseInt(match[2]),
36
- };
32
+ const match = time.length <= 64 ? /^(\d+)\/(\d+)$/.exec(time) : null;
33
+ if (!match) {
34
+ throw new RuntimeError('BadArgument', 'Invalid time signature. Expected positive integers such as 4/4.');
37
35
  }
36
+ voiceTime = { numBeats: Number(match[1]), beatValue: Number(match[2]) };
38
37
  }
39
38
  else {
40
39
  voiceTime = time;
41
40
  }
42
41
  this.time = Object.assign({ numBeats: 4, beatValue: 4, resolution: Tables.RESOLUTION }, voiceTime);
43
- this.totalTicks = new Fraction(this.time.numBeats * (this.time.resolution / this.time.beatValue), 1);
42
+ const { numBeats, beatValue, resolution } = this.time;
43
+ if (![numBeats, beatValue, resolution].every((value) => Number.isSafeInteger(value) && value > 0)) {
44
+ throw new RuntimeError('BadArgument', 'Meter and resolution must be positive safe integers.');
45
+ }
46
+ const totalTicks = numBeats * (resolution / beatValue);
47
+ if (!Number.isFinite(totalTicks) || totalTicks <= 0 || totalTicks > Number.MAX_SAFE_INTEGER) {
48
+ throw new RuntimeError('BadArgument', 'Meter exceeds the supported tick range.');
49
+ }
50
+ this.totalTicks = new Fraction(totalTicks, 1);
44
51
  this.smallestTickCount = this.totalTicks.clone();
45
52
  }
46
53
  getTotalTicks() {
54
+ this.refreshTicks();
47
55
  return this.totalTicks;
48
56
  }
49
57
  getTicksUsed() {
58
+ this.refreshTicks();
50
59
  return this.ticksUsed;
51
60
  }
52
61
  getLargestTickWidth() {
53
62
  return this.largestTickWidth;
54
63
  }
55
64
  getSmallestTickCount() {
65
+ this.refreshTicks();
56
66
  return this.smallestTickCount;
57
67
  }
58
68
  getTickables() {
@@ -66,10 +76,11 @@ export class Voice extends Element {
66
76
  return this;
67
77
  }
68
78
  getResolutionMultiplier() {
79
+ this.refreshTicks();
69
80
  return this.resolutionMultiplier;
70
81
  }
71
82
  getActualResolution() {
72
- return this.resolutionMultiplier * this.time.resolution;
83
+ return this.getResolutionMultiplier() * this.time.resolution;
73
84
  }
74
85
  setStave(stave) {
75
86
  this.stave = stave;
@@ -94,6 +105,7 @@ export class Voice extends Element {
94
105
  return this;
95
106
  }
96
107
  isComplete() {
108
+ this.refreshTicks();
97
109
  if (this.mode === VoiceMode.STRICT || this.mode === VoiceMode.FULL) {
98
110
  return this.ticksUsed.equals(this.totalTicks);
99
111
  }
@@ -113,6 +125,7 @@ export class Voice extends Element {
113
125
  return this.expTicksUsed;
114
126
  }
115
127
  softmax(tickValue) {
128
+ this.refreshTicks();
116
129
  if (!this.expTicksUsed) {
117
130
  this.expTicksUsed = this.reCalculateExpTicksUsed();
118
131
  }
@@ -121,7 +134,30 @@ export class Voice extends Element {
121
134
  const sm = exp(tickValue) / this.expTicksUsed;
122
135
  return sm;
123
136
  }
137
+ invalidateTicks() {
138
+ this.ticksDirty = true;
139
+ this.expTicksUsed = undefined;
140
+ }
141
+ refreshTicks() {
142
+ if (!this.ticksDirty)
143
+ return;
144
+ this.ticksUsed.set(0, 1);
145
+ this.totalTicks.set(this.time.numBeats * (this.time.resolution / this.time.beatValue), 1);
146
+ this.smallestTickCount = this.totalTicks.clone();
147
+ for (const tickable of this.tickables) {
148
+ if (tickable.shouldIgnoreTicks())
149
+ continue;
150
+ const ticks = tickable.getTicks();
151
+ this.ticksUsed.add(ticks);
152
+ if (ticks.lessThan(this.smallestTickCount))
153
+ this.smallestTickCount = ticks.clone();
154
+ }
155
+ this.resolutionMultiplier = this.ticksUsed.denominator;
156
+ this.totalTicks.add(0, this.resolutionMultiplier);
157
+ this.ticksDirty = false;
158
+ }
124
159
  addTickable(tickable) {
160
+ this.refreshTicks();
125
161
  if (!tickable.shouldIgnoreTicks()) {
126
162
  const ticks = tickable.getTicks();
127
163
  this.ticksUsed.add(ticks);
@@ -17,6 +17,8 @@ const AccidentalTests = {
17
17
  Start() {
18
18
  QUnit.module('Accidental');
19
19
  QUnit.test('Automatic Accidentals - Simple Tests', autoAccidentalWorking);
20
+ QUnit.test('Automatic Accidentals - Voice Order', autoAccidentalVoiceOrder);
21
+ QUnit.test('Automatic Accidentals - Simultaneous Notes', autoAccidentalSimultaneousNotes);
20
22
  const run = VexFlowTests.runTests;
21
23
  run('Bounding Box', basic, { drawBoundingBox: true });
22
24
  run('Accidental Padding', formatAccidentalSpaces);
@@ -116,6 +118,56 @@ function autoAccidentalWorking(assert) {
116
118
  assert.equal(hasAccidental(notes[9]), true, 'Added natural');
117
119
  assert.equal(hasAccidental(notes[10]), false, 'Natural remembered');
118
120
  }
121
+ function autoAccidentalVoiceOrder(assert) {
122
+ for (const reverseVoices of [false, true]) {
123
+ const halfNotes = [
124
+ new StaveNote({ keys: ['c/4'], duration: '2' }),
125
+ new StaveNote({ keys: ['c#/4'], duration: '2' }),
126
+ ];
127
+ const offsetNotes = [
128
+ new StaveNote({ keys: ['g/4'], duration: '4' }),
129
+ new StaveNote({ keys: ['c#/4'], duration: '4' }),
130
+ new StaveNote({ keys: ['g/4'], duration: '2' }),
131
+ ];
132
+ const voices = [new Voice().addTickables(halfNotes), new Voice().addTickables(offsetNotes)];
133
+ if (reverseVoices)
134
+ voices.reverse();
135
+ Accidental.applyAccidentals(voices, 'C');
136
+ const accidentals = [halfNotes, offsetNotes].map((notes) => notes.map((note) => note
137
+ .getModifiers()
138
+ .filter(isAccidental)
139
+ .map((accidental) => accidental.type)));
140
+ assert.deepEqual(accidentals, [
141
+ [[], []],
142
+ [[], ['#'], []],
143
+ ], `The earlier C# gets the sharp; the later C# remembers it (reversed voices: ${reverseVoices})`);
144
+ }
145
+ }
146
+ function autoAccidentalSimultaneousNotes(assert) {
147
+ for (const reverseVoices of [false, true]) {
148
+ const halfNotes = [
149
+ new StaveNote({ keys: ['g/4'], duration: '2' }),
150
+ new StaveNote({ keys: ['c#/4'], duration: '2' }),
151
+ ];
152
+ const offsetNotes = [
153
+ new StaveNote({ keys: ['c#/4'], duration: '4' }),
154
+ new StaveNote({ keys: ['c/4'], duration: '4' }),
155
+ new StaveNote({ keys: ['c#/4'], duration: '2' }),
156
+ ];
157
+ const voices = [new Voice().addTickables(halfNotes), new Voice().addTickables(offsetNotes)];
158
+ if (reverseVoices)
159
+ voices.reverse();
160
+ Accidental.applyAccidentals(voices, 'C');
161
+ const accidentals = [halfNotes, offsetNotes].map((notes) => notes.map((note) => note
162
+ .getModifiers()
163
+ .filter(isAccidental)
164
+ .map((accidental) => accidental.type)));
165
+ assert.deepEqual(accidentals, [
166
+ [[], ['#']],
167
+ [['#'], ['n'], ['#']],
168
+ ], `Both simultaneous C# notes get sharps after the natural (reversed voices: ${reverseVoices})`);
169
+ }
170
+ }
119
171
  function formatAccidentalSpaces(options) {
120
172
  const f = VexFlowTests.makeFactory(options, 750, 280);
121
173
  const context = f.getContext();
@@ -18,6 +18,7 @@ import { Voice } from '../src/voice.js';
18
18
  const AnnotationTests = {
19
19
  Start() {
20
20
  QUnit.module('Annotation');
21
+ QUnit.test('computedPositions', computedPositions);
21
22
  const run = VexFlowTests.runTests;
22
23
  run('Bounding Box', placement, { drawBoundingBox: true });
23
24
  run('Placement', placement, { drawBoundingBox: false });
@@ -379,3 +380,40 @@ function tabNotes(options, contextBuilder) {
379
380
  }
380
381
  VexFlowTests.register(AnnotationTests);
381
382
  export { AnnotationTests };
383
+ function computedPositions(assert) {
384
+ const ctx = new VexFlow.SVGContext(document.createElement('div'));
385
+ const stave = new Stave(10, 20, 500).setContext(ctx);
386
+ const note = new StaveNote({ keys: ['c/4'], duration: 'w' }).setStave(stave);
387
+ const annotation = new Annotation('Aligned').setContext(ctx);
388
+ note.addModifier(annotation, 0);
389
+ const voice = new Voice('4/4').addTickables([note]);
390
+ new Formatter().joinVoices([voice]).formatToStave([voice], stave);
391
+ const position = [annotation.getX(), annotation.getY(), annotation.isRendered()];
392
+ annotation.computeX();
393
+ annotation.computeY();
394
+ assert.deepEqual([annotation.getX(), annotation.getY(), annotation.isRendered()], position);
395
+ const automatic = annotation.computeY().y;
396
+ annotation.setTextBaseline(210);
397
+ assert.equal(annotation.computeY().y, 210);
398
+ annotation.setTextBaseline();
399
+ assert.equal(annotation.computeY().y, automatic);
400
+ assert.throws(() => annotation.setTextBaseline(Infinity), /BadArgument/);
401
+ for (const h of [1, 2, 3, 4])
402
+ for (const v of [1, 2, 3, 4]) {
403
+ annotation.setJustification(h).setVerticalJustification(v);
404
+ const { x } = annotation.computeX(), { y } = annotation.computeY();
405
+ annotation.draw();
406
+ assert.equal(annotation.getX(), x);
407
+ assert.equal(annotation.getY(), y);
408
+ }
409
+ class FixedLyric extends Annotation {
410
+ computeY() {
411
+ return { y: 250, textHeight: 15 };
412
+ }
413
+ }
414
+ const custom = new FixedLyric('Override').setNote(note).setIndex(0).setContext(ctx);
415
+ const x = custom.computeX().x;
416
+ custom.draw();
417
+ assert.equal(custom.getX(), x);
418
+ assert.equal(custom.getY(), 250);
419
+ }
@@ -31,8 +31,42 @@ const ArticulationTests = {
31
31
  run('Fermata Very Long Above/Below', drawFermata, { sym1: 'a@avl', sym2: 'a@uvl' });
32
32
  run('Inline/Multiple', drawArticulations2, { sym1: 'a.', sym2: 'a.' });
33
33
  run('TabNote Articulation', tabNotes, { sym1: 'a.', sym2: 'a.' });
34
+ run('Draw Is Idempotent', drawIsIdempotent);
34
35
  },
35
36
  };
37
+ function drawIsIdempotent(options, contextBuilder) {
38
+ const ctx = contextBuilder(options.elementId, 500, 250);
39
+ const stave = new Stave(10, 50, 480).addClef('treble').setContext(ctx).drawWithStyle();
40
+ const { ABOVE, BELOW } = ModifierPosition;
41
+ const articulations = [];
42
+ const note = (key, stemDirection, position, codes) => {
43
+ const staveNote = new StaveNote({ keys: [key], duration: 'q', stemDirection });
44
+ codes.forEach((code) => {
45
+ const articulation = new Articulation(code).setPosition(position);
46
+ articulations.push(articulation);
47
+ staveNote.addModifier(articulation, 0);
48
+ });
49
+ return staveNote;
50
+ };
51
+ const notes = [note('c/4', Stem.UP, ABOVE, ['a.']), note('a/3', Stem.UP, BELOW, ['a.'])];
52
+ const voice = new Voice({ numBeats: 2, beatValue: 4 }).addTickables(notes);
53
+ new Formatter().joinVoices([voice]).formatToStave([voice], stave);
54
+ const getBoxes = () => articulations.map((a) => {
55
+ const box = a.getBoundingBox();
56
+ return [box.getX(), box.getY(), box.getW(), box.getH()];
57
+ });
58
+ voice.draw(ctx, stave);
59
+ const first = getBoxes();
60
+ for (let i = 2; i <= 3; i++) {
61
+ voice.draw(ctx, stave);
62
+ options.assert.deepEqual(getBoxes(), first, `Bounding boxes after draw #${i} match those of draw #1.`);
63
+ }
64
+ const articulation = new Articulation('a.');
65
+ articulation.setOrigin(0.5, 0.5);
66
+ const [xShift, yShift] = [articulation.getXShift(), articulation.getYShift()];
67
+ articulation.setX(240).setY(160).setOrigin(0.5, 0.5);
68
+ options.assert.deepEqual([articulation.getXShift(), articulation.getYShift()], [xShift, yShift], 'Origin shifts');
69
+ }
36
70
  function drawArticulations(options) {
37
71
  const sym1 = options.params.sym1;
38
72
  const sym2 = options.params.sym2;
@@ -12,6 +12,7 @@ const BeamTests = {
12
12
  run('Auto-stemmed Beam', autoStem);
13
13
  run('Mixed Beam 1', mixed);
14
14
  run('Mixed Beam 2', mixed2);
15
+ run('Mixed Beam 3', mixed3);
15
16
  run('Dotted Beam', dotted);
16
17
  run('Partial Beam', partial);
17
18
  run('Close Trade-offs Beam', tradeoffs);
@@ -200,6 +201,22 @@ function mixed2(options) {
200
201
  f.draw();
201
202
  options.assert.ok(true, 'Multi Test');
202
203
  }
204
+ function mixed3(options) {
205
+ const f = VexFlowTests.makeFactory(options, 450, 230);
206
+ const stave = f.Stave({ y: 25 });
207
+ const score = f.EasyScore();
208
+ const voice = score.voice(score.notes('f5/32, d5/16, c5/32, c5/64, d5/128, e5/8, f5/16, d5/32, c5/64, c5/32, d5/16, e5/1024, e5/512, e5/512, e5/512, e5/1024', {
209
+ stem: 'up',
210
+ }), { time: '31/64' });
211
+ const voice2 = score.voice(score.notes('f4/32, d4/16, c4/32, c4/64, d4/128, e4/8, f4/16, e4/256, e4/512, e4/1024, e4/1024, d4/32, c4/64, c4/32, d4/16', {
212
+ stem: 'down',
213
+ }), { time: '31/64' });
214
+ f.Beam({ notes: voice.getTickables() });
215
+ f.Beam({ notes: voice2.getTickables() });
216
+ f.Formatter().joinVoices([voice, voice2]).formatToStave([voice, voice2], stave);
217
+ f.draw();
218
+ options.assert.ok(true, 'Multi Test with 1024th, 512th, and 256th notes');
219
+ }
203
220
  function dotted(options) {
204
221
  const f = VexFlowTests.makeFactory(options);
205
222
  const stave = f.Stave();
@@ -10,6 +10,7 @@ const CurveTests = {
10
10
  run('Rounded Curve', rounded);
11
11
  run('Thick Thin Curves', thickThin);
12
12
  run('Top Curve', top);
13
+ run('Bounding Box', boundingBox);
13
14
  },
14
15
  };
15
16
  function createTest(noteGroup1, noteGroup2, setupCurves) {
@@ -148,5 +149,85 @@ const top = createTest(['c5/8, f4, d4, g5', { stem: 'up' }], ['d5/8, d6, d6, g5'
148
149
  },
149
150
  });
150
151
  });
152
+ function boundingBox(options) {
153
+ const factory = VexFlowTests.makeFactory(options, 350, 200);
154
+ const stave = factory.Stave({ y: 50 });
155
+ const score = factory.EasyScore();
156
+ const notes = score.notes('c4/8, f5, d5, g5, d6, f5, d5, g5', { stem: 'up' });
157
+ const curves = [
158
+ factory.Curve({
159
+ from: notes[0],
160
+ to: notes[3],
161
+ options: {
162
+ cps: [
163
+ { x: 0, y: 10 },
164
+ { x: 0, y: 50 },
165
+ ],
166
+ },
167
+ }),
168
+ factory.Curve({ from: notes[4], to: notes[7], options: { invert: true, xShift: -10, thickness: 5 } }),
169
+ factory
170
+ .Curve({
171
+ from: notes[4],
172
+ to: notes[7],
173
+ options: {
174
+ cps: [
175
+ { x: 20, y: 30 },
176
+ { x: -20, y: -30 },
177
+ ],
178
+ },
179
+ })
180
+ .setStyle({ lineDash: '10 10' }),
181
+ factory.Curve({ from: notes[1], to: undefined, options: {} }),
182
+ factory.Curve({ from: notes[5], to: notes[6], options: { position: 'nearTop', positionEnd: 'nearTop' } }),
183
+ ];
184
+ const voices = [score.voice(notes, { time: '4/4' })];
185
+ factory.Formatter().joinVoices(voices).formatToStave(voices, stave);
186
+ const ctx = factory.getContext();
187
+ let current = { x: 0, y: 0 };
188
+ let points = [];
189
+ const moveTo = ctx.moveTo.bind(ctx);
190
+ const bezierCurveTo = ctx.bezierCurveTo.bind(ctx);
191
+ ctx.moveTo = (x, y) => {
192
+ current = { x, y };
193
+ return moveTo(x, y);
194
+ };
195
+ ctx.bezierCurveTo = (cp1x, cp1y, cp2x, cp2y, x, y) => {
196
+ for (let i = 0; i <= 1000; i++) {
197
+ const t = i / 1000;
198
+ const u = 1 - t;
199
+ const b = [u * u * u, 3 * u * u * t, 3 * u * t * t, t * t * t];
200
+ points.push({
201
+ x: b[0] * current.x + b[1] * cp1x + b[2] * cp2x + b[3] * x,
202
+ y: b[0] * current.y + b[1] * cp1y + b[2] * cp2y + b[3] * y,
203
+ });
204
+ }
205
+ current = { x, y };
206
+ return bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
207
+ };
208
+ const sampled = [];
209
+ for (const curve of curves) {
210
+ const draw = curve.draw.bind(curve);
211
+ curve.draw = () => {
212
+ points = [];
213
+ const result = draw();
214
+ sampled.push({ x: points.map((p) => p.x), y: points.map((p) => p.y) });
215
+ return result;
216
+ };
217
+ }
218
+ factory.draw();
219
+ const near = (a, b) => Math.abs(a - b) < 0.05;
220
+ curves.forEach((curve, i) => {
221
+ VexFlowTests.drawBoundingBox(ctx, curve);
222
+ const bb = curve.getBoundingBox();
223
+ const { x, y } = sampled[i];
224
+ const minX = Math.min(...x);
225
+ const minY = Math.min(...y);
226
+ options.assert.ok(near(bb.getX(), minX), `curve ${i} x ${bb.getX()} ~ ${minX}`);
227
+ options.assert.ok(near(bb.getY(), minY), `curve ${i} y ${bb.getY()} ~ ${minY}`);
228
+ options.assert.ok(near(bb.getW(), Math.max(...x) - minX), `curve ${i} w ${bb.getW()}`);
229
+ options.assert.ok(near(bb.getH(), Math.max(...y) - minY), `curve ${i} h ${bb.getH()}`);
230
+ });
231
+ }
151
232
  VexFlowTests.register(CurveTests);
152
233
  export { CurveTests };