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
@@ -33,6 +33,8 @@ export class ModifierContext {
33
33
  this.width = 0;
34
34
  this.spacing = 0;
35
35
  this.annotationRightShift = 0;
36
+ this.measuredTopLines = 0;
37
+ this.measuredBottomLines = 0;
36
38
  }
37
39
  addModifier(member) {
38
40
  L('addModifier is deprecated, use addMember instead.');
@@ -68,6 +70,9 @@ export class ModifierContext {
68
70
  getRightShiftForTie() {
69
71
  return this.state.rightShift - this.annotationRightShift;
70
72
  }
73
+ getUnmeasuredTextLines(above) {
74
+ return above ? this.state.topTextLine - this.measuredTopLines : this.state.textLine - this.measuredBottomLines;
75
+ }
71
76
  getState() {
72
77
  return this.state;
73
78
  }
@@ -103,12 +108,18 @@ export class ModifierContext {
103
108
  annotation.getVerticalJustification() === Annotation.VerticalJustify.BOTTOM;
104
109
  Annotation.format(annotations.filter((annotation) => !isOutsideNote(annotation)), state);
105
110
  const rightShiftBeforeAnnotations = state.rightShift;
111
+ const topBefore = state.topTextLine;
112
+ const bottomBefore = state.textLine;
106
113
  Annotation.format(annotations.filter(isOutsideNote), state);
114
+ const topAfter = state.topTextLine;
115
+ const bottomAfter = state.textLine;
107
116
  const rightShiftWithAnnotations = state.rightShift;
108
117
  state.rightShift = rightShiftBeforeAnnotations;
109
118
  ChordSymbol.format(members["ChordSymbol"], state);
110
119
  Bend.format(members["Bend"], state);
111
120
  Vibrato.format(members["Vibrato"], state, this);
121
+ this.measuredTopLines = state.topTextLine === topAfter ? topAfter - topBefore : 0;
122
+ this.measuredBottomLines = state.textLine === bottomAfter ? bottomAfter - bottomBefore : 0;
112
123
  this.annotationRightShift = Math.max(0, rightShiftWithAnnotations - state.rightShift);
113
124
  state.rightShift += this.annotationRightShift;
114
125
  this.width = state.leftShift + state.rightShift;
@@ -1,6 +1,6 @@
1
1
  import { Note } from './note.js';
2
2
  import { Stem } from './stem.js';
3
- import { defined, log } from './util.js';
3
+ import { defined, log, RuntimeError } from './util.js';
4
4
  function L(...args) {
5
5
  if (NoteHead.DEBUG)
6
6
  log('VexFlow.NoteHead', args);
@@ -10,7 +10,7 @@ export class NoteHead extends Note {
10
10
  return "NoteHead";
11
11
  }
12
12
  constructor(noteStruct) {
13
- var _a;
13
+ var _a, _b;
14
14
  super(noteStruct);
15
15
  this.customGlyph = false;
16
16
  this.ledger = {
@@ -22,7 +22,10 @@ export class NoteHead extends Note {
22
22
  this.y = noteStruct.y || 0;
23
23
  if (noteStruct.noteType)
24
24
  this.noteType = noteStruct.noteType;
25
- this.displaced = noteStruct.displaced || false;
25
+ this.displacementColumn = (_a = noteStruct.displacementColumn) !== null && _a !== void 0 ? _a : (noteStruct.displaced ? 1 : 0);
26
+ if (!Number.isSafeInteger(this.displacementColumn) || this.displacementColumn < 0)
27
+ throw new RuntimeError('BadArguments', 'Head displacement column must be a nonnegative integer.');
28
+ this.displaced = this.displacementColumn !== 0;
26
29
  this.stemDirection = noteStruct.stemDirection || Stem.UP;
27
30
  this.line = noteStruct.line || 0;
28
31
  this.glyphProps = Note.getGlyphProps(this.duration, this.noteType);
@@ -35,7 +38,7 @@ export class NoteHead extends Note {
35
38
  this.customGlyph = true;
36
39
  this.text = noteStruct.customGlyphCode;
37
40
  }
38
- this.setStyle((_a = noteStruct.style) !== null && _a !== void 0 ? _a : {});
41
+ this.setStyle((_b = noteStruct.style) !== null && _b !== void 0 ? _b : {});
39
42
  this.slashed = noteStruct.slashed || false;
40
43
  this.renderOptions = Object.assign({}, this.renderOptions);
41
44
  }
@@ -54,8 +57,10 @@ export class NoteHead extends Note {
54
57
  }
55
58
  getAbsoluteX() {
56
59
  const x = !this.preFormatted ? this.x : super.getAbsoluteX();
57
- const displacementStemAdjustment = Stem.WIDTH / 2;
58
- return x + (this.displaced ? (this.width - displacementStemAdjustment) * this.stemDirection : 0);
60
+ return x + this.getDisplacementX();
61
+ }
62
+ getDisplacementX() {
63
+ return this.displacementColumn * (this.width - Stem.WIDTH / 2) * this.stemDirection;
59
64
  }
60
65
  setStave(stave) {
61
66
  const line = this.getLine();
@@ -26,12 +26,13 @@ export class Ornament extends Modifier {
26
26
  for (let i = 0; i < ornaments.length; ++i) {
27
27
  const ornament = ornaments[i];
28
28
  const increment = 2;
29
+ ornament.sideOffset = 0;
29
30
  if (ornament.position === ModifierPosition.RIGHT) {
30
- ornament.xShift += rightShift + 2;
31
+ ornament.sideOffset = rightShift + 2;
31
32
  rightShift += ornament.width + Ornament.minPadding;
32
33
  }
33
34
  else if (ornament.position === ModifierPosition.LEFT) {
34
- ornament.xShift -= leftShift + ornament.width + 2;
35
+ ornament.sideOffset = -(leftShift + ornament.width + 2);
35
36
  leftShift += ornament.width + Ornament.minPadding;
36
37
  }
37
38
  else if (ornament.position === ModifierPosition.ABOVE) {
@@ -84,6 +85,7 @@ export class Ornament extends Modifier {
84
85
  }
85
86
  constructor(type) {
86
87
  super();
88
+ this.sideOffset = 0;
87
89
  this.position = ModifierPosition.ABOVE;
88
90
  if (Ornament.ornamentRight.indexOf(type) >= 0) {
89
91
  this.position = ModifierPosition.RIGHT;
@@ -130,15 +132,12 @@ export class Ornament extends Modifier {
130
132
  this.accidentalLower.setText(Tables.accidentalCodes(accid));
131
133
  return this;
132
134
  }
133
- draw() {
134
- const ctx = this.checkContext();
135
+ positionElements() {
135
136
  const note = this.checkAttachedNote();
136
- this.setRendered();
137
137
  const stave = note.checkStave();
138
- const clsAttribute = this.getAttribute('class');
139
- ctx.openGroup('ornament' + (clsAttribute ? ' ' + clsAttribute : ''), this.getAttribute('id'));
138
+ const parts = [];
140
139
  const start = note.getModifierStartXY(this.position, this.index);
141
- let glyphX = start.x;
140
+ let glyphX = start.x + this.sideOffset;
142
141
  const staffSpace = stave.getSpacingBetweenLines();
143
142
  const initialOffset = getInitialOffset(note, this.position);
144
143
  let glyphY = this.ornamentAlignWithNoteHead ? start.y : 0;
@@ -164,27 +163,48 @@ export class Ornament extends Modifier {
164
163
  else {
165
164
  delayXShift += (stave.getX() + stave.getWidth() - glyphX) * 0.5;
166
165
  }
167
- this.delayXShift = delayXShift;
168
166
  }
169
167
  glyphX += delayXShift;
170
168
  }
171
169
  L('Rendering ornament: ', this.text.charCodeAt(0), glyphX, glyphY);
172
170
  if (this.accidentalLower) {
173
- this.accidentalLower.renderText(ctx, glyphX + this.xShift - this.accidentalLower.getWidth() * 0.5, glyphY + this.yShift - this.accidentalLower.getTextMetrics().actualBoundingBoxDescent);
171
+ parts.push({
172
+ element: this.accidentalLower,
173
+ x: glyphX + this.xShift - this.accidentalLower.getWidth() / 2,
174
+ y: glyphY + this.yShift - this.accidentalLower.getTextMetrics().actualBoundingBoxDescent,
175
+ });
174
176
  glyphY -= this.accidentalLower.getHeight() + this.renderOptions.accidentalLowerPadding;
175
177
  }
176
- if (Ornament.ornamentYShift.indexOf(this.type) >= 0) {
177
- this.yShift += this.getHeight();
178
- }
178
+ const offset = Ornament.ornamentYShift.includes(this.type) ? this.getHeight() : 0;
179
179
  this.x =
180
180
  glyphX -
181
- (this.position === ModifierPosition.ABOVE || this.position === ModifierPosition.BELOW ? this.width * 0.5 : 0);
182
- this.y = glyphY;
183
- this.renderText(ctx, 0, 0);
181
+ (this.position === ModifierPosition.ABOVE || this.position === ModifierPosition.BELOW ? this.width / 2 : 0);
182
+ this.y = glyphY + offset;
183
+ parts.push({ element: this, x: 0, y: 0 });
184
184
  if (this.accidentalUpper) {
185
- glyphY -= this.getHeight() + this.renderOptions.accidentalUpperPadding;
186
- this.accidentalUpper.renderText(ctx, glyphX + this.xShift - this.accidentalUpper.getWidth() * 0.5, glyphY + this.yShift - this.accidentalUpper.getTextMetrics().actualBoundingBoxDescent);
185
+ parts.push({
186
+ element: this.accidentalUpper,
187
+ x: glyphX + this.xShift - this.accidentalUpper.getWidth() / 2,
188
+ y: this.y +
189
+ this.yShift -
190
+ this.getHeight() -
191
+ this.renderOptions.accidentalUpperPadding -
192
+ this.accidentalUpper.getTextMetrics().actualBoundingBoxDescent,
193
+ });
187
194
  }
195
+ return parts;
196
+ }
197
+ getBoundingBox() {
198
+ const boxes = this.positionElements().map(({ element, x, y }) => element.getTextInk(x + element.getX(), y + element.getY()));
199
+ return boxes.reduce((bounds, box) => bounds.mergeWith(box));
200
+ }
201
+ draw() {
202
+ const ctx = this.checkContext();
203
+ this.setRendered();
204
+ const clsAttribute = this.getAttribute('class');
205
+ ctx.openGroup('ornament' + (clsAttribute ? ' ' + clsAttribute : ''), this.getAttribute('id'));
206
+ for (const { element, x, y } of this.positionElements())
207
+ element.renderText(ctx, x, y);
188
208
  this.drawPointerRect();
189
209
  ctx.closeGroup();
190
210
  }
@@ -66,13 +66,14 @@ export class ProportionalFormatter {
66
66
  anchor.prefixes.forEach((prefix) => array.push(...prefix.contexts));
67
67
  array.push(anchor.context);
68
68
  }
69
+ TickContext.linkTimeline(this.anchors.map((anchor) => anchor.context));
69
70
  array.forEach((context) => (context.tContexts = array));
70
71
  this.contexts = { map, array, list: this.anchors.map((anchor) => anchor.tick), resolutionMultiplier };
71
72
  }
72
73
  quarters(anchor) {
73
74
  return anchor.tick / this.contexts.resolutionMultiplier / this.quarterTicks;
74
75
  }
75
- measure() {
76
+ measure(proportional = true) {
76
77
  var _a, _b, _c, _d;
77
78
  this.origin = PADDING;
78
79
  this.tail = PADDING;
@@ -115,6 +116,8 @@ export class ProportionalFormatter {
115
116
  this.tail = Math.max(this.tail, extent.right + PADDING);
116
117
  }
117
118
  }
119
+ if (!proportional)
120
+ return;
118
121
  const previous = new Map();
119
122
  for (const anchor of this.anchors) {
120
123
  const time = this.quarters(anchor);
@@ -155,16 +158,61 @@ export class ProportionalFormatter {
155
158
  }
156
159
  return { scale, width: neededWidth };
157
160
  }
161
+ opticalLayout(width) {
162
+ var _a;
163
+ if (!Number.isFinite(width) || width < 0)
164
+ throw new RuntimeError('BadArgument', 'Width must be finite and nonnegative.');
165
+ this.measure(false);
166
+ const rightEdges = new Map();
167
+ const positions = [];
168
+ const weights = [];
169
+ let priorX = 0;
170
+ let time = 0;
171
+ let weight = 0;
172
+ for (const anchor of this.anchors) {
173
+ const onset = this.quarters(anchor);
174
+ let x = priorX + PADDING;
175
+ for (const [stave, extent] of anchor.extents)
176
+ x = Math.max(x, ((_a = rightEdges.get(stave)) !== null && _a !== void 0 ? _a : 0) + PADDING + extent.left);
177
+ for (const [stave, extent] of anchor.extents)
178
+ rightEdges.set(stave, x + extent.right);
179
+ weight += Math.sqrt(onset - time);
180
+ weights.push(weight);
181
+ positions.push(x);
182
+ priorX = x;
183
+ time = onset;
184
+ }
185
+ weight += Math.sqrt(this.duration - time);
186
+ const minimum = Math.max(this.centeredWidth + 2 * PADDING, priorX + PADDING, ...Array.from(rightEdges.values(), (x) => x + PADDING));
187
+ if (width > 0 && width + EPSILON < minimum)
188
+ throw new RuntimeError('InsufficientOpticalSpace', `Optical spacing requires at least ${required(minimum)} px width; received ${width.toFixed(2)} px.`);
189
+ const available = width || minimum;
190
+ return {
191
+ width: available,
192
+ center: available / 2,
193
+ positions: positions.map((x, i) => x + (weight ? weights[i] / weight : 0) * (available - minimum)),
194
+ };
195
+ }
158
196
  minimumWidth(spacing) {
197
+ if (spacing.mode === 'optical')
198
+ return this.opticalLayout(0).width;
159
199
  return this.dimensions(spacing, 0).width;
160
200
  }
161
- format(spacing, width) {
201
+ proportionalLayout(spacing, width) {
162
202
  const dimensions = this.dimensions(spacing, width);
163
- for (const anchor of this.anchors) {
164
- const x = this.origin + this.quarters(anchor) * dimensions.scale;
203
+ return {
204
+ width: dimensions.width,
205
+ center: this.origin + (this.duration * dimensions.scale) / 2,
206
+ positions: this.anchors.map((anchor) => this.origin + this.quarters(anchor) * dimensions.scale),
207
+ };
208
+ }
209
+ format(spacing, width) {
210
+ const { positions, center, width: usedWidth, } = spacing.mode === 'optical' ? this.opticalLayout(width) : this.proportionalLayout(spacing, width);
211
+ for (const [i, anchor] of this.anchors.entries()) {
212
+ const x = positions[i];
165
213
  anchor.context.setX(x);
166
214
  anchor.context.getCenterAlignedTickables().forEach((note) => {
167
- note.setCenterXShift(this.origin + (this.duration * dimensions.scale) / 2 - x);
215
+ note.setCenterXShift(center - x);
168
216
  });
169
217
  anchor.prefixes.forEach((prefix) => {
170
218
  const stave = prefix.contexts[0].getTickables()[0].getStave();
@@ -181,6 +229,6 @@ export class ProportionalFormatter {
181
229
  }
182
230
  });
183
231
  }
184
- return dimensions.width;
232
+ return usedWidth;
185
233
  }
186
234
  }
@@ -77,41 +77,37 @@ export class StaveNote extends StemmableNote {
77
77
  note: notes[i],
78
78
  });
79
79
  }
80
- let voices = 0;
81
- let noteU = undefined;
82
- let noteM = undefined;
83
- let noteL = undefined;
84
- const draw = [false, false, false];
85
- for (let i = 0; i < notesList.length; i++) {
86
- draw[i] = notesList[i].note.renderOptions.draw !== false;
87
- }
88
- if (draw[0] && draw[1] && draw[2]) {
89
- voices = 3;
90
- noteU = notesList[0];
91
- noteM = notesList[1];
92
- noteL = notesList[2];
93
- }
94
- else if (draw[0] && draw[1]) {
95
- voices = 2;
96
- noteU = notesList[0];
97
- noteL = notesList[1];
98
- }
99
- else if (draw[0] && draw[2]) {
100
- voices = 2;
101
- noteU = notesList[0];
102
- noteL = notesList[2];
103
- }
104
- else if (draw[1] && draw[2]) {
105
- voices = 2;
106
- noteU = notesList[1];
107
- noteL = notesList[2];
108
- }
109
- else {
80
+ const visible = notesList.filter((item) => item.note.renderOptions.draw !== false);
81
+ if (visible.length < 2)
82
+ return true;
83
+ if (visible.length > 3) {
84
+ const columns = [];
85
+ for (const item of visible.sort((a, b) => b.maxLine - a.maxLine || b.line - a.line)) {
86
+ let column = columns.find((entry) => item.maxLine + 0.5 < entry.bottom);
87
+ if (!column) {
88
+ column = { bottom: item.minLine, width: 0, members: [] };
89
+ columns.push(column);
90
+ }
91
+ column.bottom = item.minLine;
92
+ column.width = Math.max(column.width, item.voiceShift);
93
+ column.members.push(item);
94
+ }
95
+ let x = 0;
96
+ for (const column of columns) {
97
+ for (const item of column.members)
98
+ item.note.setXShift(x);
99
+ if (column !== columns[columns.length - 1])
100
+ x += column.width + 2;
101
+ }
102
+ state.rightShift += x;
110
103
  return true;
111
104
  }
105
+ const voices = visible.length;
106
+ let noteU = visible[0];
107
+ let noteL = visible[voices - 1];
108
+ const noteM = voices === 3 ? visible[1] : undefined;
112
109
  if (voices === 2 && noteU.stemDirection === -1 && noteL.stemDirection === 1) {
113
- noteU = notesList[1];
114
- noteL = notesList[0];
110
+ [noteU, noteL] = [noteL, noteU];
115
111
  }
116
112
  const voiceXShift = Math.max(noteU.voiceShift, noteL.voiceShift);
117
113
  let xShift = 0;
@@ -250,19 +246,24 @@ export class StaveNote extends StemmableNote {
250
246
  return true;
251
247
  }
252
248
  constructor(noteStruct) {
253
- var _a, _b, _c;
249
+ var _a, _b, _c, _d, _e;
254
250
  super(noteStruct);
255
251
  this.minLine = 0;
256
252
  this.maxLine = 0;
253
+ this.useDefaultHeadX = false;
254
+ this.extraHeadColumns = 0;
257
255
  this.sortedKeyProps = [];
256
+ this.engraving = noteStruct.engraving;
257
+ const musicFont = (_a = noteStruct.musicFont) !== null && _a !== void 0 ? _a : (_b = this.engraving) === null || _b === void 0 ? void 0 : _b.musicFont;
258
+ if (musicFont)
259
+ this.setFont(Object.assign(Object.assign({}, this.fontInfo), { family: musicFont }));
258
260
  this.ledgerLineStyle = {};
259
- this.clef = (_a = noteStruct.clef) !== null && _a !== void 0 ? _a : 'treble';
260
- this.octaveShift = (_b = noteStruct.octaveShift) !== null && _b !== void 0 ? _b : 0;
261
+ this.clef = (_c = noteStruct.clef) !== null && _c !== void 0 ? _c : 'treble';
262
+ this.octaveShift = (_d = noteStruct.octaveShift) !== null && _d !== void 0 ? _d : 0;
261
263
  this.glyphProps = Note.getGlyphProps(this.duration, this.noteType);
262
264
  defined(this.glyphProps, 'BadArguments', `No glyph found for duration '${this.duration}' and type '${this.noteType}'`);
263
265
  this.displaced = false;
264
266
  this.dotShiftY = 0;
265
- this.useDefaultHeadX = false;
266
267
  this._noteHeads = [];
267
268
  this.modifiers = [];
268
269
  this.renderOptions = Object.assign(Object.assign({}, this.renderOptions), { strokePx: noteStruct.strokePx || StaveNote.LEDGER_LINE_OFFSET });
@@ -272,7 +273,7 @@ export class StaveNote extends StemmableNote {
272
273
  this.autoStem();
273
274
  }
274
275
  else {
275
- this.setStemDirection((_c = noteStruct.stemDirection) !== null && _c !== void 0 ? _c : Stem.UP);
276
+ this.setStemDirection((_e = noteStruct.stemDirection) !== null && _e !== void 0 ? _e : Stem.UP);
276
277
  }
277
278
  }
278
279
  reset() {
@@ -309,9 +310,8 @@ export class StaveNote extends StemmableNote {
309
310
  this._noteHeads = [];
310
311
  const stemDirection = this.getStemDirection();
311
312
  const keys = this.getKeys();
312
- let lastLine = undefined;
313
- let lineDiff = undefined;
314
- let displaced = false;
313
+ const lastLineInColumn = [];
314
+ this.extraHeadColumns = 0;
315
315
  let start;
316
316
  let end;
317
317
  let step;
@@ -328,24 +328,17 @@ export class StaveNote extends StemmableNote {
328
328
  for (let i = start; i !== end; i += step) {
329
329
  const noteProps = this.sortedKeyProps[i].keyProps;
330
330
  const line = noteProps.line;
331
- if (lastLine === undefined) {
332
- lastLine = line;
333
- }
334
- else {
335
- lineDiff = Math.abs(lastLine - line);
336
- if (lineDiff === 0 || lineDiff === 0.5) {
337
- displaced = !displaced;
338
- }
339
- else {
340
- displaced = false;
341
- this.useDefaultHeadX = true;
342
- }
343
- }
344
- lastLine = line;
331
+ let column = lastLineInColumn.findIndex((previous) => Math.abs(previous - line) >= 1);
332
+ if (i !== start && Math.abs(this.sortedKeyProps[i - step].keyProps.line - line) >= 1)
333
+ this.useDefaultHeadX = true;
334
+ if (column < 0)
335
+ column = lastLineInColumn.length;
336
+ lastLineInColumn[column] = line;
337
+ this.extraHeadColumns = Math.max(this.extraHeadColumns, column);
345
338
  const notehead = new NoteHead({
346
339
  duration: this.duration,
347
340
  noteType: this.noteType,
348
- displaced,
341
+ displacementColumn: column,
349
342
  stemDirection,
350
343
  customGlyphCode: noteProps.code,
351
344
  line: noteProps.line,
@@ -369,7 +362,6 @@ export class StaveNote extends StemmableNote {
369
362
  }
370
363
  calculateKeyProps() {
371
364
  var _a;
372
- let lastLine;
373
365
  for (let i = 0; i < this.keys.length; ++i) {
374
366
  const key = this.keys[i];
375
367
  const options = { octaveShift: (_a = this.octaveShift) !== null && _a !== void 0 ? _a : 0, duration: this.duration };
@@ -385,33 +377,44 @@ export class StaveNote extends StemmableNote {
385
377
  props.line = 3;
386
378
  }
387
379
  }
388
- const line = props.line;
389
- if (lastLine === undefined) {
390
- lastLine = line;
391
- }
392
- else {
393
- if (Math.abs(lastLine - line) < 1) {
394
- this.displaced = true;
395
- props.displaced = true;
396
- if (this.keyProps.length > 0) {
397
- this.keyProps[i - 1].displaced = true;
398
- }
399
- }
400
- }
401
- lastLine = line;
402
380
  this.keyProps.push(props);
403
381
  }
404
382
  this.keyProps.forEach((keyProps, index) => {
405
383
  this.sortedKeyProps.push({ keyProps, index });
406
384
  });
407
385
  this.sortedKeyProps.sort((a, b) => a.keyProps.line - b.keyProps.line);
386
+ for (let i = 1; i < this.sortedKeyProps.length; i++) {
387
+ const lower = this.sortedKeyProps[i - 1].keyProps;
388
+ const upper = this.sortedKeyProps[i].keyProps;
389
+ if (upper.line - lower.line < 1) {
390
+ this.displaced = true;
391
+ lower.displaced = upper.displaced = true;
392
+ }
393
+ }
394
+ }
395
+ getHeadInk() {
396
+ return this._noteHeads.map((head) => {
397
+ const displacement = head.getDisplacementX();
398
+ return head.getTextInk(this.getNoteHeadBeginX() + displacement, head.getY());
399
+ });
400
+ }
401
+ getFlagInk() {
402
+ if (!this.shouldDrawFlag())
403
+ return;
404
+ const { x, y } = this.getFlagPosition();
405
+ return this.flag.getTextInk(x, y);
406
+ }
407
+ getStemSegment() {
408
+ var _a;
409
+ if (!((_a = this.stem) === null || _a === void 0 ? void 0 : _a.isVisible()) || (!this.hasStem() && !this.beam))
410
+ return;
411
+ const adjustment = this.shouldDrawFlag() ? Metrics.get('Stem.heightAdjustmentForFlag', -3) : undefined;
412
+ return this.checkStem().getSegment(this.getStemX(), adjustment);
408
413
  }
409
414
  getBoundingBox(includeModifiers = true) {
410
415
  const boundingBox = new BoundingBox(this.getAbsoluteX(), this.ys[0], 0, 0);
411
416
  this._noteHeads.forEach((notehead) => {
412
- const displacement = notehead.isDisplaced()
413
- ? (notehead.getWidth() - Stem.WIDTH / 2) * this.getStemDirection()
414
- : 0;
417
+ const displacement = notehead.getDisplacementX();
415
418
  const box = notehead.getBoundingBox();
416
419
  box.setX(this.getNoteHeadBeginX() + displacement + notehead.getXShift());
417
420
  boundingBox.mergeWith(box);
@@ -468,10 +471,21 @@ export class StaveNote extends StemmableNote {
468
471
  return super.hasFlag() && !this.isRest();
469
472
  }
470
473
  getStemX() {
474
+ var _a;
471
475
  if (this.noteType === 'r') {
472
476
  return this.getCenterGlyphX();
473
477
  }
474
478
  else {
479
+ const up = this.stemDirection === Stem.UP;
480
+ const head = this.engraving && this._noteHeads.find((h) => !h.isDisplaced());
481
+ if (head && ((_a = this.engraving) === null || _a === void 0 ? void 0 : _a.musicFont) === head.fontInfo.family) {
482
+ const anchor = this.engraving.stemAnchor(head.text, up ? 'up' : 'down');
483
+ if (anchor)
484
+ return (this.getNoteHeadBeginX() +
485
+ head.getXShift() +
486
+ (anchor[0] * head.fontSizeInPixels) / 4 +
487
+ ((up ? -1 : 1) * Stem.WIDTH) / 2);
488
+ }
475
489
  return super.getStemX() + (this.stemDirection ? Stem.WIDTH / (2 * -this.stemDirection) : 0);
476
490
  }
477
491
  }
@@ -620,11 +634,12 @@ export class StaveNote extends StemmableNote {
620
634
  return this.keyProps[index].line;
621
635
  }
622
636
  getVoiceShiftWidth() {
623
- return this.getGlyphWidth() * (this.displaced ? 2 : 1);
637
+ return this.getGlyphWidth() * (this.displaced ? 1 + Math.max(1, this.extraHeadColumns) : 1);
624
638
  }
625
639
  calcNoteDisplacements() {
626
- this.setLeftDisplacedHeadPx(this.displaced && this.stemDirection === Stem.DOWN ? this.getGlyphWidth() : 0);
627
- this.setRightDisplacedHeadPx(!this.hasFlag() && this.displaced && this.stemDirection === Stem.UP ? this.getGlyphWidth() : 0);
640
+ const extra = this.getVoiceShiftWidth() - this.getGlyphWidth();
641
+ this.setLeftDisplacedHeadPx(this.stemDirection === Stem.DOWN ? extra : 0);
642
+ this.setRightDisplacedHeadPx(this.stemDirection === Stem.UP ? Math.max(0, extra - (this.hasFlag() ? this.getGlyphWidth() : 0)) : 0);
628
643
  }
629
644
  preFormat() {
630
645
  if (this.preFormatted)
@@ -650,7 +665,10 @@ export class StaveNote extends StemmableNote {
650
665
  this._noteHeads.forEach((nh) => {
651
666
  const offset = Tables.noteHeadStemYOffsets[nh.text];
652
667
  const anchor = offset ? offset[anchorKey] : 0;
653
- const y = nh.getY() - anchor * Tables.STAVE_LINE_DISTANCE;
668
+ const fontAnchor = this.engraving && this.engraving.musicFont === nh.fontInfo.family
669
+ ? this.engraving.stemAnchor(nh.text, anchorKey)
670
+ : undefined;
671
+ const y = nh.getY() - (fontAnchor ? (fontAnchor[1] * nh.fontSizeInPixels) / 4 : anchor * Tables.STAVE_LINE_DISTANCE);
654
672
  yTop = Math.min(y, yTop);
655
673
  yBottom = Math.max(y, yBottom);
656
674
  });
@@ -660,7 +678,7 @@ export class StaveNote extends StemmableNote {
660
678
  }
661
679
  return { yTop, yBottom };
662
680
  }
663
- getNoteHeadBounds() {
681
+ getNoteHeadBounds(layoutX = false) {
664
682
  let yTop = +Infinity;
665
683
  let yBottom = -Infinity;
666
684
  let nonDisplacedX;
@@ -677,10 +695,10 @@ export class StaveNote extends StemmableNote {
677
695
  yTop = Math.min(y, yTop);
678
696
  yBottom = Math.max(y, yBottom);
679
697
  if (displacedX === undefined && notehead.isDisplaced()) {
680
- displacedX = notehead.getAbsoluteX();
698
+ displacedX = layoutX ? this.getNoteHeadBeginX() + notehead.getDisplacementX() : notehead.getAbsoluteX();
681
699
  }
682
700
  if (nonDisplacedX === undefined && !notehead.isDisplaced()) {
683
- nonDisplacedX = notehead.getAbsoluteX();
701
+ nonDisplacedX = layoutX ? this.getNoteHeadBeginX() : notehead.getAbsoluteX();
684
702
  }
685
703
  highestLine = Math.max(line, highestLine);
686
704
  lowestLine = Math.min(line, lowestLine);
@@ -716,47 +734,42 @@ export class StaveNote extends StemmableNote {
716
734
  get noteHeads() {
717
735
  return this._noteHeads.slice();
718
736
  }
719
- drawLedgerLines() {
737
+ getLedgerLines() {
738
+ const lines = [];
720
739
  const stave = this.checkStave();
721
- const { renderOptions: { strokePx }, } = this;
722
- const ctx = this.checkContext();
723
- const width = this.getGlyphWidth() + strokePx * 2;
724
- const doubleWidth = 2 * (this.getGlyphWidth() + strokePx) - Stem.WIDTH / 2;
740
+ const { strokePx } = this.renderOptions;
725
741
  if (this.isRest())
742
+ return lines;
743
+ const { highestLine, lowestLine } = this.getNoteHeadBounds(true);
744
+ const addLedger = (line, heads) => {
745
+ if (!heads.length)
746
+ return;
747
+ const left = Math.min(...heads.map((head) => head.getDisplacementX()));
748
+ const right = Math.max(...heads.map((head) => head.getDisplacementX() + head.getWidth()));
749
+ lines.push({
750
+ x: this.getNoteHeadBeginX() + left - strokePx,
751
+ y: stave.getYForNote(line),
752
+ width: right - left + 2 * strokePx,
753
+ });
754
+ };
755
+ for (let line = 6; line <= highestLine; ++line)
756
+ addLedger(line, this._noteHeads.filter((head) => head.getLine() >= line));
757
+ for (let line = 0; line >= lowestLine; --line)
758
+ addLedger(line, this._noteHeads.filter((head) => head.getLine() <= line));
759
+ return lines;
760
+ }
761
+ drawLedgerLines() {
762
+ const lines = this.getLedgerLines();
763
+ if (!lines.length)
726
764
  return;
727
- if (!ctx) {
728
- throw new RuntimeError('NoCanvasContext', "Can't draw without a canvas context.");
729
- }
730
- const { highestLine, lowestLine, highestDisplacedLine, highestNonDisplacedLine, lowestDisplacedLine, lowestNonDisplacedLine, displacedX, nonDisplacedX, } = this.getNoteHeadBounds();
731
- if (highestLine < 6 && lowestLine > 0)
732
- return;
733
- const minX = Math.min(displacedX !== null && displacedX !== void 0 ? displacedX : 0, nonDisplacedX !== null && nonDisplacedX !== void 0 ? nonDisplacedX : 0);
734
- const drawLedgerLine = (y, normal, displaced) => {
735
- let x;
736
- if (displaced && normal)
737
- x = minX - strokePx;
738
- else if (normal)
739
- x = (nonDisplacedX !== null && nonDisplacedX !== void 0 ? nonDisplacedX : 0) - strokePx;
740
- else
741
- x = (displacedX !== null && displacedX !== void 0 ? displacedX : 0) - strokePx;
742
- const ledgerWidth = normal && displaced ? doubleWidth : width;
765
+ const ctx = this.checkContext();
766
+ ctx.save();
767
+ this.applyStyle(ctx, Object.assign(Object.assign({}, this.checkStave().getDefaultLedgerLineStyle()), this.getLedgerLineStyle()));
768
+ for (const { x, y, width } of lines) {
743
769
  ctx.beginPath();
744
770
  ctx.moveTo(x, y);
745
- ctx.lineTo(x + ledgerWidth, y);
771
+ ctx.lineTo(x + width, y);
746
772
  ctx.stroke();
747
- };
748
- const style = Object.assign(Object.assign({}, stave.getDefaultLedgerLineStyle()), this.getLedgerLineStyle());
749
- ctx.save();
750
- this.applyStyle(ctx, style);
751
- for (let line = 6; line <= highestLine; ++line) {
752
- const normal = nonDisplacedX !== undefined && line <= highestNonDisplacedLine;
753
- const displaced = highestDisplacedLine !== undefined && line <= highestDisplacedLine;
754
- drawLedgerLine(stave.getYForNote(line), normal, displaced);
755
- }
756
- for (let line = 0; line >= lowestLine; --line) {
757
- const normal = nonDisplacedX !== undefined && line >= lowestNonDisplacedLine;
758
- const displaced = lowestDisplacedLine !== undefined && line >= lowestDisplacedLine;
759
- drawLedgerLine(stave.getYForNote(line), normal, displaced);
760
773
  }
761
774
  ctx.restore();
762
775
  }