vexflow 5.1.2 → 5.3.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 (162) 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 +5325 -1730
  7. package/build/cjs/vexflow-debug-with-tests.js.map +1 -1
  8. package/build/cjs/vexflow-debug.js +4228 -1545
  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 +13 -3
  13. package/build/esm/src/articulation.js +51 -20
  14. package/build/esm/src/beam.js +170 -30
  15. package/build/esm/src/bend.js +24 -19
  16. package/build/esm/src/clef.js +3 -0
  17. package/build/esm/src/clefnote.js +5 -1
  18. package/build/esm/src/curve.js +27 -53
  19. package/build/esm/src/dot.js +14 -5
  20. package/build/esm/src/easyscore/composition.js +336 -0
  21. package/build/esm/src/easyscore/elementindex.js +81 -0
  22. package/build/esm/src/easyscore/elements.js +324 -0
  23. package/build/esm/src/easyscore/policies.js +97 -0
  24. package/build/esm/src/easyscore/rhythm.js +42 -0
  25. package/build/esm/src/easyscore.js +448 -26
  26. package/build/esm/src/element.js +17 -2
  27. package/build/esm/src/engravinggeometry.js +150 -0
  28. package/build/esm/src/engravingprofile.js +44 -0
  29. package/build/esm/src/factory.js +268 -64
  30. package/build/esm/src/formatter.js +40 -4
  31. package/build/esm/src/gracenote.js +43 -38
  32. package/build/esm/src/gracenotegroup.js +53 -56
  33. package/build/esm/src/index.js +2 -0
  34. package/build/esm/src/keysignature.js +10 -2
  35. package/build/esm/src/keysignote.js +2 -2
  36. package/build/esm/src/modifiercontext.js +11 -0
  37. package/build/esm/src/note.js +5 -0
  38. package/build/esm/src/notehead.js +11 -6
  39. package/build/esm/src/ornament.js +38 -18
  40. package/build/esm/src/parenthesis.js +1 -1
  41. package/build/esm/src/parser.js +6 -1
  42. package/build/esm/src/proportionalformatter.js +234 -0
  43. package/build/esm/src/registry.js +27 -0
  44. package/build/esm/src/sheet.js +20 -3
  45. package/build/esm/src/stave.js +9 -2
  46. package/build/esm/src/stavenote.js +140 -127
  47. package/build/esm/src/stavetie.js +39 -7
  48. package/build/esm/src/stem.js +26 -11
  49. package/build/esm/src/stemmablenote.js +6 -1
  50. package/build/esm/src/tickable.js +5 -0
  51. package/build/esm/src/tickcontext.js +19 -0
  52. package/build/esm/src/timesignature.js +5 -0
  53. package/build/esm/src/tuplet.js +60 -19
  54. package/build/esm/src/version.js +3 -3
  55. package/build/esm/src/vexflow.js +6 -1
  56. package/build/esm/tests/beam_tests.js +35 -0
  57. package/build/esm/tests/bend_tests.js +14 -1
  58. package/build/esm/tests/curve_tests.js +14 -4
  59. package/build/esm/tests/demo_repertoire_tests.js +27 -0
  60. package/build/esm/tests/demos/drums.js +54 -0
  61. package/build/esm/tests/demos/electric.js +63 -0
  62. package/build/esm/tests/demos/greensleeves.js +90 -0
  63. package/build/esm/tests/demos/joy.js +61 -0
  64. package/build/esm/tests/demos/kesh.js +80 -0
  65. package/build/esm/tests/demos/prelude.js +59 -0
  66. package/build/esm/tests/demos/quartertones.js +50 -0
  67. package/build/esm/tests/demos/saints.js +65 -0
  68. package/build/esm/tests/easyscore_tests.js +40 -0
  69. package/build/esm/tests/easyscore_types.js +65 -0
  70. package/build/esm/tests/engraving/score-layout.mjs +75 -0
  71. package/build/esm/tests/engraving/score-persistence.mjs +262 -0
  72. package/build/esm/tests/engraving/studies.mjs +279 -0
  73. package/build/esm/tests/formatter_tests.js +51 -1
  74. package/build/esm/tests/index.js +1 -0
  75. package/build/esm/tests/node/audit-dependencies-tests.mjs +42 -0
  76. package/build/esm/tests/node/easyscore-rendering-tests.mjs +332 -0
  77. package/build/esm/tests/node/easyscore-tests.mjs +1024 -0
  78. package/build/esm/tests/node/engraving-layout-tests.mjs +449 -0
  79. package/build/esm/tests/node/local-engraving-tests.mjs +128 -0
  80. package/build/esm/tests/node/proportional-spacing-tests.mjs +278 -0
  81. package/build/esm/tests/node/rendering-tests.mjs +6 -2
  82. package/build/esm/tests/threevoice_tests.js +11 -1
  83. package/build/esm/tests/vexflow_test_helpers.js +19 -10
  84. package/build/esm/tools/audit-dependencies.mjs +61 -0
  85. package/build/esm/tools/easyscore-api-audit.mjs +58 -0
  86. package/build/esm/tools/easyscore-composition.mjs +62 -0
  87. package/build/esm/tools/easyscore-example.mjs +16 -0
  88. package/build/esm/tools/easyscore-families.mjs +61 -0
  89. package/build/esm/tools/easyscore-references-example.mjs +26 -0
  90. package/build/esm/tools/easyscore-rhythm.mjs +58 -0
  91. package/build/esm/tools/easyscore-structure.mjs +88 -0
  92. package/build/esm/tools/explorer/catalog/entries.mjs +6 -0
  93. package/build/esm/tools/explorer/catalog/expression.mjs +68 -0
  94. package/build/esm/tools/explorer/catalog/helpers.mjs +29 -0
  95. package/build/esm/tools/explorer/catalog/layout.mjs +109 -0
  96. package/build/esm/tools/explorer/catalog/notes.mjs +61 -0
  97. package/build/esm/tools/explorer/catalog/staves.mjs +85 -0
  98. package/build/esm/tools/explorer/catalog/strings.mjs +25 -0
  99. package/build/esm/tools/explorer/catalog.mjs +14 -0
  100. package/build/esm/tools/score-fixtures.mjs +23 -6
  101. package/build/types/src/accidental.d.ts +6 -0
  102. package/build/types/src/articulation.d.ts +12 -1
  103. package/build/types/src/beam.d.ts +16 -0
  104. package/build/types/src/clef.d.ts +2 -0
  105. package/build/types/src/curve.d.ts +9 -0
  106. package/build/types/src/dot.d.ts +5 -0
  107. package/build/types/src/easyscore/composition.d.ts +126 -0
  108. package/build/types/src/easyscore/elementindex.d.ts +30 -0
  109. package/build/types/src/easyscore/elements.d.ts +156 -0
  110. package/build/types/src/easyscore/policies.d.ts +12 -0
  111. package/build/types/src/easyscore/rhythm.d.ts +9 -0
  112. package/build/types/src/easyscore.d.ts +153 -11
  113. package/build/types/src/element.d.ts +7 -1
  114. package/build/types/src/engravinggeometry.d.ts +31 -0
  115. package/build/types/src/engravingprofile.d.ts +20 -0
  116. package/build/types/src/factory.d.ts +97 -9
  117. package/build/types/src/formatter.d.ts +7 -1
  118. package/build/types/src/gracenote.d.ts +7 -0
  119. package/build/types/src/gracenotegroup.d.ts +7 -2
  120. package/build/types/src/index.d.ts +2 -0
  121. package/build/types/src/keysignature.d.ts +3 -0
  122. package/build/types/src/keysignote.d.ts +1 -1
  123. package/build/types/src/modifiercontext.d.ts +4 -0
  124. package/build/types/src/note.d.ts +2 -0
  125. package/build/types/src/notehead.d.ts +5 -0
  126. package/build/types/src/ornament.d.ts +7 -0
  127. package/build/types/src/parser.d.ts +5 -0
  128. package/build/types/src/proportionalformatter.d.ts +39 -0
  129. package/build/types/src/registry.d.ts +4 -0
  130. package/build/types/src/stave.d.ts +2 -0
  131. package/build/types/src/stavenote.d.ts +21 -3
  132. package/build/types/src/stavetie.d.ts +4 -0
  133. package/build/types/src/stem.d.ts +10 -1
  134. package/build/types/src/stemmablenote.d.ts +6 -1
  135. package/build/types/src/tickable.d.ts +2 -0
  136. package/build/types/src/tickcontext.d.ts +5 -0
  137. package/build/types/src/timesignature.d.ts +2 -0
  138. package/build/types/src/tuplet.d.ts +5 -48
  139. package/build/types/src/vexflow.d.ts +6 -1
  140. package/changelog/CHANGELOG.md +52 -0
  141. package/package.json +13 -3
  142. package/tests/all.html +277 -0
  143. package/tests/demo_petzold_tests.ts +435 -0
  144. package/tests/demos/drums.ts +55 -0
  145. package/tests/demos/drums.webp +0 -0
  146. package/tests/demos/electric.ts +70 -0
  147. package/tests/demos/electric.webp +0 -0
  148. package/tests/demos/greensleeves.ts +97 -0
  149. package/tests/demos/greensleeves.webp +0 -0
  150. package/tests/demos/joy.ts +65 -0
  151. package/tests/demos/joy.webp +0 -0
  152. package/tests/demos/kesh.ts +86 -0
  153. package/tests/demos/kesh.webp +0 -0
  154. package/tests/demos/prelude.ts +65 -0
  155. package/tests/demos/prelude.webp +0 -0
  156. package/tests/demos/quartertones.ts +51 -0
  157. package/tests/demos/quartertones.webp +0 -0
  158. package/tests/demos/saints.ts +70 -0
  159. package/tests/demos/saints.webp +0 -0
  160. package/tests/flow.html +550 -239
  161. package/tests/fonts.css +493 -0
  162. package/tests/minuet.webp +0 -0
