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/accidental.ts DELETED
@@ -1,570 +0,0 @@
1
- // Copyright (c) 2023-present VexFlow contributors: https://github.com/vexflow/vexflow/graphs/contributors
2
- // MIT License
3
- // @author Mohit Cheppudira
4
- // @author Greg Ristow (modifications)
5
-
6
- import { Fraction } from './fraction';
7
- import { Metrics } from './metrics';
8
- import { Modifier } from './modifier';
9
- import { ModifierContextState } from './modifiercontext';
10
- import { Music } from './music';
11
- import { Note } from './note';
12
- import { Tables } from './tables';
13
- import { Tickable } from './tickable';
14
- import { Category, isAccidental, isGraceNote, isGraceNoteGroup, isStaveNote } from './typeguard';
15
- import { defined, log } from './util';
16
- import { Voice } from './voice';
17
-
18
- type StaveLineAccidentalLayoutMetrics = {
19
- column: number;
20
- line: number;
21
- /**
22
- * A flat line needs more clearance above than below. This is
23
- * set to true if the accidental is either a flat or double flat.
24
- */
25
- flatLine: boolean;
26
- /**
27
- * Double sharps need less clearance above and below than other
28
- * accidentals.
29
- */
30
- dblSharpLine: boolean;
31
- numAcc: number;
32
- width: number;
33
- };
34
-
35
- // eslint-disable-next-line
36
- function L(...args: any[]) {
37
- if (Accidental.DEBUG) log('VexFlow.Accidental', args);
38
- }
39
-
40
- /**
41
- * An `Accidental` inherits from `Modifier`, and is formatted within a
42
- * `ModifierContext`. Accidentals are modifiers that can be attached to
43
- * notes. Support is included for both western and microtonal accidentals.
44
- *
45
- * See `tests/accidental_tests.ts` for usage examples.
46
- */
47
-
48
- export class Accidental extends Modifier {
49
- /** Accidental code provided to the constructor. */
50
- readonly type: string;
51
- /** To enable logging for this class. Set `VexFlow.Accidental.DEBUG` to `true`. */
52
- static DEBUG: boolean = false;
53
- protected cautionary: boolean;
54
-
55
- /** Accidentals category string. */
56
- static get CATEGORY(): string {
57
- return Category.Accidental;
58
- }
59
-
60
- /** Arrange accidentals inside a ModifierContext. */
61
- static format(accidentals: Accidental[], state: ModifierContextState): void {
62
- // If there are no accidentals, no need to format their positions.
63
- if (!accidentals || accidentals.length === 0) return;
64
-
65
- const noteheadAccidentalPadding = Metrics.get('Accidental.noteheadAccidentalPadding');
66
- const leftShift = state.leftShift + noteheadAccidentalPadding;
67
- const accidentalSpacing = Metrics.get('Accidental.accidentalSpacing');
68
- const additionalPadding = Metrics.get('Accidental.leftPadding'); // padding to the left of all accidentals
69
-
70
- // A type used just in this formatting function.
71
- type AccidentalLinePositionsAndXSpaceNeeds = {
72
- y?: number;
73
- line: number;
74
- /**
75
- * The amount by which the accidental requests notes be shifted to the right
76
- * to accomodate its presence.
77
- */
78
- extraXSpaceNeeded: number;
79
- accidental: Accidental;
80
- spacingBetweenStaveLines?: number;
81
- };
82
-
83
- const accidentalLinePositionsAndSpaceNeeds: AccidentalLinePositionsAndXSpaceNeeds[] = [];
84
- let prevNote = undefined;
85
- let extraXSpaceNeededForLeftDisplacedNotehead = 0;
86
-
87
- // First determine the accidentals' Y positions from the note.keys
88
- for (let i = 0; i < accidentals.length; ++i) {
89
- const accidental: Accidental = accidentals[i];
90
-
91
- const note = accidental.getNote();
92
- const stave = note.getStave();
93
- const index = accidental.checkIndex();
94
- const props = note.getKeyProps()[index];
95
-
96
- if (note !== prevNote) {
97
- // Iterate through all notes to get the displaced pixels
98
- for (let n = 0; n < note.keys.length; ++n) {
99
- // If the current extra left-space needed isn't as big as this note's,
100
- // then we need to use this note's.
101
- extraXSpaceNeededForLeftDisplacedNotehead = Math.max(
102
- note.getLeftDisplacedHeadPx() - note.getXShift(),
103
- extraXSpaceNeededForLeftDisplacedNotehead
104
- );
105
- }
106
- prevNote = note;
107
- }
108
- if (stave) {
109
- const lineSpace = stave.getSpacingBetweenLines();
110
- const y = stave.getYForLine(props.line);
111
- const accLine = Math.round((y / lineSpace) * 2) / 2;
112
- accidentalLinePositionsAndSpaceNeeds.push({
113
- y,
114
- line: accLine,
115
- extraXSpaceNeeded: extraXSpaceNeededForLeftDisplacedNotehead,
116
- accidental: accidental,
117
- spacingBetweenStaveLines: lineSpace,
118
- });
119
- } else {
120
- accidentalLinePositionsAndSpaceNeeds.push({
121
- line: props.line,
122
- extraXSpaceNeeded: extraXSpaceNeededForLeftDisplacedNotehead,
123
- accidental: accidental,
124
- });
125
- }
126
- }
127
-
128
- // Sort accidentals by line number.
129
- accidentalLinePositionsAndSpaceNeeds.sort((a, b) => b.line - a.line);
130
-
131
- const staveLineAccidentalLayoutMetrics: StaveLineAccidentalLayoutMetrics[] = [];
132
-
133
- // amount by which all accidentals must be shifted right or left for
134
- // stem flipping, notehead shifting concerns.
135
- let maxExtraXSpaceNeeded = 0;
136
-
137
- // Create an array of unique line numbers (staveLineAccidentalLayoutMetrics)
138
- // from accidentalLinePositionsAndSpaceNeeds
139
- for (let i = 0; i < accidentalLinePositionsAndSpaceNeeds.length; i++) {
140
- const accidentalLinePositionAndSpaceNeeds = accidentalLinePositionsAndSpaceNeeds[i];
141
- const accidentalType = accidentalLinePositionAndSpaceNeeds.accidental.type;
142
- const priorLineMetric = staveLineAccidentalLayoutMetrics[staveLineAccidentalLayoutMetrics.length - 1];
143
- let currentLineMetric: StaveLineAccidentalLayoutMetrics;
144
-
145
- // if this is the first line, or a new line, add a staveLineAccidentalLayoutMetric
146
- if (!priorLineMetric || priorLineMetric?.line !== accidentalLinePositionAndSpaceNeeds.line) {
147
- currentLineMetric = {
148
- line: accidentalLinePositionAndSpaceNeeds.line,
149
- flatLine: true,
150
- dblSharpLine: true,
151
- numAcc: 0,
152
- width: 0,
153
- column: 0,
154
- };
155
- staveLineAccidentalLayoutMetrics.push(currentLineMetric);
156
- } else {
157
- currentLineMetric = priorLineMetric;
158
- }
159
-
160
- // if this accidental is not a flat, the accidental needs 3.0 lines lower
161
- // clearance instead of 2.5 lines for b or bb.
162
- if (accidentalType !== 'b' && accidentalType !== 'bb') {
163
- currentLineMetric.flatLine = false;
164
- }
165
-
166
- // if this accidental is not a double sharp, the accidental needs 3.0 lines above
167
- if (accidentalType !== '##') {
168
- currentLineMetric.dblSharpLine = false;
169
- }
170
-
171
- // Track how many accidentals are on this line:
172
- currentLineMetric.numAcc++;
173
-
174
- // Track the total xOffset needed for this line which will be needed
175
- // for formatting lines w/ multiple accidentals:
176
-
177
- // width = accidental width + universal spacing between accidentals
178
- currentLineMetric.width += accidentalLinePositionAndSpaceNeeds.accidental.getWidth() + accidentalSpacing;
179
-
180
- // if this extraXSpaceNeeded is the largest so far, use it as the starting point for
181
- // all accidental columns.
182
- maxExtraXSpaceNeeded = Math.max(accidentalLinePositionAndSpaceNeeds.extraXSpaceNeeded, maxExtraXSpaceNeeded);
183
- }
184
-
185
- // ### Place Accidentals in Columns
186
- //
187
- // Default to a classic triangular layout (middle accidental farthest left),
188
- // but follow exceptions as outlined in G. Read's _Music Notation_ and
189
- // Elaine Gould's _Behind Bars_.
190
- //
191
- // Additionally, this implements different vertical collision rules for
192
- // flats (only need 2.5 lines clearance below) and double sharps (only
193
- // need 2.5 lines of clearance above or below).
194
- //
195
- // Classic layouts and exception patterns are found in the 'tables.js'
196
- // in 'Tables.accidentalColumnsTable'
197
- //
198
- // Beyond 6 vertical accidentals, default to the parallel ascending lines approach,
199
- // using as few columns as possible for the verticle structure.
200
- //
201
- // TODO (?): Allow column to be specified for an accidental at run-time?
202
-
203
- let totalColumns = 0;
204
-
205
- // establish the boundaries for a group of notes with clashing accidentals:
206
- for (let i = 0; i < staveLineAccidentalLayoutMetrics.length; i++) {
207
- let noFurtherConflicts = false;
208
- const groupStart = i;
209
- let groupEnd = i;
210
-
211
- while (groupEnd + 1 < staveLineAccidentalLayoutMetrics.length && !noFurtherConflicts) {
212
- // if this note conflicts with the next:
213
- if (
214
- this.#checkCollision(
215
- staveLineAccidentalLayoutMetrics[groupEnd],
216
- staveLineAccidentalLayoutMetrics[groupEnd + 1]
217
- )
218
- ) {
219
- // include the next note in the group:
220
- groupEnd++;
221
- } else {
222
- noFurtherConflicts = true;
223
- }
224
- }
225
-
226
- // Gets an a line from the `lineList`, relative to the current group
227
- const getGroupLine = (index: number) => staveLineAccidentalLayoutMetrics[groupStart + index];
228
- const getGroupLines = (indexes: number[]) => indexes.map(getGroupLine);
229
- const lineDifference = (indexA: number, indexB: number) => {
230
- const [a, b] = getGroupLines([indexA, indexB]).map((item) => item.line);
231
- return a - b;
232
- };
233
-
234
- const notColliding = (...indexPairs: number[][]) =>
235
- indexPairs.map(getGroupLines).every(([line1, line2]) => !this.#checkCollision(line1, line2));
236
-
237
- // Set columns for the lines in this group:
238
- const groupLength = groupEnd - groupStart + 1;
239
-
240
- // Set the accidental column for each line of the group
241
- let endCase = this.#checkCollision(
242
- staveLineAccidentalLayoutMetrics[groupStart],
243
- staveLineAccidentalLayoutMetrics[groupEnd]
244
- )
245
- ? 'a'
246
- : 'b';
247
-
248
- switch (groupLength) {
249
- case 3:
250
- if (endCase === 'a' && lineDifference(1, 2) === 0.5 && lineDifference(0, 1) !== 0.5) {
251
- endCase = 'secondOnBottom';
252
- }
253
- break;
254
- case 4:
255
- if (notColliding([0, 2], [1, 3])) {
256
- endCase = 'spacedOutTetrachord';
257
- }
258
- break;
259
- case 5:
260
- if (endCase === 'b' && notColliding([1, 3])) {
261
- endCase = 'spacedOutPentachord';
262
- if (notColliding([0, 2], [2, 4])) {
263
- endCase = 'verySpacedOutPentachord';
264
- }
265
- }
266
- break;
267
- case 6:
268
- if (notColliding([0, 3], [1, 4], [2, 5])) {
269
- endCase = 'spacedOutHexachord';
270
- }
271
- if (notColliding([0, 2], [2, 4], [1, 3], [3, 5])) {
272
- endCase = 'verySpacedOutHexachord';
273
- }
274
- break;
275
- default:
276
- break;
277
- }
278
-
279
- let groupMember;
280
- let column;
281
- // If the group contains seven members or more, use ascending parallel lines
282
- // of accidentals, using as few columns as possible while avoiding collisions.
283
- if (groupLength >= 7) {
284
- // First, determine how many columns to use:
285
- let patternLength = 2;
286
- let collisionDetected = true;
287
- while (collisionDetected === true) {
288
- collisionDetected = false;
289
- for (let line = 0; line + patternLength < staveLineAccidentalLayoutMetrics.length; line++) {
290
- if (
291
- this.#checkCollision(
292
- staveLineAccidentalLayoutMetrics[line],
293
- staveLineAccidentalLayoutMetrics[line + patternLength]
294
- )
295
- ) {
296
- collisionDetected = true;
297
- patternLength++;
298
- break;
299
- }
300
- }
301
- }
302
- // Then, assign a column to each line of accidentals
303
- for (groupMember = i; groupMember <= groupEnd; groupMember++) {
304
- column = ((groupMember - i) % patternLength) + 1;
305
- staveLineAccidentalLayoutMetrics[groupMember].column = column;
306
- totalColumns = totalColumns > column ? totalColumns : column;
307
- }
308
- } else {
309
- // If the group contains fewer than seven members, use the layouts from
310
- // the Tables.accidentalColumnsTable (See: tables.ts).
311
- for (groupMember = i; groupMember <= groupEnd; groupMember++) {
312
- column = Tables.accidentalColumnsTable[groupLength][endCase][groupMember - i];
313
- staveLineAccidentalLayoutMetrics[groupMember].column = column;
314
- totalColumns = totalColumns > column ? totalColumns : column;
315
- }
316
- }
317
-
318
- // Increment i to the last note that was set, so that if a lower set of notes
319
- // does not conflict at all with this group, it can have its own classic shape.
320
- i = groupEnd;
321
- }
322
-
323
- // ### Convert Columns to xOffsets
324
- //
325
- // This keeps columns aligned, even if they have different accidentals within them
326
- // which sometimes results in a larger xOffset than is an accidental might need
327
- // to preserve the symmetry of the accidental shape.
328
- //
329
- // Neither A.C. Vinci nor G. Read address this, and it typically only happens in
330
- // music with complex chord clusters.
331
- //
332
- // TODO (?): Optionally allow closer compression of accidentals, instead of forcing
333
- // parallel columns.
334
-
335
- // track each column's max width, which will be used as initial shift of later columns:
336
- const columnWidths: number[] = [];
337
- const columnXOffsets: number[] = [];
338
- for (let i = 0; i <= totalColumns; i++) {
339
- columnWidths[i] = 0;
340
- columnXOffsets[i] = 0;
341
- }
342
-
343
- columnWidths[0] = leftShift + maxExtraXSpaceNeeded;
344
- columnXOffsets[0] = leftShift;
345
-
346
- // Fill columnWidths with widest needed x-space;
347
- // this is what keeps the columns parallel.
348
- staveLineAccidentalLayoutMetrics.forEach((line) => {
349
- if (line.width > columnWidths[line.column]) columnWidths[line.column] = line.width;
350
- });
351
-
352
- for (let i = 1; i < columnWidths.length; i++) {
353
- // this column's offset = this column's width + previous column's offset
354
- columnXOffsets[i] = columnWidths[i] + columnXOffsets[i - 1];
355
- }
356
-
357
- const totalShift = columnXOffsets[columnXOffsets.length - 1];
358
- // Set the xShift for each accidental according to column offsets:
359
- let accCount = 0;
360
- staveLineAccidentalLayoutMetrics.forEach((line) => {
361
- let lineWidth = 0;
362
- const lastAccOnLine = accCount + line.numAcc;
363
- // handle all of the accidentals on a given line:
364
- for (accCount; accCount < lastAccOnLine; accCount++) {
365
- const xShift = columnXOffsets[line.column - 1] + lineWidth + maxExtraXSpaceNeeded;
366
- accidentalLinePositionsAndSpaceNeeds[accCount].accidental.setXShift(xShift);
367
- // keep track of the width of accidentals we've added so far, so that when
368
- // we loop, we add space for them.
369
- lineWidth += accidentalLinePositionsAndSpaceNeeds[accCount].accidental.getWidth() + accidentalSpacing;
370
- L('Line, accCount, shift: ', line.line, accCount, xShift);
371
- }
372
- });
373
- // update the overall layout with the full width of the accidental shapes:
374
- state.leftShift = totalShift + additionalPadding;
375
- }
376
-
377
- /** Helper function to determine whether two lines of accidentals collide vertically */
378
- static #checkCollision(line1: StaveLineAccidentalLayoutMetrics, line2: StaveLineAccidentalLayoutMetrics): boolean {
379
- let clearance = line2.line - line1.line;
380
- let clearanceRequired = 3;
381
- // But less clearance is required for certain accidentals: b, bb and ##.
382
- if (clearance > 0) {
383
- // then line 2 is on top
384
- clearanceRequired = line2.flatLine || line2.dblSharpLine ? 2.5 : 3.0;
385
- if (line1.dblSharpLine) clearance -= 0.5;
386
- } else {
387
- // line 1 is on top
388
- clearanceRequired = line1.flatLine || line1.dblSharpLine ? 2.5 : 3.0;
389
- if (line2.dblSharpLine) clearance -= 0.5;
390
- }
391
- const collision = Math.abs(clearance) < clearanceRequired;
392
- L('Line1, Line2, Collision: ', line1.line, line2.line, collision);
393
- return collision;
394
- }
395
-
396
- /**
397
- * Use this method to automatically apply accidentals to a set of `voices`.
398
- * The accidentals will be remembered between all the voices provided.
399
- * Optionally, you can also provide an initial `keySignature`.
400
- */
401
- static applyAccidentals(voices: Voice[], keySignature: string): void {
402
- const tickPositions: number[] = [];
403
- const tickNoteMap: Record<number, Tickable[]> = {};
404
-
405
- // Sort the tickables in each voice by their tick position in the voice.
406
- voices.forEach((voice) => {
407
- const tickPosition = new Fraction(0, 1);
408
- const tickable = voice.getTickables();
409
- tickable.forEach((t) => {
410
- if (t.shouldIgnoreTicks()) return;
411
-
412
- const notesAtPosition = tickNoteMap[tickPosition.value()];
413
-
414
- if (!notesAtPosition) {
415
- tickPositions.push(tickPosition.value());
416
- tickNoteMap[tickPosition.value()] = [t];
417
- } else {
418
- notesAtPosition.push(t);
419
- }
420
-
421
- tickPosition.add(t.getTicks());
422
- });
423
- });
424
-
425
- const music = new Music();
426
-
427
- // Default key signature is C major.
428
- if (!keySignature) keySignature = 'C';
429
-
430
- // Get the scale map, which represents the current state of each pitch.
431
- const scaleMapKey = music.createScaleMap(keySignature);
432
- const scaleMap: Record<string, string> = {};
433
-
434
- tickPositions.forEach((tickPos: number) => {
435
- const tickables = tickNoteMap[tickPos];
436
-
437
- // Array to store all pitches that modified accidental states
438
- // at this tick position
439
- const modifiedPitches: string[] = [];
440
-
441
- const processNote = (t: Tickable) => {
442
- // Only StaveNote implements .addModifier(), which is used below.
443
- if (!isStaveNote(t) || t.isRest() || t.shouldIgnoreTicks()) {
444
- return;
445
- }
446
-
447
- // Go through each key and determine if an accidental should be applied.
448
- const staveNote = t;
449
- staveNote.keys.forEach((keyString: string, keyIndex: number) => {
450
- const key = music.getNoteParts(keyString.split('/')[0]);
451
- const octave = keyString.split('/')[1];
452
-
453
- // Force a natural for every key without an accidental
454
- const accidentalString = key.accidental || 'n';
455
- const pitch = key.root + accidentalString;
456
-
457
- // Determine if the current pitch has the same accidental
458
- // as the scale state
459
- if (!scaleMap[key.root + octave]) scaleMap[key.root + octave] = scaleMapKey[key.root];
460
- const sameAccidental = scaleMap[key.root + octave] === pitch;
461
-
462
- // Determine if an identical pitch in the chord already
463
- // modified the accidental state
464
- const previouslyModified = modifiedPitches.indexOf(keyString) > -1;
465
-
466
- // Remove accidentals
467
- staveNote.getModifiers().forEach((modifier, index) => {
468
- if (isAccidental(modifier) && modifier.type == accidentalString && modifier.getIndex() == keyIndex) {
469
- staveNote.getModifiers().splice(index, 1);
470
- }
471
- });
472
-
473
- // Add the accidental to the StaveNote
474
- if (!sameAccidental || (sameAccidental && previouslyModified)) {
475
- // Modify the scale map so that the root pitch has an
476
- // updated state
477
- scaleMap[key.root + octave] = pitch;
478
-
479
- // Create the accidental
480
- const accidental = new Accidental(accidentalString);
481
-
482
- // Attach the accidental to the StaveNote
483
- staveNote.addModifier(accidental, keyIndex);
484
-
485
- // Add the pitch to list of pitches that modified accidentals
486
- modifiedPitches.push(keyString);
487
- }
488
- });
489
-
490
- // process grace notes
491
- staveNote.getModifiers().forEach((modifier: Modifier) => {
492
- if (isGraceNoteGroup(modifier)) {
493
- modifier.getGraceNotes().forEach(processNote);
494
- }
495
- });
496
- };
497
-
498
- tickables.forEach(processNote);
499
- });
500
- }
501
-
502
- /**
503
- * Create accidental.
504
- * @param type value from `VexFlow.accidentalCodes.accidentals` table in `tables.ts`.
505
- * For example: `#`, `##`, `b`, `n`, etc.
506
- */
507
- constructor(type: string) {
508
- super();
509
-
510
- L('New accidental: ', type);
511
-
512
- this.type = type;
513
- this.position = Modifier.Position.LEFT;
514
-
515
- // Cautionary accidentals have parentheses around them
516
- this.cautionary = false;
517
-
518
- this.reset();
519
- }
520
-
521
- protected reset(): void {
522
- this.text = '';
523
-
524
- if (!this.cautionary) {
525
- this.text += Tables.accidentalCodes(this.type);
526
- this.fontInfo.size = Metrics.get('Accidental.fontSize');
527
- } else {
528
- this.text += Tables.accidentalCodes('{');
529
- this.text += Tables.accidentalCodes(this.type);
530
- this.text += Tables.accidentalCodes('}');
531
- this.fontInfo.size = Metrics.get('Accidental.cautionary.fontSize');
532
- }
533
- // Accidentals attached to grace notes are rendered smaller.
534
- if (isGraceNote(this.note)) {
535
- this.fontInfo.size = Metrics.get('Accidental.grace.fontSize');
536
- }
537
- }
538
-
539
- /** Attach this accidental to `note`, which must be a `StaveNote`. */
540
- setNote(note: Note): this {
541
- defined(note, 'ArgumentError', `Bad note value: ${note}`);
542
-
543
- this.note = note;
544
- this.reset();
545
- return this;
546
- }
547
-
548
- /** If called, draws parenthesis around accidental. */
549
- setAsCautionary(): this {
550
- this.cautionary = true;
551
- this.reset();
552
- return this;
553
- }
554
-
555
- /** Render accidental onto canvas. */
556
- draw(): void {
557
- const { type, position, index } = this;
558
-
559
- const ctx = this.checkContext();
560
- const note = this.checkAttachedNote();
561
- this.setRendered();
562
-
563
- // Figure out the start `x` and `y` coordinates for note and index.
564
- const start = note.getModifierStartXY(position, index);
565
- this.x = start.x - this.width;
566
- this.y = start.y;
567
- L('Rendering: ', type, start.x, start.y);
568
- this.renderText(ctx, 0, 0);
569
- }
570
- }