vexflow-native 2.4.0 → 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 (160) 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 +7 -3
  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 +11 -9
  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 +5 -13
  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 +37 -20
  59. package/lib/module/renderer/render.js.map +1 -1
  60. package/lib/typescript/src/base/FontManager.d.ts +12 -7
  61. package/lib/typescript/src/base/FontManager.d.ts.map +1 -1
  62. package/lib/typescript/src/base/VexflowCanvas.d.ts.map +1 -1
  63. package/lib/typescript/src/base/VexflowRecordingClone.d.ts +8 -0
  64. package/lib/typescript/src/base/VexflowRecordingClone.d.ts.map +1 -0
  65. package/lib/typescript/src/base/VexflowRecordingContext.d.ts.map +1 -1
  66. package/lib/typescript/src/base/builtInTextFont.d.ts +6 -0
  67. package/lib/typescript/src/base/builtInTextFont.d.ts.map +1 -0
  68. package/lib/typescript/src/base/cssFontShorthand.d.ts +3 -0
  69. package/lib/typescript/src/base/cssFontShorthand.d.ts.map +1 -0
  70. package/lib/typescript/src/base/fonts/academico.d.ts +5 -0
  71. package/lib/typescript/src/base/fonts/academico.d.ts.map +1 -0
  72. package/lib/typescript/src/base/pictureRetirement.d.ts +26 -0
  73. package/lib/typescript/src/base/pictureRetirement.d.ts.map +1 -0
  74. package/lib/typescript/src/base/setupVexflowReactNative.d.ts +0 -8
  75. package/lib/typescript/src/base/setupVexflowReactNative.d.ts.map +1 -1
  76. package/lib/typescript/src/base/types.d.ts.map +1 -1
  77. package/lib/typescript/src/musicxml/MusicXmlParser/InternalTypes.d.ts +4 -1
  78. package/lib/typescript/src/musicxml/MusicXmlParser/InternalTypes.d.ts.map +1 -1
  79. package/lib/typescript/src/musicxml/MusicXmlParser/MeasureParser.d.ts.map +1 -1
  80. package/lib/typescript/src/musicxml/MusicXmlParser/MusicXmlNotes.d.ts +13 -0
  81. package/lib/typescript/src/musicxml/MusicXmlParser/MusicXmlNotes.d.ts.map +1 -0
  82. package/lib/typescript/src/musicxml/MusicXmlParser/PartParser.d.ts.map +1 -1
  83. package/lib/typescript/src/musicxml/MusicXmlParser/Spanners.d.ts +6 -0
  84. package/lib/typescript/src/musicxml/MusicXmlParser/Spanners.d.ts.map +1 -1
  85. package/lib/typescript/src/musicxml/MusicXmlParser/mappers.d.ts +7 -1
  86. package/lib/typescript/src/musicxml/MusicXmlParser/mappers.d.ts.map +1 -1
  87. package/lib/typescript/src/renderer/Layout/DocumentLayout.d.ts.map +1 -1
  88. package/lib/typescript/src/renderer/Layout/VerticalSpacing.d.ts +6 -0
  89. package/lib/typescript/src/renderer/Layout/VerticalSpacing.d.ts.map +1 -1
  90. package/lib/typescript/src/renderer/ScoreRenderer/ScoreOverlayPicture.d.ts +1 -1
  91. package/lib/typescript/src/renderer/ScoreRenderer/ScoreOverlayPicture.d.ts.map +1 -1
  92. package/lib/typescript/src/renderer/ScoreRenderer/ScoreRenderer.d.ts.map +1 -1
  93. package/lib/typescript/src/renderer/ScoreRenderer/ScoreScrollbar.d.ts +1 -0
  94. package/lib/typescript/src/renderer/ScoreRenderer/ScoreScrollbar.d.ts.map +1 -1
  95. package/lib/typescript/src/renderer/ScoreRenderer/types.d.ts +14 -11
  96. package/lib/typescript/src/renderer/ScoreRenderer/types.d.ts.map +1 -1
  97. package/lib/typescript/src/renderer/ScoreRenderer/utils.d.ts +8 -27
  98. package/lib/typescript/src/renderer/ScoreRenderer/utils.d.ts.map +1 -1
  99. package/lib/typescript/src/renderer/layout.d.ts +4 -1
  100. package/lib/typescript/src/renderer/layout.d.ts.map +1 -1
  101. package/lib/typescript/src/renderer/lyrics.d.ts +42 -0
  102. package/lib/typescript/src/renderer/lyrics.d.ts.map +1 -0
  103. package/lib/typescript/src/renderer/measure.d.ts +2 -2
  104. package/lib/typescript/src/renderer/measure.d.ts.map +1 -1
  105. package/lib/typescript/src/renderer/measureBounds.d.ts +3 -0
  106. package/lib/typescript/src/renderer/measureBounds.d.ts.map +1 -1
  107. package/lib/typescript/src/renderer/measureModifiers.d.ts +14 -4
  108. package/lib/typescript/src/renderer/measureModifiers.d.ts.map +1 -1
  109. package/lib/typescript/src/renderer/noteModifiers.d.ts +2 -1
  110. package/lib/typescript/src/renderer/noteModifiers.d.ts.map +1 -1
  111. package/lib/typescript/src/renderer/{fixedNoteSpacing.d.ts → noteSpacing.d.ts} +9 -1
  112. package/lib/typescript/src/renderer/noteSpacing.d.ts.map +1 -0
  113. package/lib/typescript/src/renderer/render.d.ts.map +1 -1
  114. package/lib/typescript/src/renderer/types.d.ts +17 -7
  115. package/lib/typescript/src/renderer/types.d.ts.map +1 -1
  116. package/lib/typescript/src/state/types.d.ts +8 -2
  117. package/lib/typescript/src/state/types.d.ts.map +1 -1
  118. package/package.json +34 -26
  119. package/src/base/FontManager.ts +50 -31
  120. package/src/base/VexflowCanvas.tsx +10 -10
  121. package/src/base/VexflowRecordingClone.ts +89 -0
  122. package/src/base/VexflowRecordingContext.ts +8 -81
  123. package/src/base/builtInTextFont.ts +25 -0
  124. package/src/base/cssFontShorthand.ts +45 -0
  125. package/src/base/fonts/OFL.txt +93 -0
  126. package/src/base/fonts/academico.ts +10 -0
  127. package/src/base/pictureRetirement.ts +74 -0
  128. package/src/base/setupVexflowReactNative.ts +1 -49
  129. package/src/base/types.ts +0 -3
  130. package/src/musicxml/MusicXmlParser/InternalTypes.ts +5 -0
  131. package/src/musicxml/MusicXmlParser/MeasureParser.ts +31 -182
  132. package/src/musicxml/MusicXmlParser/MusicXmlNotes.ts +198 -0
  133. package/src/musicxml/MusicXmlParser/PartParser.ts +10 -3
  134. package/src/musicxml/MusicXmlParser/Spanners.ts +11 -8
  135. package/src/musicxml/MusicXmlParser/mappers.ts +55 -6
  136. package/src/renderer/Layout/DocumentLayout.ts +12 -3
  137. package/src/renderer/Layout/VerticalSpacing.ts +46 -13
  138. package/src/renderer/ScoreRenderer/ScoreOverlayPicture.tsx +127 -66
  139. package/src/renderer/ScoreRenderer/ScoreRenderer.tsx +8 -23
  140. package/src/renderer/ScoreRenderer/ScoreScrollbar.tsx +16 -2
  141. package/src/renderer/ScoreRenderer/types.ts +14 -12
  142. package/src/renderer/ScoreRenderer/utils.ts +54 -125
  143. package/src/renderer/constants.ts +1 -1
  144. package/src/renderer/layout.ts +15 -4
  145. package/src/renderer/lyrics.ts +163 -0
  146. package/src/renderer/measure.tsx +16 -9
  147. package/src/renderer/measureBounds.ts +10 -0
  148. package/src/renderer/measureModifiers.ts +27 -7
  149. package/src/renderer/noteModifiers.ts +8 -9
  150. package/src/renderer/{fixedNoteSpacing.ts → noteSpacing.ts} +60 -9
  151. package/src/renderer/render.tsx +51 -25
  152. package/src/renderer/types.ts +17 -7
  153. package/src/state/types.ts +8 -2
  154. package/lib/module/renderer/fixedNoteSpacing.js.map +0 -1
  155. package/lib/module/utils.js +0 -44
  156. package/lib/module/utils.js.map +0 -1
  157. package/lib/typescript/src/renderer/fixedNoteSpacing.d.ts.map +0 -1
  158. package/lib/typescript/src/utils.d.ts +0 -1
  159. package/lib/typescript/src/utils.d.ts.map +0 -1
  160. package/src/utils.tsx +0 -42