@@ -1,10 +1,22 @@
1
1
  import { Articulation } from './articulation.js';
2
+ import { Clef } from './clef.js';
2
3
  import { Dot } from './dot.js';
4
+ import { compose } from './easyscore/composition.js';
5
+ import { EasyScoreReferences } from './easyscore/elementindex.js';
6
+ import { EasyScoreElements } from './easyscore/elements.js';
7
+ import { autoBeam } from './easyscore/rhythm.js';
8
+ import { Factory } from './factory.js';
9
+ import { Fraction } from './fraction.js';
3
10
  import { FretHandFinger } from './frethandfinger.js';
4
11
  import { Music } from './music.js';
12
+ import { Note } from './note.js';
5
13
  import { Parser } from './parser.js';
6
14
  import { Stem } from './stem.js';
15
+ import { Tables } from './tables.js';
16
+ import { TabNote } from './tabnote.js';
17
+ import { Tickable } from './tickable.js';
7
18
  import { defined, log, RuntimeError } from './util.js';
19
+ import { VoiceMode } from './voice.js';
8
20
  function L(...args) {
9
21
  if (EasyScore.DEBUG)
10
22
  log('VexFlow.EasyScore', args);
@@ -24,7 +36,7 @@ export class EasyScoreGrammar {
24
36
  PIECE() {
25
37
  return {
26
38
  expect: [this.CHORDORNOTE, this.PARAMS],
27
- run: () => this.builder.commitPiece(),
39
+ run: (state) => this.builder.commitPiece(state && { start: state.start, end: state.end }),
28
40
  };
29
41
  }
30
42
  PIECES() {
@@ -203,7 +215,7 @@ export class Builder {
203
215
  this.resetPiece();
204
216
  }
205
217
  getFactory() {
206
- return this.factory;
218
+ return defined(this.factory, 'NoFactory', 'Create EasyScore with a Factory before constructing notes.');
207
219
  }
208
220
  getElements() {
209
221
  return this.elements;
@@ -258,7 +270,9 @@ export class Builder {
258
270
  }
259
271
  L('endChord');
260
272
  }
261
- commitPiece() {
273
+ commitPiece(source) {
274
+ var _a;
275
+ this.piece.source = source;
262
276
  L('commitPiece');
263
277
  const { factory } = this;
264
278
  if (!factory)
@@ -275,10 +289,17 @@ export class Builder {
275
289
  '/' +
276
290
  notePiece.octave;
277
291
  });
292
+ const nativeOptions = {
293
+ octaveShift: options.octaveShift === undefined ? undefined : Number(options.octaveShift),
294
+ strokePx: options.strokePx === undefined ? undefined : Number(options.strokePx),
295
+ line: options.line === undefined ? undefined : Number(options.line),
296
+ alignCenter: String(options.alignCenter) === 'true',
297
+ durationOverride: options.durationOverride,
298
+ };
278
299
  const autoStem = stem === 'auto';
279
300
  const note = (type === null || type === void 0 ? void 0 : type.toLowerCase()) === 'g'
280
- ? factory.GhostNote({ duration, dots })
281
- : factory.StaveNote({ keys, duration, dots, type, clef, autoStem });
301
+ ? factory.GhostNote(Object.assign(Object.assign({}, nativeOptions), { duration, dots }))
302
+ : factory.StaveNote(Object.assign(Object.assign({}, nativeOptions), { keys, duration, dots, type, clef, autoStem }));
282
303
  if (!autoStem)
283
304
  note.setStemDirection(stem === 'up' ? Stem.UP : Stem.DOWN);
284
305
  const accidentals = [];
@@ -296,11 +317,32 @@ export class Builder {
296
317
  for (let i = 0; i < dots; i++)
297
318
  Dot.buildAndAttach([note], { all: true });
298
319
  this.commitHooks.forEach((commitHook) => commitHook(options, note, this));
320
+ (_a = this.onNote) === null || _a === void 0 ? void 0 : _a.call(this, note, source);
299
321
  this.elements.notes.push(note);
300
322
  this.elements.accidentals.push(accidentals);
301
323
  this.resetPiece();
302
324
  }
303
325
  }
326
+ export class EasyScoreError extends RuntimeError {
327
+ constructor(diagnostics) {
328
+ super('EasyScoreError', diagnostics.map((d) => `${d.message} (${d.line}:${d.column})`).join('; '));
329
+ this.diagnostics = diagnostics;
330
+ }
331
+ }
332
+ class NotationBuilder extends Builder {
333
+ constructor() {
334
+ super(...arguments);
335
+ this.pieces = [];
336
+ }
337
+ commitPiece(source = { start: 0, end: 0 }) {
338
+ this.pieces.push(Object.assign(Object.assign({}, this.piece), { source }));
339
+ this.resetPiece();
340
+ }
341
+ }
342
+ function diagnostic(line, code, message, source) {
343
+ const prefix = line.slice(0, source.start);
344
+ return Object.assign(Object.assign({}, source), { code, message, line: prefix.split('\n').length, column: source.start - prefix.lastIndexOf('\n') });
345
+ }
304
346
  function setId(options, note) {
305
347
  if (options.id === undefined)
306
348
  return;
@@ -313,7 +355,153 @@ function setClass(options, note) {
313
355
  options.class.split(commaSeparatedRegex).forEach((className) => note.addClass(className));
314
356
  }
315
357
  export class EasyScore {
358
+ static getSource(element) {
359
+ return EasyScoreReferences.sourceOf(element);
360
+ }
361
+ getElement(id) {
362
+ return this.references.get(id);
363
+ }
364
+ getNote(id) {
365
+ const element = this.getElement(id);
366
+ if (!(element instanceof Note))
367
+ throw new RuntimeError('BadArguments', `No note with ID: ${id}`);
368
+ return element;
369
+ }
370
+ getSource(element) {
371
+ return this.references.getSource(element);
372
+ }
373
+ adopt(element, role) {
374
+ return this.transaction(() => this.references.add(this.factory.adopt(element, role)));
375
+ }
376
+ transaction(build) {
377
+ return this.references.transaction(() => (this.factory ? this.factory.transaction(build) : build()));
378
+ }
379
+ static create(options, scoreOptions = {}) {
380
+ return new Factory(options).EasyScore(Object.assign({ throwOnError: true, strictOptions: true }, scoreOptions));
381
+ }
382
+ attach(note, modifier, index = 0) {
383
+ this.requireOwned(note);
384
+ this.checkIndex(note, index);
385
+ const owner = Factory.getOwner(modifier);
386
+ if (owner && owner !== this.factory)
387
+ throw new RuntimeError('BadArguments', 'Modifier belongs to another Factory.');
388
+ let attached;
389
+ try {
390
+ attached = modifier.getNote();
391
+ }
392
+ catch (error) {
393
+ if (!(error instanceof RuntimeError) || error.code !== 'NoNote')
394
+ throw error;
395
+ }
396
+ if (attached) {
397
+ if (attached === note && modifier.getIndex() === index && note.getModifiers().includes(modifier))
398
+ return note;
399
+ throw new RuntimeError('BadArguments', 'Modifier is already attached. Create a separate modifier.');
400
+ }
401
+ return this.transaction(() => {
402
+ this.adopt(modifier, 'modifier');
403
+ return note.addModifier(modifier, index);
404
+ });
405
+ }
406
+ attachToStave(stave, modifier, position) {
407
+ this.requireOwned(stave);
408
+ const owner = Factory.getOwner(modifier);
409
+ if (owner && owner !== this.factory)
410
+ throw new RuntimeError('BadArguments', 'Modifier belongs to another Factory.');
411
+ if (position !== undefined && (!Number.isInteger(position) || position < 0 || position > 6))
412
+ throw new RuntimeError('BadArguments', 'Invalid stave modifier position.');
413
+ if (modifier.getStave()) {
414
+ if (modifier.getStave() === stave &&
415
+ stave.getModifiers().includes(modifier) &&
416
+ (position === undefined || position === modifier.getPosition()))
417
+ return stave;
418
+ throw new RuntimeError('BadArguments', 'Stave modifier is already attached.');
419
+ }
420
+ return this.transaction(() => {
421
+ this.adopt(modifier, 'staveModifier');
422
+ stave.addModifier(modifier, position);
423
+ return stave;
424
+ });
425
+ }
426
+ withDefaults(defaults, construct) {
427
+ const previous = this.defaults;
428
+ try {
429
+ this.set(defaults);
430
+ return this.build(construct);
431
+ }
432
+ finally {
433
+ this.defaults = previous;
434
+ }
435
+ }
436
+ compose(spec) {
437
+ return compose(this, spec);
438
+ }
439
+ system(options = {}) {
440
+ return this.transaction(() => this.references.add(this.factory.System(options)));
441
+ }
442
+ sheet(options = {}) {
443
+ return this.transaction(() => this.factory.Sheet(options));
444
+ }
445
+ build(construct) {
446
+ const snapshot = {
447
+ elements: this.builder.elements,
448
+ options: this.builder.options,
449
+ piece: this.builder.piece,
450
+ rollingDuration: this.builder.rollingDuration,
451
+ };
452
+ try {
453
+ return this.transaction(() => {
454
+ const result = construct(this);
455
+ if (result && typeof result === 'object' && 'then' in result) {
456
+ throw new RuntimeError('BadArguments', 'EasyScore.build() requires a synchronous callback.');
457
+ }
458
+ return result;
459
+ });
460
+ }
461
+ catch (error) {
462
+ Object.assign(this.builder, snapshot);
463
+ throw error;
464
+ }
465
+ }
466
+ setStyle(style) {
467
+ this.factory.setStyle(style);
468
+ return this;
469
+ }
470
+ draw(options = {}) {
471
+ this.factory.draw(options);
472
+ }
473
+ reset() {
474
+ this.factory.reset();
475
+ this.builder.reset();
476
+ this.references.clear();
477
+ return this;
478
+ }
479
+ requireOwned(note) {
480
+ if (Factory.getOwner(note) !== this.factory) {
481
+ throw new RuntimeError('BadArguments', 'Note belongs to another Factory or was constructed outside this Factory.');
482
+ }
483
+ }
484
+ checkIndex(note, index) {
485
+ if (!Number.isInteger(index) ||
486
+ index < 0 ||
487
+ index >= (note instanceof TabNote ? note.getPositions().length : Math.max(1, note.getKeys().length))) {
488
+ throw new RuntimeError('BadArguments', `Invalid chord index: ${index}`);
489
+ }
490
+ }
316
491
  constructor(options = {}) {
492
+ this.references = new EasyScoreReferences();
493
+ this.make = new EasyScoreElements({
494
+ factory: () => this.factory,
495
+ manage: (construct) => this.transaction(() => this.references.add(construct())),
496
+ owned: (element) => this.requireOwned(element),
497
+ checkIndex: (note, index) => this.checkIndex(note, index),
498
+ beamStems: (notes) => this.resolveBeamStems(notes),
499
+ noteDefaults: () => ({
500
+ clef: this.defaults.clef,
501
+ autoStem: this.defaults.stem === 'auto',
502
+ stemDirection: this.defaults.stem === 'down' ? Stem.DOWN : Stem.UP,
503
+ }),
504
+ });
317
505
  this.defaults = {
318
506
  clef: 'treble',
319
507
  time: '4/4',
@@ -342,21 +530,166 @@ export class EasyScore {
342
530
  this.factory.setContext(context);
343
531
  return this;
344
532
  }
533
+ parseNotation(line, options = {}) {
534
+ var _a, _b, _c, _d;
535
+ const builder = new NotationBuilder();
536
+ builder.reset(Object.assign({ clef: this.defaults.clef, stem: this.defaults.stem }, options));
537
+ const result = new Parser(new EasyScoreGrammar(builder)).parse(line);
538
+ if (!result.success) {
539
+ const start = Math.max(0, (_b = (_a = result.furthestErrorPos) !== null && _a !== void 0 ? _a : result.errorPos) !== null && _b !== void 0 ? _b : 0);
540
+ return {
541
+ success: false,
542
+ pieces: [],
543
+ diagnostics: [
544
+ diagnostic(line, 'SyntaxError', 'Invalid EasyScore notation', {
545
+ start,
546
+ end: Math.min(line.length, start + 1),
547
+ }),
548
+ ],
549
+ };
550
+ }
551
+ const diagnostics = [];
552
+ for (const piece of builder.pieces) {
553
+ try {
554
+ const options = Object.assign(Object.assign({}, builder.options), piece.options);
555
+ this.validatePiece(piece, options);
556
+ (_d = (_c = this.options).validate) === null || _d === void 0 ? void 0 : _d.call(_c, {
557
+ piece: Object.assign(Object.assign({}, piece), { chord: piece.chord.map((note) => (Object.assign({}, note))), options: Object.assign({}, piece.options), source: Object.assign({}, piece.source) }),
558
+ options: Object.assign({}, options),
559
+ });
560
+ }
561
+ catch (error) {
562
+ diagnostics.push(diagnostic(line, 'InvalidNotation', error instanceof Error ? error.message : String(error), piece.source));
563
+ }
564
+ }
565
+ return { success: diagnostics.length === 0, pieces: diagnostics.length ? [] : builder.pieces, diagnostics };
566
+ }
567
+ validatePiece(piece, options) {
568
+ var _a;
569
+ Tables.durationToTicks(piece.duration);
570
+ if (!['auto', 'up', 'down'].includes(String(options.stem).toLowerCase())) {
571
+ throw new RuntimeError('BadArguments', `Invalid stem: ${options.stem}`);
572
+ }
573
+ if (!Object.hasOwnProperty.call(Clef.types, String(options.clef).toLowerCase())) {
574
+ throw new RuntimeError('BadArguments', `Invalid clef: ${options.clef}`);
575
+ }
576
+ for (const name of ['octaveShift', 'strokePx', 'line']) {
577
+ if (options[name] !== undefined && !Number.isFinite(Number(options[name]))) {
578
+ throw new RuntimeError('BadArguments', `Invalid numeric option: ${name}`);
579
+ }
580
+ }
581
+ if (options.alignCenter !== undefined && ![true, false, 'true', 'false'].includes(options.alignCenter)) {
582
+ throw new RuntimeError('BadArguments', 'alignCenter must be true or false.');
583
+ }
584
+ if (options.durationOverride !== undefined &&
585
+ (!(options.durationOverride instanceof Fraction) ||
586
+ !Number.isFinite(options.durationOverride.value()) ||
587
+ options.durationOverride.value() <= 0)) {
588
+ throw new RuntimeError('BadArguments', 'durationOverride must be a positive finite Fraction.');
589
+ }
590
+ if (options.articulations && this.builder.commitHooks.includes(Articulation.easyScoreHook)) {
591
+ Articulation.parseEasyScore(options.articulations);
592
+ }
593
+ if (this.options.strictOptions) {
594
+ const known = new Set([
595
+ 'stem',
596
+ 'clef',
597
+ 'duration',
598
+ 'id',
599
+ 'class',
600
+ 'articulations',
601
+ 'fingerings',
602
+ 'octaveShift',
603
+ 'strokePx',
604
+ 'line',
605
+ 'alignCenter',
606
+ 'durationOverride',
607
+ ...((_a = this.options.extensions) !== null && _a !== void 0 ? _a : []),
608
+ ]);
609
+ for (const name of Object.keys(options)) {
610
+ if (!known.has(name))
611
+ throw new RuntimeError('BadArguments', `Unknown EasyScore option: ${name}`);
612
+ }
613
+ }
614
+ }
345
615
  parse(line, options = {}) {
346
- this.builder.reset(options);
347
- const result = this.parser.parse(line);
348
- if (!result.success && this.options.throwOnError) {
349
- L(result);
350
- throw new RuntimeError('Error parsing line: ' + line);
616
+ const previous = this.builder.onNote;
617
+ const context = this.sourceContext;
618
+ this.builder.onNote = (note, span) => {
619
+ var _a, _b, _c;
620
+ previous === null || previous === void 0 ? void 0 : previous(note, span);
621
+ const source = span && Object.assign({ input: (_a = context === null || context === void 0 ? void 0 : context.input) !== null && _a !== void 0 ? _a : line, start: span.start + ((_b = context === null || context === void 0 ? void 0 : context.offset) !== null && _b !== void 0 ? _b : 0), end: span.end + ((_c = context === null || context === void 0 ? void 0 : context.offset) !== null && _c !== void 0 ? _c : 0) }, (context && { measure: context.measure }));
622
+ this.references.add(note, source);
623
+ note.getModifiers().forEach((modifier) => this.references.add(modifier, source));
624
+ };
625
+ try {
626
+ return this.parseInput(line, options);
627
+ }
628
+ finally {
629
+ this.builder.onNote = previous;
630
+ }
631
+ }
632
+ parseInput(line, options) {
633
+ var _a, _b;
634
+ if (!this.options.throwOnError) {
635
+ this.builder.reset(options);
636
+ return this.parser.parse(line);
637
+ }
638
+ const parsed = this.parseNotation(line, Object.assign({ clef: 'treble', stem: 'auto' }, options));
639
+ if (!parsed.success)
640
+ throw new EasyScoreError(parsed.diagnostics);
641
+ const snapshot = {
642
+ elements: this.builder.elements,
643
+ options: this.builder.options,
644
+ piece: this.builder.piece,
645
+ rollingDuration: this.builder.rollingDuration,
646
+ };
647
+ const build = () => {
648
+ this.builder.reset(options);
649
+ const result = this.parser.parse(line);
650
+ if (!result.success)
651
+ throw new RuntimeError('BadArguments', 'Error parsing line: ' + line);
652
+ return result;
653
+ };
654
+ try {
655
+ return this.transaction(build);
656
+ }
657
+ catch (error) {
658
+ const source = (_b = (_a = parsed.pieces[this.builder.elements.notes.length]) === null || _a === void 0 ? void 0 : _a.source) !== null && _b !== void 0 ? _b : { start: 0, end: line.length };
659
+ Object.assign(this.builder, snapshot);
660
+ throw new EasyScoreError([
661
+ diagnostic(line, 'ConstructionError', error instanceof Error ? error.message : String(error), source),
662
+ ]);
351
663
  }
352
- return result;
353
664
  }
354
665
  beam(notes, options) {
355
- this.factory.Beam({ notes, options });
666
+ var _a;
667
+ if (this.options.strictOptions)
668
+ this.make.beam({ notes, options });
669
+ else {
670
+ const autoStem = (_a = options === null || options === void 0 ? void 0 : options.autoStem) !== null && _a !== void 0 ? _a : this.resolveBeamStems(notes);
671
+ this.transaction(() => this.references.add(this.factory.Beam({ notes, options: Object.assign(Object.assign({}, options), { autoStem }) })));
672
+ }
356
673
  return notes;
357
674
  }
675
+ autoBeam(notes, options = {}) {
676
+ return autoBeam(this, notes, options);
677
+ }
678
+ resolveBeamStems(notes) {
679
+ const directions = new Set(notes.filter((note) => !note.isRest() && !note.isAutoStem()).map((note) => note.getStemDirection()));
680
+ if (directions.size === 0)
681
+ return true;
682
+ if (directions.size === 1) {
683
+ const direction = directions.values().next().value;
684
+ notes.filter((note) => note.isAutoStem()).forEach((note) => note.setStemDirection(direction, true));
685
+ }
686
+ return false;
687
+ }
358
688
  tuplet(notes, options) {
359
- this.factory.Tuplet({ notes, options });
689
+ if (this.options.strictOptions)
690
+ this.make.tuplet({ notes, options });
691
+ else
692
+ this.transaction(() => this.references.add(this.factory.Tuplet({ notes, options })));
360
693
  return notes;
361
694
  }
362
695
  notes(line, options = {}) {
@@ -364,8 +697,73 @@ export class EasyScore {
364
697
  this.parse(line, options);
365
698
  return this.builder.getElements().notes;
366
699
  }
700
+ sequence(items, options = {}) {
701
+ return this.build(() => items.flatMap((item) => {
702
+ if (typeof item === 'string')
703
+ return this.notes(item, options);
704
+ if (item instanceof Tickable) {
705
+ this.requireOwned(item);
706
+ if (item instanceof Note && Factory.getGroup(item))
707
+ throw new RuntimeError('BadArguments', 'Grouped notes cannot be sequence entries.');
708
+ return [item];
709
+ }
710
+ return [this.make.note(item)];
711
+ }));
712
+ }
367
713
  measures(line, options = {}) {
714
+ const measures = this.splitMeasures(line);
715
+ let duration = options.duration;
716
+ for (const [index, { text, offset }] of measures.entries()) {
717
+ const parsed = this.parseNotation(text, Object.assign(Object.assign({}, options), { duration }));
718
+ if (!parsed.success)
719
+ throw new EasyScoreError(parsed.diagnostics.map((d) => (Object.assign(Object.assign({}, diagnostic(line, d.code, d.message, { start: offset + d.start, end: offset + d.end })), { measure: index + 1 }))));
720
+ duration = parsed.pieces[parsed.pieces.length - 1].duration;
721
+ }
722
+ const build = () => {
723
+ duration = options.duration;
724
+ return measures.map(({ text, offset }, index) => {
725
+ const previous = this.sourceContext;
726
+ this.sourceContext = { input: line, offset, measure: index + 1 };
727
+ try {
728
+ const result = this.parse(text, Object.assign(Object.assign({ clef: this.defaults.clef, stem: this.defaults.stem }, options), { duration }));
729
+ if (!result.success)
730
+ throw new RuntimeError('BadArguments', `Invalid EasyScore measure: ${text}`);
731
+ duration = this.builder.rollingDuration;
732
+ return this.builder.getElements().notes;
733
+ }
734
+ catch (error) {
735
+ const diagnostics = error instanceof EasyScoreError
736
+ ? error.diagnostics
737
+ : [
738
+ diagnostic(text, 'ConstructionError', error instanceof Error ? error.message : String(error), {
739
+ start: 0,
740
+ end: text.length,
741
+ }),
742
+ ];
743
+ throw new EasyScoreError(diagnostics.map((d) => (Object.assign(Object.assign({}, diagnostic(line, d.code, d.message, { start: offset + d.start, end: offset + d.end })), { measure: index + 1 }))));
744
+ }
745
+ finally {
746
+ this.sourceContext = previous;
747
+ }
748
+ });
749
+ };
750
+ const snapshot = {
751
+ elements: this.builder.elements,
752
+ options: this.builder.options,
753
+ piece: this.builder.piece,
754
+ rollingDuration: this.builder.rollingDuration,
755
+ };
756
+ try {
757
+ return this.transaction(build);
758
+ }
759
+ catch (error) {
760
+ Object.assign(this.builder, snapshot);
761
+ throw error;
762
+ }
763
+ }
764
+ splitMeasures(line) {
368
765
  const parts = [];
766
+ const starts = [0];
369
767
  let start = 0;
370
768
  let quote = '';
371
769
  for (let i = 0; i < line.length; i++) {
@@ -380,31 +778,55 @@ export class EasyScore {
380
778
  else if (char === '|') {
381
779
  parts.push(line.slice(start, i));
382
780
  start = i + 1;
781
+ starts.push(start);
383
782
  }
384
783
  }
385
784
  parts.push(line.slice(start));
386
- const measures = parts.map((part, index) => {
785
+ return parts.map((part, index) => {
387
786
  let text = part.trim();
388
787
  if (index > 0)
389
788
  text = text.replace(/^,\s*/, '');
390
789
  if (index < parts.length - 1)
391
790
  text = text.replace(/\s*,$/, '');
392
791
  if (!text)
393
- throw new RuntimeError('BadArguments', 'Empty EasyScore measure. Use an explicit rest.');
394
- return text;
395
- });
396
- let duration = options.duration;
397
- return measures.map((text) => {
398
- const result = this.parse(text, Object.assign(Object.assign({ clef: this.defaults.clef, stem: this.defaults.stem }, options), { duration }));
399
- if (!result.success)
400
- throw new RuntimeError('BadArguments', `Invalid EasyScore measure: ${text}`);
401
- duration = this.builder.rollingDuration;
402
- return this.builder.getElements().notes;
792
+ throw new EasyScoreError([
793
+ Object.assign(Object.assign({}, diagnostic(line, 'EmptyMeasure', 'Empty EasyScore measure. Use an explicit rest.', {
794
+ start: starts[index],
795
+ end: starts[index] + part.length,
796
+ })), { measure: index + 1 }),
797
+ ]);
798
+ return { text, offset: starts[index] + part.indexOf(text) };
403
799
  });
404
800
  }
405
801
  voice(notes, options = {}) {
406
- options = Object.assign({ time: this.defaults.time }, options);
407
- return this.factory.Voice(options).addTickables(notes);
802
+ var _a, _b, _c;
803
+ const mode = typeof options.mode === 'string'
804
+ ? { strict: VoiceMode.STRICT, soft: VoiceMode.SOFT, full: VoiceMode.FULL }[options.mode]
805
+ : ((_a = options.mode) !== null && _a !== void 0 ? _a : VoiceMode.STRICT);
806
+ if (![VoiceMode.STRICT, VoiceMode.SOFT, VoiceMode.FULL].includes(mode)) {
807
+ throw new RuntimeError('BadArguments', 'Invalid voice mode.');
808
+ }
809
+ const factor = (_b = options.softmaxFactor) !== null && _b !== void 0 ? _b : (_c = options.options) === null || _c === void 0 ? void 0 : _c.softmaxFactor;
810
+ if (factor !== undefined && (!Number.isFinite(factor) || factor <= 0)) {
811
+ throw new RuntimeError('BadArguments', 'softmaxFactor must be positive and finite.');
812
+ }
813
+ if (this.options.strictOptions)
814
+ notes.forEach((note) => this.requireOwned(note));
815
+ if (notes.some((note) => note instanceof Note && Factory.getGroup(note))) {
816
+ throw new RuntimeError('BadArguments', 'Grouped notes cannot be inserted into a main voice.');
817
+ }
818
+ return this.transaction(() => {
819
+ var _a;
820
+ const voice = this.factory.Voice({ time: (_a = options.time) !== null && _a !== void 0 ? _a : this.defaults.time });
821
+ voice.setMode(mode);
822
+ if (factor !== undefined)
823
+ voice.setSoftmaxFactor(factor);
824
+ const ticks = notes.reduce((total, note) => (note.shouldIgnoreTicks() ? total : total.add(note.getTicks())), new Fraction(0, 1));
825
+ if (mode !== VoiceMode.SOFT && ticks.greaterThan(voice.getTotalTicks())) {
826
+ throw new RuntimeError('BadArguments', 'Too many ticks for this voice.');
827
+ }
828
+ return this.references.add(voice.addTickables(notes));
829
+ });
408
830
  }
409
831
  addCommitHook(commitHook) {
410
832
  this.builder.addCommitHook(commitHook);
@@ -206,14 +206,29 @@ export class Element {
206
206
  if (element)
207
207
  return element;
208
208
  }
209
- setAttribute(name, value) {
209
+ onIdChange(validate, changed) {
210
210
  var _a;
211
+ const listener = { validate, changed };
212
+ const listeners = ((_a = this.idListeners) !== null && _a !== void 0 ? _a : (this.idListeners = new Set()));
213
+ listeners.add(listener);
214
+ return () => listeners.delete(listener);
215
+ }
216
+ setAttribute(name, value) {
217
+ var _a, _b, _c;
211
218
  const oldID = this.attrs.id;
212
219
  const oldValue = this.attrs[name];
220
+ if (name === 'id')
221
+ (_a = this.idListeners) === null || _a === void 0 ? void 0 : _a.forEach((listener) => listener.validate(value));
213
222
  this.attrs[name] = value;
214
- (_a = this.registry) === null || _a === void 0 ? void 0 : _a.onUpdate({ id: oldID, name, value, oldValue });
223
+ (_b = this.registry) === null || _b === void 0 ? void 0 : _b.onUpdate({ id: oldID, name, value, oldValue });
224
+ if (name === 'id')
225
+ (_c = this.idListeners) === null || _c === void 0 ? void 0 : _c.forEach((listener) => listener.changed());
215
226
  return this;
216
227
  }
228
+ getTextInk(x, y) {
229
+ const m = this.textMetrics;
230
+ return new BoundingBox(x + this.xShift - m.actualBoundingBoxLeft, y + this.yShift - m.actualBoundingBoxAscent, m.actualBoundingBoxLeft + m.actualBoundingBoxRight, m.actualBoundingBoxAscent + m.actualBoundingBoxDescent);
231
+ }
217
232
  getBoundingBox() {
218
233
  return new BoundingBox(this.x + this.xShift, this.y + this.yShift - this.textMetrics.actualBoundingBoxAscent, this.width, this.height);
219
234
  }