vexflow 5.1.2 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +7 -6
  2. package/build/cjs/vexflow-bravura.js +2 -2
  3. package/build/cjs/vexflow-bravura.js.map +1 -1
  4. package/build/cjs/vexflow-core.js +2 -2
  5. package/build/cjs/vexflow-core.js.map +1 -1
  6. package/build/cjs/vexflow-debug-with-tests.js +2633 -415
  7. package/build/cjs/vexflow-debug-with-tests.js.map +1 -1
  8. package/build/cjs/vexflow-debug.js +2478 -382
  9. package/build/cjs/vexflow-debug.js.map +1 -1
  10. package/build/cjs/vexflow.js +2 -2
  11. package/build/cjs/vexflow.js.map +1 -1
  12. package/build/esm/src/accidental.js +3 -0
  13. package/build/esm/src/articulation.js +27 -14
  14. package/build/esm/src/beam.js +12 -2
  15. package/build/esm/src/clef.js +3 -0
  16. package/build/esm/src/clefnote.js +5 -1
  17. package/build/esm/src/dot.js +1 -1
  18. package/build/esm/src/easyscore/composition.js +297 -0
  19. package/build/esm/src/easyscore/elementindex.js +81 -0
  20. package/build/esm/src/easyscore/elements.js +324 -0
  21. package/build/esm/src/easyscore/policies.js +69 -0
  22. package/build/esm/src/easyscore/rhythm.js +42 -0
  23. package/build/esm/src/easyscore.js +448 -26
  24. package/build/esm/src/element.js +13 -2
  25. package/build/esm/src/factory.js +256 -60
  26. package/build/esm/src/formatter.js +32 -4
  27. package/build/esm/src/keysignature.js +9 -1
  28. package/build/esm/src/keysignote.js +2 -2
  29. package/build/esm/src/note.js +5 -0
  30. package/build/esm/src/parenthesis.js +1 -1
  31. package/build/esm/src/parser.js +6 -1
  32. package/build/esm/src/proportionalformatter.js +186 -0
  33. package/build/esm/src/registry.js +27 -0
  34. package/build/esm/src/sheet.js +20 -3
  35. package/build/esm/src/stave.js +9 -2
  36. package/build/esm/src/stavenote.js +12 -12
  37. package/build/esm/src/stemmablenote.js +6 -1
  38. package/build/esm/src/tickable.js +5 -0
  39. package/build/esm/src/tuplet.js +3 -2
  40. package/build/esm/src/version.js +3 -3
  41. package/build/esm/src/vexflow.js +2 -1
  42. package/build/esm/tests/beam_tests.js +35 -0
  43. package/build/esm/tests/easyscore_tests.js +40 -0
  44. package/build/esm/tests/easyscore_types.js +65 -0
  45. package/build/esm/tests/formatter_tests.js +41 -0
  46. package/build/esm/tests/node/easyscore-rendering-tests.mjs +332 -0
  47. package/build/esm/tests/node/easyscore-tests.mjs +953 -0
  48. package/build/esm/tests/node/proportional-spacing-tests.mjs +214 -0
  49. package/build/esm/tools/easyscore-api-audit.mjs +58 -0
  50. package/build/esm/tools/easyscore-composition.mjs +62 -0
  51. package/build/esm/tools/easyscore-example.mjs +16 -0
  52. package/build/esm/tools/easyscore-families.mjs +61 -0
  53. package/build/esm/tools/easyscore-references-example.mjs +26 -0
  54. package/build/esm/tools/easyscore-rhythm.mjs +58 -0
  55. package/build/esm/tools/easyscore-structure.mjs +88 -0
  56. package/build/esm/tools/explorer/catalog/entries.mjs +6 -0
  57. package/build/esm/tools/explorer/catalog/expression.mjs +68 -0
  58. package/build/esm/tools/explorer/catalog/helpers.mjs +29 -0
  59. package/build/esm/tools/explorer/catalog/layout.mjs +109 -0
  60. package/build/esm/tools/explorer/catalog/notes.mjs +61 -0
  61. package/build/esm/tools/explorer/catalog/staves.mjs +85 -0
  62. package/build/esm/tools/explorer/catalog/strings.mjs +25 -0
  63. package/build/esm/tools/explorer/catalog.mjs +14 -0
  64. package/build/types/src/accidental.d.ts +2 -0
  65. package/build/types/src/articulation.d.ts +6 -0
  66. package/build/types/src/beam.d.ts +2 -0
  67. package/build/types/src/clef.d.ts +2 -0
  68. package/build/types/src/easyscore/composition.d.ts +107 -0
  69. package/build/types/src/easyscore/elementindex.d.ts +30 -0
  70. package/build/types/src/easyscore/elements.d.ts +156 -0
  71. package/build/types/src/easyscore/policies.d.ts +12 -0
  72. package/build/types/src/easyscore/rhythm.d.ts +9 -0
  73. package/build/types/src/easyscore.d.ts +153 -11
  74. package/build/types/src/element.d.ts +5 -1
  75. package/build/types/src/factory.d.ts +91 -8
  76. package/build/types/src/formatter.d.ts +7 -1
  77. package/build/types/src/keysignature.d.ts +3 -0
  78. package/build/types/src/keysignote.d.ts +1 -1
  79. package/build/types/src/note.d.ts +2 -0
  80. package/build/types/src/parser.d.ts +5 -0
  81. package/build/types/src/proportionalformatter.d.ts +30 -0
  82. package/build/types/src/registry.d.ts +4 -0
  83. package/build/types/src/stave.d.ts +2 -0
  84. package/build/types/src/stavenote.d.ts +1 -1
  85. package/build/types/src/stemmablenote.d.ts +6 -1
  86. package/build/types/src/tickable.d.ts +2 -0
  87. package/build/types/src/vexflow.d.ts +2 -1
  88. package/changelog/CHANGELOG.md +35 -0
  89. package/package.json +7 -2
