vexflow 5.0.0-alpha.2 → 5.0.0-alpha.4

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 (157) hide show
  1. package/build/cjs/vexflow-bravura.js +2 -2
  2. package/build/cjs/vexflow-bravura.js.map +1 -1
  3. package/build/cjs/vexflow-core.js +2 -2
  4. package/build/cjs/vexflow-core.js.map +1 -1
  5. package/build/cjs/vexflow-debug-with-tests.js +528 -492
  6. package/build/cjs/vexflow-debug-with-tests.js.map +1 -1
  7. package/build/cjs/vexflow-debug.js +460 -452
  8. package/build/cjs/vexflow-debug.js.map +1 -1
  9. package/build/cjs/vexflow.js +2 -2
  10. package/build/cjs/vexflow.js.map +1 -1
  11. package/build/esm/src/accidental.js +22 -28
  12. package/build/esm/src/beam.js +24 -42
  13. package/build/esm/src/clefnote.js +6 -1
  14. package/build/esm/src/element.js +83 -101
  15. package/build/esm/src/fonts/gonville.js +1 -1
  16. package/build/esm/src/formatter.js +9 -17
  17. package/build/esm/src/fraction.js +15 -22
  18. package/build/esm/src/glyphnote.js +3 -2
  19. package/build/esm/src/metrics.js +3 -0
  20. package/build/esm/src/modifier.js +6 -21
  21. package/build/esm/src/multimeasurerest.js +16 -25
  22. package/build/esm/src/note.js +7 -0
  23. package/build/esm/src/registry.js +5 -19
  24. package/build/esm/src/stave.js +4 -6
  25. package/build/esm/src/stavenote.js +26 -40
  26. package/build/esm/src/stavetempo.js +4 -11
  27. package/build/esm/src/stavetie.js +82 -36
  28. package/build/esm/src/svgcontext.js +5 -12
  29. package/build/esm/src/tickable.js +13 -26
  30. package/build/esm/src/tickcontext.js +20 -2
  31. package/build/esm/src/version.js +3 -3
  32. package/build/esm/src/vibrato.js +6 -1
  33. package/build/esm/tests/clef_tests.js +5 -1
  34. package/build/esm/tests/glyphnote_tests.js +6 -0
  35. package/build/esm/tests/stavetie_tests.js +29 -0
  36. package/build/esm/tests/tabstave_tests.js +1 -0
  37. package/build/esm/tests/vexflow_test_helpers.js +25 -39
  38. package/build/types/src/accidental.d.ts +19 -1
  39. package/build/types/src/annotation.d.ts +1 -1
  40. package/build/types/src/beam.d.ts +12 -1
  41. package/build/types/src/clefnote.d.ts +2 -0
  42. package/build/types/src/element.d.ts +13 -3
  43. package/build/types/src/fonts/gonville.d.ts +1 -1
  44. package/build/types/src/formatter.d.ts +5 -3
  45. package/build/types/src/fraction.d.ts +12 -7
  46. package/build/types/src/modifier.d.ts +2 -1
  47. package/build/types/src/multimeasurerest.d.ts +4 -1
  48. package/build/types/src/note.d.ts +2 -0
  49. package/build/types/src/registry.d.ts +1 -1
  50. package/build/types/src/stavenote.d.ts +2 -1
  51. package/build/types/src/stavetempo.d.ts +3 -3
  52. package/build/types/src/stavetie.d.ts +39 -2
  53. package/build/types/src/svgcontext.d.ts +1 -1
  54. package/build/types/src/tickable.d.ts +2 -1
  55. package/build/types/src/tickcontext.d.ts +30 -0
  56. package/package.json +2 -4
  57. package/tests/flow.html +2 -2
  58. package/entry/vexflow-bravura.ts +0 -25
  59. package/entry/vexflow-core.ts +0 -16
  60. package/entry/vexflow-debug-with-tests.ts +0 -64
  61. package/entry/vexflow-debug.ts +0 -54
  62. package/entry/vexflow.ts +0 -47
  63. package/src/accidental.ts +0 -570
  64. package/src/annotation.ts +0 -294
  65. package/src/articulation.ts +0 -383
  66. package/src/barnote.ts +0 -95
  67. package/src/beam.ts +0 -999
  68. package/src/bend.ts +0 -268
  69. package/src/boundingbox.ts +0 -108
  70. package/src/canvascontext.ts +0 -348
  71. package/src/chordsymbol.ts +0 -473
  72. package/src/clef.ts +0 -164
  73. package/src/clefnote.ts +0 -50
  74. package/src/crescendo.ts +0 -132
  75. package/src/curve.ts +0 -195
  76. package/src/dot.ts +0 -171
  77. package/src/easyscore.ts +0 -538
  78. package/src/element.ts +0 -692
  79. package/src/factory.ts +0 -694
  80. package/src/font.ts +0 -343
  81. package/src/fonts/academico.ts +0 -2
  82. package/src/fonts/academicobold.ts +0 -2
  83. package/src/fonts/bravura.ts +0 -2
  84. package/src/fonts/gonville.ts +0 -2
  85. package/src/fonts/petaluma.ts +0 -2
  86. package/src/fonts/petalumascript.ts +0 -2
  87. package/src/formatter.ts +0 -1107
  88. package/src/fraction.ts +0 -245
  89. package/src/frethandfinger.ts +0 -180
  90. package/src/ghostnote.ts +0 -75
  91. package/src/glyphnote.ts +0 -68
  92. package/src/glyphs.ts +0 -5880
  93. package/src/gracenote.ts +0 -146
  94. package/src/gracenotegroup.ts +0 -194
  95. package/src/gracetabnote.ts +0 -30
  96. package/src/index.ts +0 -90
  97. package/src/keymanager.ts +0 -153
  98. package/src/keysignature.ts +0 -272
  99. package/src/keysignote.ts +0 -46
  100. package/src/metrics.ts +0 -222
  101. package/src/modifier.ts +0 -216
  102. package/src/modifiercontext.ts +0 -177
  103. package/src/multimeasurerest.ts +0 -229
  104. package/src/music.ts +0 -443
  105. package/src/note.ts +0 -690
  106. package/src/notehead.ts +0 -158
  107. package/src/notesubgroup.ts +0 -88
  108. package/src/ornament.ts +0 -301
  109. package/src/parenthesis.ts +0 -89
  110. package/src/parser.ts +0 -263
  111. package/src/pedalmarking.ts +0 -273
  112. package/src/registry.ts +0 -146
  113. package/src/rendercontext.ts +0 -98
  114. package/src/renderer.ts +0 -166
  115. package/src/repeatnote.ts +0 -25
  116. package/src/stave.ts +0 -885
  117. package/src/stavebarline.ts +0 -231
  118. package/src/staveconnector.ts +0 -281
  119. package/src/stavehairpin.ts +0 -209
  120. package/src/staveline.ts +0 -343
  121. package/src/stavemodifier.ts +0 -93
  122. package/src/stavenote.ts +0 -1230
  123. package/src/staverepetition.ts +0 -148
  124. package/src/stavesection.ts +0 -54
  125. package/src/stavetempo.ts +0 -162
  126. package/src/stavetext.ts +0 -69
  127. package/src/stavetie.ts +0 -235
  128. package/src/stavevolta.ts +0 -66
  129. package/src/stem.ts +0 -225
  130. package/src/stemmablenote.ts +0 -248
  131. package/src/stringnumber.ts +0 -286
  132. package/src/strokes.ts +0 -214
  133. package/src/svgcontext.ts +0 -639
  134. package/src/system.ts +0 -327
  135. package/src/tables.ts +0 -796
  136. package/src/tabnote.ts +0 -449
  137. package/src/tabslide.ts +0 -115
  138. package/src/tabstave.ts +0 -31
  139. package/src/tabtie.ts +0 -44
  140. package/src/textbracket.ts +0 -231
  141. package/src/textdynamics.ts +0 -101
  142. package/src/textnote.ts +0 -175
  143. package/src/tickable.ts +0 -374
  144. package/src/tickcontext.ts +0 -280
  145. package/src/timesignature.ts +0 -229
  146. package/src/timesignote.ts +0 -45
  147. package/src/tremolo.ts +0 -51
  148. package/src/tuning.ts +0 -90
  149. package/src/tuplet.ts +0 -349
  150. package/src/typeguard.ts +0 -136
  151. package/src/util.ts +0 -169
  152. package/src/version.ts +0 -4
  153. package/src/vexflow.ts +0 -378
  154. package/src/vibrato.ts +0 -99
  155. package/src/vibratobracket.ts +0 -81
  156. package/src/voice.ts +0 -302
  157. package/src/web.ts +0 -35
