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/beam.ts DELETED
@@ -1,999 +0,0 @@
1
- // Copyright (c) 2023-present VexFlow contributors: https://github.com/vexflow/vexflow/graphs/contributors
2
- // MIT License
3
-
4
- import { Element } from './element';
5
- import { Fraction } from './fraction';
6
- import { Note } from './note';
7
- import { RenderContext } from './rendercontext';
8
- import { Stem } from './stem';
9
- import { StemmableNote } from './stemmablenote';
10
- import { Tables } from './tables';
11
- import { Tuplet, TupletLocation } from './tuplet';
12
- import { Category, isStaveNote, isTabNote } from './typeguard';
13
- import { RuntimeError } from './util';
14
- import { Voice } from './voice';
15
-
16
- function calculateStemDirection(notes: StemmableNote[]) {
17
- let lineSum = 0;
18
- notes.forEach((note) => {
19
- if (note.keyProps) {
20
- note.keyProps.forEach((keyProp) => {
21
- lineSum += keyProp.line - 3;
22
- });
23
- }
24
- });
25
-
26
- if (lineSum >= 0) {
27
- return Stem.DOWN;
28
- }
29
- return Stem.UP;
30
- }
31
-
32
- function getStemSlope(firstNote: StemmableNote, lastNote: StemmableNote) {
33
- const firstStemTipY = firstNote.getStemExtents().topY;
34
- const firstStemX = firstNote.getStemX();
35
- const lastStemTipY = lastNote.getStemExtents().topY;
36
- const lastStemX = lastNote.getStemX();
37
- return (lastStemTipY - firstStemTipY) / (lastStemX - firstStemX);
38
- }
39
-
40
- export const BEAM_LEFT = 'L';
41
- export const BEAM_RIGHT = 'R';
42
- export const BEAM_BOTH = 'B';
43
-
44
- export type PartialBeamDirection = typeof BEAM_LEFT | typeof BEAM_RIGHT | typeof BEAM_BOTH;
45
-
46
- /** `Beams` span over a set of `StemmableNotes`. */
47
- export class Beam extends Element {
48
- static get CATEGORY(): string {
49
- return Category.Beam;
50
- }
51
-
52
- public renderOptions: {
53
- flatBeamOffset?: number;
54
- flatBeams: boolean;
55
- secondaryBreakTicks?: number;
56
- showStemlets: boolean;
57
- beamWidth: number;
58
- maxSlope: number;
59
- minSlope: number;
60
- slopeIterations: number;
61
- slopeCost: number;
62
- stemletExtension: number;
63
- partialBeamLength: number;
64
- minFlatBeamOffset: number;
65
- };
66
-
67
- notes: StemmableNote[];
68
- postFormatted: boolean;
69
- slope: number = 0;
70
-
71
- readonly #stemDirection: number;
72
- readonly #ticks: number;
73
-
74
- #yShift: number = 0;
75
- #breakOnIndexes: number[];
76
- #beamCount: number;
77
- #unbeamable?: boolean;
78
-
79
- /**
80
- * Overrides to default beam directions for secondary-level beams that do not
81
- * connect to any other note. See further explanation at
82
- * `setPartialBeamSideAt`
83
- */
84
- #forcedPartialDirections: {
85
- [noteIndex: number]: PartialBeamDirection;
86
- } = {};
87
-
88
- /** Get the direction of the beam */
89
- getStemDirection(): number {
90
- return this.#stemDirection;
91
- }
92
-
93
- /**
94
- * Get the default beam groups for a provided time signature.
95
- * Attempt to guess if the time signature is not found in table.
96
- * Currently this is fairly naive.
97
- */
98
- static getDefaultBeamGroups(timeSig: string): Fraction[] {
99
- if (!timeSig || timeSig === 'c') {
100
- timeSig = '4/4';
101
- }
102
-
103
- const defaults: { [key: string]: [string] } = {
104
- '1/2': ['1/2'],
105
- '2/2': ['1/2'],
106
- '3/2': ['1/2'],
107
- '4/2': ['1/2'],
108
-
109
- '1/4': ['1/4'],
110
- '2/4': ['1/4'],
111
- '3/4': ['1/4'],
112
- '4/4': ['1/4'],
113
-
114
- '1/8': ['1/8'],
115
- '2/8': ['2/8'],
116
- '3/8': ['3/8'],
117
- '4/8': ['2/8'],
118
-
119
- '1/16': ['1/16'],
120
- '2/16': ['2/16'],
121
- '3/16': ['3/16'],
122
- '4/16': ['2/16'],
123
- };
124
-
125
- const groups: string[] = defaults[timeSig];
126
-
127
- if (groups === undefined) {
128
- // If no beam groups found, naively determine
129
- // the beam groupings from the time signature
130
- const beatTotal = parseInt(timeSig.split('/')[0], 10);
131
- const beatValue = parseInt(timeSig.split('/')[1], 10);
132
-
133
- const tripleMeter = beatTotal % 3 === 0;
134
-
135
- if (tripleMeter) {
136
- return [new Fraction(3, beatValue)];
137
- } else if (beatValue > 4) {
138
- return [new Fraction(2, beatValue)];
139
- } else if (beatValue <= 4) {
140
- return [new Fraction(1, beatValue)];
141
- }
142
- } else {
143
- return groups.map((group) => new Fraction().parse(group));
144
- }
145
-
146
- return [new Fraction(1, 4)];
147
- }
148
-
149
- /**
150
- * A helper function to automatically build basic beams for a voice. For more
151
- * complex auto-beaming use `Beam.generateBeams()`.
152
- * @param voice the voice to generate the beams for
153
- * @param stemDirection a stem direction to apply to the entire voice
154
- * @param groups an array of `Fraction` representing beat groupings for the beam
155
- */
156
- static applyAndGetBeams(voice: Voice, stemDirection?: number, groups?: Fraction[]): Beam[] {
157
- return Beam.generateBeams(voice.getTickables() as StemmableNote[], { groups, stemDirection });
158
- }
159
-
160
- /**
161
- * A helper function to autimatically build beams for a voice with
162
- * configuration options.
163
- *
164
- * Example configuration object:
165
- *
166
- * ```
167
- * config = {
168
- * groups: [new VexFlow.Fraction(2, 8)],
169
- * stemDirection: -1,
170
- * beamRests: true,
171
- * beamMiddleOnly: true,
172
- * showStemlets: false
173
- * };
174
- * ```
175
- * @param notes an array of notes to create the beams for
176
- * @param config the configuration object
177
- * @param config.stemDirection set to apply the same direction to all notes
178
- * @param config.beamRests set to `true` to include rests in the beams
179
- * @param config.beamMiddleOnly set to `true` to only beam rests in the middle of the beat
180
- * @param config.showStemlets set to `true` to draw stemlets for rests
181
- * @param config.maintainStemDirections set to `true` to not apply new stem directions
182
- * @param config.groups array of `Fractions` that represent the beat structure to beam the notes
183
- *
184
- */
185
- static generateBeams(
186
- notes: StemmableNote[],
187
- config: {
188
- flatBeamOffset?: number;
189
- flatBeams?: boolean;
190
- secondaryBreaks?: string;
191
- showStemlets?: boolean;
192
- maintainStemDirections?: boolean;
193
- beamMiddleOnly?: boolean;
194
- beamRests?: boolean;
195
- groups?: Fraction[];
196
- stemDirection?: number;
197
- } = {}
198
- ): Beam[] {
199
- if (!config.groups || !config.groups.length) {
200
- config.groups = [new Fraction(2, 8)];
201
- }
202
-
203
- // Convert beam groups to tick amounts
204
- const tickGroups = config.groups.map((group) => {
205
- if (!group.multiply) {
206
- throw new RuntimeError('InvalidBeamGroups', 'The beam groups must be an array of VexFlow.Fractions');
207
- }
208
- return group.clone().multiply(Tables.RESOLUTION, 1);
209
- });
210
-
211
- const unprocessedNotes: StemmableNote[] = notes;
212
- let currentTickGroup = 0;
213
- let noteGroups: StemmableNote[][] = [];
214
- let currentGroup: StemmableNote[] = [];
215
-
216
- function getTotalTicks(notes: Note[]) {
217
- return notes.reduce((memo, note) => note.getTicks().clone().add(memo), new Fraction(0, 1));
218
- }
219
-
220
- function nextTickGroup() {
221
- if (tickGroups.length - 1 > currentTickGroup) {
222
- currentTickGroup += 1;
223
- } else {
224
- currentTickGroup = 0;
225
- }
226
- }
227
-
228
- function createGroups() {
229
- let nextGroup: StemmableNote[] = [];
230
- // number of ticks in current group
231
- let currentGroupTotalTicks = new Fraction(0, 1);
232
- unprocessedNotes.forEach((unprocessedNote) => {
233
- nextGroup = [];
234
- if (unprocessedNote.shouldIgnoreTicks()) {
235
- noteGroups.push(currentGroup);
236
- currentGroup = nextGroup;
237
- return; // Ignore untickables (like bar notes)
238
- }
239
- currentGroup.push(unprocessedNote);
240
- const ticksPerGroup = tickGroups[currentTickGroup].clone();
241
- const totalTicks = getTotalTicks(currentGroup).add(currentGroupTotalTicks);
242
-
243
- // Double the amount of ticks in a group, if it's an unbeamable tuplet
244
- const unbeamable = Tables.durationToNumber(unprocessedNote.getDuration()) < 8;
245
- if (unbeamable && unprocessedNote.getTuplet()) {
246
- ticksPerGroup.numerator *= 2;
247
- }
248
-
249
- // If the note that was just added overflows the group tick total
250
- if (totalTicks.greaterThan(ticksPerGroup)) {
251
- // If the overflow note can be beamed, start the next group
252
- // with it. Unbeamable notes leave the group overflowed.
253
- if (!unbeamable) {
254
- const note = currentGroup.pop();
255
- if (note) nextGroup.push(note);
256
- }
257
- noteGroups.push(currentGroup);
258
-
259
- // We have overflown, so we're going to next tick group. As we might have
260
- // overflown by more than 1 group, we need to go forward as many times as
261
- // needed, decreasing currentGroupTotalTicks by as many ticks as there are
262
- // in current groups as we go forward.
263
- do {
264
- currentGroupTotalTicks = totalTicks.subtract(tickGroups[currentTickGroup]);
265
- nextTickGroup();
266
- } while (currentGroupTotalTicks.greaterThanEquals(tickGroups[currentTickGroup]));
267
- currentGroup = nextGroup;
268
- } else if (totalTicks.equals(ticksPerGroup)) {
269
- noteGroups.push(currentGroup);
270
- currentGroupTotalTicks = new Fraction(0, 1);
271
- currentGroup = nextGroup;
272
- nextTickGroup();
273
- }
274
- });
275
-
276
- // Adds any remainder notes beam
277
- if (currentGroup.length > 0) {
278
- noteGroups.push(currentGroup);
279
- }
280
- }
281
- function getBeamGroups() {
282
- return noteGroups.filter((group) => {
283
- if (group.length > 1) {
284
- let beamable = true;
285
- group.forEach((note) => {
286
- if (note.getIntrinsicTicks() >= Tables.durationToTicks('4')) {
287
- beamable = false;
288
- }
289
- });
290
- return beamable;
291
- }
292
- return false;
293
- });
294
- }
295
-
296
- // Splits up groups by Rest
297
- function sanitizeGroups() {
298
- const sanitizedGroups: StemmableNote[][] = [];
299
- noteGroups.forEach((group) => {
300
- let tempGroup: StemmableNote[] = [];
301
- group.forEach((note, index, group) => {
302
- const isFirstOrLast = index === 0 || index === group.length - 1;
303
- const prevNote = group[index - 1];
304
-
305
- const breaksOnEachRest = !config.beamRests && note.isRest();
306
- const breaksOnFirstOrLastRest = config.beamRests && config.beamMiddleOnly && note.isRest() && isFirstOrLast;
307
-
308
- let breakOnStemChange = false;
309
- if (config.maintainStemDirections && prevNote && !note.isRest() && !prevNote.isRest()) {
310
- const prevDirection = prevNote.getStemDirection();
311
- const currentDirection = note.getStemDirection();
312
- breakOnStemChange = currentDirection !== prevDirection;
313
- }
314
-
315
- const isUnbeamableDuration = parseInt(note.getDuration(), 10) < 8;
316
-
317
- // Determine if the group should be broken at this note
318
- const shouldBreak = breaksOnEachRest || breaksOnFirstOrLastRest || breakOnStemChange || isUnbeamableDuration;
319
-
320
- if (shouldBreak) {
321
- // Add current group
322
- if (tempGroup.length > 0) {
323
- sanitizedGroups.push(tempGroup);
324
- }
325
-
326
- // Start a new group. Include the current note if the group
327
- // was broken up by stem direction, as that note needs to start
328
- // the next group of notes
329
- tempGroup = breakOnStemChange ? [note] : [];
330
- } else {
331
- // Add note to group
332
- tempGroup.push(note);
333
- }
334
- });
335
-
336
- // If there is a remaining group, add it as well
337
- if (tempGroup.length > 0) {
338
- sanitizedGroups.push(tempGroup);
339
- }
340
- });
341
-
342
- noteGroups = sanitizedGroups;
343
- }
344
-
345
- function formatStems() {
346
- noteGroups.forEach((group) => {
347
- let stemDirection;
348
- if (config.maintainStemDirections) {
349
- const note = findFirstNote(group);
350
- stemDirection = note ? note.getStemDirection() : Stem.UP;
351
- } else {
352
- if (config.stemDirection) {
353
- stemDirection = config.stemDirection;
354
- } else {
355
- stemDirection = calculateStemDirection(group);
356
- }
357
- }
358
- applyStemDirection(group, stemDirection);
359
- });
360
- }
361
-
362
- function findFirstNote(group: StemmableNote[]) {
363
- for (let i = 0; i < group.length; i++) {
364
- const note = group[i];
365
- if (!note.isRest()) {
366
- return note;
367
- }
368
- }
369
-
370
- return false;
371
- }
372
-
373
- function applyStemDirection(group: StemmableNote[], direction: number) {
374
- group.forEach((note) => {
375
- note.setStemDirection(direction);
376
- });
377
- }
378
-
379
- // Get all of the tuplets in all of the note groups
380
- function getTuplets() {
381
- const uniqueTuplets: Tuplet[] = [];
382
-
383
- // Go through all of the note groups and inspect for tuplets
384
- noteGroups.forEach((group) => {
385
- let tuplet: Tuplet;
386
- group.forEach((note) => {
387
- const noteTuplet = note.getTuplet();
388
- if (noteTuplet && tuplet !== noteTuplet) {
389
- tuplet = noteTuplet;
390
- uniqueTuplets.push(tuplet);
391
- }
392
- });
393
- });
394
- return uniqueTuplets;
395
- }
396
-
397
- // Using closures to store the variables throughout the various functions
398
- // IMO Keeps it this process lot cleaner - but not super consistent with
399
- // the rest of the API's style - Silverwolf90 (Cyril)
400
- createGroups();
401
- sanitizeGroups();
402
- formatStems();
403
-
404
- // Get the notes to be beamed
405
- const beamedNoteGroups = getBeamGroups();
406
-
407
- // Get the tuplets in order to format them accurately
408
- const allTuplets = getTuplets();
409
-
410
- // Create a VexFlow.Beam from each group of notes to be beamed
411
- const beams: Beam[] = [];
412
- beamedNoteGroups.forEach((group) => {
413
- const beam = new Beam(group);
414
-
415
- if (config.showStemlets) {
416
- beam.renderOptions.showStemlets = true;
417
- }
418
- if (config.secondaryBreaks) {
419
- beam.renderOptions.secondaryBreakTicks = Tables.durationToTicks(config.secondaryBreaks);
420
- }
421
- if (config.flatBeams === true) {
422
- beam.renderOptions.flatBeams = true;
423
- beam.renderOptions.flatBeamOffset = config.flatBeamOffset;
424
- }
425
- beams.push(beam);
426
- });
427
-
428
- // Reformat tuplets
429
- allTuplets.forEach((tuplet) => {
430
- // Set the tuplet location based on the stem direction
431
- const direction =
432
- (tuplet.notes[0] as StemmableNote).stemDirection === Stem.DOWN ? TupletLocation.BOTTOM : TupletLocation.TOP;
433
- tuplet.setTupletLocation(direction);
434
-
435
- // If any of the notes in the tuplet are not beamed, draw a bracket.
436
- let bracketed = false;
437
- for (let i = 0; i < tuplet.notes.length; i++) {
438
- const note = tuplet.notes[i];
439
- if (!note.hasBeam()) {
440
- bracketed = true;
441
- break;
442
- }
443
- }
444
- tuplet.setBracketed(bracketed);
445
- });
446
-
447
- return beams;
448
- }
449
-
450
- constructor(notes: StemmableNote[], autoStem: boolean = false) {
451
- super();
452
-
453
- if (!notes || notes.length === 0) {
454
- throw new RuntimeError('BadArguments', 'No notes provided for beam.');
455
- }
456
-
457
- if (notes.length === 1) {
458
- throw new RuntimeError('BadArguments', 'Too few notes for beam.');
459
- }
460
-
461
- // Validate beam line, direction and ticks.
462
- this.#ticks = notes[0].getIntrinsicTicks();
463
-
464
- if (this.#ticks >= Tables.durationToTicks('4')) {
465
- throw new RuntimeError('BadArguments', 'Beams can only be applied to notes shorter than a quarter note.');
466
- }
467
-
468
- let i; // shared iterator
469
- let note;
470
-
471
- this.#stemDirection = notes[0].getStemDirection();
472
-
473
- let stemDirection = this.#stemDirection;
474
- // Figure out optimal stem direction based on given notes
475
-
476
- if (autoStem && isStaveNote(notes[0])) {
477
- stemDirection = calculateStemDirection(notes);
478
- } else if (autoStem && isTabNote(notes[0])) {
479
- // Auto Stem TabNotes
480
- const stemWeight = notes.reduce((memo, note) => memo + note.getStemDirection(), 0);
481
- stemDirection = stemWeight > -1 ? Stem.UP : Stem.DOWN;
482
- }
483
-
484
- // Apply stem directions and attach beam to notes
485
- for (i = 0; i < notes.length; ++i) {
486
- note = notes[i];
487
- if (autoStem) {
488
- note.setStemDirection(stemDirection);
489
- this.#stemDirection = stemDirection;
490
- }
491
- note.setBeam(this);
492
- }
493
-
494
- this.postFormatted = false;
495
- this.notes = notes;
496
- this.#beamCount = this.getBeamCount();
497
- this.#breakOnIndexes = [];
498
- this.renderOptions = {
499
- beamWidth: 5,
500
- maxSlope: 0.25,
501
- minSlope: -0.25,
502
- slopeIterations: 20,
503
- slopeCost: 100,
504
- showStemlets: false,
505
- stemletExtension: 7,
506
- partialBeamLength: 10,
507
- flatBeams: false,
508
- minFlatBeamOffset: 15,
509
- };
510
- }
511
-
512
- /** Get the notes in this beam. */
513
- getNotes(): StemmableNote[] {
514
- return this.notes;
515
- }
516
-
517
- /** Get the max number of beams in the set of notes. */
518
- getBeamCount(): number {
519
- const beamCounts = this.notes.map((note) => note.getGlyphProps().beamCount);
520
-
521
- const maxBeamCount = beamCounts.reduce((max, beamCount) => (beamCount > max ? beamCount : max));
522
-
523
- return maxBeamCount;
524
- }
525
-
526
- /** Set which note `indexes` to break the secondary beam at. */
527
- breakSecondaryAt(indexes: number[]): this {
528
- this.#breakOnIndexes = indexes;
529
- return this;
530
- }
531
-
532
- /**
533
- * Forces the direction of a partial beam (a secondary-level beam that exists
534
- * on one note only of the beam group). This is useful in rhythms such as 6/8
535
- * eighth-sixteenth-eighth-sixteenth, where the direction of the beam on the
536
- * first sixteenth note can help imply whether the rhythm is to be felt as
537
- * three groups of eighth notes (typical) or as two groups of three-sixteenths
538
- * (less common):
539
- * ```
540
- * ┌───┬──┬──┐ ┌──┬──┬──┐
541
- * │ ├─ │ ─┤ vs │ ─┤ │ ─┤
542
- * │ │ │ │ │ │ │ │
543
- * ```
544
- */
545
- setPartialBeamSideAt(noteIndex: number, side: PartialBeamDirection) {
546
- this.#forcedPartialDirections[noteIndex] = side;
547
- return this;
548
- }
549
-
550
- /**
551
- * Restore the default direction of a partial beam (a secondary-level beam
552
- * that does not connect to any other notes).
553
- */
554
- unsetPartialBeamSideAt(noteIndex: number) {
555
- delete this.#forcedPartialDirections[noteIndex];
556
- return this;
557
- }
558
-
559
- /**
560
- * @param firstX specified in pixels.
561
- * @param firstY specified in pixels.
562
- *
563
- * @return the y coordinate for linear function.
564
- */
565
- getSlopeY(x: number, firstX: number, firstY: number, slope: number): number {
566
- return firstY + (x - firstX) * slope;
567
- }
568
-
569
- /** Calculate the best possible slope for the provided notes. */
570
- calculateSlope(): void {
571
- const {
572
- notes,
573
- renderOptions: { maxSlope, minSlope, slopeIterations, slopeCost },
574
- } = this;
575
-
576
- const stemDirection = this.#stemDirection;
577
-
578
- const firstNote = notes[0];
579
- const initialSlope = getStemSlope(firstNote, notes[notes.length - 1]);
580
- const increment = (maxSlope - minSlope) / slopeIterations;
581
- let minCost = Number.MAX_VALUE;
582
- let bestSlope = 0;
583
- let yShift = 0;
584
-
585
- // iterate through slope values to find best weighted fit
586
- for (let slope = minSlope; slope <= maxSlope; slope += increment) {
587
- let totalStemExtension = 0;
588
- let yShiftTemp = 0;
589
-
590
- // iterate through notes, calculating y shift and stem extension
591
- for (let i = 1; i < notes.length; ++i) {
592
- const note = notes[i];
593
- if (note.hasStem() || note.isRest()) {
594
- const adjustedStemTipY =
595
- this.getSlopeY(note.getStemX(), firstNote.getStemX(), firstNote.getStemExtents().topY, slope) + yShiftTemp;
596
-
597
- const stemTipY = note.getStemExtents().topY;
598
- // beam needs to be shifted up to accommodate note
599
- if (stemTipY * stemDirection < adjustedStemTipY * stemDirection) {
600
- const diff = Math.abs(stemTipY - adjustedStemTipY);
601
- yShiftTemp += diff * -stemDirection;
602
- totalStemExtension += diff * i;
603
- } else {
604
- // beam overshoots note, account for the difference
605
- totalStemExtension += (stemTipY - adjustedStemTipY) * stemDirection;
606
- }
607
- }
608
- }
609
-
610
- // most engraving books suggest aiming for a slope about half the angle of the
611
- // difference between the first and last notes' stem length;
612
- const idealSlope = initialSlope / 2;
613
- const distanceFromIdeal = Math.abs(idealSlope - slope);
614
-
615
- // This tries to align most beams to something closer to the idealSlope, but
616
- // doesn't go crazy. To disable, set this.renderOptions.slopeCost = 0
617
- const cost = slopeCost * distanceFromIdeal + Math.abs(totalStemExtension);
618
-
619
- // update state when a more ideal slope is found
620
- if (cost < minCost) {
621
- minCost = cost;
622
- bestSlope = slope;
623
- yShift = yShiftTemp;
624
- }
625
- }
626
-
627
- this.slope = bestSlope;
628
- this.#yShift = yShift;
629
- }
630
-
631
- /** Calculate a slope and y-shift for flat beams. */
632
- calculateFlatSlope(): void {
633
- const {
634
- notes,
635
- renderOptions: { beamWidth, minFlatBeamOffset, flatBeamOffset },
636
- } = this;
637
-
638
- const stemDirection = this.#stemDirection;
639
-
640
- // If a flat beam offset has not yet been supplied or calculated,
641
- // generate one based on the notes in this particular note group
642
- let total = 0;
643
- let extremeY = 0; // Store the highest or lowest note here
644
- let extremeBeamCount = 0; // The beam count of the extreme note
645
- let currentExtreme = 0;
646
- for (let i = 0; i < notes.length; i++) {
647
- // Total up all of the offsets so we can average them out later
648
- const note = notes[i];
649
- const stemTipY = note.getStemExtents().topY;
650
- total += stemTipY;
651
-
652
- // Store the highest (stems-up) or lowest (stems-down) note so the
653
- // offset can be adjusted in case the average isn't enough
654
- if (stemDirection === Stem.DOWN && currentExtreme < stemTipY) {
655
- currentExtreme = stemTipY;
656
- extremeY = Math.max(...note.getYs());
657
- extremeBeamCount = note.getBeamCount();
658
- } else if (stemDirection === Stem.UP && (currentExtreme === 0 || currentExtreme > stemTipY)) {
659
- currentExtreme = stemTipY;
660
- extremeY = Math.min(...note.getYs());
661
- extremeBeamCount = note.getBeamCount();
662
- }
663
- }
664
-
665
- // Average the offsets to try and come up with a reasonable one that
666
- // works for all of the notes in the beam group.
667
- let offset = total / notes.length;
668
-
669
- // In case the average isn't long enough, add or subtract some more
670
- // based on the highest or lowest note (again, based on the stem
671
- // direction). This also takes into account the added height due to
672
- // the width of the beams.
673
- const extremeTest = minFlatBeamOffset + extremeBeamCount * beamWidth * 1.5;
674
- const newOffset = extremeY + extremeTest * -stemDirection;
675
- if (stemDirection === Stem.DOWN && offset < newOffset) {
676
- offset = extremeY + extremeTest;
677
- } else if (stemDirection === Stem.UP && offset > newOffset) {
678
- offset = extremeY - extremeTest;
679
- }
680
-
681
- if (!flatBeamOffset) {
682
- // Set the offset for the group based on the calculations above.
683
- this.renderOptions.flatBeamOffset = offset;
684
- } else if (stemDirection === Stem.DOWN && offset > flatBeamOffset) {
685
- this.renderOptions.flatBeamOffset = offset;
686
- } else if (stemDirection === Stem.UP && offset < flatBeamOffset) {
687
- this.renderOptions.flatBeamOffset = offset;
688
- }
689
-
690
- // For flat beams, the slope and yShift are 0.
691
- this.slope = 0;
692
- this.#yShift = 0;
693
- }
694
-
695
- /** Return the Beam y offset. */
696
- getBeamYToDraw(): number {
697
- const firstNote = this.notes[0];
698
- const firstStemTipY = firstNote.getStemExtents().topY;
699
- let beamY = firstStemTipY;
700
-
701
- // For flat beams, set the first and last Y to the offset, rather than
702
- // using the note's stem extents.
703
- if (this.renderOptions.flatBeams && this.renderOptions.flatBeamOffset) {
704
- beamY = this.renderOptions.flatBeamOffset;
705
- }
706
- return beamY;
707
- }
708
-
709
- /**
710
- * Create new stems for the notes in the beam, so that each stem
711
- * extends into the beams.
712
- */
713
- applyStemExtensions(): void {
714
- const {
715
- notes,
716
- slope,
717
- renderOptions: { showStemlets, stemletExtension, beamWidth },
718
- } = this;
719
-
720
- const yShift = this.#yShift;
721
- const beamCount = this.#beamCount;
722
-
723
- const firstNote = notes[0];
724
- const firstStemTipY = this.getBeamYToDraw();
725
- const firstStemX = firstNote.getStemX();
726
-
727
- for (let i = 0; i < notes.length; ++i) {
728
- const note = notes[i];
729
- const stem = note.getStem();
730
- if (stem) {
731
- const stemX = note.getStemX();
732
- const { topY: stemTipY } = note.getStemExtents();
733
- const beamedStemTipY = this.getSlopeY(stemX, firstStemX, firstStemTipY, slope) + yShift;
734
- const preBeamExtension = stem.getExtension();
735
- const beamExtension =
736
- note.getStemDirection() === Stem.UP ? stemTipY - beamedStemTipY : beamedStemTipY - stemTipY;
737
- // Determine necessary extension for cross-stave notes in the beam group
738
- let crossStemExtension = 0;
739
- if (note.getStemDirection() !== this.#stemDirection) {
740
- const beamCount = note.getGlyphProps().beamCount;
741
- crossStemExtension = (1 + (beamCount - 1) * 1.5) * this.renderOptions.beamWidth;
742
-
743
- /* This will be required if the partial beams are moved to the note side.
744
- if (i > 0 && note.getGlyph().beamCount > 1) {
745
- const prevBeamCount = this.notes[i - 1].getGlyph().beamCount;
746
- const beamDiff = Math.abs(prevBeamCount - beamCount);
747
- if (beamDiff > 0) crossStemExtension -= beamDiff * (this.renderOptions.beamWidth * 1.5);
748
- }
749
- */
750
- }
751
-
752
- stem.setExtension(preBeamExtension + beamExtension + crossStemExtension);
753
- stem.adjustHeightForBeam();
754
-
755
- if (note.isRest() && showStemlets) {
756
- const totalBeamWidth = (beamCount - 1) * beamWidth * 1.5 + beamWidth;
757
- stem.setVisibility(true).setStemlet(true, totalBeamWidth + stemletExtension);
758
- }
759
- }
760
- }
761
- }
762
-
763
- /** Return upper level beam direction. */
764
- lookupBeamDirection(
765
- duration: string,
766
- prevTick: number,
767
- tick: number,
768
- nextTick: number,
769
- noteIndex: number
770
- ): PartialBeamDirection {
771
- if (duration === '4') {
772
- return BEAM_LEFT;
773
- }
774
-
775
- const forcedBeamDirection = this.#forcedPartialDirections[noteIndex];
776
- if (forcedBeamDirection) return forcedBeamDirection;
777
-
778
- const lookupDuration = `${Tables.durationToNumber(duration) / 2}`;
779
- const prevNoteGetsBeam = prevTick < Tables.durationToTicks(lookupDuration);
780
- const nextNoteGetsBeam = nextTick < Tables.durationToTicks(lookupDuration);
781
- const noteGetsBeam = tick < Tables.durationToTicks(lookupDuration);
782
-
783
- if (prevNoteGetsBeam && nextNoteGetsBeam && noteGetsBeam) {
784
- return BEAM_BOTH;
785
- } else if (prevNoteGetsBeam && !nextNoteGetsBeam && noteGetsBeam) {
786
- return BEAM_LEFT;
787
- } else if (!prevNoteGetsBeam && nextNoteGetsBeam && noteGetsBeam) {
788
- return BEAM_RIGHT;
789
- }
790
-
791
- return this.lookupBeamDirection(lookupDuration, prevTick, tick, nextTick, noteIndex);
792
- }
793
-
794
- /** Get the x coordinates for the beam lines of specific `duration`. */
795
- getBeamLines(duration: string): { start: number; end?: number }[] {
796
- const tickOfDuration = Tables.durationToTicks(duration);
797
- let beamStarted = false;
798
-
799
- type BeamInfo = { start: number; end?: number };
800
- const beamLines: BeamInfo[] = [];
801
- let currentBeam: BeamInfo | undefined = undefined;
802
- const partialBeamLength = this.renderOptions.partialBeamLength;
803
- let previousShouldBreak = false;
804
- let tickTally = 0;
805
- for (let i = 0; i < this.notes.length; ++i) {
806
- const note = this.notes[i];
807
-
808
- // See if we need to break secondary beams on this note.
809
- const ticks = note.getTicks().value();
810
- tickTally += ticks;
811
- let shouldBreak = false;
812
-
813
- // 8th note beams are always drawn.
814
- if (parseInt(duration, 10) >= 8) {
815
- // First, check to see if any indexes were set up through breakSecondaryAt()
816
- shouldBreak = this.#breakOnIndexes.indexOf(i) !== -1;
817
-
818
- // If the secondary breaks were auto-configured in the render options,
819
- // handle that as well.
820
- if (this.renderOptions.secondaryBreakTicks && tickTally >= this.renderOptions.secondaryBreakTicks) {
821
- tickTally = 0;
822
- shouldBreak = true;
823
- }
824
- }
825
- const noteGetsBeam = note.getIntrinsicTicks() < tickOfDuration;
826
-
827
- const stemX = note.getStemX() - Stem.WIDTH / 2;
828
-
829
- // Check to see if the next note in the group will get a beam at this
830
- // level. This will help to inform the partial beam logic below.
831
- const prevNote = this.notes[i - 1];
832
- const nextNote = this.notes[i + 1];
833
- const nextNoteGetsBeam = nextNote && nextNote.getIntrinsicTicks() < tickOfDuration;
834
- const prevNoteGetsBeam = prevNote && prevNote.getIntrinsicTicks() < tickOfDuration;
835
- const beamAlone = prevNote && nextNote && noteGetsBeam && !prevNoteGetsBeam && !nextNoteGetsBeam;
836
- // const beamAlone = noteGetsBeam && !prevNoteGetsBeam && !nextNoteGetsBeam;
837
- if (noteGetsBeam) {
838
- // This note gets a beam at the current level
839
- if (beamStarted) {
840
- // We're currently in the middle of a beam. Just continue it on to
841
- // the stem X of the current note.
842
- currentBeam = beamLines[beamLines.length - 1];
843
- currentBeam.end = stemX;
844
-
845
- // If a secondary beam break is set up, end the beam right now.
846
- if (shouldBreak) {
847
- beamStarted = false;
848
- if (nextNote && !nextNoteGetsBeam && currentBeam.end === undefined) {
849
- // This note gets a beam,.but the next one does not. This means
850
- // we need a partial pointing right.
851
- currentBeam.end = currentBeam.start - partialBeamLength;
852
- }
853
- }
854
- } else {
855
- // No beam started yet. Start a new one.
856
- currentBeam = { start: stemX, end: undefined };
857
- beamStarted = true;
858
-
859
- if (beamAlone) {
860
- // previous and next beam exists and does not get a beam but current gets it.
861
- const prevTick = prevNote.getIntrinsicTicks();
862
- const nextTick = nextNote.getIntrinsicTicks();
863
- const tick = note.getIntrinsicTicks();
864
- const beamDirection = this.lookupBeamDirection(duration, prevTick, tick, nextTick, i);
865
-
866
- if ([BEAM_LEFT, BEAM_BOTH].includes(beamDirection)) {
867
- currentBeam.end = currentBeam.start - partialBeamLength;
868
- } else {
869
- currentBeam.end = currentBeam.start + partialBeamLength;
870
- }
871
- } else if (!nextNoteGetsBeam) {
872
- // The next note doesn't get a beam. Draw a partial.
873
- if ((previousShouldBreak || i === 0) && nextNote) {
874
- // This is the first note (but not the last one), or it is
875
- // following a secondary break. Draw a partial to the right.
876
- currentBeam.end = currentBeam.start + partialBeamLength;
877
- } else {
878
- // By default, draw a partial to the left.
879
- currentBeam.end = currentBeam.start - partialBeamLength;
880
- }
881
- } else if (shouldBreak) {
882
- // This note should have a secondary break after it. Even though
883
- // we just started a beam, it needs to end immediately.
884
- currentBeam.end = currentBeam.start - partialBeamLength;
885
- beamStarted = false;
886
- }
887
- beamLines.push(currentBeam);
888
- }
889
- } else {
890
- // The current note does not get a beam.
891
- beamStarted = false;
892
- }
893
-
894
- // Store the secondary break flag to inform the partial beam logic in
895
- // the next iteration of the loop.
896
- previousShouldBreak = shouldBreak;
897
- }
898
-
899
- // Add a partial beam pointing left if this is the last note in the group
900
- const lastBeam = beamLines[beamLines.length - 1];
901
- if (lastBeam && lastBeam.end === undefined) {
902
- lastBeam.end = lastBeam.start - partialBeamLength;
903
- }
904
- return beamLines;
905
- }
906
-
907
- /** Render the stems for each note. */
908
- protected drawStems(ctx: RenderContext): void {
909
- this.notes.forEach((note) => {
910
- const stem = note.getStem();
911
- if (stem) {
912
- const stemX = note.getStemX();
913
- stem.setNoteHeadXBounds(stemX, stemX);
914
- stem.setContext(ctx).draw();
915
- }
916
- }, this);
917
- }
918
-
919
- // Render the beam lines
920
- protected drawBeamLines(ctx: RenderContext): void {
921
- const validBeamDurations = ['4', '8', '16', '32', '64'];
922
-
923
- const firstNote = this.notes[0];
924
- let beamY = this.getBeamYToDraw();
925
- const firstStemX = firstNote.getStemX();
926
- const beamThickness = this.renderOptions.beamWidth * this.#stemDirection;
927
-
928
- // Draw the beams.
929
- for (let i = 0; i < validBeamDurations.length; ++i) {
930
- const duration = validBeamDurations[i];
931
- const beamLines = this.getBeamLines(duration);
932
-
933
- for (let j = 0; j < beamLines.length; ++j) {
934
- const beamLine = beamLines[j];
935
- const startBeamX = beamLine.start;
936
-
937
- const startBeamY = this.getSlopeY(startBeamX, firstStemX, beamY, this.slope);
938
- const lastBeamX = beamLine.end;
939
- if (lastBeamX) {
940
- const lastBeamY = this.getSlopeY(lastBeamX, firstStemX, beamY, this.slope);
941
-
942
- ctx.beginPath();
943
- ctx.moveTo(startBeamX, startBeamY);
944
- ctx.lineTo(startBeamX, startBeamY + beamThickness);
945
- ctx.lineTo(lastBeamX + 1, lastBeamY + beamThickness);
946
- ctx.lineTo(lastBeamX + 1, lastBeamY);
947
- ctx.closePath();
948
- ctx.fill();
949
- } else {
950
- throw new RuntimeError('NoLastBeamX', 'lastBeamX undefined.');
951
- }
952
- }
953
-
954
- beamY += beamThickness * 1.5;
955
- }
956
- }
957
-
958
- /** Pre-format the beam. */
959
- preFormat(): this {
960
- return this;
961
- }
962
-
963
- /**
964
- * Post-format the beam. This can only be called after
965
- * the notes in the beam have both `x` and `y` values. ie: they've
966
- * been formatted and have staves.
967
- */
968
- postFormat(): void {
969
- if (this.postFormatted) return;
970
-
971
- // Calculate a smart slope if we're not forcing the beams to be flat.
972
- if (isTabNote(this.notes[0]) || this.renderOptions.flatBeams) {
973
- this.calculateFlatSlope();
974
- } else {
975
- this.calculateSlope();
976
- }
977
- this.applyStemExtensions();
978
-
979
- this.postFormatted = true;
980
- }
981
-
982
- /** Render the beam to the canvas context */
983
- draw(): void {
984
- const ctx = this.checkContext();
985
- this.setRendered();
986
- if (this.#unbeamable) return;
987
-
988
- if (!this.postFormatted) {
989
- this.postFormat();
990
- }
991
-
992
- this.drawStems(ctx);
993
- this.applyStyle();
994
- ctx.openGroup('beam', this.getAttribute('id'));
995
- this.drawBeamLines(ctx);
996
- ctx.closeGroup();
997
- this.restoreStyle();
998
- }
999
- }