@@ -316,6 +316,9 @@ export class Accidental extends Modifier {
316
316
  this.reset();
317
317
  return this;
318
318
  }
319
+ isCautionary() {
320
+ return this.cautionary;
321
+ }
319
322
  draw() {
320
323
  const { type, position, index } = this;
321
324
  const ctx = this.checkContext();
@@ -9,6 +9,7 @@ function L(...args) {
9
9
  log('VexFlow.Articulation', args);
10
10
  }
11
11
  const { ABOVE, BELOW } = Modifier.Position;
12
+ const easyScoreGlyphs = new Set(Object.values(Glyphs));
12
13
  function roundToNearestHalf(mathFn, value) {
13
14
  return mathFn(value / 0.5) * 0.5;
14
15
  }
@@ -190,24 +191,36 @@ export class Articulation extends Modifier {
190
191
  state.rightShift += overlap / 2;
191
192
  return true;
192
193
  }
193
- static easyScoreHook({ articulations }, note, builder) {
194
- if (!articulations)
195
- return;
196
- const articNameToCode = {
194
+ static parseEasyScore(articulations) {
195
+ const aliases = {
197
196
  staccato: 'a.',
198
197
  tenuto: 'a-',
199
198
  accent: 'a>',
199
+ fermata: 'a@',
200
+ marcato: 'a^',
201
+ staccatissimo: 'av',
200
202
  };
201
- articulations
202
- .split(',')
203
- .map((articString) => articString.trim().split('.'))
204
- .map(([name, position]) => {
205
- const artic = { type: articNameToCode[name] };
206
- if (position)
207
- artic.position = Modifier.PositionString[position];
208
- return builder.getFactory().Articulation(artic);
209
- })
210
- .map((artic) => note.addModifier(artic, 0));
203
+ const singleCode = articulations.trim().replace(/\.(above|below|left|right)$/, '');
204
+ const items = Tables.articulationCodes(singleCode) ? [articulations] : articulations.split(',');
205
+ return items.map((value) => {
206
+ var _a;
207
+ const match = /^(.*)\.(above|below|left|right)$/.exec(value.trim());
208
+ const name = match ? match[1] : value.trim();
209
+ const type = Object.hasOwnProperty.call(aliases, name) ? aliases[name] : name;
210
+ const glyph = Object.hasOwnProperty.call(Glyphs, type) ? Glyphs[type] : type;
211
+ if (!Object.hasOwnProperty.call((_a = Tables.articulationCodes(type)) !== null && _a !== void 0 ? _a : {}, 'betweenLines') &&
212
+ !easyScoreGlyphs.has(glyph)) {
213
+ throw new RuntimeError('BadArguments', `Unknown EasyScore articulation: ${name}`);
214
+ }
215
+ return { type: glyph, position: match ? Modifier.PositionString[match[2]] : undefined };
216
+ });
217
+ }
218
+ static easyScoreHook({ articulations }, note, builder) {
219
+ if (!articulations)
220
+ return;
221
+ Articulation.parseEasyScore(articulations).forEach((params) => {
222
+ note.addModifier(builder.getFactory().Articulation(params), 0);
223
+ });
211
224
  }
212
225
  constructor(type) {
213
226
  var _a;
@@ -195,6 +195,16 @@ export class Beam extends Element {
195
195
  }
196
196
  function formatStems() {
197
197
  noteGroups.forEach((group) => {
198
+ if (config.stemPolicy === 'preserve')
199
+ return;
200
+ if (config.stemPolicy === 'explicit') {
201
+ const explicit = new Set(group.filter((note) => !note.isRest() && !note.isAutoStem()).map((note) => note.getStemDirection()));
202
+ if (explicit.size > 1)
203
+ return;
204
+ const direction = explicit.size ? [...explicit][0] : calculateStemDirection(group);
205
+ group.filter((note) => note.isAutoStem()).forEach((note) => note.setStemDirection(direction, true));
206
+ return;
207
+ }
198
208
  let stemDirection;
199
209
  if (config.maintainStemDirections) {
200
210
  const note = findFirstNote(group);
@@ -222,7 +232,7 @@ export class Beam extends Element {
222
232
  }
223
233
  function applyStemDirection(group, direction) {
224
234
  group.forEach((note) => {
225
- note.setStemDirection(direction);
235
+ note.setStemDirection(direction, config.stemDirection === undefined && note.isAutoStem());
226
236
  });
227
237
  }
228
238
  function getTuplets() {
@@ -303,7 +313,7 @@ export class Beam extends Element {
303
313
  for (i = 0; i < notes.length; ++i) {
304
314
  note = notes[i];
305
315
  if (autoStem) {
306
- note.setStemDirection(stemDirection);
316
+ note.setStemDirection(stemDirection, true);
307
317
  this._stemDirection = stemDirection;
308
318
  }
309
319
  note.setBeam(this);
@@ -73,6 +73,9 @@ export class Clef extends StaveModifier {
73
73
  this.setType(type, size, annotation);
74
74
  L('Creating clef:', type);
75
75
  }
76
+ getType() {
77
+ return this.type;
78
+ }
76
79
  setType(type, size = 'default', annotation) {
77
80
  this.type = type;
78
81
  this.code = Clef.types[type].code;
@@ -30,6 +30,10 @@ export class ClefNote extends Note {
30
30
  this.clef.renderText(ctx, 0, 0);
31
31
  }
32
32
  getBoundingBox() {
33
- return this.clef.getBoundingBox();
33
+ const box = this.clef.getBoundingBox();
34
+ const stave = this.getStave();
35
+ if (stave)
36
+ box.setY(stave.getYForLine(this.clef.line) + this.clef.getYShift() - this.clef.getTextMetrics().actualBoundingBoxAscent);
37
+ return box;
34
38
  }
35
39
  }
@@ -105,7 +105,7 @@ export class Dot extends Modifier {
105
105
  }
106
106
  setNote(note) {
107
107
  this.note = note;
108
- this.font = note.font;
108
+ this.setFont(note.fontInfo);
109
109
  return this;
110
110
  }
111
111
  setDotShiftY(y) {
@@ -0,0 +1,297 @@
1
+ import { Factory } from '../factory.js';
2
+ import { Fraction } from '../fraction.js';
3
+ import { Note } from '../note.js';
4
+ import { StemmableNote } from '../stemmablenote.js';
5
+ import { Tickable } from '../tickable.js';
6
+ import { RuntimeError } from '../util.js';
7
+ import { Voice } from '../voice.js';
8
+ import { applyCompositionAccidentals } from './policies.js';
9
+ function invalid(message) {
10
+ throw new RuntimeError('BadComposition', message);
11
+ }
12
+ function ticksFor(time) {
13
+ return new Voice(time).getTotalTicks().clone();
14
+ }
15
+ function buildVoice(score, spec, initial, display) {
16
+ var _a;
17
+ return score.withDefaults({ clef: initial.clef, time: initial.time, stem: (_a = spec.stem) !== null && _a !== void 0 ? _a : 'auto' }, () => {
18
+ var _a;
19
+ let state = Object.assign({}, initial);
20
+ const notes = [];
21
+ const changes = [];
22
+ const assignments = new Map();
23
+ const generated = new Set();
24
+ for (const item of typeof spec.notes === 'string' ? [spec.notes] : spec.notes) {
25
+ if (typeof item === 'string') {
26
+ notes.push(...score.notes(item));
27
+ score.builder
28
+ .getElements()
29
+ .accidentals.flat()
30
+ .forEach((mark) => {
31
+ if (mark)
32
+ generated.add(mark);
33
+ });
34
+ }
35
+ else if (item instanceof Tickable) {
36
+ if (Factory.getOwner(item) !== score.factory)
37
+ invalid('Adopt native notes before composing them.');
38
+ try {
39
+ item.getVoice();
40
+ invalid('Composition requires notes that are not already in a voice.');
41
+ }
42
+ catch (error) {
43
+ if (!(error instanceof RuntimeError) || error.code !== 'NoVoice')
44
+ throw error;
45
+ }
46
+ notes.push(item);
47
+ }
48
+ else if ('change' in item) {
49
+ const previous = state;
50
+ state = Object.assign(Object.assign({}, state), item.change);
51
+ changes.push({ index: notes.length, state: Object.assign({}, state) });
52
+ if (display) {
53
+ if (item.change.clef)
54
+ notes.push(score.make.clefNote({ type: state.clef, options: { size: 'small' } }));
55
+ if (item.change.key)
56
+ notes.push(score.make.keySigNote({ key: state.key, cancelKey: previous.key, clef: state.clef }));
57
+ if (item.change.time)
58
+ notes.push(score.make.timeSigNote({ time: state.time }));
59
+ }
60
+ score.set({ clef: state.clef, time: state.time });
61
+ }
62
+ else {
63
+ const note = 'tab' in item
64
+ ? score.make.tabNote(item.tab, item.drawStem)
65
+ : score.make.note('note' in item ? item.note : item);
66
+ if ('id' in item && item.id !== undefined)
67
+ note.setAttribute('id', item.id);
68
+ if ('stave' in item && item.stave)
69
+ assignments.set(note, item.stave);
70
+ notes.push(note);
71
+ }
72
+ }
73
+ const timed = notes.filter((note) => !note.shouldIgnoreTicks());
74
+ for (const group of (_a = spec.tuplets) !== null && _a !== void 0 ? _a : []) {
75
+ if (!Number.isInteger(group.start) ||
76
+ !Number.isInteger(group.count) ||
77
+ group.start < 0 ||
78
+ group.count < 1 ||
79
+ group.start + group.count > timed.length)
80
+ invalid('Tuplet range is outside its voice.');
81
+ const members = timed.slice(group.start, group.start + group.count);
82
+ if (!members.every((note) => note instanceof Note))
83
+ invalid('Tuplets require native notes.');
84
+ score.make.tuplet({ notes: members, options: group.options });
85
+ }
86
+ if (spec.autoBeam) {
87
+ if (!timed.every((note) => note instanceof StemmableNote))
88
+ invalid('Automatic beams require stemmable notes.');
89
+ score.set({ time: initial.time });
90
+ score.autoBeam(timed, typeof spec.autoBeam === 'boolean' ? {} : spec.autoBeam);
91
+ }
92
+ return { notes, state, changes, assignments, generated };
93
+ });
94
+ }
95
+ function stateChanges(voice) {
96
+ return voice.changes.map(({ index, state }) => ({
97
+ at: voice.notes
98
+ .slice(0, index)
99
+ .reduce((sum, note) => (note.shouldIgnoreTicks() ? sum : sum.add(note.getTicks())), new Fraction(0, 1)),
100
+ state,
101
+ }));
102
+ }
103
+ function addSignatures(score, stave, state, previous) {
104
+ if (!previous || previous.clef !== state.clef)
105
+ score.attachToStave(stave, score.make.clef(state.clef));
106
+ if (state.clef !== 'tab' && (!previous || previous.key !== state.key))
107
+ score.attachToStave(stave, score.make.keySignature(state.key, previous === null || previous === void 0 ? void 0 : previous.key));
108
+ if (!previous || previous.time !== state.time)
109
+ score.attachToStave(stave, score.make.timeSignature(state.time));
110
+ }
111
+ function buildSpans(score, spec, measures, diagnostics) {
112
+ var _a;
113
+ return ((_a = spec.spans) !== null && _a !== void 0 ? _a : []).map((span) => {
114
+ const from = span.from === undefined ? undefined : score.getNote(span.from);
115
+ const to = span.to === undefined ? undefined : score.getNote(span.to);
116
+ for (const note of [from, to])
117
+ if (note && !measures.has(note))
118
+ invalid('Span endpoints must belong to this composition.');
119
+ if (from && to && measures.get(from) !== measures.get(to)) {
120
+ if (spec.crossMeasureSpans !== 'manual')
121
+ invalid('Cross-measure spans need explicit manual segmentation.');
122
+ diagnostics.push({
123
+ code: 'ManualSpan',
124
+ message: 'A cross-measure span will not split when Sheet wraps. Replace it with native partial segments before drawing across rows.',
125
+ });
126
+ }
127
+ if (span.kind === 'tie')
128
+ return score.make.tie(Object.assign(Object.assign({}, span), { from, to }));
129
+ if (span.kind === 'curve')
130
+ return score.make.curve({ from, to, options: span.options });
131
+ if (!from || !to)
132
+ invalid('Hairpins require both endpoints.');
133
+ return score.make.hairpin({ from, to, type: span.type, options: span.options });
134
+ });
135
+ }
136
+ function buildStaffMeasure(score, spec, staff, index, previous, tracking) {
137
+ var _a, _b, _c, _d;
138
+ const assignments = new Map();
139
+ const measure = staff.measures[index];
140
+ if (!measure.voices.length)
141
+ invalid('Every stave measure needs at least one voice.');
142
+ const state = {
143
+ clef: (_a = measure.clef) !== null && _a !== void 0 ? _a : previous.clef,
144
+ key: (_b = measure.key) !== null && _b !== void 0 ? _b : previous.key,
145
+ time: (_c = measure.time) !== null && _c !== void 0 ? _c : previous.time,
146
+ };
147
+ const span = (_d = measure.span) !== null && _d !== void 0 ? _d : state.time;
148
+ const ticks = ticksFor(span);
149
+ const built = measure.voices.map((voice, voiceIndex) => buildVoice(score, voice, state, voiceIndex === 0));
150
+ const changes = stateChanges(built[0]);
151
+ const signature = (items) => JSON.stringify(items.map(({ at, state }) => [at.clone().simplify().toString(), state]));
152
+ for (const voice of built) {
153
+ if (signature(stateChanges(voice)) !== signature(changes))
154
+ invalid('Inline staff changes must agree in all voices.');
155
+ const actual = voice.notes.reduce((sum, note) => (note.shouldIgnoreTicks() ? sum : sum.add(note.getTicks())), new Fraction(0, 1));
156
+ if (!actual.equals(ticks))
157
+ invalid(`Measure ${index + 1} on ${staff.id} does not fill its declared span.`);
158
+ for (const note of voice.notes) {
159
+ if (tracking.seen.has(note))
160
+ invalid('A note cannot belong to two composition voices.');
161
+ tracking.seen.add(note);
162
+ if (note instanceof Note)
163
+ tracking.noteMeasures.set(note, index);
164
+ }
165
+ voice.assignments.forEach((id, note) => assignments.set(note, id));
166
+ }
167
+ const nativeVoices = built.map((voice, voiceIndex) => score.voice(voice.notes, Object.assign(Object.assign({}, measure.voices[voiceIndex].options), { time: span, mode: 'strict' })));
168
+ let currentKey = state.key;
169
+ const keys = [];
170
+ for (const change of changes)
171
+ if (change.state.key !== currentKey) {
172
+ currentKey = change.state.key;
173
+ keys.push({ at: change.at, key: currentKey });
174
+ }
175
+ const policy = {
176
+ key: state.key,
177
+ changes: keys,
178
+ generated: new Set(built.flatMap((voice) => [...voice.generated])),
179
+ };
180
+ const stave = staff.kind === 'tab'
181
+ ? score.make.tabStave({ options: staff.options })
182
+ : score.make.stave({ options: Object.assign(Object.assign({}, staff.options), { clef: state.clef }) });
183
+ addSignatures(score, stave, state, index && spec.signatures !== 'every-measure' ? previous : undefined);
184
+ return {
185
+ stave,
186
+ voices: nativeVoices,
187
+ notes: built.map((voice) => voice.notes),
188
+ assignments,
189
+ policy,
190
+ ticks,
191
+ state: built[0].state,
192
+ };
193
+ }
194
+ export function compose(score, spec) {
195
+ var _a, _b;
196
+ const count = (_b = (_a = spec.staves[0]) === null || _a === void 0 ? void 0 : _a.measures.length) !== null && _b !== void 0 ? _b : 0;
197
+ if (!count || !spec.staves.length)
198
+ invalid('A composition needs staves and measures.');
199
+ if (new Set(spec.staves.map((stave) => stave.id)).size !== spec.staves.length ||
200
+ spec.staves.some((stave) => !stave.id))
201
+ invalid('Staff IDs must be unique and nonempty.');
202
+ if (spec.staves.some((stave) => stave.measures.length !== count))
203
+ invalid('All staves need the same number of measures.');
204
+ if (spec.accidentals && !['literal', 'key-aware'].includes(spec.accidentals))
205
+ invalid('Unknown accidental policy.');
206
+ if (spec.signatures && !['changes', 'every-measure'].includes(spec.signatures))
207
+ invalid('Unknown signature policy.');
208
+ if (spec.crossMeasureSpans && !['reject', 'manual'].includes(spec.crossMeasureSpans))
209
+ invalid('Unknown span policy.');
210
+ const nativeInputs = [];
211
+ for (const stave of spec.staves)
212
+ for (const measure of stave.measures)
213
+ for (const voice of measure.voices)
214
+ if (typeof voice.notes !== 'string')
215
+ for (const item of voice.notes)
216
+ if (item instanceof Note)
217
+ nativeInputs.push(item);
218
+ if (nativeInputs.length &&
219
+ (spec.accidentals === 'key-aware' ||
220
+ spec.staves.some((stave) => stave.measures.some((measure) => measure.voices.some((voice) => { var _a; return voice.autoBeam || ((_a = voice.tuplets) === null || _a === void 0 ? void 0 : _a.length); })))))
221
+ invalid('Apply rhythm and accidental policies before adopting native inputs, or use typed note descriptions.');
222
+ const priorStaves = new Map(nativeInputs.map((note) => [note, note.getStave()]));
223
+ const seen = new Set();
224
+ try {
225
+ return score.build(() => {
226
+ const result = {
227
+ sheet: score.sheet(spec.sheet),
228
+ systems: [],
229
+ staves: [],
230
+ voices: [],
231
+ notes: [],
232
+ spans: [],
233
+ diagnostics: [],
234
+ getElement: (id) => score.getElement(id),
235
+ getNote: (id) => score.getNote(id),
236
+ };
237
+ if (spec.signatures !== 'every-measure')
238
+ result.diagnostics.push({
239
+ code: 'SignaturePolicy',
240
+ message: 'Signatures appear at the first measure and explicit changes. Sheet does not repeat them at wrapped row starts.',
241
+ });
242
+ const states = spec.staves.map((stave) => {
243
+ var _a, _b, _c;
244
+ return ({
245
+ clef: (_a = stave.clef) !== null && _a !== void 0 ? _a : (stave.kind === 'tab' ? 'tab' : 'treble'),
246
+ key: (_b = stave.key) !== null && _b !== void 0 ? _b : 'C',
247
+ time: (_c = stave.time) !== null && _c !== void 0 ? _c : '4/4',
248
+ });
249
+ });
250
+ const noteMeasures = new Map();
251
+ for (let index = 0; index < count; index++) {
252
+ const system = result.sheet.addSystem(spec.system);
253
+ result.systems.push(system);
254
+ const parts = spec.staves.map((staff, staffIndex) => {
255
+ const part = buildStaffMeasure(score, spec, staff, index, states[staffIndex], { seen, noteMeasures });
256
+ states[staffIndex] = part.state;
257
+ system.addStave(Object.assign(Object.assign({ stave: part.stave, voices: part.voices }, (staff.spaceAbove === undefined ? {} : { spaceAbove: staff.spaceAbove })), (staff.spaceBelow === undefined ? {} : { spaceBelow: staff.spaceBelow })));
258
+ return part;
259
+ });
260
+ if (parts.some((part) => !part.ticks.equals(parts[0].ticks)))
261
+ invalid('Staves must share the same actual measure span.');
262
+ const staves = parts.map((part) => part.stave);
263
+ const voices = parts.map((part) => part.voices);
264
+ const notes = parts.map((part) => part.notes);
265
+ const policies = parts.map((part) => part.policy);
266
+ const assignments = new Map(parts.flatMap((part) => [...part.assignments]));
267
+ assignments.forEach((id, note) => {
268
+ const target = spec.staves.findIndex((staff) => staff.id === id);
269
+ if (target < 0)
270
+ invalid(`Unknown cross-staff target: ${id}`);
271
+ note.setStave(staves[target]);
272
+ });
273
+ if (spec.accidentals === 'key-aware') {
274
+ const generated = new Set(policies.flatMap((policy) => [...policy.generated]));
275
+ policies.forEach((policy, staffIndex) => applyCompositionAccidentals(score, voices.flat(), policy.key, policy.changes, generated, staves[staffIndex]));
276
+ }
277
+ result.staves.push(staves);
278
+ result.voices.push(voices);
279
+ result.notes.push(notes);
280
+ }
281
+ result.spans = buildSpans(score, spec, noteMeasures, result.diagnostics);
282
+ return result;
283
+ });
284
+ }
285
+ catch (error) {
286
+ for (const note of nativeInputs)
287
+ if (seen.has(note)) {
288
+ note.clearVoice();
289
+ const stave = priorStaves.get(note);
290
+ if (stave)
291
+ note.setStave(stave);
292
+ else
293
+ note.clearStave();
294
+ }
295
+ throw error;
296
+ }
297
+ }
@@ -0,0 +1,81 @@
1
+ import { RuntimeError } from '../util.js';
2
+ export class EasyScoreReferences {
3
+ constructor() {
4
+ this.ids = new Map();
5
+ this.entries = new Map();
6
+ this.scopes = [];
7
+ }
8
+ static sourceOf(element) {
9
+ const source = this.sources.get(element);
10
+ return source && Object.assign({}, source);
11
+ }
12
+ get(id) {
13
+ return this.ids.get(id);
14
+ }
15
+ getSource(element) {
16
+ var _a;
17
+ const source = (_a = this.entries.get(element)) === null || _a === void 0 ? void 0 : _a.source;
18
+ return source && Object.assign({}, source);
19
+ }
20
+ validate(element, id) {
21
+ if (!id)
22
+ throw new RuntimeError('BadArguments', 'Score elements need a nonempty ID.');
23
+ const existing = this.ids.get(id);
24
+ if (existing && existing !== element)
25
+ throw new RuntimeError('BadArguments', `Duplicate score element ID: ${id}`);
26
+ }
27
+ add(element, source) {
28
+ var _a;
29
+ const previous = this.entries.get(element);
30
+ if (previous)
31
+ return element;
32
+ const id = element.getAttribute('id');
33
+ this.validate(element, id);
34
+ const entry = {
35
+ id,
36
+ source: source && Object.assign({}, source),
37
+ unsubscribe: element.onIdChange((next) => this.validate(element, next), () => {
38
+ this.ids.delete(entry.id);
39
+ entry.id = element.getAttribute('id');
40
+ this.ids.set(entry.id, element);
41
+ }),
42
+ };
43
+ this.entries.set(element, entry);
44
+ this.ids.set(id, element);
45
+ if (entry.source)
46
+ EasyScoreReferences.sources.set(element, entry.source);
47
+ (_a = this.scopes[this.scopes.length - 1]) === null || _a === void 0 ? void 0 : _a.push(() => this.remove(element));
48
+ return element;
49
+ }
50
+ remove(element) {
51
+ const entry = this.entries.get(element);
52
+ if (!entry)
53
+ return;
54
+ entry.unsubscribe();
55
+ this.ids.delete(entry.id);
56
+ this.entries.delete(element);
57
+ if (entry.source === EasyScoreReferences.sources.get(element))
58
+ EasyScoreReferences.sources.delete(element);
59
+ }
60
+ clear() {
61
+ for (const element of this.entries.keys())
62
+ this.remove(element);
63
+ }
64
+ transaction(build) {
65
+ var _a;
66
+ const undo = [];
67
+ this.scopes.push(undo);
68
+ try {
69
+ const result = build();
70
+ this.scopes.pop();
71
+ (_a = this.scopes[this.scopes.length - 1]) === null || _a === void 0 ? void 0 : _a.push(...undo);
72
+ return result;
73
+ }
74
+ catch (error) {
75
+ this.scopes.pop();
76
+ undo.reverse().forEach((revert) => revert());
77
+ throw error;
78
+ }
79
+ }
80
+ }
81
+ EasyScoreReferences.sources = new WeakMap();