vexflow-native 1.7.0 → 1.9.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 (129) hide show
  1. package/README.md +33 -348
  2. package/lib/module/base/FontManager.js +0 -0
  3. package/lib/module/base/FontManager.js.map +1 -1
  4. package/lib/module/base/VexflowRecordingContext.js +2 -0
  5. package/lib/module/base/VexflowRecordingContext.js.map +1 -1
  6. package/lib/module/base/index.js +1 -0
  7. package/lib/module/base/index.js.map +1 -1
  8. package/lib/module/musicxml/MusicXmlParser/MeasureParser.js +24 -7
  9. package/lib/module/musicxml/MusicXmlParser/MeasureParser.js.map +1 -1
  10. package/lib/module/musicxml/MusicXmlParser/MusicXmlDirections.js +11 -3
  11. package/lib/module/musicxml/MusicXmlParser/MusicXmlDirections.js.map +1 -1
  12. package/lib/module/musicxml/MusicXmlParser/Spanners.js +21 -5
  13. package/lib/module/musicxml/MusicXmlParser/Spanners.js.map +1 -1
  14. package/lib/module/musicxml/MusicXmlParser/mappers.js +1 -1
  15. package/lib/module/musicxml/MusicXmlParser/mappers.js.map +1 -1
  16. package/lib/module/percussion/index.js +8 -0
  17. package/lib/module/percussion/index.js.map +1 -0
  18. package/lib/module/renderer/ScoreRenderer/ScoreRenderer.js +4 -0
  19. package/lib/module/renderer/ScoreRenderer/ScoreRenderer.js.map +1 -1
  20. package/lib/module/renderer/fixedNoteSpacing.js +56 -0
  21. package/lib/module/renderer/fixedNoteSpacing.js.map +1 -0
  22. package/lib/module/renderer/index.js +1 -0
  23. package/lib/module/renderer/index.js.map +1 -1
  24. package/lib/module/renderer/itemLayout.js +108 -0
  25. package/lib/module/renderer/itemLayout.js.map +1 -0
  26. package/lib/module/renderer/measure.js +31 -102
  27. package/lib/module/renderer/measure.js.map +1 -1
  28. package/lib/module/renderer/measureBounds.js +73 -0
  29. package/lib/module/renderer/measureBounds.js.map +1 -0
  30. package/lib/module/renderer/measureModifiers.js +99 -0
  31. package/lib/module/renderer/measureModifiers.js.map +1 -0
  32. package/lib/module/renderer/noteModifiers.js +212 -0
  33. package/lib/module/renderer/noteModifiers.js.map +1 -0
  34. package/lib/module/renderer/render.js +34 -115
  35. package/lib/module/renderer/render.js.map +1 -1
  36. package/lib/module/renderer/scale.js +16 -2
  37. package/lib/module/renderer/scale.js.map +1 -1
  38. package/lib/module/renderer/scoreParsing.js +37 -188
  39. package/lib/module/renderer/scoreParsing.js.map +1 -1
  40. package/lib/module/renderer/stave.js +37 -0
  41. package/lib/module/renderer/stave.js.map +1 -0
  42. package/lib/module/renderer/useScoreRecording.js +10 -3
  43. package/lib/module/renderer/useScoreRecording.js.map +1 -1
  44. package/lib/module/renderer/vfKeys.js +72 -0
  45. package/lib/module/renderer/vfKeys.js.map +1 -0
  46. package/lib/module/state/index.js +1 -0
  47. package/lib/module/state/index.js.map +1 -1
  48. package/lib/typescript/src/base/FontManager.d.ts +7 -0
  49. package/lib/typescript/src/base/FontManager.d.ts.map +1 -1
  50. package/lib/typescript/src/base/VexflowRecordingContext.d.ts +1 -0
  51. package/lib/typescript/src/base/VexflowRecordingContext.d.ts.map +1 -1
  52. package/lib/typescript/src/base/index.d.ts +1 -0
  53. package/lib/typescript/src/base/index.d.ts.map +1 -1
  54. package/lib/typescript/src/musicxml/MusicXmlParser/InternalTypes.d.ts +4 -2
  55. package/lib/typescript/src/musicxml/MusicXmlParser/InternalTypes.d.ts.map +1 -1
  56. package/lib/typescript/src/musicxml/MusicXmlParser/MeasureParser.d.ts.map +1 -1
  57. package/lib/typescript/src/musicxml/MusicXmlParser/MusicXmlDirections.d.ts +6 -1
  58. package/lib/typescript/src/musicxml/MusicXmlParser/MusicXmlDirections.d.ts.map +1 -1
  59. package/lib/typescript/src/musicxml/MusicXmlParser/Spanners.d.ts +6 -1
  60. package/lib/typescript/src/musicxml/MusicXmlParser/Spanners.d.ts.map +1 -1
  61. package/lib/typescript/src/musicxml/MusicXmlParser/mappers.d.ts.map +1 -1
  62. package/lib/typescript/src/musicxml/index.d.ts +1 -0
  63. package/lib/typescript/src/musicxml/index.d.ts.map +1 -1
  64. package/lib/typescript/src/percussion/index.d.ts +4 -0
  65. package/lib/typescript/src/percussion/index.d.ts.map +1 -0
  66. package/lib/typescript/src/renderer/ScoreRenderer/ScoreRenderer.d.ts.map +1 -1
  67. package/lib/typescript/src/renderer/fixedNoteSpacing.d.ts +17 -0
  68. package/lib/typescript/src/renderer/fixedNoteSpacing.d.ts.map +1 -0
  69. package/lib/typescript/src/renderer/index.d.ts +2 -0
  70. package/lib/typescript/src/renderer/index.d.ts.map +1 -1
  71. package/lib/typescript/src/renderer/itemLayout.d.ts +23 -0
  72. package/lib/typescript/src/renderer/itemLayout.d.ts.map +1 -0
  73. package/lib/typescript/src/renderer/layout.d.ts +1 -1
  74. package/lib/typescript/src/renderer/layout.d.ts.map +1 -1
  75. package/lib/typescript/src/renderer/measure.d.ts +3 -6
  76. package/lib/typescript/src/renderer/measure.d.ts.map +1 -1
  77. package/lib/typescript/src/renderer/measureBounds.d.ts +13 -0
  78. package/lib/typescript/src/renderer/measureBounds.d.ts.map +1 -0
  79. package/lib/typescript/src/renderer/measureModifiers.d.ts +20 -0
  80. package/lib/typescript/src/renderer/measureModifiers.d.ts.map +1 -0
  81. package/lib/typescript/src/renderer/noteModifiers.d.ts +29 -0
  82. package/lib/typescript/src/renderer/noteModifiers.d.ts.map +1 -0
  83. package/lib/typescript/src/renderer/render.d.ts +2 -27
  84. package/lib/typescript/src/renderer/render.d.ts.map +1 -1
  85. package/lib/typescript/src/renderer/scale.d.ts.map +1 -1
  86. package/lib/typescript/src/renderer/scoreParsing.d.ts +14 -40
  87. package/lib/typescript/src/renderer/scoreParsing.d.ts.map +1 -1
  88. package/lib/typescript/src/renderer/stave.d.ts +11 -0
  89. package/lib/typescript/src/renderer/stave.d.ts.map +1 -0
  90. package/lib/typescript/src/renderer/types.d.ts +53 -4
  91. package/lib/typescript/src/renderer/types.d.ts.map +1 -1
  92. package/lib/typescript/src/renderer/useScoreRecording.d.ts +2 -2
  93. package/lib/typescript/src/renderer/useScoreRecording.d.ts.map +1 -1
  94. package/lib/typescript/src/renderer/vfKeys.d.ts +17 -0
  95. package/lib/typescript/src/renderer/vfKeys.d.ts.map +1 -0
  96. package/lib/typescript/src/state/index.d.ts +1 -0
  97. package/lib/typescript/src/state/index.d.ts.map +1 -1
  98. package/lib/typescript/src/state/types.d.ts +39 -6
  99. package/lib/typescript/src/state/types.d.ts.map +1 -1
  100. package/package.json +15 -5
  101. package/src/base/FontManager.ts +0 -0
  102. package/src/base/VexflowRecordingContext.ts +1 -0
  103. package/src/base/index.ts +1 -0
  104. package/src/musicxml/MusicXmlParser/InternalTypes.ts +5 -2
  105. package/src/musicxml/MusicXmlParser/MeasureParser.ts +36 -7
  106. package/src/musicxml/MusicXmlParser/MusicXmlDirections.ts +25 -8
  107. package/src/musicxml/MusicXmlParser/Spanners.ts +27 -4
  108. package/src/musicxml/MusicXmlParser/mappers.ts +7 -0
  109. package/src/musicxml/index.ts +1 -0
  110. package/src/percussion/index.ts +7 -0
  111. package/src/renderer/Layout/VerticalSpacing.ts +1 -1
  112. package/src/renderer/ScoreRenderer/ScoreRenderer.tsx +4 -0
  113. package/src/renderer/fixedNoteSpacing.ts +78 -0
  114. package/src/renderer/index.ts +8 -0
  115. package/src/renderer/itemLayout.ts +137 -0
  116. package/src/renderer/layout.ts +1 -1
  117. package/src/renderer/measure.tsx +85 -182
  118. package/src/renderer/measureBounds.ts +109 -0
  119. package/src/renderer/measureModifiers.ts +133 -0
  120. package/src/renderer/noteModifiers.ts +298 -0
  121. package/src/renderer/render.tsx +66 -171
  122. package/src/renderer/scale.ts +21 -1
  123. package/src/renderer/scoreParsing.tsx +78 -262
  124. package/src/renderer/stave.ts +44 -0
  125. package/src/renderer/types.ts +67 -4
  126. package/src/renderer/useScoreRecording.ts +11 -3
  127. package/src/renderer/vfKeys.ts +88 -0
  128. package/src/state/index.ts +1 -0
  129. package/src/state/types.ts +48 -5