@@ -1,12 +1,5 @@
1
- import {
2
- Skia,
3
- type SkPicture,
4
- type SkTypefaceFontProvider,
5
- type Transforms3d,
6
- } from 'react-native-skia';
7
- import type { SharedValue } from 'react-native-reanimated';
8
-
9
- import FontManager from '../../base/FontManager';
1
+ import { Skia, type SkPicture, type Transforms3d } from 'react-native-skia';
2
+
10
3
  import { renderVexflowRecordingCommands } from '../../base/VexflowRecordingReplay';
11
4
  import { isVexflowNativeDebugEnabled } from '../../shared/debug';
12
5
  import { insets, renderOptions, spacing } from '../constants';
@@ -18,16 +11,10 @@ import type {
18
11
  Viewport,
19
12
  } from '../types';
20
13
  import { createVisibleViewport } from '../viewport';
21
- import type {
22
- CreateScorePictureParams,
23
- OverlayFontManagerSlot,
24
- OverlayProfileState,
25
- PictureDisposalState,
26
- } from './types';
27
-
28
- // The reanimated plugin rewrites 'worklet' function declarations into
29
- // non-hoisted assignments, so nowMsWorklet must precede the worklets below
30
- // that call it.
14
+ import type { CreateScorePictureParams, OverlayProfileState } from './types';
15
+
16
+ // The worklets plugin rewrites 'worklet' function declarations into
17
+ // non-hoisted assignments, so a worklet must precede the worklets calling it.
31
18
  export function nowMsWorklet(): number {
32
19
  'worklet';
33
20
 
@@ -39,6 +26,8 @@ function nowMs(): number {
39
26
  }
40
27
 
41
28
  function roundMs(value: number): number {
29
+ 'worklet';
30
+
42
31
  return Math.round(value * 10) / 10;
43
32
  }
44
33
 
@@ -58,6 +47,7 @@ export function createScorePicture({
58
47
  fontManager,
59
48
  recordedCommands,
60
49
  replayFontManager,
50
+ scoreId,
61
51
  styleOverrides,
62
52
  }: CreateScorePictureParams) {
63
53
  try {
@@ -68,6 +58,7 @@ export function createScorePicture({
68
58
  fontManager,
69
59
  recordedCommands,
70
60
  replayFontManager,
61
+ scoreId,
71
62
  styleOverrides,
72
63
  });
73
64
 
@@ -75,6 +66,7 @@ export function createScorePicture({
75
66
  commandCount: recordedCommands.length,
76
67
  contentSize,
77
68
  durationMs: nowMs() - start,
69
+ scoreId,
78
70
  });
79
71
 
80
72
  return picture;
@@ -149,24 +141,6 @@ export function createPictureTransform(
149
141
  return transform;
150
142
  }
151
143
 
152
- /**
153
- * Runtime-local lazy FontManager: worklets cannot copy a class instance into
154
- * a closure, so each runtime constructs its own on first use and keeps it in
155
- * the slot (slot contents never cross runtimes; only the initial `null` is
156
- * serialized).
157
- */
158
- export function getOverlayFontManager(
159
- slot: SharedValue<OverlayFontManagerSlot>,
160
- fontProvider: SkTypefaceFontProvider,
161
- defaultFont: string
162
- ): FontManager {
163
- 'worklet';
164
-
165
- const state = slot.value;
166
-
167
- return (state.manager ??= new FontManager(fontProvider, defaultFont));
168
- }
169
-
170
144
  let emptyOverlayPicture: SkPicture | null = null;
171
145
 
172
146
  /**
@@ -184,123 +158,78 @@ export function getEmptyOverlayPicture(): SkPicture {
184
158
  return emptyOverlayPicture;
185
159
  }
186
160
 
187
- /**
188
- * Two-generation deferred disposal: react-native-skia commits the Canvas tree
189
- * asynchronously, so a retiring picture may still be referenced by the
190
- * committed Picture node or a commit in flight. Only pictures two
191
- * supersessions old are disposed. `next === null` marks a frame without an
192
- * owned picture (none, or the shared blank one), which never enters the ring.
193
- */
194
- export function retirePicture(
195
- state: PictureDisposalState,
196
- next: SkPicture | null
197
- ) {
198
- 'worklet';
199
-
200
- if (state.prev === next) {
201
- return;
202
- }
203
-
204
- if (state.prev != null) {
205
- state.pending.push(state.prev);
161
+ export const EMPTY_OVERLAY_PROFILE: OverlayProfileState = {
162
+ windowStartMs: null,
163
+ count: 0,
164
+ totalMs: 0,
165
+ maxMs: 0,
166
+ commandCount: 0,
167
+ };
206
168
 
207
- while (state.pending.length > 2) {
208
- state.pending.shift()?.dispose();
209
- }
210
- }
211
-
212
- state.prev = next;
213
- }
214
-
215
- /** Disposes the superseded pictures only; the current one stays alive. */
216
- export function disposeRetiredPictures(state: PictureDisposalState) {
169
+ /** Logs a non-empty profile window and starts a new one. */
170
+ export function flushOverlayProfile(
171
+ state: OverlayProfileState,
172
+ scoreId: string
173
+ ): OverlayProfileState {
217
174
  'worklet';
218
175
 
219
- for (const pending of state.pending) {
220
- pending.dispose();
176
+ if (state.count === 0) {
177
+ return state;
221
178
  }
222
- state.pending.length = 0;
223
- }
224
179
 
225
- export function disposePictures(state: PictureDisposalState) {
226
- 'worklet';
227
-
228
- disposeRetiredPictures(state);
229
-
230
- state.prev?.dispose();
231
- state.prev = null;
232
- }
233
-
234
- export function retireOverlayPicture(
235
- disposal: SharedValue<PictureDisposalState>,
236
- next: SkPicture | null
237
- ) {
238
- 'worklet';
239
-
240
- if (typeof _WORKLET === 'undefined' || !_WORKLET) {
241
- // The mapper's seed run happens on JS against a copy of the state; writes
242
- // here would never be seen by the UI runtime, so skip tracking entirely
243
- // (leaks at most one picture per mapper re-creation).
244
- return;
245
- }
246
-
247
- retirePicture(disposal.value, next);
248
- }
249
-
250
- export function disposeOverlayPictures(
251
- disposal: SharedValue<PictureDisposalState>
252
- ) {
253
- 'worklet';
180
+ console.info('[ScoreRenderer] overlay profile', {
181
+ scoreId,
182
+ commandCount: state.commandCount,
183
+ count: state.count,
184
+ totalMs: roundMs(state.totalMs),
185
+ meanMs: roundMs(state.totalMs / state.count),
186
+ maxMs: roundMs(state.maxMs),
187
+ });
254
188
 
255
- disposePictures(disposal.value);
189
+ return EMPTY_OVERLAY_PROFILE;
256
190
  }
257
191
 
258
- /** Throttled (≤1/s) UI-thread record timing; debug flag only. */
259
- export function logOverlayProfile(
260
- profile: SharedValue<OverlayProfileState>,
192
+ /** Throttled (≤1/s) record timing; the window opens at its first sample. */
193
+ export function addOverlayProfileSample(
194
+ state: OverlayProfileState,
195
+ scoreId: string,
261
196
  commandCount: number,
262
- durationMs: number
263
- ) {
197
+ durationMs: number,
198
+ atMs: number
199
+ ): OverlayProfileState {
264
200
  'worklet';
265
201
 
266
- const stats = profile.value;
267
- stats.count += 1;
268
-
269
- if (durationMs > stats.maxMs) {
270
- stats.maxMs = durationMs;
271
- }
272
-
273
- const now = nowMsWorklet();
274
-
275
- if (now - stats.windowStartMs < 1000) {
276
- return;
277
- }
278
-
279
- console.info('[ScoreRenderer] overlay profile', {
202
+ const windowStartMs = state.windowStartMs ?? atMs;
203
+ const next = {
204
+ windowStartMs,
205
+ count: state.count + 1,
206
+ totalMs: state.totalMs + durationMs,
207
+ maxMs: Math.max(state.maxMs, durationMs),
280
208
  commandCount,
281
- maxMs: Math.round(stats.maxMs * 10) / 10,
282
- count: stats.count,
283
- });
209
+ };
284
210
 
285
- stats.windowStartMs = now;
286
- stats.maxMs = 0;
287
- stats.count = 0;
211
+ return atMs - windowStartMs < 1000
212
+ ? next
213
+ : flushOverlayProfile(next, scoreId);
288
214
  }
289
215
 
290
216
  function logScorePictureProfile({
291
217
  commandCount,
292
218
  contentSize,
293
219
  durationMs,
220
+ scoreId,
294
221
  }: {
295
222
  commandCount: number;
296
223
  contentSize: RendererSize;
297
224
  durationMs: number;
225
+ scoreId: string;
298
226
  }) {
299
227
  if (!isVexflowNativeDebugEnabled()) {
300
228
  return;
301
229
  }
302
230
 
303
231
  console.info('[ScoreRenderer] picture profile', {
232
+ scoreId,
304
233
  contentSize,
305
234
  commandCount,
306
235
  durationMs: roundMs(durationMs),
@@ -13,7 +13,7 @@ export const spacing: ScoreSpacing = {
13
13
  uniformSystemPitch: false,
14
14
  firstSystemIndent: 0,
15
15
  lastSystemFill: 'justify',
16
- clefOnEachSystem: false,
16
+ clefOnEachSystem: true,
17
17
  };
18
18
 
19
19
  export const renderOptions: RenderOptions = {
@@ -8,7 +8,10 @@ import {
8
8
  layoutDocumentGroup,
9
9
  resolveDocumentEvenMeasureWidth,
10
10
  } from './Layout/DocumentLayout';
11
- import { resolveSystemVerticalLayout } from './Layout/VerticalSpacing';
11
+ import {
12
+ resolveSystemVerticalLayout,
13
+ resolveVerseBaselines,
14
+ } from './Layout/VerticalSpacing';
12
15
  import type { SystemVerticalLayout } from './Layout/VerticalSpacing';
13
16
  import {
14
17
  buildMeasurementGroups,
@@ -16,6 +19,7 @@ import {
16
19
  resolveGroupStaves,
17
20
  type ResolvedMeasureState,
18
21
  } from './scoreParsing';
22
+ import type { VerseBaselines } from './lyrics';
19
23
  import type { MeasuredScore } from './measure';
20
24
  import type { StaffVerticalBounds } from './measureBounds';
21
25
  import type {
@@ -29,7 +33,7 @@ export interface MeasuredGroupMeasure {
29
33
  groupId: string;
30
34
  measureIndex: number;
31
35
  intrinsicWidth: number;
32
- systemStartClefWidth?: number;
36
+ systemStartModifierWidth?: number;
33
37
  measureNumbers: number[];
34
38
  staffBounds: StaffVerticalBounds[];
35
39
  tempoMarkBaselines?: Record<string, number>;
@@ -52,6 +56,8 @@ export interface MeasureLayoutPlan {
52
56
  width: number;
53
57
  height: number;
54
58
  staffYOffsets: number[];
59
+ /** Per staff index, shared by the system's measures; absent = no lyrics. */
60
+ verseBaselines?: Array<VerseBaselines | undefined>;
55
61
  systemIndex: number;
56
62
  }
57
63
 
@@ -182,8 +188,8 @@ function buildGroupLayoutContext(
182
188
  groupId: measure.groupId,
183
189
  measureIndex: measure.measureIndex,
184
190
  intrinsicWidth: measure.intrinsicNoteWidth,
185
- ...(measure.systemStartClefWidth
186
- ? { systemStartClefWidth: measure.systemStartClefWidth }
191
+ ...(measure.systemStartModifierWidth
192
+ ? { systemStartModifierWidth: measure.systemStartModifierWidth }
187
193
  : {}),
188
194
  measureNumbers: measure.measureNumbers,
189
195
  staffBounds: measure.staffBounds,
@@ -206,6 +212,10 @@ function layoutInfiniteScoreGroup(
206
212
  group.staves.length,
207
213
  options.spacing.staffGap
208
214
  );
215
+ const verseBaselines = resolveVerseBaselines(
216
+ group.measures,
217
+ group.staves.length
218
+ );
209
219
  const maxIntrinsicWidth = Math.max(
210
220
  ...group.measures.map((measure) => measure.intrinsicWidth),
211
221
  0
@@ -229,6 +239,7 @@ function layoutInfiniteScoreGroup(
229
239
  width,
230
240
  height: verticalLayout.height,
231
241
  staffYOffsets: verticalLayout.staffYOffsets,
242
+ ...(verseBaselines ? { verseBaselines } : {}),
232
243
  systemIndex: 0,
233
244
  });
234
245
 
@@ -0,0 +1,163 @@
1
+ import {
2
+ Annotation,
3
+ AnnotationVerticalJustify,
4
+ BoundingBox,
5
+ Font,
6
+ ModifierPosition,
7
+ } from 'vexflow';
8
+ import type { Note } from 'vexflow';
9
+
10
+ import type { LyricAttachment } from '../state';
11
+
12
+ const LYRIC = {
13
+ font: { size: 10, weight: 'normal' },
14
+ /** One staff space between a staff's lowest other ink and the tallest
15
+ * verse-1 letter. */
16
+ verseClearance: 10,
17
+ /** Baseline-to-baseline distance of consecutive verse lines, in ems. */
18
+ verseLineHeightEm: 1.2,
19
+ };
20
+
21
+ /** The verse lines a staff needs: the distinct verses present, in order, and
22
+ * the tallest ascent and descent among their lyrics. */
23
+ export interface VerseLines {
24
+ verses: number[];
25
+ ascent: number;
26
+ descent: number;
27
+ }
28
+
29
+ /** Baseline y of each verse line relative to the stave origin, by verse. */
30
+ export type VerseBaselines = ReadonlyMap<number, number>;
31
+
32
+ /** Undefined verses sort first, as their own verse line. */
33
+ export function verseOf(lyric: LyricAttachment): number {
34
+ return lyric.verse ?? -Infinity;
35
+ }
36
+
37
+ /**
38
+ * A lyric reserves its width like any annotation but is drawn on its verse
39
+ * line, which the layout places per system once the staff's other ink is
40
+ * known; until placed it draws nothing and has no ink.
41
+ */
42
+ export class Lyric extends Annotation {
43
+ private baselineY?: number;
44
+
45
+ constructor(text: string, readonly verse: number, textFontFamily: string) {
46
+ super(text);
47
+ this.setFont({ family: textFontFamily, ...LYRIC.font });
48
+ // Neither TOP nor BOTTOM, so `Annotation.format` reserves the lyric's
49
+ // width without stacking it under the note's other marks.
50
+ this.setVerticalJustification(AnnotationVerticalJustify.CENTER);
51
+ }
52
+
53
+ setBaselineY(baselineY: number) {
54
+ this.baselineY = baselineY;
55
+ }
56
+
57
+ getBoundingBox(): BoundingBox {
58
+ if (this.baselineY !== undefined) {
59
+ return super.getBoundingBox();
60
+ }
61
+
62
+ // Unplaced: empty at the notehead, so it widens no note or staff bounds.
63
+ const note = this.checkAttachedNote();
64
+
65
+ return new BoundingBox(note.getAbsoluteX(), note.getYs()[0]!, 0, 0);
66
+ }
67
+
68
+ draw() {
69
+ this.setRendered();
70
+
71
+ if (this.baselineY === undefined) {
72
+ return;
73
+ }
74
+
75
+ const ctx = this.checkContext();
76
+ const start = this.checkAttachedNote().getModifierStartXY(
77
+ ModifierPosition.ABOVE,
78
+ this.checkIndex()
79
+ );
80
+
81
+ ctx.openGroup('annotation', this.getAttribute('id'));
82
+ this.x = start.x - this.getWidth() / 2;
83
+ this.y = this.baselineY;
84
+ this.renderText(ctx, 0, 0);
85
+ ctx.closeGroup();
86
+ }
87
+ }
88
+
89
+ /** The verse lines of a note's lyrics; undefined without lyrics. */
90
+ export function noteVerseLines(note: Note): VerseLines | undefined {
91
+ return note
92
+ .getModifiers()
93
+ .filter((modifier) => modifier instanceof Lyric)
94
+ .reduce<VerseLines | undefined>((lines, lyric) => {
95
+ const { actualBoundingBoxAscent, actualBoundingBoxDescent } =
96
+ lyric.getTextMetrics();
97
+
98
+ return mergeVerseLines(lines, {
99
+ verses: [lyric.verse],
100
+ ascent: actualBoundingBoxAscent,
101
+ descent: actualBoundingBoxDescent,
102
+ });
103
+ }, undefined);
104
+ }
105
+
106
+ export function mergeVerseLines(
107
+ left: VerseLines | undefined,
108
+ right: VerseLines | undefined
109
+ ): VerseLines | undefined {
110
+ if (!left || !right) {
111
+ return left ?? right;
112
+ }
113
+
114
+ return {
115
+ verses: [...new Set([...left.verses, ...right.verses])].sort(
116
+ (a, b) => a - b
117
+ ),
118
+ ascent: Math.max(left.ascent, right.ascent),
119
+ descent: Math.max(left.descent, right.descent),
120
+ };
121
+ }
122
+
123
+ /**
124
+ * One level line per verse below `contentBottom` (stave-origin space): verse
125
+ * lines in verse order, a line height apart, the first clearing the content.
126
+ * `bottom` is the lowest ink of the last line.
127
+ */
128
+ export function layoutVerseLines(
129
+ contentBottom: number,
130
+ { verses, ascent, descent }: VerseLines
131
+ ): { baselines: VerseBaselines; bottom: number } {
132
+ const lineHeight =
133
+ Font.convertSizeToPixelValue(LYRIC.font.size) * LYRIC.verseLineHeightEm;
134
+ const firstBaseline = contentBottom + LYRIC.verseClearance + ascent;
135
+ const baselines = new Map(
136
+ verses.map((verse, line) => [verse, firstBaseline + line * lineHeight])
137
+ );
138
+
139
+ return {
140
+ baselines,
141
+ bottom: firstBaseline + (verses.length - 1) * lineHeight + descent,
142
+ };
143
+ }
144
+
145
+ /** Places the lyrics of a note, already on its stave, on their verse lines. */
146
+ export function placeLyrics(note: Note, baselines: VerseBaselines | undefined) {
147
+ if (!baselines) {
148
+ return;
149
+ }
150
+
151
+ const staveY = note.checkStave().getY();
152
+
153
+ note
154
+ .getModifiers()
155
+ .filter((modifier) => modifier instanceof Lyric)
156
+ .forEach((lyric) => {
157
+ const baseline = baselines.get(lyric.verse);
158
+
159
+ if (baseline !== undefined) {
160
+ lyric.setBaselineY(staveY + baseline);
161
+ }
162
+ });
163
+ }
@@ -14,7 +14,9 @@ import {
14
14
  resolveGroupStaves,
15
15
  } from './scoreParsing';
16
16
  import {
17
+ alignNoteStarts,
17
18
  applyMeasureModifiers,
19
+ getFormatReferenceStave,
18
20
  resolveMeasureModifiers,
19
21
  } from './measureModifiers';
20
22
  import { mergeNoteBounds, mergeY } from './measureBounds';
@@ -43,9 +45,9 @@ export interface MeasuredMeasure {
43
45
  intrinsicNoteWidth: number;
44
46
  /**
45
47
  * Extra width the measure needs when it starts a system and
46
- * `spacing.clefOnEachSystem` adds its clef; absent = 0.
48
+ * `spacing.clefOnEachSystem` adds its clef and key signature; absent = 0.
47
49
  */
48
- systemStartClefWidth?: number;
50
+ systemStartModifierWidth?: number;
49
51
  }
50
52
 
51
53
  export interface MeasuredScore {
@@ -148,9 +150,9 @@ export function measureScore(
148
150
  );
149
151
 
150
152
  try {
151
- // Clef and time signature sit before the note area, so the intrinsic
152
- // width must include them or an empty measure with a time signature
153
- // measures ~0 wide and the signature clips.
153
+ // Clef, key and time signature sit before the note area, so the
154
+ // intrinsic width must include them or an empty measure with a time
155
+ // signature measures ~0 wide and the signature clips.
154
156
  const leftModifierWidth = measureLeftModifierWidth(
155
157
  staffMeasurementContexts
156
158
  );
@@ -159,8 +161,10 @@ export function measureScore(
159
161
  ? formatter.preCalculateMinTotalWidth(allVoices) *
160
162
  Math.max(1, minIntrinsicSizeMultiplier)
161
163
  : 0) + leftModifierWidth;
162
- const systemStartClefWidth =
164
+ // The first measure already shows the system-start modifiers.
165
+ const systemStartModifierWidth =
163
166
  clefOnEachSystem &&
167
+ measureIndex > 0 &&
164
168
  measureLeftModifierWidth(
165
169
  staffMeasurementContexts.map((context) => ({
166
170
  ...context,
@@ -187,7 +191,7 @@ export function measureScore(
187
191
  staffBounds,
188
192
  ...(tempoMarkBaselines ? { tempoMarkBaselines } : {}),
189
193
  intrinsicNoteWidth,
190
- ...(systemStartClefWidth ? { systemStartClefWidth } : {}),
194
+ ...(systemStartModifierWidth ? { systemStartModifierWidth } : {}),
191
195
  });
192
196
  } catch (error) {
193
197
  throw new Error(
@@ -272,6 +276,9 @@ function measureStaffVerticalBounds({
272
276
  resolvedState
273
277
  )
274
278
  );
279
+
280
+ alignNoteStarts(renderedStaves);
281
+
275
282
  const staffIndexById = new Map(
276
283
  staves.map((staff, staffIndex) => [staff.id, staffIndex])
277
284
  );
@@ -308,8 +315,8 @@ function measureStaffVerticalBounds({
308
315
  }
309
316
  );
310
317
 
311
- if (allVoices.length > 0 && renderedStaves[0]) {
312
- formatter.formatToStave(allVoices, renderedStaves[0]);
318
+ if (allVoices.length > 0 && renderedStaves.length > 0) {
319
+ formatter.formatToStave(allVoices, getFormatReferenceStave(renderedStaves));
313
320
  }
314
321
 
315
322
  staffMeasurementContexts.forEach(
@@ -5,12 +5,16 @@ import type {
5
5
  RenderContext,
6
6
  } from 'vexflow';
7
7
 
8
+ import { mergeVerseLines, noteVerseLines } from './lyrics';
9
+ import type { VerseLines } from './lyrics';
8
10
  import { hasNoteHeads } from './noteModifiers';
9
11
  import type { VFVoiceNote } from './scoreParsing';
10
12
 
11
13
  export interface StaffVerticalBounds {
12
14
  top: number;
15
+ /** Lowest ink but the lyrics, which sit on `lyrics` verse lines below it. */
13
16
  bottom: number;
17
+ lyrics?: VerseLines;
14
18
  }
15
19
 
16
20
  /**
@@ -92,6 +96,12 @@ export function mergeNoteBounds(
92
96
  if (hasNoteHeads(note)) {
93
97
  mergeBoundingBox(bounds, note.getBoundingBox());
94
98
  }
99
+
100
+ const lyrics = mergeVerseLines(bounds.lyrics, noteVerseLines(note));
101
+
102
+ if (lyrics) {
103
+ bounds.lyrics = lyrics;
104
+ }
95
105
  }
96
106
 
97
107
  function mergeBoundingBox(bounds: StaffVerticalBounds, box: BoundingBox) {
@@ -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;