@mcqj/vexflow 0.0.1-alpha.6 → 0.0.1-alpha.8

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.
@@ -6,16 +6,13 @@ import { Stave } from './stave.js';
6
6
  import { StaveConnector } from './staveconnector.js';
7
7
  import { Tables } from './tables.js';
8
8
  import { TickContext } from './tickcontext.js';
9
- import { isCategory, isNote, isStaveNote } from './typeguard.js';
9
+ import { isNote, isStaveNote } from './typeguard.js';
10
10
  import { defined, log, midLine, RuntimeError, sumArray } from './util.js';
11
11
  import { Voice } from './voice.js';
12
12
  function L(...args) {
13
13
  if (Formatter.DEBUG)
14
14
  log('VexFlow.Formatter', args);
15
15
  }
16
- function isBarNote(tickable) {
17
- return isCategory(tickable, "BarNote");
18
- }
19
16
  function getRestLineForNextNoteGroup(notes, currRestLine, currNoteIndex, compare) {
20
17
  let nextRestLine = currRestLine;
21
18
  for (let noteIndex = currNoteIndex + 1; noteIndex < notes.length; noteIndex++) {
@@ -152,6 +149,8 @@ export class Formatter {
152
149
  map: {},
153
150
  array: [],
154
151
  list: [],
152
+ spacingList: [],
153
+ dependentList: [],
155
154
  resolutionMultiplier: 0,
156
155
  };
157
156
  this.modifierContexts = [];
@@ -181,15 +180,18 @@ export class Formatter {
181
180
  throw new RuntimeError('BadArgument', "'voices' required to run preCalculateMinTotalWidth");
182
181
  }
183
182
  this.createTickContexts(voices);
184
- const { list: contextList, map: contextMap } = this.tickContexts;
183
+ const { spacingList: contextList, map: contextMap } = this.tickContexts;
184
+ const spacingVoices = voices.filter((voice) => !voice.isDependent());
185
+ const hasSpacingVoices = spacingVoices.length > 0;
185
186
  this.minTotalWidth = 0;
186
187
  contextList.forEach((tick) => {
187
188
  const context = contextMap[tick];
188
189
  context.preFormat();
189
- if (context.getTickables().length < voices.length) {
190
+ const spacingTickables = hasSpacingVoices ? context.getNonDependentTickables() : context.getTickables();
191
+ if (spacingTickables.length < (hasSpacingVoices ? spacingVoices.length : voices.length)) {
190
192
  unalignedCtxCount += 1;
191
193
  }
192
- context.getTickables().forEach((t) => {
194
+ spacingTickables.forEach((t) => {
193
195
  wsum += t.getMetrics().width;
194
196
  dsum += t.getTicks().value();
195
197
  widths.push(t.getMetrics().width);
@@ -252,9 +254,7 @@ export class Formatter {
252
254
  staveTickToContextMap[integerTicks] = newContext;
253
255
  }
254
256
  tickable.addToModifierContext(staveTickToContextMap[integerTicks]);
255
- if (!isBarNote(tickable)) {
256
- ticksUsed.add(tickable.getTicks());
257
- }
257
+ ticksUsed.add(tickable.getTicks());
258
258
  });
259
259
  });
260
260
  this.modifierContexts.push({
@@ -269,6 +269,8 @@ export class Formatter {
269
269
  map: {},
270
270
  array: [],
271
271
  list: [],
272
+ spacingList: [],
273
+ dependentList: [],
272
274
  resolutionMultiplier: 0,
273
275
  };
274
276
  }
@@ -288,15 +290,30 @@ export class Formatter {
288
290
  }
289
291
  const tickContext = tickToContextMap[integerTicks];
290
292
  tickContext.addTickable(tickable, voiceIndex, voice.isDependent());
291
- if (!isBarNote(tickable)) {
292
- ticksUsed.add(tickable.getTicks());
293
- }
293
+ ticksUsed.add(tickable.getTicks());
294
294
  });
295
295
  });
296
+ const sortedTickList = tickList.sort((a, b) => a - b);
297
+ const spacingList = [];
298
+ const dependentList = [];
299
+ sortedTickList.forEach((tick) => {
300
+ if (tickToContextMap[tick].hasOnlyDependentTickables()) {
301
+ dependentList.push(tick);
302
+ }
303
+ else {
304
+ spacingList.push(tick);
305
+ }
306
+ });
307
+ if (spacingList.length === 0) {
308
+ spacingList.push(...dependentList);
309
+ dependentList.length = 0;
310
+ }
296
311
  const contexts = {
297
312
  map: tickToContextMap,
298
313
  array: tickContexts,
299
- list: tickList.sort((a, b) => a - b),
314
+ list: sortedTickList,
315
+ spacingList,
316
+ dependentList,
300
317
  resolutionMultiplier,
301
318
  };
302
319
  this.tickContexts = contexts;
@@ -314,7 +331,7 @@ export class Formatter {
314
331
  if (!contexts) {
315
332
  throw new RuntimeError('NoTickContexts', 'preFormat requires TickContexts');
316
333
  }
317
- const { list: contextList, map: contextMap } = contexts;
334
+ const { spacingList: contextList, map: contextMap } = contexts;
318
335
  this.lossHistory = [];
319
336
  if (voicesParam && stave) {
320
337
  voicesParam.forEach((voice) => voice.setStave(stave).preFormat());
@@ -340,8 +357,10 @@ export class Formatter {
340
357
  const expTicksUsed = sumArray(contextList.map(exp));
341
358
  this.minTotalWidth = x + shift;
342
359
  this.hasMinTotalWidth = true;
343
- if (justifyWidth <= 0)
360
+ if (justifyWidth <= 0) {
361
+ this.positionDependentContexts();
344
362
  return this.evaluate();
363
+ }
345
364
  const firstContext = contextMap[contextList[0]];
346
365
  const lastContext = contextMap[contextList[contextList.length - 1]];
347
366
  function calculateIdealDistances(adjustedJustifyWidth) {
@@ -432,8 +451,10 @@ export class Formatter {
432
451
  let targetWidth = adjustedJustifyWidth;
433
452
  const distances = calculateIdealDistances(targetWidth);
434
453
  let actualWidth = shiftToIdealDistances(distances);
435
- if (contextList.length === 1)
454
+ if (contextList.length === 1) {
455
+ this.positionDependentContexts();
436
456
  return 0;
457
+ }
437
458
  const calcMinDistance = (targetWidth, distances) => {
438
459
  let mdCalc = targetWidth / 2;
439
460
  if (distances.length > 1) {
@@ -470,16 +491,47 @@ export class Formatter {
470
491
  iterations--;
471
492
  }
472
493
  this.justifyWidth = justifyWidth;
494
+ this.positionDependentContexts();
473
495
  return this.evaluate();
474
496
  }
497
+ positionDependentContexts() {
498
+ const contexts = this.tickContexts;
499
+ if (!contexts)
500
+ return;
501
+ const { spacingList, dependentList, map } = contexts;
502
+ if (spacingList.length === 0 || dependentList.length === 0)
503
+ return;
504
+ let nextIndex = 0;
505
+ dependentList.forEach((tick) => {
506
+ while (nextIndex < spacingList.length && spacingList[nextIndex] < tick) {
507
+ nextIndex++;
508
+ }
509
+ const prevTick = nextIndex > 0 ? spacingList[nextIndex - 1] : undefined;
510
+ const nextTick = nextIndex < spacingList.length ? spacingList[nextIndex] : undefined;
511
+ const context = map[tick];
512
+ context.preFormat();
513
+ if (prevTick !== undefined && nextTick !== undefined) {
514
+ const prevX = map[prevTick].getX();
515
+ const nextX = map[nextTick].getX();
516
+ const ratio = (tick - prevTick) / (nextTick - prevTick);
517
+ context.setX(prevX + (nextX - prevX) * ratio);
518
+ }
519
+ else if (prevTick !== undefined) {
520
+ context.setX(map[prevTick].getX());
521
+ }
522
+ else if (nextTick !== undefined) {
523
+ context.setX(map[nextTick].getX());
524
+ }
525
+ });
526
+ }
475
527
  evaluate() {
476
528
  const contexts = this.tickContexts;
477
529
  const justifyWidth = this.justifyWidth;
478
530
  this.contextGaps = { total: 0, gaps: [] };
479
- contexts.list.forEach((tick, index) => {
531
+ contexts.spacingList.forEach((tick, index) => {
480
532
  if (index === 0)
481
533
  return;
482
- const prevTick = contexts.list[index - 1];
534
+ const prevTick = contexts.spacingList[index - 1];
483
535
  const prevContext = contexts.map[prevTick];
484
536
  const context = contexts.map[tick];
485
537
  const prevMetrics = prevContext.getMetrics();
@@ -506,6 +558,8 @@ export class Formatter {
506
558
  }
507
559
  }
508
560
  this.voices.forEach((voice) => {
561
+ if (voice.isDependent())
562
+ return;
509
563
  voice.getTickables().forEach((note, i, notes) => {
510
564
  const duration = note.getTicks().clone().simplify().toString();
511
565
  const metrics = note.getMetrics();
@@ -530,6 +584,8 @@ export class Formatter {
530
584
  });
531
585
  let totalDeviation = 0;
532
586
  this.voices.forEach((voice) => {
587
+ if (voice.isDependent())
588
+ return;
533
589
  voice.getTickables().forEach((note) => {
534
590
  const duration = note.getTicks().clone().simplify().toString();
535
591
  const metrics = note.getFormatterMetrics();
@@ -553,7 +609,7 @@ export class Formatter {
553
609
  const alpha = (_a = options === null || options === void 0 ? void 0 : options.alpha) !== null && _a !== void 0 ? _a : 0.5;
554
610
  let shift = 0;
555
611
  this.totalShift = 0;
556
- contexts.list.forEach((tick, index, list) => {
612
+ contexts.spacingList.forEach((tick, index, list) => {
557
613
  const context = contexts.map[tick];
558
614
  const prevContext = index > 0 ? contexts.map[list[index - 1]] : undefined;
559
615
  const nextContext = index < list.length - 1 ? contexts.map[list[index + 1]] : undefined;
@@ -573,6 +629,7 @@ export class Formatter {
573
629
  shift *= alpha;
574
630
  this.totalShift += shift;
575
631
  });
632
+ this.positionDependentContexts();
576
633
  return this.evaluate();
577
634
  }
578
635
  postFormat() {
@@ -86,6 +86,12 @@ export class TickContext {
86
86
  getTickables() {
87
87
  return this.tickables;
88
88
  }
89
+ getNonDependentTickables() {
90
+ return this.tickables.filter((tickable) => !this.dependentTickables.has(tickable));
91
+ }
92
+ hasOnlyDependentTickables() {
93
+ return this.tickables.length > 0 && this.dependentTickables.size === this.tickables.length;
94
+ }
89
95
  getTickableForVoice(voiceIndex) {
90
96
  return this.tickablesByVoice[voiceIndex];
91
97
  }
@@ -1,3 +1,3 @@
1
- export const VERSION = '0.0.1-alpha.6';
2
- export const ID = 'a4bb5ff157f4570b2d6149b7199b0baa4c7e3775';
3
- export const DATE = '2026-09-14T15:22:17.080Z';
1
+ export const VERSION = '0.0.1-alpha.8';
2
+ export const ID = '42e29bbb2b9017041df14c9597ce8a3252077ea9';
3
+ export const DATE = '2026-11-22T12:24:07.969Z';
@@ -6,6 +6,7 @@ import { Articulation } from '../src/articulation.js';
6
6
  import { BarNote } from '../src/barnote.js';
7
7
  import { Beam } from '../src/beam.js';
8
8
  import { Bend } from '../src/bend.js';
9
+ import { ClefNote } from '../src/clefnote.js';
9
10
  import { Dot } from '../src/dot.js';
10
11
  import { Element } from '../src/element.js';
11
12
  import { FontWeight } from '../src/font.js';
@@ -23,6 +24,7 @@ import { StaveNote } from '../src/stavenote.js';
23
24
  import { Stem } from '../src/stem.js';
24
25
  import { StringNumber } from '../src/stringnumber.js';
25
26
  import { TextNote } from '../src/textnote.js';
27
+ import { TimeSigNote } from '../src/timesignote.js';
26
28
  import { Tuplet } from '../src/tuplet.js';
27
29
  import { Voice } from '../src/voice.js';
28
30
  import { MockTickable } from './mocks.js';
@@ -72,7 +74,9 @@ const FormatterTests = {
72
74
  run('Tight 2', tightNotes2);
73
75
  run('Annotations', annotations);
74
76
  VexFlowTests.test('Ignored bar notes preserve lyric tick alignment', ignoredBarNotesPreserveLyricTickAlignment);
77
+ VexFlowTests.test('Inline clef and time signatures preserve note spacing', inlineSpacersPreserveNoteSpacing);
75
78
  VexFlowTests.test('Dependent voices do not affect music layout', dependentVoicesDoNotAffectMusicLayout);
79
+ VexFlowTests.test('Off-grid dependent voices do not affect music layout', dependentOffGridVoicesDoNotAffectMusicLayout);
76
80
  run('Proportional Formatting - No Tuning', proportional, { debug: true, iterations: 0 });
77
81
  run('Proportional Formatting - No Justification', proportional, { justify: false, debug: true, iterations: 0 });
78
82
  run('Proportional Formatting (20 iterations)', proportional, { debug: true, iterations: 20, alpha: 0.5 });
@@ -84,18 +88,34 @@ function getGlyphWidth(glyph) {
84
88
  return el.getWidth();
85
89
  }
86
90
  function ignoredBarNotesPreserveLyricTickAlignment(assert) {
87
- const musicNotes = Array.from({ length: 12 }, () => new StaveNote({ keys: ['c/4'], duration: '8' }));
91
+ const musicNotes = [
92
+ ...Array.from({ length: 6 }, () => new StaveNote({ keys: ['c/4'], duration: '8' })),
93
+ new BarNote(),
94
+ ...Array.from({ length: 6 }, () => new StaveNote({ keys: ['c/4'], duration: '8' })),
95
+ ];
88
96
  const when = new TextNote({ text: 'When', duration: '8' });
89
97
  const lyricNotes = [
90
98
  ...Array.from({ length: 6 }, () => new GhostNote({ duration: '8' })),
91
- new BarNote(),
99
+ new GhostNote({ duration: 'b' }),
92
100
  when,
93
101
  ...Array.from({ length: 5 }, () => new TextNote({ text: '', duration: '8' })),
94
102
  ];
95
103
  const musicVoice = new Voice({ numBeats: 6, beatValue: 4 }).addTickables(musicNotes);
96
- const lyricVoice = new Voice({ numBeats: 6, beatValue: 4 }).addTickables(lyricNotes);
104
+ const lyricVoice = new Voice({ numBeats: 6, beatValue: 4 }).setMode(Voice.Mode.SOFT).addTickables(lyricNotes);
97
105
  new Formatter().joinVoices([musicVoice, lyricVoice]).format([musicVoice, lyricVoice], 500);
98
- assert.strictEqual(when.getTickContext(), musicNotes[6].getTickContext());
106
+ assert.notStrictEqual(musicNotes[6].getTickContext(), musicNotes[7].getTickContext());
107
+ assert.strictEqual(when.getTickContext(), musicNotes[7].getTickContext());
108
+ }
109
+ function inlineSpacersPreserveNoteSpacing(assert) {
110
+ const firstNote = new StaveNote({ keys: ['c/4'], duration: '4' });
111
+ const clef = new ClefNote('alto', 'small');
112
+ const secondNote = new StaveNote({ keys: ['c/4'], duration: '4', clef: 'alto' });
113
+ const timeSignature = new TimeSigNote('3/4');
114
+ const thirdNote = new StaveNote({ keys: ['c/4'], duration: '4', clef: 'alto' });
115
+ const voice = new Voice('4/4').setMode(Voice.Mode.SOFT).addTickables([firstNote, clef, secondNote, timeSignature, thirdNote]);
116
+ new Formatter().joinVoices([voice]).format([voice], 500);
117
+ assert.notStrictEqual(clef.getTickContext(), secondNote.getTickContext());
118
+ assert.notStrictEqual(timeSignature.getTickContext(), thirdNote.getTickContext());
99
119
  }
100
120
  function dependentVoicesDoNotAffectMusicLayout(assert) {
101
121
  const makeMusicNotes = () => Array.from({ length: 4 }, () => new StaveNote({ keys: ['c/4'], duration: '4' }));
@@ -115,6 +135,31 @@ function dependentVoicesDoNotAffectMusicLayout(assert) {
115
135
  assert.strictEqual(lyric.getX(), musicNotes[1].getX());
116
136
  musicNotes.forEach((note, index) => assert.strictEqual(note.getX(), baselineNotes[index].getX()));
117
137
  }
138
+ function dependentOffGridVoicesDoNotAffectMusicLayout(assert) {
139
+ const makeMusicNotes = () => Array.from({ length: 4 }, () => new StaveNote({ keys: ['c/4'], duration: '4' }));
140
+ const makeLyricNotes = () => Array.from({ length: 16 }, (_, i) => i % 2 === 0 ? new GhostNote({ duration: '16' }) : new TextNote({ text: 'x', duration: '16' }));
141
+ const baselineNotes = makeMusicNotes();
142
+ const baselineVoice = new Voice('4/4').addTickables(baselineNotes);
143
+ const baselineFormatter = new Formatter().joinVoices([baselineVoice]);
144
+ const baselineMinWidth = baselineFormatter.preCalculateMinTotalWidth([baselineVoice]);
145
+ baselineFormatter.format([baselineVoice], 500);
146
+ const musicNotes = makeMusicNotes();
147
+ const musicVoice = new Voice('4/4').addTickables(musicNotes);
148
+ const lyricNotes = makeLyricNotes();
149
+ const lyricVoice = new Voice('4/4').setMode(Voice.Mode.SOFT).setDependent(true).addTickables(lyricNotes);
150
+ const formatter = new Formatter().joinVoices([musicVoice, lyricVoice]);
151
+ assert.strictEqual(formatter.preCalculateMinTotalWidth([musicVoice, lyricVoice]), baselineMinWidth);
152
+ formatter.format([musicVoice, lyricVoice], 500);
153
+ const tickContexts = formatter.getTickContexts();
154
+ assert.ok(tickContexts);
155
+ if (!tickContexts)
156
+ return;
157
+ assert.equal(tickContexts.spacingList.length, 4);
158
+ assert.equal(tickContexts.dependentList.length, 12);
159
+ musicNotes.forEach((note, index) => assert.strictEqual(note.getX(), baselineNotes[index].getX()));
160
+ assert.ok(lyricNotes[1].getX() > musicNotes[0].getX());
161
+ assert.ok(lyricNotes[1].getX() < musicNotes[1].getX());
162
+ }
118
163
  function getResolutionMultiplier(assert) {
119
164
  const [voice1, voice2] = getTestVoices();
120
165
  assert.equal(voice1.getResolutionMultiplier(), voice2.getResolutionMultiplier(), 'Voices with same smallest duration have the same resolution multiplier');
@@ -28,7 +28,12 @@ export interface FormatParams {
28
28
  context?: RenderContext;
29
29
  }
30
30
  export interface AlignmentTickContexts {
31
+ /** All tick positions, sorted. */
31
32
  list: number[];
33
+ /** Tick positions whose contexts participate in spacing and justification. */
34
+ spacingList: number[];
35
+ /** Tick positions whose contexts contain only dependent tickables. */
36
+ dependentList: number[];
32
37
  map: Record<number, TickContext>;
33
38
  array: TickContext[];
34
39
  resolutionMultiplier: number;
@@ -184,6 +189,15 @@ export declare class Formatter {
184
189
  * of all the tickables/notes in the formatter.
185
190
  */
186
191
  preFormat(justifyWidth?: number, renderingContext?: RenderContext, voicesParam?: Voice[], stave?: Stave): number;
192
+ /**
193
+ * Position contexts that contain only dependent tickables.
194
+ *
195
+ * Dependent voices follow the layout of the other voices, so their contexts
196
+ * are not part of the spacing list. Instead, place each one between the
197
+ * surrounding spacing contexts, interpolating by tick. Contexts before the
198
+ * first or after the last spacing context are aligned with that context.
199
+ */
200
+ protected positionDependentContexts(): void;
187
201
  /** Calculate the total cost of this formatting decision. */
188
202
  evaluate(): number;
189
203
  /**
@@ -65,6 +65,17 @@ export declare class TickContext {
65
65
  getMaxTickable(): Tickable | undefined;
66
66
  getMinTickable(): Tickable | undefined;
67
67
  getTickables(): Tickable[];
68
+ /**
69
+ * Return the tickables that participate in spacing. Tickables from dependent
70
+ * voices follow the layout of the other voices and are excluded.
71
+ */
72
+ getNonDependentTickables(): Tickable[];
73
+ /**
74
+ * Return true if this context contains tickables, all of which belong to
75
+ * dependent voices. Such contexts should not create a spacing slot of their
76
+ * own; they are positioned from the surrounding non-dependent contexts.
77
+ */
78
+ hasOnlyDependentTickables(): boolean;
68
79
  /**
69
80
  * Introduced on 2020-04-17 as getTickablesForVoice(voiceIndex).
70
81
  * https://github.com/0xfe/vexflow/blame/dc97b0cc5bb93171c0038638c34362dc958222ca/src/tickcontext.js#L63
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mcqj/vexflow",
3
- "version": "0.0.1-alpha.6",
3
+ "version": "0.0.1-alpha.8",
4
4
  "description": "A JavaScript library for rendering music notation and guitar tablature.",
5
5
  "author": {
6
6
  "name": "mcqj",
@@ -69,7 +69,7 @@
69
69
  "eslint-plugin-import-x": "^4.17.1",
70
70
  "eslint-plugin-simple-import-sort": "^12.1.1",
71
71
  "globals": "^17.12.0",
72
- "jsdom": "^30.0.1",
72
+ "jsdom": "^30.1.3",
73
73
  "jspdf": "^4.0.0",
74
74
  "magic-string": "^1.2.3",
75
75
  "opentype.js": "^2.0.0",
@@ -113,8 +113,8 @@
113
113
  },
114
114
  "allowScripts": {
115
115
  "canvas@3.2.3": true,
116
- "core-js@3.50.0": true,
117
116
  "fsevents@2.3.3": true,
118
- "unrs-resolver@1.12.2": true
117
+ "unrs-resolver@1.12.2": true,
118
+ "core-js@3.51.0": true
119
119
  }
120
120
  }