package/src/formatter.ts DELETED
@@ -1,1107 +0,0 @@
1
- // Copyright (c) 2023-present VexFlow contributors: https://github.com/vexflow/vexflow/graphs/contributors
2
- // MIT License
3
-
4
- import { Beam } from './beam';
5
- import { BoundingBox } from './boundingbox';
6
- import { Fraction } from './fraction';
7
- import { Metrics } from './metrics';
8
- import { ModifierContext } from './modifiercontext';
9
- import { RenderContext } from './rendercontext';
10
- import { Stave } from './stave';
11
- import { StaveConnector } from './staveconnector';
12
- import { StemmableNote } from './stemmablenote';
13
- import { Tables } from './tables';
14
- import { TabNote } from './tabnote';
15
- import { TabStave } from './tabstave';
16
- import { Tickable } from './tickable';
17
- import { TickContext } from './tickcontext';
18
- import { isNote, isStaveNote } from './typeguard';
19
- import { defined, log, midLine, RuntimeError, sumArray } from './util';
20
- import { Voice } from './voice';
21
-
22
- interface Distance {
23
- maxNegativeShiftPx: number;
24
- expectedDistance: number;
25
- fromTickable?: Tickable;
26
- errorPx?: number;
27
- fromTickablePx?: number;
28
- }
29
-
30
- export interface FormatterOptions {
31
- /** Defaults to Tables.SOFTMAX_FACTOR. */
32
- softmaxFactor?: number;
33
-
34
- /** Defaults to `false`. */
35
- globalSoftmax?: boolean;
36
-
37
- /** Defaults to 5. */
38
- maxIterations?: number;
39
- }
40
-
41
- export interface FormatParams {
42
- alignRests?: boolean;
43
- stave?: Stave;
44
- context?: RenderContext;
45
- autoBeam?: boolean;
46
- }
47
-
48
- export interface AlignmentContexts<T> {
49
- list: number[];
50
- map: Record<number, T>;
51
- array: T[];
52
- resolutionMultiplier: number;
53
- }
54
-
55
- export interface AlignmentModifierContexts {
56
- map: Map<Stave | undefined, Record<number, ModifierContext>>;
57
- array: ModifierContext[];
58
- resolutionMultiplier: number;
59
- }
60
-
61
- type addToContextFn<T> = (tickable: Tickable, context: T, voiceIndex: number) => void;
62
- type makeContextFn<T> = (tick?: { tickID: number }) => T;
63
-
64
- /**
65
- * Create `Alignment`s for each tick in `voices`. Also calculate the
66
- * total number of ticks in voices.
67
- */
68
- function createContexts<T>(
69
- voices: Voice[],
70
- makeContext: makeContextFn<T>,
71
- addToContext: addToContextFn<T>
72
- ): AlignmentContexts<T> {
73
- if (voices.length === 0)
74
- return {
75
- map: {},
76
- array: [],
77
- list: [],
78
- resolutionMultiplier: 0,
79
- };
80
-
81
- // Initialize tick maps.
82
- const tickToContextMap: Record<number, T> = {};
83
- const tickList: number[] = [];
84
- const contexts: T[] = [];
85
- const resolutionMultiplier = Formatter.getResolutionMultiplier(voices);
86
- // For each voice, extract notes and create a context for every
87
- // new tick that hasn't been seen before.
88
- voices.forEach((voice, voiceIndex) => {
89
- // Use resolution multiplier as denominator so that no additional expansion
90
- // of fractional tick values is needed.
91
- const ticksUsed = new Fraction(0, resolutionMultiplier);
92
-
93
- voice.getTickables().forEach((tickable) => {
94
- const integerTicks = ticksUsed.numerator;
95
-
96
- // If we have no tick context for this tick, create one.
97
- if (!tickToContextMap[integerTicks]) {
98
- const newContext = makeContext({ tickID: integerTicks });
99
- contexts.push(newContext);
100
- tickToContextMap[integerTicks] = newContext;
101
- // Maintain a list of unique integerTicks.
102
- tickList.push(integerTicks);
103
- }
104
-
105
- // Add this tickable to the TickContext.
106
- addToContext(tickable, tickToContextMap[integerTicks], voiceIndex);
107
- ticksUsed.add(tickable.getTicks());
108
- });
109
- });
110
-
111
- return {
112
- map: tickToContextMap,
113
- array: contexts,
114
- list: tickList.sort((a, b) => a - b),
115
- resolutionMultiplier,
116
- };
117
- }
118
-
119
- // eslint-disable-next-line
120
- function L(...args: any[]) {
121
- if (Formatter.DEBUG) log('VexFlow.Formatter', args);
122
- }
123
-
124
- /**
125
- * Get the rest line number of the next non-rest note(s).
126
- * @param notes array of Notes
127
- * @param currRestLine
128
- * @param currNoteIndex current note index
129
- * @param compare if true, return the midpoint between the current rest line and the next rest line
130
- * @returns a line number, which determines the vertical position of a rest.
131
- */
132
- function getRestLineForNextNoteGroup(
133
- notes: Tickable[],
134
- currRestLine: number,
135
- currNoteIndex: number,
136
- compare: boolean
137
- ): number {
138
- // If no valid next note group, nextRestLine is same as current.
139
- let nextRestLine = currRestLine;
140
-
141
- // Start with the next note and keep going until we find a valid non-rest note group.
142
- for (let noteIndex = currNoteIndex + 1; noteIndex < notes.length; noteIndex++) {
143
- const note = notes[noteIndex];
144
- if (isNote(note) && !note.isRest() && !note.shouldIgnoreTicks()) {
145
- nextRestLine = note.getLineForRest();
146
- break;
147
- }
148
- }
149
-
150
- // Locate the mid point between two lines.
151
- if (compare && currRestLine !== nextRestLine) {
152
- const top = Math.max(currRestLine, nextRestLine);
153
- const bot = Math.min(currRestLine, nextRestLine);
154
- nextRestLine = midLine(top, bot);
155
- }
156
- return nextRestLine;
157
- }
158
-
159
- /**
160
- * Format implements the formatting and layout algorithms that are used
161
- * to position notes in a voice. The algorithm can align multiple voices both
162
- * within a stave, and across multiple staves.
163
- *
164
- * To do this, the formatter breaks up voices into a grid of rational-valued
165
- * `ticks`, to which each note is assigned. Then, minimum widths are assigned
166
- * to each tick based on the widths of the notes and modifiers in that tick. This
167
- * establishes the smallest amount of space required for each tick.
168
- *
169
- * Finally, the formatter distributes the left over space proportionally to
170
- * all the ticks, setting the `x` values of the notes in each tick.
171
- *
172
- * See `tests/formatter_tests.ts` for usage examples. The helper functions included
173
- * here (`FormatAndDraw`, `FormatAndDrawTab`) also serve as useful usage examples.
174
- */
175
- export class Formatter {
176
- // To enable logging for this class. Set `VexFlow.Formatter.DEBUG` to `true`.
177
- static DEBUG: boolean = false;
178
- protected hasMinTotalWidth: boolean;
179
- protected minTotalWidth: number;
180
- protected contextGaps: {
181
- total: number;
182
- gaps: { x1: number; x2: number }[];
183
- };
184
- protected justifyWidth: number;
185
- protected totalCost: number;
186
- protected totalShift: number;
187
- protected tickContexts: AlignmentContexts<TickContext>;
188
- protected formatterOptions: Required<FormatterOptions>;
189
- protected modifierContexts: AlignmentModifierContexts[];
190
- protected voices: Voice[];
191
- protected lossHistory: number[];
192
- protected durationStats: Record<string, { mean: number; count: number }>;
193
-
194
- /**
195
- * Helper function to layout "notes" one after the other without
196
- * regard for proportions. Useful for tests and debugging.
197
- */
198
- static SimpleFormat(notes: Tickable[], x = 0, { paddingBetween = 10 } = {}): void {
199
- notes.reduce((accumulator, note) => {
200
- note.addToModifierContext(new ModifierContext());
201
- const tick = new TickContext().addTickable(note).preFormat();
202
- const metrics = tick.getMetrics();
203
- tick.setX(accumulator + metrics.totalLeftPx);
204
-
205
- return accumulator + tick.getWidth() + metrics.totalRightPx + paddingBetween;
206
- }, x);
207
- }
208
-
209
- /** Helper function to plot formatter debug info. */
210
- static plotDebugging(
211
- ctx: RenderContext,
212
- formatter: Formatter,
213
- xPos: number,
214
- y1: number,
215
- y2: number,
216
- options?: { stavePadding: number }
217
- ): void {
218
- options = {
219
- stavePadding: Metrics.get('Stave.padding'),
220
- ...options,
221
- };
222
-
223
- const x = xPos + options.stavePadding;
224
- const contextGaps = formatter.contextGaps;
225
-
226
- function stroke(x1: number, x2: number, color: string) {
227
- ctx.beginPath();
228
- ctx.setStrokeStyle(color);
229
- ctx.setFillStyle(color);
230
- ctx.setLineWidth(1);
231
- ctx.fillRect(x1, y1, Math.max(x2 - x1, 0), y2 - y1);
232
- }
233
-
234
- ctx.save();
235
- ctx.setFont(Metrics.get('fontFamily'), 8);
236
-
237
- contextGaps.gaps.forEach((gap) => {
238
- stroke(x + gap.x1, x + gap.x2, 'rgba(100,200,100,0.4)');
239
- ctx.setFillStyle('green');
240
- ctx.fillText(Math.round(gap.x2 - gap.x1).toString(), x + gap.x1, y2 + 12);
241
- });
242
-
243
- ctx.setFillStyle('red');
244
- ctx.fillText(
245
- `Loss: ${(formatter.totalCost ?? 0).toFixed(2)} Shift: ${(formatter.totalShift ?? 0).toFixed(
246
- 2
247
- )} Gap: ${contextGaps.total.toFixed(2)}`,
248
- x - 20,
249
- y2 + 27
250
- );
251
- ctx.restore();
252
- }
253
-
254
- /**
255
- * Helper function to format and draw a single voice. Returns a bounding
256
- * box for the notation.
257
- * @param ctx the rendering context
258
- * @param stave the stave to which to draw (`Stave` or `TabStave`)
259
- * @param notes array of `Note` instances (`Note`, `TextNote`, `TabNote`, etc.)
260
- * @param params one of below:
261
- * * Setting `autoBeam` only `(context, stave, notes, true)` or
262
- * `(ctx, stave, notes, {autoBeam: true})`
263
- * * Setting `alignRests` a struct is needed `(context, stave, notes, {alignRests: true})`
264
- * * Setting both a struct is needed `(context, stave, notes, {
265
- * autoBeam: true, alignRests: true})`
266
- * * `autoBeam` automatically generates beams for the notes.
267
- * * `alignRests` aligns rests with nearby notes.
268
- */
269
- static FormatAndDraw(
270
- ctx: RenderContext,
271
- stave: Stave,
272
- notes: StemmableNote[],
273
- params?: FormatParams | boolean
274
- ): BoundingBox | undefined {
275
- let options = {
276
- autoBeam: false,
277
- alignRests: false,
278
- };
279
-
280
- if (typeof params === 'object') {
281
- options = { ...options, ...params };
282
- } else if (typeof params === 'boolean') {
283
- options.autoBeam = params;
284
- }
285
-
286
- // Start by creating a voice and adding all the notes to it.
287
- const voice = new Voice(Tables.TIME4_4).setMode(Voice.Mode.SOFT).addTickables(notes);
288
-
289
- // Then create beams, if requested.
290
- const beams = options.autoBeam ? Beam.applyAndGetBeams(voice) : [];
291
-
292
- // Instantiate a `Formatter` and format the notes.
293
- new Formatter()
294
- .joinVoices([voice]) // , { alignRests: options.alignRests })
295
- .formatToStave([voice], stave, { alignRests: options.alignRests, stave });
296
-
297
- // Render the voice and beams to the stave.
298
- voice.setStave(stave).draw(ctx, stave);
299
- beams.forEach((beam) => beam.setContext(ctx).draw());
300
-
301
- // Return the bounding box of the voice.
302
- return voice.getBoundingBox();
303
- }
304
-
305
- /**
306
- * Helper function to format and draw aligned tab and stave notes in two
307
- * separate staves.
308
- * @param ctx the rendering context
309
- * @param tabstave a `TabStave` instance on which to render `TabNote`s.
310
- * @param stave a `Stave` instance on which to render `Note`s.
311
- * @param notes array of `Note` instances for the stave (`Note`, `BarNote`, etc.)
312
- * @param tabnotes array of `Note` instances for the tab stave (`TabNote`, `BarNote`, etc.)
313
- * @param autoBeam automatically generate beams.
314
- * @param params a configuration object:
315
- * * `autoBeam` automatically generates beams for the notes.
316
- * * `alignRests` aligns rests with nearby notes.
317
- */
318
- static FormatAndDrawTab(
319
- ctx: RenderContext,
320
- tabstave: TabStave,
321
- stave: Stave,
322
- tabnotes: TabNote[],
323
- notes: Tickable[],
324
- autoBeam: boolean,
325
- params: FormatParams
326
- ): void {
327
- let opts = {
328
- autoBeam,
329
- alignRests: false,
330
- };
331
-
332
- if (typeof params === 'object') {
333
- opts = { ...opts, ...params };
334
- } else if (typeof params === 'boolean') {
335
- opts.autoBeam = params;
336
- }
337
-
338
- // Create a `4/4` voice for `notes`.
339
- const notevoice = new Voice(Tables.TIME4_4).setMode(Voice.Mode.SOFT).addTickables(notes);
340
-
341
- // Create a `4/4` voice for `tabnotes`.
342
- const tabvoice = new Voice(Tables.TIME4_4).setMode(Voice.Mode.SOFT).addTickables(tabnotes);
343
-
344
- // Then create beams, if requested.
345
- const beams = opts.autoBeam ? Beam.applyAndGetBeams(notevoice) : [];
346
-
347
- // Instantiate a `Formatter` and align tab and stave notes.
348
- new Formatter()
349
- .joinVoices([notevoice]) // , { alignRests: opts.alignRests })
350
- .joinVoices([tabvoice])
351
- .formatToStave([notevoice, tabvoice], stave, { alignRests: opts.alignRests });
352
-
353
- // Render voices and beams to staves.
354
- notevoice.draw(ctx, stave);
355
- tabvoice.draw(ctx, tabstave);
356
- beams.forEach((beam) => beam.setContext(ctx).draw());
357
-
358
- // Draw a connector between tab and note staves.
359
- new StaveConnector(stave, tabstave).setContext(ctx).draw();
360
- }
361
-
362
- /**
363
- * Automatically set the vertical position of rests based on previous/next note positions.
364
- * @param tickables an array of Tickables.
365
- * @param alignAllNotes If `false`, only align rests that are within a group of beamed notes.
366
- * @param alignTuplets If `false`, ignores tuplets.
367
- */
368
- static AlignRestsToNotes(tickables: Tickable[], alignAllNotes: boolean, alignTuplets?: boolean): void {
369
- tickables.forEach((currTickable: Tickable, index: number) => {
370
- if (isStaveNote(currTickable) && currTickable.isRest()) {
371
- if (currTickable.getTuplet() && !alignTuplets) {
372
- return;
373
- }
374
-
375
- // If activated rests not on default can be rendered as specified.
376
- const line = currTickable.getLineForRest();
377
- if (line !== 3) {
378
- return;
379
- }
380
-
381
- if (alignAllNotes || currTickable.getBeam()) {
382
- // Align rests with previous/next notes.
383
- const props = currTickable.getKeyProps()[0];
384
- if (index === 0) {
385
- props.line = getRestLineForNextNoteGroup(tickables, props.line, index, false);
386
- } else if (index > 0 && index < tickables.length) {
387
- // If previous tickable is a rest, use its line number.
388
- const prevTickable = tickables[index - 1];
389
- if (isStaveNote(prevTickable)) {
390
- if (prevTickable.isRest()) {
391
- props.line = prevTickable.getKeyProps()[0].line;
392
- } else {
393
- const restLine = prevTickable.getLineForRest();
394
- // Get the rest line for next valid non-rest note group.
395
- props.line = getRestLineForNextNoteGroup(tickables, restLine, index, true);
396
- }
397
- }
398
- }
399
- currTickable.setKeyLine(0, props.line);
400
- }
401
- }
402
- });
403
- }
404
-
405
- constructor(options?: FormatterOptions) {
406
- this.formatterOptions = {
407
- globalSoftmax: false,
408
- softmaxFactor: Tables.SOFTMAX_FACTOR,
409
- maxIterations: 5,
410
- ...options,
411
- };
412
- this.justifyWidth = 0;
413
- this.totalCost = 0;
414
- this.totalShift = 0;
415
- this.durationStats = {};
416
-
417
- // Minimum width required to render all the notes in the voices.
418
- this.minTotalWidth = 0;
419
-
420
- // This is set to `true` after `minTotalWidth` is calculated.
421
- this.hasMinTotalWidth = false;
422
-
423
- // Arrays of tick and modifier contexts.
424
- this.tickContexts = {
425
- map: {},
426
- array: [],
427
- list: [],
428
- resolutionMultiplier: 0,
429
- };
430
-
431
- this.modifierContexts = [];
432
-
433
- // Gaps between contexts, for free movement of notes post
434
- // formatting.
435
- this.contextGaps = {
436
- total: 0,
437
- gaps: [],
438
- };
439
-
440
- this.voices = [];
441
- this.lossHistory = [];
442
- }
443
-
444
- /**
445
- * Find all the rests in each of the `voices` and align them to neighboring notes.
446
- *
447
- * @param voices
448
- * @param alignAllNotes If `false`, only align rests within beamed groups of notes. If `true`, align all rests.
449
- */
450
- alignRests(voices: Voice[], alignAllNotes: boolean): void {
451
- if (!voices || !voices.length) {
452
- throw new RuntimeError('BadArgument', 'No voices to format rests');
453
- }
454
-
455
- voices.forEach((voice) => Formatter.AlignRestsToNotes(voice.getTickables(), alignAllNotes));
456
- }
457
-
458
- /**
459
- * Estimate the width required to render 'voices'. This is done by:
460
- * 1. Sum the widths of all the tick contexts
461
- * 2. Estimate the padding.
462
- * The latter is done by calculating the padding 3 different ways, and taking the
463
- * greatest value:
464
- * 1. the padding required for unaligned notes in different voices
465
- * 2. the padding based on the stddev of the tickable widths
466
- * 3. the padding based on the stddev of the tickable durations.
467
- *
468
- * The last 2 quantities estimate a 'width entropy', where notes might need more
469
- * room than the proportional formatting gives them. A measure of all same duration
470
- * and width will need no extra padding, and all these quantities will be
471
- * zero in that case.
472
- *
473
- * Note: joinVoices has to be called before calling preCalculateMinTotalWidth.
474
- *
475
- * @param voices the voices that contain the notes
476
- * @returns the estimated width in pixels
477
- */
478
- preCalculateMinTotalWidth(voices: Voice[]): number {
479
- const unalignedPadding = Metrics.get('Stave.unalignedNotePadding');
480
- // Calculate additional padding based on 3 methods:
481
- // 1) unaligned beats in voices, 2) variance of width, 3) variance of durations
482
- let unalignedCtxCount = 0;
483
- let wsum = 0;
484
- let dsum = 0;
485
- const widths: number[] = [];
486
- const durations: number[] = [];
487
-
488
- // Cache results.
489
- if (this.hasMinTotalWidth) return this.minTotalWidth;
490
-
491
- // Create tick contexts.
492
- if (!voices) {
493
- throw new RuntimeError('BadArgument', "'voices' required to run preCalculateMinTotalWidth");
494
- }
495
-
496
- this.createTickContexts(voices);
497
-
498
- // eslint-disable-next-line
499
- const { list: contextList, map: contextMap } = this.tickContexts!;
500
- this.minTotalWidth = 0;
501
-
502
- // Go through each tick context and calculate total width,
503
- // and also accumulate values used in padding hints
504
- contextList.forEach((tick) => {
505
- const context = contextMap[tick];
506
- context.preFormat();
507
- // If this TC doesn't have all the voices on it, it's unaligned.
508
- // so increment the unaligned padding accumulator
509
- if (context.getTickables().length < voices.length) {
510
- unalignedCtxCount += 1;
511
- }
512
- // Calculate the 'width entropy' over all the Tickables.
513
- context.getTickables().forEach((t: Tickable) => {
514
- wsum += t.getMetrics().width;
515
- dsum += t.getTicks().value();
516
- widths.push(t.getMetrics().width);
517
- durations.push(t.getTicks().value());
518
- });
519
- const width = context.getWidth();
520
- this.minTotalWidth += width;
521
- });
522
-
523
- this.hasMinTotalWidth = true;
524
- // normalized (0-1) STDDEV of widths/durations gives us padding hints.
525
- const wavg = wsum > 0 ? wsum / widths.length : 1 / widths.length;
526
- const wvar = sumArray(widths.map((ll) => Math.pow(ll - wavg, 2)));
527
- const wpads = Math.pow(wvar / widths.length, 0.5) / wavg;
528
-
529
- const davg = dsum / durations.length;
530
- const dvar = sumArray(durations.map((ll) => Math.pow(ll - davg, 2)));
531
- const dpads = Math.pow(dvar / durations.length, 0.5) / davg;
532
-
533
- // Find max of 3 methods pad the width with that
534
- const padmax = Math.max(dpads, wpads) * contextList.length * unalignedPadding;
535
- const unalignedPad = unalignedPadding * unalignedCtxCount;
536
-
537
- return this.minTotalWidth + Math.max(unalignedPad, padmax);
538
- }
539
-
540
- /**
541
- * Get minimum width required to render all voices. Either `format` or
542
- * `preCalculateMinTotalWidth` must be called before this method.
543
- */
544
- getMinTotalWidth(): number {
545
- if (!this.hasMinTotalWidth) {
546
- throw new RuntimeError(
547
- 'NoMinTotalWidth',
548
- "Call 'preCalculateMinTotalWidth' or 'preFormat' before calling 'getMinTotalWidth'"
549
- );
550
- }
551
-
552
- return this.minTotalWidth;
553
- }
554
-
555
- /** Calculate the resolution multiplier for `voices`. */
556
- static getResolutionMultiplier(voices: Voice[]): number {
557
- if (!voices || !voices.length) {
558
- throw new RuntimeError('BadArgument', 'No voices to format');
559
- }
560
- const totalTicks = voices[0].getTotalTicks();
561
- const resolutionMultiplier = voices.reduce((accumulator, voice) => {
562
- if (!voice.getTotalTicks().equals(totalTicks)) {
563
- throw new RuntimeError('TickMismatch', 'Voices should have same total note duration in ticks.');
564
- }
565
-
566
- if (voice.getMode() === Voice.Mode.STRICT && !voice.isComplete()) {
567
- throw new RuntimeError('IncompleteVoice', 'Voice does not have enough notes.');
568
- }
569
-
570
- return Math.max(accumulator, Fraction.LCM(accumulator, voice.getResolutionMultiplier()));
571
- }, 1);
572
- return resolutionMultiplier;
573
- }
574
-
575
- /** Create a `ModifierContext` for each tick in `voices`. */
576
- createModifierContexts(voices: Voice[]) {
577
- if (voices.length === 0) return;
578
- const resolutionMultiplier = Formatter.getResolutionMultiplier(voices);
579
-
580
- // Initialize tick maps.
581
- const tickToContextMap: Map<Stave | undefined, Record<number, ModifierContext>> = new Map();
582
- const contexts: ModifierContext[] = [];
583
-
584
- // For each voice, extract notes and create a context for every
585
- // new tick that hasn't been seen before.
586
- voices.forEach((voice) => {
587
- // Use resolution multiplier as denominator so that no additional expansion
588
- // of fractional tick values is needed.
589
- const ticksUsed = new Fraction(0, resolutionMultiplier);
590
-
591
- voice.getTickables().forEach((tickable) => {
592
- const integerTicks = ticksUsed.numerator;
593
- let staveTickToContextMap = tickToContextMap.get(tickable.getStave());
594
-
595
- // If we have no tick context for this tick, create one.
596
- if (!staveTickToContextMap) {
597
- tickToContextMap.set(tickable.getStave(), {});
598
- staveTickToContextMap = tickToContextMap.get(tickable.getStave());
599
- }
600
- if (!(staveTickToContextMap ? staveTickToContextMap[integerTicks] : undefined)) {
601
- const newContext = new ModifierContext();
602
- contexts.push(newContext);
603
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
604
- staveTickToContextMap![integerTicks] = newContext;
605
- }
606
-
607
- // Add this tickable to the TickContext.
608
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
609
- tickable.addToModifierContext(staveTickToContextMap![integerTicks]);
610
- ticksUsed.add(tickable.getTicks());
611
- });
612
- });
613
-
614
- this.modifierContexts.push({
615
- map: tickToContextMap,
616
- array: contexts,
617
- resolutionMultiplier,
618
- });
619
- }
620
-
621
- /**
622
- * Create a `TickContext` for each tick in `voices`. Also calculate the
623
- * total number of ticks in voices.
624
- */
625
- createTickContexts(voices: Voice[]): AlignmentContexts<TickContext> {
626
- const fn: addToContextFn<TickContext> = (tickable: Tickable, context: TickContext, voiceIndex: number) =>
627
- context.addTickable(tickable, voiceIndex);
628
- const contexts = createContexts(voices, (tick?: { tickID: number }) => new TickContext(tick), fn);
629
- this.tickContexts = contexts;
630
- const contextArray = this.tickContexts.array;
631
-
632
- contextArray.forEach((context) => {
633
- context.tContexts = contextArray;
634
- });
635
- return contexts;
636
- }
637
-
638
- /**
639
- * Get the AlignmentContexts of TickContexts that were created by createTickContexts.
640
- * Returns undefined if createTickContexts has not yet been run.
641
- */
642
- getTickContexts(): AlignmentContexts<TickContext> | undefined {
643
- return this.tickContexts;
644
- }
645
-
646
- /**
647
- * This is the core formatter logic. Format voices and justify them
648
- * to `justifyWidth` pixels. `renderingContext` is required to justify elements
649
- * that can't retrieve widths without a canvas. This method sets the `x` positions
650
- * of all the tickables/notes in the formatter.
651
- */
652
- preFormat(justifyWidth = 0, renderingContext?: RenderContext, voicesParam?: Voice[], stave?: Stave): number {
653
- // Initialize context maps.
654
- const contexts = this.tickContexts;
655
- if (!contexts) {
656
- throw new RuntimeError('NoTickContexts', 'preFormat requires TickContexts');
657
- }
658
-
659
- const { list: contextList, map: contextMap } = contexts;
660
-
661
- // Reset loss history for evaluator.
662
- this.lossHistory = [];
663
-
664
- // If voices and a stave were provided, set the Stave for each voice
665
- // and preFormat to apply Y values to the notes;
666
- if (voicesParam && stave) {
667
- voicesParam.forEach((voice) => voice.setStave(stave).preFormat());
668
- }
669
-
670
- // Now distribute the ticks to each tick context, and assign them their
671
- // own X positions.
672
- let x = 0;
673
- let shift = 0;
674
- this.minTotalWidth = 0;
675
- let totalTicks = 0;
676
-
677
- // Pass 1: Give each note maximum width requested by context.
678
- contextList.forEach((tick) => {
679
- const context = contextMap[tick];
680
-
681
- // Make sure that all tickables in this context have calculated their
682
- // space requirements.
683
- context.preFormat();
684
-
685
- const width = context.getWidth();
686
- this.minTotalWidth += width;
687
-
688
- const maxTicks = context.getMaxTicks().value();
689
- totalTicks += maxTicks;
690
-
691
- const metrics = context.getMetrics();
692
- x = x + shift + metrics.totalLeftPx;
693
- context.setX(x);
694
-
695
- // Calculate shift for the next tick.
696
- shift = width - metrics.totalLeftPx;
697
- });
698
-
699
- // Use softmax based on all notes across all staves. (options.globalSoftmax)
700
- const { globalSoftmax, softmaxFactor, maxIterations } = this.formatterOptions;
701
-
702
- const exp = (tick: number) => softmaxFactor ** (contextMap[tick].getMaxTicks().value() / totalTicks);
703
- const expTicksUsed = sumArray(contextList.map(exp));
704
-
705
- this.minTotalWidth = x + shift;
706
- this.hasMinTotalWidth = true;
707
-
708
- // No justification needed. End formatting.
709
- if (justifyWidth <= 0) return this.evaluate();
710
-
711
- // Start justification. Subtract the right extra pixels of the final context because the formatter
712
- // justifies based on the context's X position, which is the left-most part of the note head.
713
- const firstContext = contextMap[contextList[0]];
714
- const lastContext = contextMap[contextList[contextList.length - 1]];
715
-
716
- // Calculate the "distance error" between the tick contexts. The expected distance is the spacing proportional to
717
- // the softmax of the ticks.
718
- function calculateIdealDistances(adjustedJustifyWidth: number): Distance[] {
719
- const distances: Distance[] = contextList.map((tick: number, i: number) => {
720
- const context: TickContext = contextMap[tick];
721
- const voices = context.getTickablesByVoice();
722
- let backTickable: Tickable | undefined;
723
- if (i > 0) {
724
- const prevContext: TickContext = contextMap[contextList[i - 1]];
725
- // Go through each tickable and search backwards for another tickable
726
- // in the same voice. If found, use that duration (ticks) to calculate
727
- // the expected distance.
728
- for (let j = i - 1; j >= 0; j--) {
729
- const backTick: TickContext = contextMap[contextList[j]];
730
- const backVoices = backTick.getTickablesByVoice();
731
-
732
- // Look for matching voices between tick contexts.
733
- const matchingVoices: string[] = [];
734
- Object.keys(voices).forEach((v) => {
735
- if (backVoices[v]) {
736
- matchingVoices.push(v);
737
- }
738
- });
739
-
740
- if (matchingVoices.length > 0) {
741
- // Found matching voices, get largest duration
742
- let maxTicks = 0;
743
- let maxNegativeShiftPx = Infinity;
744
- let expectedDistance = 0;
745
-
746
- matchingVoices.forEach((v) => {
747
- const ticks = backVoices[v].getTicks().value();
748
- if (ticks > maxTicks) {
749
- backTickable = backVoices[v];
750
- maxTicks = ticks;
751
- }
752
-
753
- // Calculate the limits of the shift based on modifiers, etc.
754
- const thisTickable = voices[v];
755
- const insideLeftEdge =
756
- thisTickable.getX() -
757
- (thisTickable.getMetrics().modLeftPx + thisTickable.getMetrics().leftDisplacedHeadPx);
758
-
759
- const backMetrics = backVoices[v].getMetrics();
760
- const insideRightEdge =
761
- backVoices[v].getX() + backMetrics.notePx + backMetrics.modRightPx + backMetrics.rightDisplacedHeadPx;
762
-
763
- // Don't allow shifting if notes in the same voice can collide
764
- maxNegativeShiftPx = Math.min(maxNegativeShiftPx, insideLeftEdge - insideRightEdge);
765
- });
766
-
767
- // Don't shift further left than the notehead of the last context. Actually, stay at most 5% to the right
768
- // so that two different tick contexts don't align across staves.
769
- maxNegativeShiftPx = Math.min(
770
- maxNegativeShiftPx,
771
- context.getX() - (prevContext.getX() + adjustedJustifyWidth * 0.05)
772
- );
773
-
774
- // Calculate the expected distance of the current context from the last matching tickable. The
775
- // distance is scaled down by the softmax for the voice.
776
- if (globalSoftmax) {
777
- const t = totalTicks;
778
- expectedDistance = (softmaxFactor ** (maxTicks / t) / expTicksUsed) * adjustedJustifyWidth;
779
- } else if (typeof backTickable !== 'undefined') {
780
- expectedDistance = backTickable.getVoice().softmax(maxTicks) * adjustedJustifyWidth;
781
- }
782
- return {
783
- expectedDistance,
784
- maxNegativeShiftPx,
785
- fromTickable: backTickable,
786
- };
787
- }
788
- }
789
- }
790
-
791
- return { expectedDistance: 0, fromTickablePx: 0, maxNegativeShiftPx: 0 };
792
- });
793
- return distances;
794
- }
795
-
796
- function shiftToIdealDistances(idealDistances: Distance[]): number {
797
- // Distribute ticks to the contexts based on the calculated distance error.
798
- const centerX = adjustedJustifyWidth / 2;
799
- let spaceAccum = 0;
800
-
801
- contextList.forEach((tick, index) => {
802
- const context = contextMap[tick];
803
- if (index > 0) {
804
- const contextX = context.getX();
805
- const ideal = idealDistances[index];
806
- const errorPx = defined(ideal.fromTickable).getX() + ideal.expectedDistance - (contextX + spaceAccum);
807
-
808
- let negativeShiftPx = 0;
809
- if (errorPx > 0) {
810
- spaceAccum += errorPx;
811
- } else if (errorPx < 0) {
812
- negativeShiftPx = Math.min(ideal.maxNegativeShiftPx, Math.abs(errorPx));
813
- spaceAccum += -negativeShiftPx;
814
- }
815
- context.setX(contextX + spaceAccum);
816
- }
817
- // Move center aligned tickables to middle
818
- context.getCenterAlignedTickables().forEach((tickable: Tickable) => {
819
- tickable.setCenterXShift(centerX - context.getX());
820
- });
821
- });
822
-
823
- return lastContext.getX() - firstContext.getX();
824
- }
825
-
826
- const adjustedJustifyWidth =
827
- justifyWidth -
828
- lastContext.getMetrics().notePx -
829
- lastContext.getMetrics().totalRightPx -
830
- firstContext.getMetrics().totalLeftPx;
831
- const configMinPadding = Metrics.get('Stave.endPaddingMin');
832
- const configMaxPadding = Metrics.get('Stave.endPaddingMax');
833
- const leftPadding = Metrics.get('Stave.padding');
834
- let targetWidth = adjustedJustifyWidth;
835
- const distances = calculateIdealDistances(targetWidth);
836
- let actualWidth = shiftToIdealDistances(distances);
837
-
838
- // Just one context. Done formatting.
839
- if (contextList.length === 1) return 0;
840
- const calcMinDistance = (targetWidth: number, distances: Distance[]) => {
841
- let mdCalc = targetWidth / 2;
842
- if (distances.length > 1) {
843
- for (let di = 1; di < distances.length; ++di) {
844
- mdCalc = Math.min(distances[di].expectedDistance / 2, mdCalc);
845
- }
846
- }
847
- return mdCalc;
848
- };
849
- const minDistance = calcMinDistance(targetWidth, distances);
850
-
851
- // right justify to either the configured padding, or the min distance between notes, whichever is greatest.
852
- // This * 2 keeps the existing formatting unless there is 'a lot' of extra whitespace, which won't break
853
- // existing visual regression tests.
854
- const paddingMaxCalc = (curTargetWidth: number) => {
855
- let lastTickablePadding = 0;
856
- const lastTickable = lastContext && lastContext.getMaxTickable();
857
- if (lastTickable) {
858
- const voice = lastTickable.getVoice();
859
- // If the number of actual ticks in the measure <> configured ticks, right-justify
860
- // because the softmax won't yield the correct value
861
- if (voice.getTicksUsed().value() > voice.getTotalTicks().value()) {
862
- return configMaxPadding * 2 < minDistance ? minDistance : configMaxPadding;
863
- }
864
- const tickWidth = lastTickable.getWidth();
865
- lastTickablePadding =
866
- voice.softmax(lastContext.getMaxTicks().value()) * curTargetWidth - (tickWidth + leftPadding);
867
- }
868
- return configMaxPadding * 2 < lastTickablePadding ? lastTickablePadding : configMaxPadding;
869
- };
870
- let paddingMax = paddingMaxCalc(targetWidth);
871
- let paddingMin = paddingMax - (configMaxPadding - configMinPadding);
872
- const maxX = adjustedJustifyWidth - paddingMin;
873
-
874
- let iterations = maxIterations;
875
- // Adjust justification width until the right margin is as close as possible to the calculated padding,
876
- // without going over
877
- while ((actualWidth > maxX && iterations > 0) || (actualWidth + paddingMax < maxX && iterations > 1)) {
878
- targetWidth -= actualWidth - maxX;
879
- paddingMax = paddingMaxCalc(targetWidth);
880
- paddingMin = paddingMax - (configMaxPadding - configMinPadding);
881
- actualWidth = shiftToIdealDistances(calculateIdealDistances(targetWidth));
882
- iterations--;
883
- }
884
-
885
- this.justifyWidth = justifyWidth;
886
- return this.evaluate();
887
- }
888
-
889
- /** Calculate the total cost of this formatting decision. */
890
- evaluate(): number {
891
- const contexts = this.tickContexts;
892
- const justifyWidth = this.justifyWidth;
893
- // Calculate available slack per tick context. This works out how much freedom
894
- // to move a context has in either direction, without affecting other notes.
895
- this.contextGaps = { total: 0, gaps: [] };
896
- contexts.list.forEach((tick, index) => {
897
- if (index === 0) return;
898
- const prevTick = contexts.list[index - 1];
899
- const prevContext = contexts.map[prevTick];
900
- const context = contexts.map[tick];
901
- const prevMetrics = prevContext.getMetrics();
902
- const currMetrics = context.getMetrics();
903
-
904
- // Calculate X position of right edge of previous note
905
- const insideRightEdge = prevContext.getX() + prevMetrics.notePx + prevMetrics.totalRightPx;
906
- // Calculate X position of left edge of current note
907
- const insideLeftEdge = context.getX() - currMetrics.totalLeftPx;
908
- const gap = insideLeftEdge - insideRightEdge;
909
- this.contextGaps.total += gap;
910
- this.contextGaps.gaps.push({ x1: insideRightEdge, x2: insideLeftEdge });
911
-
912
- // Tell the tick contexts how much they can reposition themselves.
913
- context.getFormatterMetrics().freedom.left = gap;
914
- prevContext.getFormatterMetrics().freedom.right = gap;
915
- });
916
-
917
- // Calculate mean distance in each voice for each duration type, then calculate
918
- // how far each note is from the mean.
919
- this.durationStats = {};
920
- const durationStats = this.durationStats;
921
-
922
- function updateStats(duration: string, space: number) {
923
- const stats = durationStats[duration];
924
- if (stats === undefined) {
925
- durationStats[duration] = { mean: space, count: 1 };
926
- } else {
927
- stats.count += 1;
928
- stats.mean = (stats.mean + space) / 2;
929
- }
930
- }
931
-
932
- this.voices.forEach((voice) => {
933
- voice.getTickables().forEach((note, i, notes) => {
934
- const duration = note.getTicks().clone().simplify().toString();
935
- const metrics = note.getMetrics();
936
- const formatterMetrics = note.getFormatterMetrics();
937
- const leftNoteEdge = note.getX() + metrics.notePx + metrics.modRightPx + metrics.rightDisplacedHeadPx;
938
- let space = 0;
939
-
940
- if (i < notes.length - 1) {
941
- const rightNote = notes[i + 1];
942
- const rightMetrics = rightNote.getMetrics();
943
- const rightNoteEdge = rightNote.getX() - rightMetrics.modLeftPx - rightMetrics.leftDisplacedHeadPx;
944
-
945
- space = rightNoteEdge - leftNoteEdge;
946
- formatterMetrics.space.used = rightNote.getX() - note.getX();
947
- rightNote.getFormatterMetrics().freedom.left = space;
948
- } else {
949
- space = justifyWidth - leftNoteEdge;
950
- formatterMetrics.space.used = justifyWidth - note.getX();
951
- }
952
-
953
- formatterMetrics.freedom.right = space;
954
- updateStats(duration, formatterMetrics.space.used);
955
- });
956
- });
957
-
958
- // Calculate how much each note deviates from the mean. Loss function is square
959
- // root of the sum of squared deviations.
960
- let totalDeviation = 0;
961
- this.voices.forEach((voice) => {
962
- voice.getTickables().forEach((note) => {
963
- const duration = note.getTicks().clone().simplify().toString();
964
- const metrics = note.getFormatterMetrics();
965
-
966
- metrics.space.mean = durationStats[duration].mean;
967
- metrics.duration = duration;
968
- metrics.iterations += 1;
969
- metrics.space.deviation = metrics.space.used - metrics.space.mean;
970
-
971
- totalDeviation += metrics.space.deviation ** 2;
972
- });
973
- });
974
-
975
- this.totalCost = Math.sqrt(totalDeviation);
976
- this.lossHistory.push(this.totalCost);
977
- return this.totalCost;
978
- }
979
-
980
- /**
981
- * Run a single iteration of rejustification. At a high level, this method calculates
982
- * the overall "loss" (or cost) of this layout, and repositions tickcontexts in an
983
- * attempt to reduce the cost. You can call this method multiple times until it finds
984
- * and oscillates around a global minimum.
985
- * @param options[alpha] the "learning rate" for the formatter. It determines how much of a shift
986
- * the formatter should make based on its cost function.
987
- */
988
- tune(options?: { alpha?: number }): number {
989
- const contexts = this.tickContexts;
990
- if (!contexts) {
991
- return 0;
992
- }
993
-
994
- const alpha = options?.alpha ?? 0.5;
995
-
996
- // Move `current` tickcontext by `shift` pixels, and adjust the freedom
997
- // on adjacent tickcontexts.
998
- function move(current: TickContext, shift: number, prev?: TickContext, next?: TickContext) {
999
- current.setX(current.getX() + shift);
1000
- current.getFormatterMetrics().freedom.left += shift;
1001
- current.getFormatterMetrics().freedom.right -= shift;
1002
-
1003
- if (prev) prev.getFormatterMetrics().freedom.right += shift;
1004
- if (next) next.getFormatterMetrics().freedom.left -= shift;
1005
- }
1006
-
1007
- let shift = 0;
1008
- this.totalShift = 0;
1009
- contexts.list.forEach((tick, index, list) => {
1010
- const context = contexts.map[tick];
1011
- const prevContext = index > 0 ? contexts.map[list[index - 1]] : undefined;
1012
- const nextContext = index < list.length - 1 ? contexts.map[list[index + 1]] : undefined;
1013
-
1014
- move(context, shift, prevContext, nextContext);
1015
-
1016
- const cost = -sumArray(context.getTickables().map((t) => t.getFormatterMetrics().space.deviation));
1017
-
1018
- if (cost > 0) {
1019
- shift = -Math.min(context.getFormatterMetrics().freedom.right, Math.abs(cost));
1020
- } else if (cost < 0) {
1021
- if (nextContext) {
1022
- shift = Math.min(nextContext.getFormatterMetrics().freedom.right, Math.abs(cost));
1023
- } else {
1024
- shift = 0;
1025
- }
1026
- }
1027
-
1028
- shift *= alpha;
1029
- this.totalShift += shift;
1030
- });
1031
-
1032
- return this.evaluate();
1033
- }
1034
-
1035
- /**
1036
- * This is the top-level call for all formatting logic completed
1037
- * after `x` *and* `y` values have been computed for the notes
1038
- * in the voices.
1039
- */
1040
- postFormat(): this {
1041
- this.modifierContexts.forEach((modifierContexts) => {
1042
- modifierContexts.array.forEach((mc) => mc.postFormat());
1043
- });
1044
-
1045
- this.tickContexts.list.forEach((tick) => {
1046
- this.tickContexts.map[tick].postFormat();
1047
- });
1048
-
1049
- return this;
1050
- }
1051
-
1052
- /**
1053
- * Take all `voices` and create `ModifierContext`s out of them. This tells
1054
- * the formatters that the voices belong on a single stave.
1055
- */
1056
- joinVoices(voices: Voice[]): this {
1057
- this.createModifierContexts(voices);
1058
- this.hasMinTotalWidth = false;
1059
- return this;
1060
- }
1061
-
1062
- /**
1063
- * Align rests in voices, justify the contexts, and position the notes
1064
- * so voices are aligned and ready to render onto the stave. This method
1065
- * mutates the `x` positions of all tickables in `voices`.
1066
- *
1067
- * Voices are full justified to fit in `justifyWidth` pixels.
1068
- *
1069
- * Set `options.context` to the rendering context. Set `options.alignRests`
1070
- * to true to enable rest alignment.
1071
- */
1072
- format(voices: Voice[], justifyWidth?: number, options?: FormatParams): this {
1073
- const opts = {
1074
- alignRests: false,
1075
- ...options,
1076
- };
1077
-
1078
- this.voices = voices;
1079
- const softmaxFactor = this.formatterOptions.softmaxFactor;
1080
- if (softmaxFactor) {
1081
- this.voices.forEach((v) => v.setSoftmaxFactor(softmaxFactor));
1082
- }
1083
-
1084
- this.alignRests(voices, opts.alignRests);
1085
- this.createTickContexts(voices);
1086
- this.preFormat(justifyWidth, opts.context, voices, opts.stave);
1087
-
1088
- // Only postFormat if a stave was supplied for y value formatting
1089
- if (opts.stave) this.postFormat();
1090
-
1091
- return this;
1092
- }
1093
-
1094
- // This method is just like `format` except that the `justifyWidth` is inferred from the `stave`.
1095
- formatToStave(voices: Voice[], stave: Stave, optionsParam?: FormatParams): this {
1096
- const options: FormatParams = { context: stave.getContext(), ...optionsParam };
1097
-
1098
- // eslint-disable-next-line
1099
- const justifyWidth = stave.getNoteEndX() - stave.getNoteStartX() - Stave.defaultPadding;
1100
- L('Formatting voices to width: ', justifyWidth);
1101
- return this.format(voices, justifyWidth, options);
1102
- }
1103
-
1104
- getTickContext(tick: number): TickContext | undefined {
1105
- return this.tickContexts?.map[tick];
1106
- }
1107
- }