vexflow-native 2.3.1 → 2.5.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 (172) hide show
  1. package/README.md +7 -1
  2. package/lib/module/base/FontManager.js +41 -27
  3. package/lib/module/base/FontManager.js.map +1 -1
  4. package/lib/module/base/VexflowCanvas.js +8 -6
  5. package/lib/module/base/VexflowCanvas.js.map +1 -1
  6. package/lib/module/base/VexflowRecordingClone.js +83 -0
  7. package/lib/module/base/VexflowRecordingClone.js.map +1 -0
  8. package/lib/module/base/VexflowRecordingContext.js +1 -80
  9. package/lib/module/base/VexflowRecordingContext.js.map +1 -1
  10. package/lib/module/base/builtInTextFont.js +21 -0
  11. package/lib/module/base/builtInTextFont.js.map +1 -0
  12. package/lib/module/base/cssFontShorthand.js +34 -0
  13. package/lib/module/base/cssFontShorthand.js.map +1 -0
  14. package/lib/module/base/fonts/OFL.txt +93 -0
  15. package/lib/module/base/fonts/academico.js +12 -0
  16. package/lib/module/base/fonts/academico.js.map +1 -0
  17. package/lib/module/base/pictureRetirement.js +70 -0
  18. package/lib/module/base/pictureRetirement.js.map +1 -0
  19. package/lib/module/base/setupVexflowReactNative.js +1 -36
  20. package/lib/module/base/setupVexflowReactNative.js.map +1 -1
  21. package/lib/module/musicxml/MusicXmlParser/MeasureParser.js +22 -119
  22. package/lib/module/musicxml/MusicXmlParser/MeasureParser.js.map +1 -1
  23. package/lib/module/musicxml/MusicXmlParser/MusicXmlNotes.js +129 -0
  24. package/lib/module/musicxml/MusicXmlParser/MusicXmlNotes.js.map +1 -0
  25. package/lib/module/musicxml/MusicXmlParser/PartParser.js +8 -1
  26. package/lib/module/musicxml/MusicXmlParser/PartParser.js.map +1 -1
  27. package/lib/module/musicxml/MusicXmlParser/Spanners.js +8 -5
  28. package/lib/module/musicxml/MusicXmlParser/Spanners.js.map +1 -1
  29. package/lib/module/musicxml/MusicXmlParser/mappers.js +83 -3
  30. package/lib/module/musicxml/MusicXmlParser/mappers.js.map +1 -1
  31. package/lib/module/renderer/Layout/DocumentLayout.js +13 -4
  32. package/lib/module/renderer/Layout/DocumentLayout.js.map +1 -1
  33. package/lib/module/renderer/Layout/VerticalSpacing.js +37 -7
  34. package/lib/module/renderer/Layout/VerticalSpacing.js.map +1 -1
  35. package/lib/module/renderer/ScoreRenderer/ScoreOverlayPicture.js +80 -46
  36. package/lib/module/renderer/ScoreRenderer/ScoreOverlayPicture.js.map +1 -1
  37. package/lib/module/renderer/ScoreRenderer/ScoreRenderer.js +10 -22
  38. package/lib/module/renderer/ScoreRenderer/ScoreRenderer.js.map +1 -1
  39. package/lib/module/renderer/ScoreRenderer/ScoreScrollbar.js +18 -8
  40. package/lib/module/renderer/ScoreRenderer/ScoreScrollbar.js.map +1 -1
  41. package/lib/module/renderer/ScoreRenderer/utils.js +42 -88
  42. package/lib/module/renderer/ScoreRenderer/utils.js.map +1 -1
  43. package/lib/module/renderer/constants.js +1 -1
  44. package/lib/module/renderer/layout.js +11 -4
  45. package/lib/module/renderer/layout.js.map +1 -1
  46. package/lib/module/renderer/lyrics.js +127 -0
  47. package/lib/module/renderer/lyrics.js.map +1 -0
  48. package/lib/module/renderer/measure.js +52 -13
  49. package/lib/module/renderer/measure.js.map +1 -1
  50. package/lib/module/renderer/measureBounds.js +5 -0
  51. package/lib/module/renderer/measureBounds.js.map +1 -1
  52. package/lib/module/renderer/measureModifiers.js +24 -6
  53. package/lib/module/renderer/measureModifiers.js.map +1 -1
  54. package/lib/module/renderer/noteModifiers.js +6 -14
  55. package/lib/module/renderer/noteModifiers.js.map +1 -1
  56. package/lib/module/renderer/{fixedNoteSpacing.js → noteSpacing.js} +46 -10
  57. package/lib/module/renderer/noteSpacing.js.map +1 -0
  58. package/lib/module/renderer/render.js +41 -21
  59. package/lib/module/renderer/render.js.map +1 -1
  60. package/lib/module/renderer/scale.js +8 -1
  61. package/lib/module/renderer/scale.js.map +1 -1
  62. package/lib/module/renderer/tempoMark.js +162 -0
  63. package/lib/module/renderer/tempoMark.js.map +1 -0
  64. package/lib/module/renderer/useScoreRecording.js +2 -1
  65. package/lib/module/renderer/useScoreRecording.js.map +1 -1
  66. package/lib/typescript/src/base/FontManager.d.ts +12 -7
  67. package/lib/typescript/src/base/FontManager.d.ts.map +1 -1
  68. package/lib/typescript/src/base/VexflowCanvas.d.ts.map +1 -1
  69. package/lib/typescript/src/base/VexflowRecordingClone.d.ts +8 -0
  70. package/lib/typescript/src/base/VexflowRecordingClone.d.ts.map +1 -0
  71. package/lib/typescript/src/base/VexflowRecordingContext.d.ts.map +1 -1
  72. package/lib/typescript/src/base/builtInTextFont.d.ts +6 -0
  73. package/lib/typescript/src/base/builtInTextFont.d.ts.map +1 -0
  74. package/lib/typescript/src/base/cssFontShorthand.d.ts +3 -0
  75. package/lib/typescript/src/base/cssFontShorthand.d.ts.map +1 -0
  76. package/lib/typescript/src/base/fonts/academico.d.ts +5 -0
  77. package/lib/typescript/src/base/fonts/academico.d.ts.map +1 -0
  78. package/lib/typescript/src/base/pictureRetirement.d.ts +26 -0
  79. package/lib/typescript/src/base/pictureRetirement.d.ts.map +1 -0
  80. package/lib/typescript/src/base/setupVexflowReactNative.d.ts +0 -8
  81. package/lib/typescript/src/base/setupVexflowReactNative.d.ts.map +1 -1
  82. package/lib/typescript/src/base/types.d.ts.map +1 -1
  83. package/lib/typescript/src/musicxml/MusicXmlParser/InternalTypes.d.ts +4 -1
  84. package/lib/typescript/src/musicxml/MusicXmlParser/InternalTypes.d.ts.map +1 -1
  85. package/lib/typescript/src/musicxml/MusicXmlParser/MeasureParser.d.ts.map +1 -1
  86. package/lib/typescript/src/musicxml/MusicXmlParser/MusicXmlNotes.d.ts +13 -0
  87. package/lib/typescript/src/musicxml/MusicXmlParser/MusicXmlNotes.d.ts.map +1 -0
  88. package/lib/typescript/src/musicxml/MusicXmlParser/PartParser.d.ts.map +1 -1
  89. package/lib/typescript/src/musicxml/MusicXmlParser/Spanners.d.ts +6 -0
  90. package/lib/typescript/src/musicxml/MusicXmlParser/Spanners.d.ts.map +1 -1
  91. package/lib/typescript/src/musicxml/MusicXmlParser/mappers.d.ts +7 -1
  92. package/lib/typescript/src/musicxml/MusicXmlParser/mappers.d.ts.map +1 -1
  93. package/lib/typescript/src/renderer/Layout/DocumentLayout.d.ts.map +1 -1
  94. package/lib/typescript/src/renderer/Layout/VerticalSpacing.d.ts +6 -0
  95. package/lib/typescript/src/renderer/Layout/VerticalSpacing.d.ts.map +1 -1
  96. package/lib/typescript/src/renderer/ScoreRenderer/ScoreOverlayPicture.d.ts +1 -1
  97. package/lib/typescript/src/renderer/ScoreRenderer/ScoreOverlayPicture.d.ts.map +1 -1
  98. package/lib/typescript/src/renderer/ScoreRenderer/ScoreRenderer.d.ts.map +1 -1
  99. package/lib/typescript/src/renderer/ScoreRenderer/ScoreScrollbar.d.ts +1 -0
  100. package/lib/typescript/src/renderer/ScoreRenderer/ScoreScrollbar.d.ts.map +1 -1
  101. package/lib/typescript/src/renderer/ScoreRenderer/types.d.ts +14 -11
  102. package/lib/typescript/src/renderer/ScoreRenderer/types.d.ts.map +1 -1
  103. package/lib/typescript/src/renderer/ScoreRenderer/utils.d.ts +8 -27
  104. package/lib/typescript/src/renderer/ScoreRenderer/utils.d.ts.map +1 -1
  105. package/lib/typescript/src/renderer/layout.d.ts +5 -1
  106. package/lib/typescript/src/renderer/layout.d.ts.map +1 -1
  107. package/lib/typescript/src/renderer/lyrics.d.ts +42 -0
  108. package/lib/typescript/src/renderer/lyrics.d.ts.map +1 -0
  109. package/lib/typescript/src/renderer/measure.d.ts +7 -2
  110. package/lib/typescript/src/renderer/measure.d.ts.map +1 -1
  111. package/lib/typescript/src/renderer/measureBounds.d.ts +3 -0
  112. package/lib/typescript/src/renderer/measureBounds.d.ts.map +1 -1
  113. package/lib/typescript/src/renderer/measureModifiers.d.ts +14 -4
  114. package/lib/typescript/src/renderer/measureModifiers.d.ts.map +1 -1
  115. package/lib/typescript/src/renderer/noteModifiers.d.ts +3 -2
  116. package/lib/typescript/src/renderer/noteModifiers.d.ts.map +1 -1
  117. package/lib/typescript/src/renderer/{fixedNoteSpacing.d.ts → noteSpacing.d.ts} +9 -1
  118. package/lib/typescript/src/renderer/noteSpacing.d.ts.map +1 -0
  119. package/lib/typescript/src/renderer/render.d.ts.map +1 -1
  120. package/lib/typescript/src/renderer/scale.d.ts.map +1 -1
  121. package/lib/typescript/src/renderer/tempoMark.d.ts +21 -0
  122. package/lib/typescript/src/renderer/tempoMark.d.ts.map +1 -0
  123. package/lib/typescript/src/renderer/types.d.ts +31 -7
  124. package/lib/typescript/src/renderer/types.d.ts.map +1 -1
  125. package/lib/typescript/src/state/types.d.ts +11 -3
  126. package/lib/typescript/src/state/types.d.ts.map +1 -1
  127. package/package.json +34 -26
  128. package/src/base/FontManager.ts +50 -31
  129. package/src/base/VexflowCanvas.tsx +10 -10
  130. package/src/base/VexflowRecordingClone.ts +89 -0
  131. package/src/base/VexflowRecordingContext.ts +8 -81
  132. package/src/base/builtInTextFont.ts +25 -0
  133. package/src/base/cssFontShorthand.ts +45 -0
  134. package/src/base/fonts/OFL.txt +93 -0
  135. package/src/base/fonts/academico.ts +10 -0
  136. package/src/base/pictureRetirement.ts +74 -0
  137. package/src/base/setupVexflowReactNative.ts +1 -49
  138. package/src/base/types.ts +0 -3
  139. package/src/musicxml/MusicXmlParser/InternalTypes.ts +5 -0
  140. package/src/musicxml/MusicXmlParser/MeasureParser.ts +31 -182
  141. package/src/musicxml/MusicXmlParser/MusicXmlNotes.ts +198 -0
  142. package/src/musicxml/MusicXmlParser/PartParser.ts +10 -3
  143. package/src/musicxml/MusicXmlParser/Spanners.ts +11 -8
  144. package/src/musicxml/MusicXmlParser/mappers.ts +55 -6
  145. package/src/renderer/Layout/DocumentLayout.ts +12 -3
  146. package/src/renderer/Layout/VerticalSpacing.ts +46 -13
  147. package/src/renderer/ScoreRenderer/ScoreOverlayPicture.tsx +127 -66
  148. package/src/renderer/ScoreRenderer/ScoreRenderer.tsx +8 -23
  149. package/src/renderer/ScoreRenderer/ScoreScrollbar.tsx +16 -2
  150. package/src/renderer/ScoreRenderer/types.ts +14 -12
  151. package/src/renderer/ScoreRenderer/utils.ts +54 -125
  152. package/src/renderer/constants.ts +1 -1
  153. package/src/renderer/layout.ts +19 -4
  154. package/src/renderer/lyrics.ts +163 -0
  155. package/src/renderer/measure.tsx +70 -12
  156. package/src/renderer/measureBounds.ts +10 -0
  157. package/src/renderer/measureModifiers.ts +27 -7
  158. package/src/renderer/noteModifiers.ts +9 -10
  159. package/src/renderer/{fixedNoteSpacing.ts → noteSpacing.ts} +60 -9
  160. package/src/renderer/render.tsx +63 -27
  161. package/src/renderer/scale.ts +9 -0
  162. package/src/renderer/tempoMark.ts +224 -0
  163. package/src/renderer/types.ts +32 -7
  164. package/src/renderer/useScoreRecording.ts +1 -0
  165. package/src/state/types.ts +11 -3
  166. package/lib/module/renderer/fixedNoteSpacing.js.map +0 -1
  167. package/lib/module/utils.js +0 -44
  168. package/lib/module/utils.js.map +0 -1
  169. package/lib/typescript/src/renderer/fixedNoteSpacing.d.ts.map +0 -1
  170. package/lib/typescript/src/utils.d.ts +0 -1
  171. package/lib/typescript/src/utils.d.ts.map +0 -1
  172. package/src/utils.tsx +0 -42