@@ -1,15 +1,8 @@
1
1
  import {
2
- Accidental as VFAccidental,
3
- Articulation as VFArticulation,
4
2
  Beam,
5
- Dot,
6
3
  Element,
7
4
  Fraction as VFFraction,
8
5
  GhostNote,
9
- GraceNote as VFGraceNote,
10
- GraceNoteGroup,
11
- ModifierPosition,
12
- Parenthesis,
13
6
  StaveNote,
14
7
  Stem,
15
8
  Tuplet,
@@ -18,15 +11,11 @@ import {
18
11
  import type { StemmableNote } from 'vexflow';
19
12
 
20
13
  import type {
21
- Articulation,
22
14
  Clef,
15
+ Direction,
23
16
  KeySignature,
24
- DurationValue,
25
- GraceNoteAttachment,
26
17
  Meter,
27
18
  NoteAttachment,
28
- Notehead,
29
- Pitch,
30
19
  Score,
31
20
  Staff,
32
21
  StaffGroup,
@@ -37,6 +26,15 @@ import type {
37
26
  VoiceItem,
38
27
  VoiceTimingMode,
39
28
  } from '../state';
29
+ import {
30
+ applyDots,
31
+ applyMeasureDirections,
32
+ applyNoteModifiers,
33
+ decorateStaveNote,
34
+ restAttachments,
35
+ } from './noteModifiers';
36
+ import { durationToVF, pitchToVFKey, restKeyForStaffLine } from './vfKeys';
37
+ import type { DecorateItem } from './types';
40
38
 
41
39
  export type StaffGroupLookup = {
42
40
  groupId: string;
@@ -60,35 +58,22 @@ export interface MakeVFVoiceOptions {
60
58
  * rebuilding it on every call.
61
59
  */
62
60
  attachmentsByOwner?: Map<string, NoteAttachment[]>;
61
+ /** Owning staff; on a one-line staff auto stems point up. */
62
+ staff?: Staff;
63
+ /** Measure directions drawn on this voice's first drawn item. */
64
+ directions?: Direction[];
65
+ itemContext?: {
66
+ decorateItem: DecorateItem;
67
+ staff: Staff;
68
+ measureIndex: number;
69
+ };
63
70
  }
64
71
 
65
- /**
66
- * Maps library notehead names to VexFlow key glyph codes.
67
- */
68
- export const NOTEHEAD_TO_VF_CODE: Record<Notehead, string> = {
69
- 'x': 'x',
70
- 'circle-x': 'cx',
71
- 'diamond': 'h',
72
- 'circle': 'ci',
73
- 'square': 'sq',
74
- 'triangle': 'tu',
75
- 'triangle-down': 'td',
76
- 'slash': 'sf',
77
- };
78
-
79
- /**
80
- * Maps library articulation names to VexFlow articulation codes.
81
- */
82
- export const ARTICULATION_TO_VF_CODE: Record<Articulation, string> = {
83
- staccato: 'a.',
84
- staccatissimo: 'av',
85
- tenuto: 'a-',
86
- accent: 'a>',
87
- marcato: 'a^',
88
- fermata: 'a@',
89
- open: 'ah',
90
- stopped: 'a+',
91
- };
72
+ type ItemDecorator = (
73
+ item: VoiceItem,
74
+ note: StaveNote,
75
+ attachments: readonly NoteAttachment[]
76
+ ) => void;
92
77
 
93
78
  /**
94
79
  * Maps the library stem direction to the numeric VexFlow value.
@@ -105,197 +90,6 @@ export function toVFStemDirection(dir?: StemDirection): number | undefined {
105
90
  return undefined;
106
91
  }
107
92
 
108
- /**
109
- * Converts an internal pitch into the VexFlow key string format.
110
- */
111
- export function pitchToVFKey(pitch: Pitch): string {
112
- const accidental =
113
- pitch.accidental === 'quarter-flat'
114
- ? 'db'
115
- : pitch.accidental === 'quarter-sharp'
116
- ? 'd#'
117
- : pitch.accidental ?? '';
118
-
119
- const key = `${pitch.step.toLowerCase()}${accidental}/${pitch.octave}`;
120
-
121
- if (pitch.notehead) {
122
- return `${key}/${NOTEHEAD_TO_VF_CODE[pitch.notehead]}`;
123
- }
124
-
125
- return key;
126
- }
127
-
128
- /**
129
- * Converts a duration into the VexFlow duration token, including rests.
130
- */
131
- export function durationToVF(duration: DurationValue, isRest = false): string {
132
- const length =
133
- duration.length === 'long' || duration.length === 'breve'
134
- ? '1/2'
135
- : duration.length;
136
-
137
- // Dots drive VexFlow's tick math, so rests need them in the token too or
138
- // strict voices come up short.
139
- const dots = 'd'.repeat(duration.dots ?? 0);
140
-
141
- return `${length}${dots}${isRest ? 'r' : ''}`;
142
- }
143
-
144
- /**
145
- * Applies the requested number of augmentation dots to a note.
146
- */
147
- export function applyDots(note: StaveNote, dots?: 0 | 1 | 2 | 3) {
148
- for (let i = 0; i < (dots ?? 0); i++) {
149
- Dot.buildAndAttach([note], { all: true });
150
- }
151
- }
152
-
153
- /**
154
- * Adds pitch accidentals to the matching keys in a VexFlow note.
155
- */
156
- export function addPitchAccidentals(
157
- note: StaveNote,
158
- pitches: readonly Pitch[]
159
- ) {
160
- pitches.forEach((pitch, index) => {
161
- if (!pitch.accidental) {
162
- return;
163
- }
164
-
165
- const type =
166
- pitch.accidental === 'quarter-flat'
167
- ? 'db'
168
- : pitch.accidental === 'quarter-sharp'
169
- ? 'd#'
170
- : pitch.accidental;
171
-
172
- note.addModifier(new VFAccidental(type), index);
173
- });
174
- }
175
-
176
- /**
177
- * Wraps each ghost pitch of a note in parentheses.
178
- */
179
- export function applyGhostParentheses(
180
- note: StaveNote,
181
- pitches: readonly Pitch[]
182
- ) {
183
- pitches.forEach((pitch, index) => {
184
- if (!pitch.ghost) {
185
- return;
186
- }
187
-
188
- note.addModifier(new Parenthesis(ModifierPosition.LEFT), index);
189
- note.addModifier(new Parenthesis(ModifierPosition.RIGHT), index);
190
- });
191
- }
192
-
193
- function hasAccentAttachment(attachments: NoteAttachment[] | undefined) {
194
- return (
195
- attachments?.some(
196
- (attachment) =>
197
- attachment.type === 'articulation' &&
198
- attachment.articulation === 'accent'
199
- ) ?? false
200
- );
201
- }
202
-
203
- /**
204
- * Draws one accent above a note whose pitches carry the `accent` flag, unless
205
- * the owner already has an accent attachment.
206
- */
207
- export function applyPitchAccent(
208
- note: StaveNote,
209
- pitches: readonly Pitch[],
210
- attachments?: NoteAttachment[]
211
- ) {
212
- if (!pitches.some((pitch) => pitch.accent)) {
213
- return;
214
- }
215
-
216
- if (hasAccentAttachment(attachments)) {
217
- return;
218
- }
219
-
220
- note.addModifier(new VFArticulation(ARTICULATION_TO_VF_CODE.accent), 0);
221
- }
222
-
223
- /**
224
- * Attaches the owner's articulation and grace-note modifiers to a VexFlow
225
- * note; dynamics and lyrics are drawn elsewhere.
226
- */
227
- export function applyNoteModifiers(
228
- note: StaveNote,
229
- clef: Clef,
230
- attachments: NoteAttachment[] | undefined
231
- ) {
232
- if (!attachments) {
233
- return;
234
- }
235
-
236
- for (const attachment of attachments) {
237
- if (attachment.type === 'articulation') {
238
- const articulation = new VFArticulation(
239
- ARTICULATION_TO_VF_CODE[attachment.articulation]
240
- );
241
-
242
- if (attachment.placement === 'below') {
243
- articulation.setPosition(ModifierPosition.BELOW);
244
- }
245
-
246
- note.addModifier(articulation, 0);
247
- } else if (attachment.type === 'grace') {
248
- applyGraceNoteGroup(note, clef, attachment);
249
- }
250
- }
251
- }
252
-
253
- /**
254
- * Grace notes stem up unless the owner was built stem-down (auto stems that
255
- * flip later in `Beam.generateBeams` are not followed); two or more are
256
- * beamed together, with the acciaccatura slash on the first stem only.
257
- */
258
- function applyGraceNoteGroup(
259
- note: StaveNote,
260
- clef: Clef,
261
- attachment: GraceNoteAttachment
262
- ) {
263
- if (attachment.notes.length === 0) {
264
- return;
265
- }
266
-
267
- const stemDirection =
268
- note.getStemDirection() === Stem.DOWN ? Stem.DOWN : Stem.UP;
269
- const graceNotes = attachment.notes.map((graceNote, index) => {
270
- const vfGraceNote = new VFGraceNote({
271
- clef,
272
- keys: [pitchToVFKey(graceNote.pitch)],
273
- duration: durationToVF(graceNote.duration),
274
- slash: index === 0 && attachment.slash === true,
275
- stemDirection,
276
- });
277
- decorateStaveNote(vfGraceNote, [graceNote.pitch], graceNote.duration);
278
- return vfGraceNote;
279
- });
280
- const group = new GraceNoteGroup(graceNotes);
281
-
282
- if (graceNotes.length > 1) {
283
- group.beamNotes();
284
- }
285
-
286
- note.addModifier(group, 0);
287
- }
288
-
289
- function decorateStaveNote(
290
- note: StaveNote,
291
- pitches: readonly Pitch[],
292
- duration: DurationValue
293
- ) {
294
- addPitchAccidentals(note, pitches);
295
- applyGhostParentheses(note, pitches);
296
- applyDots(note, duration.dots);
297
- }
298
-
299
93
  export function indexAttachmentsByOwner(
300
94
  score: Score
301
95
  ): Map<string, NoteAttachment[]> {
@@ -341,48 +135,55 @@ function spacerTickWidth(): number {
341
135
  export function voiceItemToStaveNote(
342
136
  item: VoiceItem,
343
137
  clef: Clef,
344
- attachments?: NoteAttachment[]
138
+ attachments?: NoteAttachment[],
139
+ decorate?: ItemDecorator
345
140
  ): VFVoiceNote {
346
- if (item.type === 'rest') {
347
- if (item.kind === 'hidden' || item.kind === 'spacer') {
348
- const note = new GhostNote(durationToVF(item.duration));
349
- if (item.kind === 'spacer') {
350
- note.setWidth(spacerTickWidth());
351
- }
352
- return note;
141
+ if (
142
+ item.type === 'rest' &&
143
+ (item.kind === 'hidden' || item.kind === 'spacer')
144
+ ) {
145
+ const note = new GhostNote(durationToVF(item.duration));
146
+
147
+ if (item.kind === 'spacer') {
148
+ note.setWidth(spacerTickWidth());
353
149
  }
354
150
 
355
- const note = new StaveNote({
356
- clef,
357
- keys: ['b/4'],
358
- duration: durationToVF(item.duration, true),
359
- });
360
- applyDots(note, item.duration.dots);
361
151
  return note;
362
152
  }
363
153
 
364
- if (item.type === 'note') {
154
+ const note = buildStaveNote(item, clef);
155
+ const applied =
156
+ (item.type === 'rest' ? restAttachments(attachments) : attachments) ?? [];
157
+
158
+ applyNoteModifiers(note, clef, applied);
159
+ decorate?.(item, note, applied);
160
+
161
+ return note;
162
+ }
163
+
164
+ function buildStaveNote(item: VoiceItem, clef: Clef): StaveNote {
165
+ if (item.type === 'rest') {
365
166
  const note = new StaveNote({
366
167
  clef,
367
- keys: [pitchToVFKey(item.pitch)],
368
- duration: durationToVF(item.duration),
369
- stemDirection: toVFStemDirection(item.stemDirection),
168
+ keys: [restKeyForStaffLine(clef, item.staffLine)],
169
+ duration: durationToVF(item.duration, true),
370
170
  });
371
- decorateStaveNote(note, [item.pitch], item.duration);
372
- applyPitchAccent(note, [item.pitch], attachments);
373
- applyNoteModifiers(note, clef, attachments);
171
+
172
+ applyDots(note, item.duration.dots);
173
+
374
174
  return note;
375
175
  }
376
176
 
177
+ const pitches = item.type === 'note' ? [item.pitch] : item.pitches;
377
178
  const note = new StaveNote({
378
179
  clef,
379
- keys: item.pitches.map(pitchToVFKey),
180
+ keys: pitches.map(pitchToVFKey),
380
181
  duration: durationToVF(item.duration),
381
182
  stemDirection: toVFStemDirection(item.stemDirection),
382
183
  });
383
- decorateStaveNote(note, item.pitches, item.duration);
384
- applyPitchAccent(note, item.pitches, attachments);
385
- applyNoteModifiers(note, clef, attachments);
184
+
185
+ decorateStaveNote(note, pitches, item.duration);
186
+
386
187
  return note;
387
188
  }
388
189
 
@@ -478,13 +279,27 @@ export function makeVFVoice(
478
279
  } {
479
280
  const attachmentsByOwner =
480
281
  options.attachmentsByOwner ?? indexAttachmentsByOwner(score);
481
- const notes = voice.items.map((item) =>
482
- voiceItemToStaveNote(
282
+ const { itemContext } = options;
283
+ const notes = voice.items.map((item) => {
284
+ const itemClef = options.resolveClef?.(item) ?? clef;
285
+ const decorate: ItemDecorator | undefined = itemContext
286
+ ? (decoratedItem, note, attachments) =>
287
+ itemContext.decorateItem(decoratedItem, note, {
288
+ clef: itemClef,
289
+ staff: itemContext.staff,
290
+ measureIndex: itemContext.measureIndex,
291
+ attachments,
292
+ })
293
+ : undefined;
294
+
295
+ return voiceItemToStaveNote(
483
296
  item,
484
- options.resolveClef?.(item) ?? clef,
485
- attachmentsByOwner.get(item.id)
486
- )
487
- );
297
+ itemClef,
298
+ attachmentsByOwner.get(item.id),
299
+ decorate
300
+ );
301
+ });
302
+ applyMeasureDirections(notes, options.directions);
488
303
 
489
304
  const noteByItemId = new Map<string, VFVoiceNote>();
490
305
  voice.items.forEach((item, index) =>
@@ -531,7 +346,8 @@ export function makeVFVoice(
531
346
  }
532
347
 
533
348
  const groups = beamGroupsToVF(meter);
534
- const maintainStemDirections = voice.items.some(hasExplicitStemDirection);
349
+ const maintainStemDirections =
350
+ options.staff?.lines === 1 || voice.items.some(hasExplicitStemDirection);
535
351
  const beamOptions =
536
352
  groups || maintainStemDirections
537
353
  ? {
@@ -0,0 +1,44 @@
1
+ import type { Stave } from 'vexflow';
2
+
3
+ import type { StaffLines } from '../state';
4
+
5
+ /**
6
+ * Indices (0 = top) of the lines a `lines`-line staff draws on five-line
7
+ * geometry: the middle line plus `lines - 1` around it.
8
+ */
9
+ function visibleLineIndices(lineCount: number, lines?: StaffLines): number[] {
10
+ const middleLine = (lineCount - 1) / 2;
11
+ const reach = ((lines ?? lineCount) - 1) / 2;
12
+
13
+ return Array.from({ length: lineCount }, (_, index) => index).filter(
14
+ (index) => Math.abs(index - middleLine) <= reach
15
+ );
16
+ }
17
+
18
+ /**
19
+ * Hides the outer lines of a 5-line stave so `lines` stay visible around the
20
+ * middle one. Must run after construction: the constructor resets the line
21
+ * config.
22
+ */
23
+ export function applyStaffLines(stave: Stave, lines?: StaffLines): Stave {
24
+ const lineCount = stave.getNumLines();
25
+
26
+ if (lines === undefined || lines === lineCount) {
27
+ return stave;
28
+ }
29
+
30
+ const visible = new Set(visibleLineIndices(lineCount, lines));
31
+
32
+ return stave.setConfigForLines(
33
+ Array.from({ length: lineCount }, (_, index) => ({
34
+ visible: visible.has(index),
35
+ }))
36
+ );
37
+ }
38
+
39
+ /** Stroke centre y of every drawn line of a rendered stave, top to bottom. */
40
+ export function visibleLineYs(stave: Stave, lines?: StaffLines): number[] {
41
+ return visibleLineIndices(stave.getNumLines(), lines).map((index) =>
42
+ stave.getYForLine(index)
43
+ );
44
+ }
@@ -1,8 +1,9 @@
1
1
  import type { SkTypefaceFontProvider } from '@shopify/react-native-skia';
2
2
  import type { SharedValue } from 'react-native-reanimated';
3
+ import type { RenderContext, StaveNote } from 'vexflow';
3
4
 
4
5
  import type { VexflowStyleOverride } from '../base';
5
- import type { Score } from '../state';
6
+ import type { Clef, NoteAttachment, Score, Staff, VoiceItem } from '../state';
6
7
  import type { ScoreColorScheme } from './colorScheme';
7
8
 
8
9
  export type RendererType = 'infiniteScore' | 'document' | 'documentEven';
@@ -47,7 +48,48 @@ export interface ScoreScrollGeometry {
47
48
  maxScroll: number;
48
49
  }
49
50
 
50
- export interface ScoreRendererProps {
51
+ /** Where a voice item sits when its VexFlow note is built. */
52
+ export interface ScoreItemContext {
53
+ clef: Clef;
54
+ staff: Staff;
55
+ measureIndex: number;
56
+ /** For rests, the rest-eligible subset (everything but grace). */
57
+ attachments: readonly NoteAttachment[];
58
+ }
59
+
60
+ /**
61
+ * Called once per drawable item (not hidden/spacer rests) in BOTH the
62
+ * measurement and the drawing pass, after the item's own attachments are
63
+ * applied, before measure directions and before formatting, so added
64
+ * modifiers count in width and vertical bounds. Must be deterministic in its
65
+ * inputs; `note` is rebuilt on every pass.
66
+ */
67
+ export type DecorateItem = (
68
+ item: VoiceItem,
69
+ note: StaveNote,
70
+ context: ScoreItemContext
71
+ ) => void;
72
+
73
+ /**
74
+ * Called in the drawing pass only, right after the note and its modifiers
75
+ * are drawn, inside the item's color group. `layout` is the item's geometry
76
+ * in content space — the space `ctx` draws in (VexFlow units before
77
+ * `render.scale`); `onItemsLayout` receives the same entry scaled to view
78
+ * space.
79
+ */
80
+ export type DrawItem = (
81
+ ctx: RenderContext,
82
+ item: VoiceItem,
83
+ note: StaveNote,
84
+ layout: Readonly<ScoreItemLayout>
85
+ ) => void;
86
+
87
+ export interface ScoreItemHooks {
88
+ decorateItem?: DecorateItem;
89
+ onDrawItem?: DrawItem;
90
+ }
91
+
92
+ export interface ScoreRendererProps extends ScoreItemHooks {
51
93
  score: Score;
52
94
  defaultFont: string;
53
95
  fontManager: SkTypefaceFontProvider;
@@ -158,6 +200,19 @@ export interface ScoreItemLayout {
158
200
  */
159
201
  headCenterX: number;
160
202
  measureIndex: number;
203
+ /**
204
+ * Union box of the item's drawn modifiers (articulations, annotations,
205
+ * dynamics, lyrics, grace notes, parentheses, accidentals, dots), in the
206
+ * same space as `x`. undefined when the item has no modifiers.
207
+ */
208
+ modifierBounds?: ScoreItemBounds;
209
+ }
210
+
211
+ export interface ScoreItemBounds {
212
+ left: number;
213
+ right: number;
214
+ top: number;
215
+ bottom: number;
161
216
  }
162
217
 
163
218
  /**
@@ -182,10 +237,18 @@ export interface ScoreMeasureItemsLayout {
182
237
  y: number;
183
238
  /** Height of the measure's system block. */
184
239
  height: number;
185
- /** Top edge of this stave's top staff line. */
240
+ /** Top edge of this stave's top staff line (hidden lines included). */
186
241
  staveLineTopY: number;
187
- /** Bottom edge of this stave's bottom staff line. */
242
+ /** Bottom edge of this stave's bottom staff line (hidden lines included). */
188
243
  staveLineBottomY: number;
244
+ /**
245
+ * Stroke centre y of each drawn line, top to bottom (5, 3 or 1 entries).
246
+ * On a five-line staff `visibleLineYs[0] === staveLineTopY` and the last
247
+ * entry is `staveLineBottomY - lineWidth`; with hidden lines
248
+ * `staveLineTopY`/`staveLineBottomY` still span the five-line geometry, so
249
+ * read the drawn line from here. Always emitted by the renderer.
250
+ */
251
+ visibleLineYs?: number[];
189
252
  }
190
253
 
191
254
  /**
@@ -21,6 +21,7 @@ import type { ResolvedScoreColorScheme } from './colorScheme';
21
21
  import type {
22
22
  RendererRect,
23
23
  RendererType,
24
+ ScoreItemHooks,
24
25
  ScoreItemsLayout,
25
26
  ScoreOptions,
26
27
  } from './types';
@@ -43,15 +44,17 @@ export interface ScoreRecording {
43
44
  }
44
45
 
45
46
  export function useScoreRecording({
47
+ decorateItem,
46
48
  defaultFont,
47
49
  enabled = true,
48
50
  fontManager,
49
51
  colorScheme,
52
+ onDrawItem,
50
53
  options,
51
54
  rendererType,
52
55
  score,
53
56
  viewport,
54
- }: {
57
+ }: ScoreItemHooks & {
55
58
  defaultFont: string;
56
59
  enabled?: boolean;
57
60
  fontManager: SkTypefaceFontProvider;
@@ -82,7 +85,7 @@ export function useScoreRecording({
82
85
  defaultFont,
83
86
  colorScheme
84
87
  );
85
- const measuredScore = measureScore(score, options);
88
+ const measuredScore = measureScore(score, options, { decorateItem });
86
89
  const measureMs = nowMs() - measureStart;
87
90
 
88
91
  const layoutStart = nowMs();
@@ -97,7 +100,10 @@ export function useScoreRecording({
97
100
 
98
101
  const renderStart = nowMs();
99
102
  const itemsLayout = scaleItemsLayoutToViewSpace(
100
- renderScore(ctx, score, layoutPlan, options),
103
+ renderScore(ctx, score, layoutPlan, options, {
104
+ decorateItem,
105
+ onDrawItem,
106
+ }),
101
107
  scale
102
108
  );
103
109
  const renderMs = nowMs() - renderStart;
@@ -130,9 +136,11 @@ export function useScoreRecording({
130
136
  };
131
137
  }, [
132
138
  colorScheme,
139
+ decorateItem,
133
140
  defaultFont,
134
141
  enabled,
135
142
  fontManager,
143
+ onDrawItem,
136
144
  options,
137
145
  rendererType,
138
146
  score,
@@ -0,0 +1,88 @@
1
+ import type { Clef, DurationValue, Notehead, Pitch, Rest } from '../state';
2
+
3
+ /**
4
+ * Maps library notehead names to VexFlow key glyph codes.
5
+ */
6
+ const NOTEHEAD_TO_VF_CODE: Record<Notehead, string> = {
7
+ 'x': 'x',
8
+ 'circle-x': 'cx',
9
+ 'diamond': 'h',
10
+ 'circle': 'ci',
11
+ 'square': 'sq',
12
+ 'triangle': 'tu',
13
+ 'triangle-down': 'td',
14
+ 'slash': 'sf',
15
+ };
16
+
17
+ /**
18
+ * Converts an internal pitch into the VexFlow key string format.
19
+ */
20
+ export function pitchToVFKey(pitch: Pitch): string {
21
+ const accidental =
22
+ pitch.accidental === 'quarter-flat'
23
+ ? 'db'
24
+ : pitch.accidental === 'quarter-sharp'
25
+ ? 'd#'
26
+ : pitch.accidental ?? '';
27
+
28
+ const key = `${pitch.step.toLowerCase()}${accidental}/${pitch.octave}`;
29
+
30
+ if (pitch.notehead) {
31
+ return `${key}/${NOTEHEAD_TO_VF_CODE[pitch.notehead]}`;
32
+ }
33
+
34
+ return key;
35
+ }
36
+
37
+ const STEPS = ['c', 'd', 'e', 'f', 'g', 'a', 'b'] as const;
38
+ const MIDDLE_STAFF_LINE = 2;
39
+
40
+ /** Staff lines a pitch moves up from its treble position (VexFlow tables). */
41
+ const CLEF_LINE_SHIFT: Record<Clef, number> = {
42
+ 'treble': 0,
43
+ 'bass': 6,
44
+ 'alto': 3,
45
+ 'tenor': 4,
46
+ 'soprano': 1,
47
+ 'mezzo-soprano': 2,
48
+ 'baritone-c': 5,
49
+ 'baritone-f': 5,
50
+ 'subbass': 7,
51
+ 'french': -1,
52
+ 'percussion': 0,
53
+ 'tab': 0,
54
+ };
55
+
56
+ /**
57
+ * VexFlow key placing a rest on `staffLine` (0 = bottom line … 4 = top line,
58
+ * undefined = middle line) under `clef`. VexFlow lines are pitch-based per
59
+ * clef, so the key is the treble pitch of the line minus the clef's shift,
60
+ * counting diatonic steps from c/4 (the ledger line below a treble staff).
61
+ */
62
+ export function restKeyForStaffLine(
63
+ clef: Clef,
64
+ staffLine: Rest['staffLine']
65
+ ): string {
66
+ const line = (staffLine ?? MIDDLE_STAFF_LINE) + 1;
67
+ const diatonicIndex = 2 * (line - CLEF_LINE_SHIFT[clef]);
68
+ const step = STEPS[((diatonicIndex % 7) + 7) % 7]!;
69
+ const octave = 4 + Math.floor(diatonicIndex / 7);
70
+
71
+ return `${step}/${octave}`;
72
+ }
73
+
74
+ /**
75
+ * Converts a duration into the VexFlow duration token, including rests.
76
+ */
77
+ export function durationToVF(duration: DurationValue, isRest = false): string {
78
+ const length =
79
+ duration.length === 'long' || duration.length === 'breve'
80
+ ? '1/2'
81
+ : duration.length;
82
+
83
+ // Dots drive VexFlow's tick math, so rests need them in the token too or
84
+ // strict voices come up short.
85
+ const dots = 'd'.repeat(duration.dots ?? 0);
86
+
87
+ return `${length}${dots}${isRest ? 'r' : ''}`;
88
+ }