@mcqj/vexflow 0.0.1-alpha.7 → 0.0.1-alpha.9

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.
@@ -149,6 +149,8 @@ export class Formatter {
149
149
  map: {},
150
150
  array: [],
151
151
  list: [],
152
+ spacingList: [],
153
+ dependentList: [],
152
154
  resolutionMultiplier: 0,
153
155
  };
154
156
  this.modifierContexts = [];
@@ -178,15 +180,18 @@ export class Formatter {
178
180
  throw new RuntimeError('BadArgument', "'voices' required to run preCalculateMinTotalWidth");
179
181
  }
180
182
  this.createTickContexts(voices);
181
- 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;
182
186
  this.minTotalWidth = 0;
183
187
  contextList.forEach((tick) => {
184
188
  const context = contextMap[tick];
185
189
  context.preFormat();
186
- if (context.getTickables().length < voices.length) {
190
+ const spacingTickables = hasSpacingVoices ? context.getNonDependentTickables() : context.getTickables();
191
+ if (spacingTickables.length < (hasSpacingVoices ? spacingVoices.length : voices.length)) {
187
192
  unalignedCtxCount += 1;
188
193
  }
189
- context.getTickables().forEach((t) => {
194
+ spacingTickables.forEach((t) => {
190
195
  wsum += t.getMetrics().width;
191
196
  dsum += t.getTicks().value();
192
197
  widths.push(t.getMetrics().width);
@@ -264,6 +269,8 @@ export class Formatter {
264
269
  map: {},
265
270
  array: [],
266
271
  list: [],
272
+ spacingList: [],
273
+ dependentList: [],
267
274
  resolutionMultiplier: 0,
268
275
  };
269
276
  }
@@ -286,10 +293,27 @@ export class Formatter {
286
293
  ticksUsed.add(tickable.getTicks());
287
294
  });
288
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
+ }
289
311
  const contexts = {
290
312
  map: tickToContextMap,
291
313
  array: tickContexts,
292
- list: tickList.sort((a, b) => a - b),
314
+ list: sortedTickList,
315
+ spacingList,
316
+ dependentList,
293
317
  resolutionMultiplier,
294
318
  };
295
319
  this.tickContexts = contexts;
@@ -307,7 +331,8 @@ export class Formatter {
307
331
  if (!contexts) {
308
332
  throw new RuntimeError('NoTickContexts', 'preFormat requires TickContexts');
309
333
  }
310
- const { list: contextList, map: contextMap } = contexts;
334
+ const { spacingList: contextList, map: contextMap } = contexts;
335
+ this.justifyWidth = justifyWidth;
311
336
  this.lossHistory = [];
312
337
  if (voicesParam && stave) {
313
338
  voicesParam.forEach((voice) => voice.setStave(stave).preFormat());
@@ -333,8 +358,10 @@ export class Formatter {
333
358
  const expTicksUsed = sumArray(contextList.map(exp));
334
359
  this.minTotalWidth = x + shift;
335
360
  this.hasMinTotalWidth = true;
336
- if (justifyWidth <= 0)
361
+ if (justifyWidth <= 0) {
362
+ this.positionDependentContexts();
337
363
  return this.evaluate();
364
+ }
338
365
  const firstContext = contextMap[contextList[0]];
339
366
  const lastContext = contextMap[contextList[contextList.length - 1]];
340
367
  function calculateIdealDistances(adjustedJustifyWidth) {
@@ -425,8 +452,10 @@ export class Formatter {
425
452
  let targetWidth = adjustedJustifyWidth;
426
453
  const distances = calculateIdealDistances(targetWidth);
427
454
  let actualWidth = shiftToIdealDistances(distances);
428
- if (contextList.length === 1)
455
+ if (contextList.length === 1) {
456
+ this.positionDependentContexts();
429
457
  return 0;
458
+ }
430
459
  const calcMinDistance = (targetWidth, distances) => {
431
460
  let mdCalc = targetWidth / 2;
432
461
  if (distances.length > 1) {
@@ -462,17 +491,71 @@ export class Formatter {
462
491
  actualWidth = shiftToIdealDistances(calculateIdealDistances(targetWidth));
463
492
  iterations--;
464
493
  }
465
- this.justifyWidth = justifyWidth;
494
+ this.positionDependentContexts();
466
495
  return this.evaluate();
467
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
+ const firstSpacingContext = map[spacingList[0]];
505
+ const lastSpacingTick = spacingList[spacingList.length - 1];
506
+ const lastSpacingContext = map[lastSpacingTick];
507
+ const finalTick = lastSpacingTick + lastSpacingContext.getMaxTicks().value();
508
+ const centerX = this.justifyWidth > 0
509
+ ? (this.justifyWidth -
510
+ lastSpacingContext.getMetrics().notePx -
511
+ lastSpacingContext.getMetrics().totalRightPx -
512
+ firstSpacingContext.getMetrics().totalLeftPx) /
513
+ 2
514
+ : undefined;
515
+ const endX = this.justifyWidth > 0 ? this.justifyWidth : undefined;
516
+ let nextIndex = 0;
517
+ dependentList.forEach((tick) => {
518
+ while (nextIndex < spacingList.length && spacingList[nextIndex] < tick) {
519
+ nextIndex++;
520
+ }
521
+ const prevTick = nextIndex > 0 ? spacingList[nextIndex - 1] : undefined;
522
+ const nextTick = nextIndex < spacingList.length ? spacingList[nextIndex] : undefined;
523
+ const context = map[tick];
524
+ context.preFormat();
525
+ if (prevTick !== undefined && nextTick !== undefined) {
526
+ const prevX = map[prevTick].getX();
527
+ const nextX = map[nextTick].getX();
528
+ const ratio = (tick - prevTick) / (nextTick - prevTick);
529
+ context.setX(prevX + (nextX - prevX) * ratio);
530
+ }
531
+ else if (prevTick !== undefined) {
532
+ const prevX = map[prevTick].getX();
533
+ if (endX !== undefined && finalTick > prevTick) {
534
+ const ratio = Math.min(1, (tick - prevTick) / (finalTick - prevTick));
535
+ context.setX(prevX + (endX - prevX) * ratio);
536
+ }
537
+ else {
538
+ context.setX(prevX);
539
+ }
540
+ }
541
+ else if (nextTick !== undefined) {
542
+ context.setX(map[nextTick].getX());
543
+ }
544
+ if (centerX !== undefined) {
545
+ context.getCenterAlignedTickables().forEach((tickable) => {
546
+ tickable.setCenterXShift(centerX - context.getX());
547
+ });
548
+ }
549
+ });
550
+ }
468
551
  evaluate() {
469
552
  const contexts = this.tickContexts;
470
553
  const justifyWidth = this.justifyWidth;
471
554
  this.contextGaps = { total: 0, gaps: [] };
472
- contexts.list.forEach((tick, index) => {
555
+ contexts.spacingList.forEach((tick, index) => {
473
556
  if (index === 0)
474
557
  return;
475
- const prevTick = contexts.list[index - 1];
558
+ const prevTick = contexts.spacingList[index - 1];
476
559
  const prevContext = contexts.map[prevTick];
477
560
  const context = contexts.map[tick];
478
561
  const prevMetrics = prevContext.getMetrics();
@@ -499,6 +582,8 @@ export class Formatter {
499
582
  }
500
583
  }
501
584
  this.voices.forEach((voice) => {
585
+ if (voice.isDependent())
586
+ return;
502
587
  voice.getTickables().forEach((note, i, notes) => {
503
588
  const duration = note.getTicks().clone().simplify().toString();
504
589
  const metrics = note.getMetrics();
@@ -523,6 +608,8 @@ export class Formatter {
523
608
  });
524
609
  let totalDeviation = 0;
525
610
  this.voices.forEach((voice) => {
611
+ if (voice.isDependent())
612
+ return;
526
613
  voice.getTickables().forEach((note) => {
527
614
  const duration = note.getTicks().clone().simplify().toString();
528
615
  const metrics = note.getFormatterMetrics();
@@ -546,7 +633,7 @@ export class Formatter {
546
633
  const alpha = (_a = options === null || options === void 0 ? void 0 : options.alpha) !== null && _a !== void 0 ? _a : 0.5;
547
634
  let shift = 0;
548
635
  this.totalShift = 0;
549
- contexts.list.forEach((tick, index, list) => {
636
+ contexts.spacingList.forEach((tick, index, list) => {
550
637
  const context = contexts.map[tick];
551
638
  const prevContext = index > 0 ? contexts.map[list[index - 1]] : undefined;
552
639
  const nextContext = index < list.length - 1 ? contexts.map[list[index + 1]] : undefined;
@@ -566,6 +653,7 @@ export class Formatter {
566
653
  shift *= alpha;
567
654
  this.totalShift += shift;
568
655
  });
656
+ this.positionDependentContexts();
569
657
  return this.evaluate();
570
658
  }
571
659
  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.7';
2
- export const ID = 'a4bb5ff157f4570b2d6149b7199b0baa4c7e3775';
3
- export const DATE = '2026-09-14T16:33:09.139Z';
1
+ export const VERSION = '0.0.1-alpha.8';
2
+ export const ID = 'beeb3933573a1cbf00a85d294d8524fabba6f406';
3
+ export const DATE = '2026-11-23T01:19:49.890Z';
@@ -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,10 @@ 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);
80
+ VexFlowTests.test('Off-grid dependent voices honor center alignment', dependentOffGridVoicesCenterAlign);
76
81
  run('Proportional Formatting - No Tuning', proportional, { debug: true, iterations: 0 });
77
82
  run('Proportional Formatting - No Justification', proportional, { justify: false, debug: true, iterations: 0 });
78
83
  run('Proportional Formatting (20 iterations)', proportional, { debug: true, iterations: 20, alpha: 0.5 });
@@ -102,6 +107,17 @@ function ignoredBarNotesPreserveLyricTickAlignment(assert) {
102
107
  assert.notStrictEqual(musicNotes[6].getTickContext(), musicNotes[7].getTickContext());
103
108
  assert.strictEqual(when.getTickContext(), musicNotes[7].getTickContext());
104
109
  }
110
+ function inlineSpacersPreserveNoteSpacing(assert) {
111
+ const firstNote = new StaveNote({ keys: ['c/4'], duration: '4' });
112
+ const clef = new ClefNote('alto', 'small');
113
+ const secondNote = new StaveNote({ keys: ['c/4'], duration: '4', clef: 'alto' });
114
+ const timeSignature = new TimeSigNote('3/4');
115
+ const thirdNote = new StaveNote({ keys: ['c/4'], duration: '4', clef: 'alto' });
116
+ const voice = new Voice('4/4').setMode(Voice.Mode.SOFT).addTickables([firstNote, clef, secondNote, timeSignature, thirdNote]);
117
+ new Formatter().joinVoices([voice]).format([voice], 500);
118
+ assert.notStrictEqual(clef.getTickContext(), secondNote.getTickContext());
119
+ assert.notStrictEqual(timeSignature.getTickContext(), thirdNote.getTickContext());
120
+ }
105
121
  function dependentVoicesDoNotAffectMusicLayout(assert) {
106
122
  const makeMusicNotes = () => Array.from({ length: 4 }, () => new StaveNote({ keys: ['c/4'], duration: '4' }));
107
123
  const baselineNotes = makeMusicNotes();
@@ -120,6 +136,56 @@ function dependentVoicesDoNotAffectMusicLayout(assert) {
120
136
  assert.strictEqual(lyric.getX(), musicNotes[1].getX());
121
137
  musicNotes.forEach((note, index) => assert.strictEqual(note.getX(), baselineNotes[index].getX()));
122
138
  }
139
+ function dependentOffGridVoicesDoNotAffectMusicLayout(assert) {
140
+ const makeMusicNotes = () => Array.from({ length: 4 }, () => new StaveNote({ keys: ['c/4'], duration: '4' }));
141
+ const makeLyricNotes = () => Array.from({ length: 16 }, (_, i) => i % 2 === 0 ? new GhostNote({ duration: '16' }) : new TextNote({ text: 'x', duration: '16' }));
142
+ const baselineNotes = makeMusicNotes();
143
+ const baselineVoice = new Voice('4/4').addTickables(baselineNotes);
144
+ const baselineFormatter = new Formatter().joinVoices([baselineVoice]);
145
+ const baselineMinWidth = baselineFormatter.preCalculateMinTotalWidth([baselineVoice]);
146
+ baselineFormatter.format([baselineVoice], 500);
147
+ const musicNotes = makeMusicNotes();
148
+ const musicVoice = new Voice('4/4').addTickables(musicNotes);
149
+ const lyricNotes = makeLyricNotes();
150
+ const lyricVoice = new Voice('4/4').setMode(Voice.Mode.SOFT).setDependent(true).addTickables(lyricNotes);
151
+ const formatter = new Formatter().joinVoices([musicVoice, lyricVoice]);
152
+ assert.strictEqual(formatter.preCalculateMinTotalWidth([musicVoice, lyricVoice]), baselineMinWidth);
153
+ formatter.format([musicVoice, lyricVoice], 500);
154
+ const tickContexts = formatter.getTickContexts();
155
+ assert.ok(tickContexts);
156
+ if (!tickContexts)
157
+ return;
158
+ assert.equal(tickContexts.spacingList.length, 4);
159
+ assert.equal(tickContexts.dependentList.length, 12);
160
+ musicNotes.forEach((note, index) => assert.strictEqual(note.getX(), baselineNotes[index].getX()));
161
+ assert.ok(lyricNotes[1].getX() > musicNotes[0].getX());
162
+ assert.ok(lyricNotes[1].getX() < musicNotes[1].getX());
163
+ const lastMusicX = musicNotes[3].getX();
164
+ const trailingLyricX = lyricNotes[13].getX();
165
+ const lastLyricX = lyricNotes[15].getX();
166
+ assert.ok(trailingLyricX > lastMusicX, 'First trailing lyric should follow the final music onset.');
167
+ assert.ok(lastLyricX > trailingLyricX, 'Trailing lyrics should not overlap.');
168
+ assert.ok(lastLyricX < 500, 'Trailing lyrics should stay within the justified width.');
169
+ }
170
+ function dependentOffGridVoicesCenterAlign(assert) {
171
+ const musicNotes = Array.from({ length: 4 }, () => new StaveNote({ keys: ['c/4'], duration: '4' }));
172
+ const musicVoice = new Voice('4/4').addTickables(musicNotes);
173
+ const centered = new TextNote({ text: 'x', duration: '16', alignCenter: true });
174
+ const lyricNotes = Array.from({ length: 16 }, (_, i) => (i === 5 ? centered : new GhostNote({ duration: '16' })));
175
+ const lyricVoice = new Voice('4/4').setMode(Voice.Mode.SOFT).setDependent(true).addTickables(lyricNotes);
176
+ const formatter = new Formatter().joinVoices([musicVoice, lyricVoice]);
177
+ formatter.format([musicVoice, lyricVoice], 500);
178
+ const tickContexts = formatter.getTickContexts();
179
+ assert.ok(tickContexts);
180
+ if (!tickContexts)
181
+ return;
182
+ const firstContext = tickContexts.map[tickContexts.spacingList[0]];
183
+ const lastContext = tickContexts.map[tickContexts.spacingList[tickContexts.spacingList.length - 1]];
184
+ const adjustedJustifyWidth = 500 - lastContext.getMetrics().notePx - lastContext.getMetrics().totalRightPx - firstContext.getMetrics().totalLeftPx;
185
+ const expectedCenterXShift = adjustedJustifyWidth / 2 - centered.getTickContext().getX();
186
+ assert.ok(expectedCenterXShift !== 0);
187
+ assert.ok(Math.abs(centered.getCenterXShift() - expectedCenterXShift) < 1e-9, 'Center-aligned dependent tickables should use the same justified center as spacing tickables.');
188
+ }
123
189
  function getResolutionMultiplier(assert) {
124
190
  const [voice1, voice2] = getTestVoices();
125
191
  assert.equal(voice1.getResolutionMultiplier(), voice2.getResolutionMultiplier(), 'Voices with same smallest duration have the same resolution multiplier');