@@ -67,22 +67,22 @@ const END_BARLINE_TYPES: Record<Barline, BarlineType> = {
67
67
 
68
68
  /**
69
69
  * Resolves the tri-state measure modifiers: `true` shows, `false` hides,
70
- * `undefined` falls back to the default (clef on the first measure, and on
71
- * a measure that `startsSystemWithClef`; meter and key signature hidden,
72
- * single barlines).
70
+ * `undefined` falls back to the default (clef and key signature on the first
71
+ * measure and on a measure that `repeatsSystemStart`; meter hidden, single
72
+ * barlines).
73
73
  */
74
74
  export function resolveMeasureModifiers(
75
75
  measure: Pick<Measure, 'leftModifiers' | 'rightModifiers'>,
76
76
  measureIndex: number,
77
- startsSystemWithClef = false
77
+ repeatsSystemStart = false
78
78
  ): ResolvedMeasureModifiers {
79
79
  const { leftModifiers, rightModifiers } = measure;
80
+ const showsBeginModifiers = measureIndex === 0 || repeatsSystemStart;
80
81
 
81
82
  return {
82
- showClef:
83
- leftModifiers?.showClef ?? (measureIndex === 0 || startsSystemWithClef),
83
+ showClef: leftModifiers?.showClef ?? showsBeginModifiers,
84
84
  showMeter: leftModifiers?.showMeter ?? false,
85
- showKeySignature: leftModifiers?.showKeySignature ?? false,
85
+ showKeySignature: leftModifiers?.showKeySignature ?? showsBeginModifiers,
86
86
  startBarline: leftModifiers?.startBarline ?? 'single',
87
87
  endBarline: rightModifiers?.endBarline ?? 'single',
88
88
  };
@@ -125,6 +125,26 @@ export function applyMeasureModifiers(
125
125
  return stave;
126
126
  }
127
127
 
128
+ /**
129
+ * Starts the notes of every stave at the widest begin-modifier block, as
130
+ * VexFlow's `System` does, so same-tick notes line up across a staff group.
131
+ */
132
+ export function alignNoteStarts(staves: Stave[]) {
133
+ const noteStartX = Math.max(...staves.map((stave) => stave.getNoteStartX()));
134
+
135
+ staves.forEach((stave) => stave.setNoteStartX(noteStartX));
136
+ }
137
+
138
+ /**
139
+ * The stave with the smallest note-end x (a repeat-end barline on one stave
140
+ * narrows it); formatting to it keeps notes inside every stave of the group.
141
+ */
142
+ export function getFormatReferenceStave(staves: Stave[]): Stave {
143
+ return staves.reduce((reference, stave) =>
144
+ stave.getNoteEndX() < reference.getNoteEndX() ? stave : reference
145
+ );
146
+ }
147
+
128
148
  /** Major-key VexFlow spec for the key's accidentals, respelt enharmonically beyond 7 sharps/flats. */
129
149
  export function keySignatureToVFSpec(keySignature: KeySignature): string {
130
150
  const { tonic, accidental, mode = 'major' } = keySignature;
@@ -25,6 +25,7 @@ import type {
25
25
  Pitch,
26
26
  } from '../state';
27
27
  import { renderOptions } from './constants';
28
+ import { Lyric, verseOf } from './lyrics';
28
29
  import { durationToVF, pitchToVFKey } from './vfKeys';
29
30
 
30
31
  /**
@@ -65,8 +66,6 @@ const DYNAMIC_FONT_SIZE = 30;
65
66
 
66
67
  const ANNOTATION_FONT = { size: 10, weight: 'bold' };
67
68
 
68
- const LYRIC_FONT = { size: 10, weight: 'normal' };
69
-
70
69
  const DIRECTION_FONT = { size: 11, weight: 'bold' };
71
70
 
72
71
  /** `GhostNote`s have no glyphs, so their element box is the origin. */
@@ -141,13 +140,14 @@ function verticalJustification(placement: 'above' | 'below') {
141
140
  }
142
141
 
143
142
  function byVerse(left: LyricAttachment, right: LyricAttachment) {
144
- return (left.verse ?? -Infinity) - (right.verse ?? -Infinity);
143
+ return verseOf(left) - verseOf(right);
145
144
  }
146
145
 
147
146
  /**
148
147
  * Attaches the owner's marks to a VexFlow note in a fixed order regardless of
149
148
  * the attachments' order: articulations, annotations, dynamics, lyrics (by
150
- * verse), grace notes. Same-side marks stack outward in that order.
149
+ * verse), grace notes. Same-side marks stack outward in that order, except
150
+ * lyrics, which sit on their staff's verse lines (`lyrics.ts`).
151
151
  */
152
152
  export function applyNoteModifiers(
153
153
  note: StaveNote,
@@ -203,11 +203,10 @@ export function applyNoteModifiers(
203
203
  )
204
204
  .sort(byVerse)
205
205
  .forEach((attachment) => {
206
- const lyric = new VFAnnotation(attachment.text);
207
-
208
- lyric.setFont({ family: textFontFamily, ...LYRIC_FONT });
209
- lyric.setVerticalJustification(AnnotationVerticalJustify.BOTTOM);
210
- note.addModifier(lyric, 0);
206
+ note.addModifier(
207
+ new Lyric(attachment.text, verseOf(attachment), textFontFamily),
208
+ 0
209
+ );
211
210
  });
212
211
 
213
212
  for (const attachment of attachments) {
@@ -256,7 +255,7 @@ function applyGraceNoteGroup(
256
255
  /**
257
256
  * Draws each text direction of a measure on the voice's first drawn item,
258
257
  * after that item's own marks; a voice of spacers draws none. Tempo
259
- * directions are not drawn.
258
+ * directions are drawn by `tempoMark.ts`.
260
259
  */
261
260
  export function applyMeasureDirections(
262
261
  notes: readonly StemmableNote[],
@@ -45,22 +45,16 @@ export function applyFixedNoteSpacing(
45
45
  const multiplier = contexts.resolutionMultiplier || 1;
46
46
  const lastTick = lastTickKey / multiplier;
47
47
 
48
- // Tick context x is relative to noteStartX + the stave's left note padding
49
- // (see Tickable.getAbsoluteX), so the usable span ends at noteEndX. The
50
- // padding is derived from Stave statics because the `Metrics` module is not
51
- // re-exported by every vexflow build.
52
- const stavePadding = Stave.defaultPadding - Stave.rightPadding;
53
- const noteAreaWidth =
54
- stave.getNoteEndX() - stave.getNoteStartX() - stavePadding;
48
+ const areaWidth = noteAreaWidth(stave);
55
49
  const firstLeft = contexts.map[contexts.list[0]!]!.getMetrics().totalLeftPx;
56
- let span = noteAreaWidth - firstLeft;
50
+ let span = areaWidth - firstLeft;
57
51
 
58
52
  const lastContext = contexts.map[lastTickKey]!;
59
53
  const lastOverflow =
60
54
  firstLeft +
61
55
  (lastTick / totalTicks) * span +
62
56
  lastContext.getWidth() -
63
- noteAreaWidth;
57
+ areaWidth;
64
58
 
65
59
  if (lastOverflow > 0) {
66
60
  span -= (lastOverflow * totalTicks) / lastTick;
@@ -76,3 +70,60 @@ export function applyFixedNoteSpacing(
76
70
  );
77
71
  }
78
72
  }
73
+
74
+ /**
75
+ * Compresses the tick contexts linearly, anchored at the first one, when
76
+ * VexFlow's minimum widths run any of them past the note area. The anchor
77
+ * keeps a centre-aligned rest's centre shift valid; beams post-format after
78
+ * this, so they and modifiers follow the final positions. Returns the
79
+ * applied factor, 1 when nothing moved.
80
+ */
81
+ export function squeezeNoteSpacing(formatter: Formatter, stave: Stave) {
82
+ const contexts = formatter.getTickContexts();
83
+
84
+ if (!contexts) {
85
+ return 1;
86
+ }
87
+
88
+ const areaWidth = noteAreaWidth(stave);
89
+ const firstX = contexts.map[contexts.list[0]!]?.getX() ?? 0;
90
+ let scale = 1;
91
+
92
+ for (const tickKey of contexts.list) {
93
+ const context = contexts.map[tickKey]!;
94
+ const offset = context.getX() - firstX;
95
+
96
+ if (offset > 0) {
97
+ scale = Math.min(
98
+ scale,
99
+ (areaWidth - context.getWidth() - firstX) / offset
100
+ );
101
+ }
102
+ }
103
+
104
+ if (scale >= 1 || !(scale > 0)) {
105
+ return 1;
106
+ }
107
+
108
+ for (const tickKey of contexts.list) {
109
+ const context = contexts.map[tickKey]!;
110
+
111
+ context.setX(firstX + (context.getX() - firstX) * scale);
112
+ }
113
+
114
+ return scale;
115
+ }
116
+
117
+ /**
118
+ * Width a tick context x may span: x is relative to noteStartX + the stave's
119
+ * left note padding (see Tickable.getAbsoluteX), so the area ends at
120
+ * noteEndX. The padding is derived from Stave statics because the `Metrics`
121
+ * module is not re-exported by every vexflow build.
122
+ */
123
+ function noteAreaWidth(stave: Stave) {
124
+ return (
125
+ stave.getNoteEndX() -
126
+ stave.getNoteStartX() -
127
+ (Stave.defaultPadding - Stave.rightPadding)
128
+ );
129
+ }
@@ -15,14 +15,18 @@ import type {
15
15
  ScoreLayoutPlan,
16
16
  } from './layout';
17
17
  import {
18
+ alignNoteStarts,
18
19
  applyMeasureModifiers,
20
+ getFormatReferenceStave,
19
21
  resolveMeasureModifiers,
20
22
  } from './measureModifiers';
21
23
  import { indexAttachmentsByOwner, makeVFVoice } from './scoreParsing';
22
- import { applyFixedNoteSpacing } from './fixedNoteSpacing';
23
24
  import { itemLayoutOf } from './itemLayout';
25
+ import { placeLyrics } from './lyrics';
24
26
  import { hasNoteHeads } from './noteModifiers';
27
+ import { applyFixedNoteSpacing, squeezeNoteSpacing } from './noteSpacing';
25
28
  import { applyStaffLines, visibleLineYs } from './stave';
29
+ import { drawTempoMarks } from './tempoMark';
26
30
  import type { ScoreItemHooks, ScoreItemsLayout, ScoreOptions } from './types';
27
31
  import type { VFVoiceNote } from './scoreParsing';
28
32
 
@@ -42,10 +46,11 @@ export function renderScore(
42
46
  );
43
47
  const measuresByGroup = groupMeasuresByIndex(layoutPlan.measures);
44
48
  const attachmentsByOwner = indexAttachmentsByOwner(score);
45
- const itemsLayout: ScoreItemsLayout = {
49
+ const itemsLayout: Required<ScoreItemsLayout> = {
46
50
  items: {},
47
51
  measures: [],
48
52
  contentSize: layoutPlan.contentSize,
53
+ tempoMarks: [],
49
54
  };
50
55
 
51
56
  for (const system of layoutPlan.systems) {
@@ -115,7 +120,7 @@ function renderMeasure(
115
120
  measurePlan: MeasureLayoutPlan,
116
121
  attachmentsByOwner: Map<string, NoteAttachment[]>,
117
122
  options: RenderMeasureOptions,
118
- itemsLayout: ScoreItemsLayout
123
+ itemsLayout: Required<ScoreItemsLayout>
119
124
  ) {
120
125
  const formatter = new Formatter();
121
126
  const resolvedStateByStaffId = new Map(
@@ -159,6 +164,7 @@ function renderMeasure(
159
164
  }));
160
165
  const vfVoices = voiceArtifacts.map(({ vfVoice }) => vfVoice);
161
166
 
167
+ centreMeasureRest(voiceArtifacts);
162
168
  formatter.joinVoices(vfVoices);
163
169
 
164
170
  return {
@@ -191,7 +197,7 @@ function renderMeasure(
191
197
  staff.lines
192
198
  );
193
199
 
194
- applyMeasureModifiers(
200
+ return applyMeasureModifiers(
195
201
  stave,
196
202
  resolveMeasureModifiers(
197
203
  measure,
@@ -200,14 +206,13 @@ function renderMeasure(
200
206
  ),
201
207
  resolvedState
202
208
  );
203
- stave.setContext(ctx).draw();
204
- return stave;
205
209
  });
206
- const renderedStaveByStaffId = new Map(
207
- group.staves.map((staff, staffIndex) => [
208
- staff.id,
209
- renderedStaves[staffIndex],
210
- ])
210
+
211
+ alignNoteStarts(renderedStaves);
212
+ renderedStaves.forEach((stave) => stave.setContext(ctx).draw());
213
+
214
+ const staffIndexById = new Map(
215
+ group.staves.map((staff, staffIndex) => [staff.id, staffIndex])
211
216
  );
212
217
 
213
218
  renderStaffConnectors(ctx, group, renderedStaves, options);
@@ -215,26 +220,31 @@ function renderMeasure(
215
220
  staffRenderArtifacts.forEach(({ voiceArtifacts }) => {
216
221
  voiceArtifacts.forEach(({ items, notes, ownerStaffId }) => {
217
222
  items.forEach((item, index) => {
218
- const targetStave =
219
- renderedStaveByStaffId.get(item.targetStaffId ?? ownerStaffId) ??
220
- renderedStaveByStaffId.get(ownerStaffId);
223
+ const staffIndex =
224
+ staffIndexById.get(item.targetStaffId ?? ownerStaffId) ??
225
+ staffIndexById.get(ownerStaffId);
226
+ const note = notes[index];
221
227
 
222
- if (targetStave) {
223
- notes[index]?.setStave(targetStave);
228
+ if (staffIndex === undefined || !note) {
229
+ return;
224
230
  }
231
+
232
+ note.setStave(renderedStaves[staffIndex]!);
233
+ placeLyrics(note, measurePlan.verseBaselines?.[staffIndex]);
225
234
  });
226
235
  });
227
236
  });
228
237
 
238
+ let noteSpacingScale = 1;
239
+
229
240
  if (allVoices.length > 0) {
230
- // Format against the stave with the narrowest note area, so notes never
231
- // overrun a stave whose clef or time signature pushes its note start
232
- // further right.
233
241
  const referenceStave = getFormatReferenceStave(renderedStaves);
234
242
  formatter.formatToStave(allVoices, referenceStave);
235
243
 
236
- if (options.fixedNoteSpacing && referenceStave) {
244
+ if (options.fixedNoteSpacing) {
237
245
  applyFixedNoteSpacing(formatter, allVoices, referenceStave);
246
+ } else {
247
+ noteSpacingScale = squeezeNoteSpacing(formatter, referenceStave);
238
248
  }
239
249
  }
240
250
 
@@ -262,17 +272,41 @@ function renderMeasure(
262
272
  }
263
273
  );
264
274
 
265
- collectMeasureLayout(itemsLayout, measurePlan, group.staves, renderedStaves);
275
+ drawTempoMarks(
276
+ ctx,
277
+ group,
278
+ measurePlan,
279
+ renderedStaves,
280
+ options.textFontFamily,
281
+ itemsLayout.tempoMarks
282
+ );
283
+ collectMeasureLayout(
284
+ itemsLayout,
285
+ measurePlan,
286
+ group.staves,
287
+ renderedStaves,
288
+ noteSpacingScale
289
+ );
266
290
  }
267
291
 
268
292
  /**
269
- * The stave with the narrowest note area — formatting to it keeps notes
270
- * inside every stave of the group.
293
+ * A staff measure whose only visible item is a rest holds a measure rest,
294
+ * engraved centred in the bar. Hidden and spacer rests don't count.
271
295
  */
272
- function getFormatReferenceStave(renderedStaves: Stave[]): Stave {
273
- return renderedStaves.reduce((reference, stave) =>
274
- stave.getNoteStartX() > reference.getNoteStartX() ? stave : reference
296
+ function centreMeasureRest(
297
+ voiceArtifacts: Array<{ items: VoiceItem[]; notes: VFVoiceNote[] }>
298
+ ) {
299
+ const visible = voiceArtifacts.flatMap(({ items, notes }) =>
300
+ items.flatMap((item, index) =>
301
+ item.type !== 'rest' || (item.kind ?? 'visible') === 'visible'
302
+ ? [{ item, note: notes[index]! }]
303
+ : []
304
+ )
275
305
  );
306
+
307
+ if (visible.length === 1 && visible[0]!.item.type === 'rest') {
308
+ visible[0]!.note.setCenterAlignment(true);
309
+ }
276
310
  }
277
311
 
278
312
  /**
@@ -283,7 +317,8 @@ function collectMeasureLayout(
283
317
  itemsLayout: ScoreItemsLayout,
284
318
  measurePlan: MeasureLayoutPlan,
285
319
  staves: GroupLayoutContext['staves'],
286
- renderedStaves: Stave[]
320
+ renderedStaves: Stave[],
321
+ noteSpacingScale: number
287
322
  ) {
288
323
  staves.forEach((staff, staffIndex) => {
289
324
  const stave = renderedStaves[staffIndex];
@@ -306,6 +341,7 @@ function collectMeasureLayout(
306
341
  staveLineTopY: stave.getTopLineTopY(),
307
342
  staveLineBottomY: stave.getBottomLineBottomY(),
308
343
  visibleLineYs: visibleLineYs(stave, staff.lines),
344
+ ...(noteSpacingScale < 1 ? { noteSpacingScale } : {}),
309
345
  });
310
346
  });
311
347
  }
@@ -104,6 +104,15 @@ export function scaleItemsLayoutToViewSpace(
104
104
  : {}),
105
105
  })),
106
106
  contentSize: toViewSize(itemsLayout.contentSize, scale),
107
+ ...(itemsLayout.tempoMarks
108
+ ? {
109
+ tempoMarks: itemsLayout.tempoMarks.map((mark) => ({
110
+ ...mark,
111
+ bounds: scaleBounds(mark.bounds, scale),
112
+ bpmBounds: scaleBounds(mark.bpmBounds, scale),
113
+ })),
114
+ }
115
+ : {}),
107
116
  };
108
117
  }
109
118
 
@@ -0,0 +1,224 @@
1
+ import { Element, StaveModifierPosition, TimeSignature } from 'vexflow';
2
+ import type { Stave } from 'vexflow';
3
+
4
+ import type { VexflowRecordingContext } from '../base';
5
+ import type { Direction, NoteLength, Tempo, TempoDirection } from '../state';
6
+ import type { GroupLayoutContext, MeasureLayoutPlan } from './layout';
7
+ import type { ScoreItemBounds, ScoreTempoMarkLayout } from './types';
8
+
9
+ /** Sizes in VexFlow font points, gaps in content units. */
10
+ const TEMPO_MARK = {
11
+ textFont: { size: 12, weight: 'bold' },
12
+ glyphFontSize: 20,
13
+ wordGap: 5,
14
+ dotGap: 2,
15
+ equalsGap: 4,
16
+ baselineGap: 8,
17
+ };
18
+
19
+ /** SMuFL metronome note glyphs, drawn with the music font. */
20
+ const METRONOME_GLYPHS: Record<NoteLength, string> = {
21
+ long: '\uECA1',
22
+ breve: '\uECA0',
23
+ w: '\uECA2',
24
+ h: '\uECA3',
25
+ q: '\uECA5',
26
+ 8: '\uECA7',
27
+ 16: '\uECA9',
28
+ 32: '\uECAB',
29
+ 64: '\uECAD',
30
+ 128: '\uECAF',
31
+ };
32
+
33
+ const METRONOME_AUGMENTATION_DOT = '\uECB7';
34
+
35
+ interface TempoMarkPart {
36
+ element: Element;
37
+ /** Left edge relative to the mark's left edge. */
38
+ x: number;
39
+ width: number;
40
+ ascent: number;
41
+ descent: number;
42
+ }
43
+
44
+ interface TempoMarkParts {
45
+ parts: TempoMarkPart[];
46
+ bpm: TempoMarkPart;
47
+ width: number;
48
+ ascent: number;
49
+ descent: number;
50
+ }
51
+
52
+ /** Only the first tempo direction of a measure is drawn. */
53
+ export function firstTempoDirection(
54
+ directions: readonly Direction[] | undefined
55
+ ): TempoDirection | undefined {
56
+ return directions?.find(
57
+ (direction): direction is TempoDirection => direction.type === 'tempo'
58
+ );
59
+ }
60
+
61
+ /**
62
+ * Baseline and top of the mark relative to the stave origin, placed so its
63
+ * lowest point clears the staff's measured content top (same space) by a gap.
64
+ */
65
+ export function reserveTempoMark(
66
+ stave: Stave,
67
+ contentTop: number,
68
+ tempo: Tempo,
69
+ textFontFamily: string
70
+ ): { baseline: number; top: number } {
71
+ const { ascent, descent } = layoutTempoMarkParts(tempo, textFontFamily);
72
+ const baseline =
73
+ Math.min(stave.getYForTopText() - stave.getY(), contentTop) -
74
+ TEMPO_MARK.baselineGap -
75
+ descent;
76
+
77
+ return { baseline, top: baseline - ascent };
78
+ }
79
+
80
+ /**
81
+ * Draws the first tempo direction of each stave of the measure at the
82
+ * baseline the measure pass reserved, inside the direction's color group.
83
+ */
84
+ export function drawTempoMarks(
85
+ ctx: VexflowRecordingContext,
86
+ group: GroupLayoutContext,
87
+ measurePlan: MeasureLayoutPlan,
88
+ renderedStaves: Stave[],
89
+ textFontFamily: string,
90
+ tempoMarks: ScoreTempoMarkLayout[]
91
+ ) {
92
+ const { measureIndex, systemIndex } = measurePlan;
93
+ const baselines = group.measures.find(
94
+ (measure) => measure.measureIndex === measureIndex
95
+ )?.tempoMarkBaselines;
96
+
97
+ group.staves.forEach((staff, staffIndex) => {
98
+ const baseline = baselines?.[staff.id];
99
+ const direction = firstTempoDirection(
100
+ staff.measures[measureIndex]?.directions
101
+ );
102
+ const stave = renderedStaves[staffIndex];
103
+
104
+ if (baseline === undefined || !direction || !stave) {
105
+ return;
106
+ }
107
+
108
+ const mark = layoutTempoMarkParts(direction.tempo, textFontFamily);
109
+ const left = markLeft(stave);
110
+ const baselineY = stave.getY() + baseline;
111
+
112
+ ctx.beginColorGroup(direction.id);
113
+
114
+ try {
115
+ mark.parts.forEach(({ element, x }) =>
116
+ element.renderText(ctx, left + x, baselineY)
117
+ );
118
+ } finally {
119
+ ctx.endColorGroup();
120
+ }
121
+
122
+ tempoMarks.push({
123
+ directionId: direction.id,
124
+ staffId: staff.id,
125
+ measureIndex,
126
+ systemIndex,
127
+ bounds: boundsAt(left, baselineY, mark),
128
+ bpmBounds: boundsAt(left + mark.bpm.x, baselineY, mark.bpm),
129
+ });
130
+ });
131
+ }
132
+
133
+ /** Left edge of the time signature when shown, else the note start. */
134
+ function markLeft(stave: Stave): number {
135
+ const [timeSignature] = stave.getModifiers(
136
+ StaveModifierPosition.BEGIN,
137
+ TimeSignature.CATEGORY
138
+ );
139
+
140
+ return timeSignature?.getX() ?? stave.getNoteStartX();
141
+ }
142
+
143
+ function boundsAt(
144
+ left: number,
145
+ baselineY: number,
146
+ {
147
+ width,
148
+ ascent,
149
+ descent,
150
+ }: Pick<TempoMarkPart, 'width' | 'ascent' | 'descent'>
151
+ ): ScoreItemBounds {
152
+ return {
153
+ left,
154
+ right: left + width,
155
+ top: baselineY - ascent,
156
+ bottom: baselineY + descent,
157
+ };
158
+ }
159
+
160
+ /** `[text] <note glyph><dots> = <bpm>`; a missing beat unit is a quarter. */
161
+ function layoutTempoMarkParts(
162
+ { bpm, beatUnit, text }: Tempo,
163
+ textFontFamily: string
164
+ ): TempoMarkParts {
165
+ const parts: TempoMarkPart[] = [];
166
+ let x = 0;
167
+ const append = (element: Element, gapBefore: number) => {
168
+ const { actualBoundingBoxAscent, actualBoundingBoxDescent } =
169
+ element.getTextMetrics();
170
+ const part = {
171
+ element,
172
+ x: parts.length > 0 ? x + gapBefore : x,
173
+ width: element.getWidth(),
174
+ ascent: actualBoundingBoxAscent,
175
+ descent: actualBoundingBoxDescent,
176
+ };
177
+
178
+ parts.push(part);
179
+ x = part.x + part.width;
180
+
181
+ return part;
182
+ };
183
+
184
+ if (text) {
185
+ append(textElement(text, textFontFamily), 0);
186
+ }
187
+
188
+ append(
189
+ glyphElement(METRONOME_GLYPHS[beatUnit?.length ?? 'q']),
190
+ TEMPO_MARK.wordGap
191
+ );
192
+
193
+ for (let dot = 0; dot < (beatUnit?.dots ?? 0); dot++) {
194
+ append(glyphElement(METRONOME_AUGMENTATION_DOT), TEMPO_MARK.dotGap);
195
+ }
196
+
197
+ append(textElement('=', textFontFamily), TEMPO_MARK.equalsGap);
198
+
199
+ const bpmPart = append(
200
+ textElement(String(bpm), textFontFamily),
201
+ TEMPO_MARK.equalsGap
202
+ );
203
+
204
+ return {
205
+ parts,
206
+ bpm: bpmPart,
207
+ width: x,
208
+ ascent: Math.max(...parts.map((part) => part.ascent)),
209
+ descent: Math.max(...parts.map((part) => part.descent)),
210
+ };
211
+ }
212
+
213
+ function textElement(text: string, textFontFamily: string): Element {
214
+ return new Element('StaveTempo')
215
+ .setFont({ family: textFontFamily, ...TEMPO_MARK.textFont })
216
+ .setText(text);
217
+ }
218
+
219
+ /** Music-font glyph; the family comes from VexFlow's configured fonts. */
220
+ function glyphElement(glyph: string): Element {
221
+ return new Element('StaveTempo.glyph')
222
+ .setFontSize(TEMPO_MARK.glyphFontSize)
223
+ .setText(glyph);
224
+ }