vexflow 5.0.0 → 5.1.1

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 (130) hide show
  1. package/LICENSE +3 -3
  2. package/README.md +46 -53
  3. package/build/cjs/vexflow-bravura.js +2 -2
  4. package/build/cjs/vexflow-bravura.js.map +1 -1
  5. package/build/cjs/vexflow-core.js +2 -2
  6. package/build/cjs/vexflow-core.js.map +1 -1
  7. package/build/cjs/vexflow-debug-with-tests.js +3825 -1396
  8. package/build/cjs/vexflow-debug-with-tests.js.map +1 -1
  9. package/build/cjs/vexflow-debug.js +2577 -984
  10. package/build/cjs/vexflow-debug.js.map +1 -1
  11. package/build/cjs/vexflow.js +2 -2
  12. package/build/cjs/vexflow.js.map +1 -1
  13. package/build/esm/src/accidental.js +1 -0
  14. package/build/esm/src/annotation.js +31 -8
  15. package/build/esm/src/beam.js +4 -2
  16. package/build/esm/src/chordsymbol.js +3 -1
  17. package/build/esm/src/clef.js +3 -1
  18. package/build/esm/src/curve.js +68 -11
  19. package/build/esm/src/easyscore.js +40 -1
  20. package/build/esm/src/element.js +49 -11
  21. package/build/esm/src/factory.js +46 -9
  22. package/build/esm/src/flag.js +3 -1
  23. package/build/esm/src/font.js +20 -1
  24. package/build/esm/src/formatter.js +34 -36
  25. package/build/esm/src/fraction.js +4 -1
  26. package/build/esm/src/glyphnote.js +3 -1
  27. package/build/esm/src/gracenotegroup.js +18 -1
  28. package/build/esm/src/index.js +2 -0
  29. package/build/esm/src/keysignature.js +3 -1
  30. package/build/esm/src/metrics.js +58 -3
  31. package/build/esm/src/modifiercontext.js +15 -1
  32. package/build/esm/src/note.js +2 -2
  33. package/build/esm/src/notehead.js +3 -1
  34. package/build/esm/src/ornament.js +3 -1
  35. package/build/esm/src/pedalmarking.js +44 -5
  36. package/build/esm/src/registry.js +16 -6
  37. package/build/esm/src/rendercontext.js +10 -0
  38. package/build/esm/src/sheet.js +117 -0
  39. package/build/esm/src/stave.js +13 -8
  40. package/build/esm/src/stavebarline.js +53 -1
  41. package/build/esm/src/staveline.js +2 -0
  42. package/build/esm/src/stavenote.js +54 -19
  43. package/build/esm/src/stavetie.js +3 -1
  44. package/build/esm/src/stem.js +2 -1
  45. package/build/esm/src/stemmablenote.js +9 -0
  46. package/build/esm/src/stringnumber.js +0 -1
  47. package/build/esm/src/strokes.js +10 -0
  48. package/build/esm/src/svgcontext.js +14 -4
  49. package/build/esm/src/svgexport.js +68 -0
  50. package/build/esm/src/system.js +14 -0
  51. package/build/esm/src/tables.js +69 -37
  52. package/build/esm/src/tabnote.js +20 -1
  53. package/build/esm/src/textbracket.js +5 -4
  54. package/build/esm/src/textdynamics.js +5 -0
  55. package/build/esm/src/textmetricscache.js +93 -0
  56. package/build/esm/src/textnote.js +3 -3
  57. package/build/esm/src/tickable.js +56 -22
  58. package/build/esm/src/timesignature.js +30 -9
  59. package/build/esm/src/timesignote.js +3 -1
  60. package/build/esm/src/tuning.js +2 -2
  61. package/build/esm/src/tuplet.js +79 -29
  62. package/build/esm/src/util.js +1 -0
  63. package/build/esm/src/version.js +3 -3
  64. package/build/esm/src/vexflow.js +14 -2
  65. package/build/esm/src/voice.js +44 -8
  66. package/build/esm/tests/accidental_tests.js +52 -0
  67. package/build/esm/tests/annotation_tests.js +38 -0
  68. package/build/esm/tests/articulation_tests.js +34 -0
  69. package/build/esm/tests/beam_tests.js +17 -0
  70. package/build/esm/tests/curve_tests.js +81 -0
  71. package/build/esm/tests/font_tests.js +32 -1
  72. package/build/esm/tests/formatter_tests.js +58 -23
  73. package/build/esm/tests/gracenote_tests.js +58 -0
  74. package/build/esm/tests/gracetabnote_tests.js +40 -0
  75. package/build/esm/tests/keysignature_tests.js +14 -3
  76. package/build/esm/tests/node/metrics-tests.mjs +278 -0
  77. package/build/esm/tests/node/package-input-tests.mjs +149 -0
  78. package/build/esm/tests/node/render-metrics-tests.mjs +78 -0
  79. package/build/esm/tests/node/rendering-tests.mjs +75 -0
  80. package/build/esm/tests/node/sheet-tests.mjs +202 -0
  81. package/build/esm/tests/node/svg-export-tests.mjs +182 -0
  82. package/build/esm/tests/pedalmarking_tests.js +25 -0
  83. package/build/esm/tests/rests_tests.js +6 -0
  84. package/build/esm/tests/stave_tests.js +6 -3
  85. package/build/esm/tests/stavenote_tests.js +100 -55
  86. package/build/esm/tests/strokes_tests.js +19 -5
  87. package/build/esm/tests/timesignature_tests.js +19 -0
  88. package/build/esm/tests/tuplet_tests.js +273 -12
  89. package/build/esm/tests/unison_tests.js +13 -13
  90. package/build/esm/tests/voice_tests.js +34 -0
  91. package/build/esm/tools/render-metrics.mjs +49 -0
  92. package/build/esm/tools/score-fixtures.mjs +94 -0
  93. package/build/esm/tools/sheet-fixture.mjs +90 -0
  94. package/build/esm/tools/visual-regression.mjs +106 -0
  95. package/build/types/src/annotation.d.ts +17 -1
  96. package/build/types/src/curve.d.ts +24 -7
  97. package/build/types/src/easyscore.d.ts +8 -0
  98. package/build/types/src/element.d.ts +7 -0
  99. package/build/types/src/factory.d.ts +18 -1
  100. package/build/types/src/font.d.ts +2 -0
  101. package/build/types/src/formatter.d.ts +23 -14
  102. package/build/types/src/gracenotegroup.d.ts +5 -0
  103. package/build/types/src/index.d.ts +2 -0
  104. package/build/types/src/metrics.d.ts +2 -0
  105. package/build/types/src/modifiercontext.d.ts +4 -0
  106. package/build/types/src/pedalmarking.d.ts +4 -1
  107. package/build/types/src/registry.d.ts +2 -0
  108. package/build/types/src/rendercontext.d.ts +12 -0
  109. package/build/types/src/sheet.d.ts +49 -0
  110. package/build/types/src/stave.d.ts +4 -4
  111. package/build/types/src/stavebarline.d.ts +10 -0
  112. package/build/types/src/stavenote.d.ts +11 -0
  113. package/build/types/src/strokes.d.ts +4 -0
  114. package/build/types/src/svgcontext.d.ts +5 -0
  115. package/build/types/src/svgexport.d.ts +22 -0
  116. package/build/types/src/system.d.ts +4 -0
  117. package/build/types/src/tables.d.ts +9 -0
  118. package/build/types/src/tabnote.d.ts +4 -0
  119. package/build/types/src/textbracket.d.ts +1 -1
  120. package/build/types/src/textdynamics.d.ts +3 -0
  121. package/build/types/src/textmetricscache.d.ts +21 -0
  122. package/build/types/src/tickable.d.ts +27 -10
  123. package/build/types/src/timesignature.d.ts +4 -0
  124. package/build/types/src/tuplet.d.ts +8 -0
  125. package/build/types/src/util.d.ts +1 -0
  126. package/build/types/src/vexflow.d.ts +8 -1
  127. package/build/types/src/voice.d.ts +6 -0
  128. package/changelog/CHANGELOG.md +109 -0
  129. package/package.json +44 -26
  130. package/tests/flow.html +15 -7
@@ -0,0 +1,149 @@
1
+ import assert from 'node:assert/strict';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import test from 'node:test';
7
+ import { fileURLToPath } from 'node:url';
8
+ const root = fileURLToPath(new URL('../../', import.meta.url));
9
+ const coreURL = new URL('../../build/esm/entry/vexflow-core.js', import.meta.url).href;
10
+ function runIsolated(source) {
11
+ const result = spawnSync(process.execPath, ['--input-type=module', '-e', source], {
12
+ cwd: root,
13
+ timeout: 3000,
14
+ encoding: 'utf8',
15
+ });
16
+ assert.ifError(result.error);
17
+ assert.equal(result.status, 0, result.stderr || result.stdout);
18
+ }
19
+ function checkCore(source) {
20
+ runIsolated(`import assert from 'node:assert/strict';
21
+ import { Element, Registry, Fraction, Voice, GhostNote, Tuning } from ${JSON.stringify(coreURL)};
22
+ ${source}`);
23
+ }
24
+ test('all published ESM entries load', () => {
25
+ const pkg = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url)));
26
+ for (const entry of Object.values(pkg.exports)) {
27
+ runIsolated(`await import(${JSON.stringify(new URL(`../../${entry.import}`, import.meta.url).href)});`);
28
+ }
29
+ });
30
+ test('ESM rewrite preserves packages, URLs, comments, and explicit extensions', () => {
31
+ const directory = mkdtempSync(join(tmpdir(), 'vexflow-esm-'));
32
+ try {
33
+ const input = `import clone from 'structured-clone-es';
34
+ import scoped from '@scope/package';
35
+ import 'node:fs';
36
+ import 'https://example.com/module';
37
+ import './already.js';
38
+ import './data.json';
39
+ import './side-effect';
40
+ import value from "../value";
41
+ export * from './';
42
+ export { default } from '.';
43
+ export * from '@scope/other';
44
+ const lazy = import('./lazy');
45
+ const text = "import './not-an-import';";
46
+ // import './comment';
47
+ `;
48
+ const filename = join(directory, 'fixture.js');
49
+ writeFileSync(filename, input);
50
+ const command = [join(root, 'tools/fix-esm-imports.mjs'), directory];
51
+ assert.equal(spawnSync(process.execPath, command).status, 0);
52
+ const expected = input
53
+ .replace("'./side-effect'", "'./side-effect.js'")
54
+ .replace('"../value"', '"../value.js"')
55
+ .replace("from './'", "from './index.js'")
56
+ .replace("from '.'", "from './index.js'")
57
+ .replace("import('./lazy')", "import('./lazy.js')");
58
+ assert.equal(readFileSync(filename, 'utf8'), expected);
59
+ assert.equal(spawnSync(process.execPath, command).status, 0);
60
+ assert.equal(readFileSync(filename, 'utf8'), expected, 'rewrite is idempotent');
61
+ }
62
+ finally {
63
+ rmSync(directory, { recursive: true, force: true });
64
+ }
65
+ });
66
+ test('registry treats prototype-related IDs and classes as ordinary data', () => {
67
+ checkCore(`
68
+ const before = Object.getOwnPropertyDescriptors(Object.prototype);
69
+ const registry = new Registry();
70
+ for (const id of ['reviewProbe', '__proto__', 'constructor', 'toString']) {
71
+ const element = registry.register(new Element(), id).getElementById(id);
72
+ assert.ok(element);
73
+ for (const name of ['__proto__', 'constructor', 'toString']) {
74
+ element.addClass(name);
75
+ assert.ok(registry.getElementsByClass(name).includes(element));
76
+ element.removeClass(name);
77
+ assert.ok(!registry.getElementsByClass(name).includes(element));
78
+ }
79
+ }
80
+ for (const name of ['__proto__', 'constructor', 'toString', 'missing']) {
81
+ assert.throws(() => registry.setIndexValue(name, 'value', 'id', new Element()), /BadArgument/);
82
+ assert.throws(() => registry.updateIndex({id:'reviewProbe', name, value:'value'}), /BadArgument/);
83
+ assert.deepEqual(registry.getElementsByAttribute(name, 'value'), []);
84
+ }
85
+ assert.deepEqual(Object.getOwnPropertyDescriptors(Object.prototype), before);
86
+ registry.clear();
87
+ assert.equal(registry.getElementById('__proto__'), undefined);
88
+ `);
89
+ });
90
+ for (const duration of ["'9'.repeat(10000) + 'X'", "'4' + 'd'.repeat(100000)", "'prefix4'", "'4junk'"]) {
91
+ test(`reject malformed duration: ${duration}`, () => checkCore(`assert.throws(() => new GhostNote(${duration}));`));
92
+ }
93
+ test('valid durations and tuning still work', () => {
94
+ checkCore(`
95
+ for (const duration of ['1/2', 'w', 'h', 'q', '4', '8d', '16dd', '4r', '4n', '4h', '4m', '4s']) {
96
+ assert.ok(new GhostNote(duration).getTicks().value() > 0, duration);
97
+ }
98
+ assert.equal(new Tuning(' E/5 , B/4 , G/4 ').getValueForString(2), new Tuning('standard').getValueForString(2));
99
+ assert.throws(() => new Tuning('constructor'));
100
+ assert.throws(() => new Tuning(' '.repeat(100000) + 'X'));
101
+ `);
102
+ });
103
+ for (const meter of [
104
+ "'9'.repeat(100000)",
105
+ "'9'.repeat(400) + '/4'",
106
+ "'4/0'",
107
+ "'0/4'",
108
+ "'prefix4/4'",
109
+ "'4/4suffix'",
110
+ "''",
111
+ '{numBeats:Infinity,beatValue:4}',
112
+ '{numBeats:4,beatValue:NaN}',
113
+ '{numBeats:4,beatValue:0}',
114
+ '{numBeats:-1,beatValue:4}',
115
+ '{numBeats:1.5,beatValue:4}',
116
+ '{numBeats:4,beatValue:4,resolution:0}',
117
+ '{numBeats:4,beatValue:4,resolution:Infinity}',
118
+ '{numBeats:Number.MAX_SAFE_INTEGER,beatValue:1}',
119
+ ]) {
120
+ test(`reject invalid meter: ${meter}`, () => checkCore(`assert.throws(() => new Voice(${meter}).isComplete(), /BadArgument/);`));
121
+ }
122
+ test('valid meters preserve tick counts', () => {
123
+ checkCore(`
124
+ assert.equal(new Voice().getTotalTicks().value(), new Voice('4/4').getTotalTicks().value());
125
+ assert.equal(new Voice('3/8').getTotalTicks().value(), 6144);
126
+ assert.equal(new Voice({numBeats:3,beatValue:8,resolution:480}).getTotalTicks().value(), 180);
127
+ `);
128
+ });
129
+ for (const value of ['Infinity', '-Infinity', 'NaN']) {
130
+ test(`fraction rejects ${value} in both operands`, () => checkCore(`
131
+ assert.throws(() => Fraction.GCD(${value}, 1), /BadArgument/);
132
+ assert.throws(() => Fraction.GCD(1, ${value}), /BadArgument/);
133
+ assert.throws(() => new Fraction(${value}, 1), /BadArgument/);
134
+ assert.throws(() => new Fraction(1, ${value}), /BadArgument/);
135
+ `));
136
+ }
137
+ test('fraction rejects zero denominators and overflow without changing its value', () => {
138
+ checkCore(`
139
+ assert.throws(() => new Fraction(1, 0), /BadArgument/);
140
+ const fraction = new Fraction(1, 2);
141
+ assert.throws(() => fraction.divide(0), /BadArgument/);
142
+ assert.equal(fraction.value(), 0.5);
143
+ assert.throws(() => new Fraction(Number.MAX_VALUE).multiply(2), /BadArgument/);
144
+ assert.equal(new Fraction(0, 2).simplify().value(), 0);
145
+ assert.equal(new Fraction(1, -2).simplify().value(), -0.5);
146
+ assert.equal(new Fraction(0.5, 1).simplify().toString(), '1/2');
147
+ assert.equal(Fraction.GCD(0, 0), 0);
148
+ `);
149
+ });
@@ -0,0 +1,78 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import assert from 'node:assert/strict';
11
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
12
+ import { tmpdir } from 'node:os';
13
+ import { join } from 'node:path';
14
+ import test from 'node:test';
15
+ import { createCanvas } from 'canvas';
16
+ import { analyzeLayout, comparePixels } from '../../tools/render-metrics.mjs';
17
+ import { compareDirectories } from '../../tools/visual-regression.mjs';
18
+ test('layout diagnostics detect moved notes, clipping, and non-finite bounds', () => {
19
+ const boxes = [
20
+ { id: 'a', group: 'voice', x: 5, y: 5, width: 10, height: 10 },
21
+ { id: 'b', group: 'voice', x: 20, y: 5, width: 10, height: 10 },
22
+ ];
23
+ const viewport = { width: 40, height: 30 };
24
+ assert.deepEqual(analyzeLayout(boxes, viewport), { invalid: [], overflow: [], collisions: [] });
25
+ boxes[1].x = 10;
26
+ assert.equal(analyzeLayout(boxes, viewport).collisions[0].area, 50);
27
+ boxes[1].x = 35;
28
+ assert.equal(analyzeLayout(boxes, viewport).overflow[0].excess, 5);
29
+ boxes[1].x = NaN;
30
+ assert.deepEqual(analyzeLayout(boxes, viewport).invalid, ['b']);
31
+ boxes[1] = Object.assign(Object.assign({}, boxes[0]), { id: 'intentional overlap', group: 'other voice' });
32
+ assert.deepEqual(analyzeLayout(boxes, viewport).collisions, []);
33
+ });
34
+ test('pixel metrics detect color and alpha changes', () => {
35
+ const a = new Uint8Array([255, 255, 255, 255, 0, 0, 0, 255]);
36
+ assert.equal(comparePixels(a, a).changed, 0);
37
+ const b = a.slice();
38
+ b[0] = 250;
39
+ b[7] = 0;
40
+ assert.equal(comparePixels(a, b).changed, 2);
41
+ assert.equal(comparePixels(a, b, 5).changed, 1);
42
+ });
43
+ test('visual comparison reports changed, missing, resized, and corrupt images', () => __awaiter(void 0, void 0, void 0, function* () {
44
+ const root = yield mkdtemp(join(tmpdir(), 'vexflow-visual-'));
45
+ const before = join(root, 'before');
46
+ const after = join(root, 'after');
47
+ const output = join(root, 'report');
48
+ try {
49
+ yield mkdir(before);
50
+ yield mkdir(after);
51
+ yield assert.rejects(compareDirectories(before, after, output), /must contain/);
52
+ const canvas = createCanvas(20, 20);
53
+ const ctx = canvas.getContext('2d');
54
+ ctx.fillStyle = 'white';
55
+ ctx.fillRect(0, 0, 20, 20);
56
+ const white = canvas.toBuffer('image/png');
57
+ yield writeFile(join(before, 'same.png'), white);
58
+ yield writeFile(join(after, 'same.png'), white);
59
+ assert.deepEqual(yield compareDirectories(before, after, output), { total: 1, failed: 0 });
60
+ ctx.fillStyle = 'black';
61
+ ctx.fillRect(5, 5, 2, 2);
62
+ yield writeFile(join(before, 'changed.png'), white);
63
+ yield writeFile(join(after, 'changed.png'), canvas.toBuffer('image/png'));
64
+ yield writeFile(join(before, 'missing.png'), white);
65
+ yield writeFile(join(after, 'new.png'), white);
66
+ yield writeFile(join(before, 'size.png'), white);
67
+ yield writeFile(join(after, 'size.png'), createCanvas(10, 10).toBuffer('image/png'));
68
+ yield writeFile(join(before, 'broken.png'), white);
69
+ yield writeFile(join(after, 'broken.png'), 'not a PNG');
70
+ assert.deepEqual(yield compareDirectories(before, after, output), { total: 6, failed: 5 });
71
+ const report = JSON.parse(yield readFile(join(output, 'results.json'), 'utf8'));
72
+ assert.equal(report.results.find((r) => r.name === 'changed.png').changedPixels, 4);
73
+ assert.ok((yield readFile(join(output, 'index.html'), 'utf8')).includes('diff-changed.png'));
74
+ }
75
+ finally {
76
+ yield rm(root, { recursive: true, force: true });
77
+ }
78
+ }));
@@ -0,0 +1,75 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import assert from 'node:assert/strict';
11
+ import { spawnSync } from 'node:child_process';
12
+ import { mkdirSync, readdirSync, readFileSync } from 'node:fs';
13
+ import { join } from 'node:path';
14
+ import test from 'node:test';
15
+ import { fileURLToPath } from 'node:url';
16
+ import puppeteer from 'puppeteer';
17
+ import { renderScore } from '../../tools/score-fixtures.mjs';
18
+ const root = fileURLToPath(new URL('../../', import.meta.url));
19
+ test('jsdom registers fonts, renders PNGs, and exports portable SVG', () => {
20
+ const directory = join(root, 'build/jsdom-smoke');
21
+ mkdirSync(directory, { recursive: true });
22
+ const script = `
23
+ const assert=require('node:assert/strict');const fs=require('node:fs');
24
+ const {JSDOM}=require('jsdom');const {registerFont}=require('canvas');const opentype=require('opentype.js');
25
+ const dom=new JSDOM('<div id="score"></div>');global.window=dom.window;global.document=dom.window.document;
26
+ const fonts=['bravura/bravura','academico/academico'].map((name,i)=>{
27
+ const file='node_modules/@vexflow-fonts/'+name+'.otf';const family=i?'Academico':'Bravura';
28
+ registerFont(file,{family});return {family,font:opentype.loadSync(file)};
29
+ });
30
+ const VF=require('./build/cjs/vexflow-debug.js');VF.setFonts('Bravura','Academico');
31
+ const renderer=new VF.Renderer(document.getElementById('score'),VF.Renderer.Backends.SVG);renderer.resize(400,200);
32
+ const ctx=renderer.getContext();new VF.Stave(10,40,350).addClef('treble').addTimeSignature('4/4').setContext(ctx).draw();
33
+ ctx.setFont('Academico',12).fillText('Font-aware jsdom export',20,150);
34
+ const svg=ctx.toSVG(fonts);assert.ok(!svg.includes('<text'));assert.ok(svg.includes('<path'));
35
+ fs.writeFileSync(${JSON.stringify(join(directory, 'score.svg'))},svg);dom.window.close();
36
+ `;
37
+ const run = (args) => {
38
+ const r = spawnSync(process.execPath, args, { cwd: root, timeout: 30000, encoding: 'utf8' });
39
+ assert.ifError(r.error);
40
+ assert.equal(r.status, 0, r.stderr + r.stdout);
41
+ };
42
+ run(['-e', script]);
43
+ run(['tools/generate_images_jsdom.js', 'build', directory, '--fonts=bravura', '--module=Clef']);
44
+ const pngs = readdirSync(directory).filter((file) => file.endsWith('.png'));
45
+ assert.equal(pngs.length, 7);
46
+ for (const file of pngs)
47
+ assert.equal(readFileSync(join(directory, file)).subarray(1, 4).toString(), 'PNG');
48
+ });
49
+ test('score benchmark fixtures render', () => __awaiter(void 0, void 0, void 0, function* () {
50
+ const browser = yield puppeteer.launch({
51
+ headless: true,
52
+ args: process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : [],
53
+ });
54
+ try {
55
+ const page = yield browser.newPage();
56
+ yield page.setContent('<div id="score"></div>');
57
+ yield page.addScriptTag({ path: join(root, 'build/cjs/vexflow-debug.js') });
58
+ yield page.evaluate(() => __awaiter(void 0, void 0, void 0, function* () {
59
+ yield document.fonts.ready;
60
+ }));
61
+ for (const kind of ['chorale', 'piano', 'chamber']) {
62
+ const result = yield page.evaluate(renderScore, { kind, systems: 1 });
63
+ const expected = {
64
+ chorale: { notes: 48, staves: 8 },
65
+ piano: { notes: 64, staves: 8 },
66
+ chamber: { notes: 144, staves: 12 },
67
+ }[kind];
68
+ assert.deepEqual({ notes: result.notes, staves: result.staves }, expected);
69
+ assert.ok(result.svg.includes('<path'));
70
+ }
71
+ }
72
+ finally {
73
+ yield browser.close();
74
+ }
75
+ }));
@@ -0,0 +1,202 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ var __rest = (this && this.__rest) || function (s, e) {
11
+ var t = {};
12
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
13
+ t[p] = s[p];
14
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
15
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
16
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
17
+ t[p[i]] = s[p[i]];
18
+ }
19
+ return t;
20
+ };
21
+ import assert from 'node:assert/strict';
22
+ import test from 'node:test';
23
+ import { fileURLToPath } from 'node:url';
24
+ import puppeteer from 'puppeteer';
25
+ import { analyzeLayout } from '../../tools/render-metrics.mjs';
26
+ import { renderSheetStudy } from '../../tools/sheet-fixture.mjs';
27
+ const root = fileURLToPath(new URL('../../', import.meta.url));
28
+ test('responsive sheets and themes on Canvas and SVG', (t) => __awaiter(void 0, void 0, void 0, function* () {
29
+ const browser = yield puppeteer.launch({
30
+ headless: true,
31
+ args: process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : [],
32
+ });
33
+ try {
34
+ const page = yield browser.newPage();
35
+ yield page.setContent('<div id="score"></div>');
36
+ yield page.addScriptTag({ path: `${root}build/cjs/vexflow-debug.js` });
37
+ yield page.evaluate(() => __awaiter(void 0, void 0, void 0, function* () {
38
+ yield document.fonts.ready;
39
+ }));
40
+ for (const font of ['Bravura', 'Petaluma']) {
41
+ for (const backend of ['svg', 'canvas']) {
42
+ yield t.test(`${font} ${backend}: resize, bounds, colors`, () => __awaiter(void 0, void 0, void 0, function* () {
43
+ const result = yield page.evaluate(renderSheetStudy, { font, backend, widths: [320, 680] });
44
+ const [wide, narrow, restored] = result.snapshots;
45
+ assert.deepEqual(restored, wide, 'wide/narrow/wide reflow is deterministic');
46
+ assert.ok(narrow.rows.length > wide.rows.length, 'narrow viewport wraps more rows');
47
+ for (const snapshot of result.snapshots) {
48
+ const metrics = analyzeLayout(snapshot.boxes, { width: snapshot.width + 40, height: snapshot.height + 40 });
49
+ assert.deepEqual(metrics.invalid, []);
50
+ assert.deepEqual(metrics.collisions, [], 'curated voices and measures do not overlap');
51
+ const reportedOverflow = snapshot.rows.some((row) => row.overflow > 0);
52
+ if (!reportedOverflow)
53
+ assert.deepEqual(metrics.overflow, []);
54
+ }
55
+ if (backend === 'svg') {
56
+ assert.equal(result.cssWidth, '720px');
57
+ const colors = result.colors.flatMap((item) => [item.fill, item.stroke]);
58
+ assert.ok(colors.includes('rgb(231, 237, 245)'), 'theme reaches marks');
59
+ assert.ok(colors.includes('rgb(237, 155, 64)'), 'explicit highlight survives');
60
+ assert.ok(!colors.includes('rgb(0, 0, 0)'), 'no hard-coded black marks');
61
+ }
62
+ else {
63
+ const pixels = yield page.evaluate(() => {
64
+ const canvas = document.querySelector('canvas');
65
+ const data = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height).data;
66
+ let theme = 0, highlight = 0, black = 0;
67
+ for (let i = 0; i < data.length; i += 4) {
68
+ if (data[i + 3] < 250)
69
+ continue;
70
+ if (data[i] === 231 && data[i + 1] === 237 && data[i + 2] === 245)
71
+ theme++;
72
+ if (data[i] === 237 && data[i + 1] === 155 && data[i + 2] === 64)
73
+ highlight++;
74
+ if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0)
75
+ black++;
76
+ }
77
+ return { theme, highlight, black };
78
+ });
79
+ assert.ok(pixels.theme > 100);
80
+ assert.ok(pixels.highlight > 10);
81
+ assert.equal(pixels.black, 0);
82
+ }
83
+ }));
84
+ }
85
+ }
86
+ yield t.test('theme changes preserve local styles and repeated tuplet draws', () => __awaiter(void 0, void 0, void 0, function* () {
87
+ for (const backend of ['svg', 'canvas']) {
88
+ const result = yield page.evaluate((backend) => {
89
+ const VF = VexFlow;
90
+ const host = document.getElementById('score');
91
+ host.replaceChildren();
92
+ const target = backend === 'canvas' ? host.appendChild(document.createElement('canvas')) : host;
93
+ target.id = backend === 'canvas' ? 'score-canvas' : 'score';
94
+ const f = new VF.Factory({ renderer: { elementId: target.id, width: 600, height: 300 } });
95
+ const score = f.EasyScore();
96
+ const notes = score.notes('C5/8, D5, E5, F5/q, G5, A5');
97
+ f.Tuplet({ notes: notes.slice(0, 3), options: { suffix: VF.Glyphs.metNoteQuarterUp } });
98
+ f.System({ width: 560, y: 50 })
99
+ .addStave({ voices: [score.voice(notes)] })
100
+ .addClef('treble');
101
+ const bracket = f.TextBracket({
102
+ from: notes[3],
103
+ to: notes[5],
104
+ text: '8',
105
+ options: { superscript: 'va', position: 'top' },
106
+ });
107
+ const pedal = f.PedalMarking({ notes: [notes[0], notes[5]] });
108
+ for (const element of [bracket, pedal]) {
109
+ element.renderOptions.color = '#ff0000';
110
+ element.setStyle({ fillStyle: '#00aa00', strokeStyle: '#00aa00' });
111
+ }
112
+ const frames = [];
113
+ for (const color of ['#112233', '#ddeeff', '#112233']) {
114
+ f.setStyle({ fillStyle: color, strokeStyle: color });
115
+ f.getContext().clear();
116
+ f.draw({ retain: true });
117
+ frames.push(backend === 'canvas'
118
+ ? target.toDataURL()
119
+ : [...host.querySelectorAll('path,text,rect')].map((node) => {
120
+ const style = getComputedStyle(node);
121
+ return {
122
+ text: node.textContent,
123
+ x: node.getAttribute('x'),
124
+ y: node.getAttribute('y'),
125
+ d: node.getAttribute('d'),
126
+ fill: style.fill,
127
+ stroke: style.stroke,
128
+ };
129
+ }));
130
+ }
131
+ const defaults = f.getContext().getDefaultStyle();
132
+ f.reset();
133
+ return { frames, defaults, voices: f.getVoices().length };
134
+ }, backend);
135
+ assert.deepEqual(result.frames[0], result.frames[2], `${backend}: redraw returns identical output`);
136
+ assert.notDeepEqual(result.frames[0], result.frames[1], `${backend}: changing theme changes output`);
137
+ assert.deepEqual(result.defaults, {}, 'drawing restores context defaults');
138
+ assert.equal(result.voices, 0, 'reset releases retained score');
139
+ if (backend === 'svg') {
140
+ const colors = result.frames[0].flatMap((item) => [item.fill, item.stroke]);
141
+ assert.ok(colors.includes('rgb(0, 170, 0)'), 'explicit bracket and pedal color renders');
142
+ assert.ok(!colors.includes('rgb(255, 0, 0)'), 'explicit styles override legacy colors');
143
+ }
144
+ }
145
+ }));
146
+ yield t.test('empty and oversized sheets, parser boundaries, and ownership', () => __awaiter(void 0, void 0, void 0, function* () {
147
+ const result = yield page.evaluate(() => {
148
+ const VF = VexFlow;
149
+ const f = new VF.Factory({ renderer: { elementId: 'score', width: 600, height: 400 } });
150
+ const empty = f.Sheet({ width: 50 }).format().getRows();
151
+ const score = f.EasyScore();
152
+ const measures = score.measures('C4/h[id="a|b"], E4, |, G4, C5');
153
+ const durations = measures.map((notes) => notes.map((note) => note.getDuration()));
154
+ const invalid = ['', 'C4/w || C4/w', '| C4/w', 'C4/w | rubbish'].map((line) => {
155
+ try {
156
+ score.measures(line);
157
+ return false;
158
+ }
159
+ catch (_a) {
160
+ return true;
161
+ }
162
+ });
163
+ const sheet = f.Sheet({ width: 50 });
164
+ const system = sheet.addSystem();
165
+ system.addStave({ voices: [score.voice(measures[0])] }).addClef('treble');
166
+ sheet.format();
167
+ const rows = sheet.getRows().map((_a) => {
168
+ var { systems } = _a, row = __rest(_a, ["systems"]);
169
+ return row;
170
+ });
171
+ let builds = 0;
172
+ class CountedNote extends VF.StaveNote {
173
+ buildNoteHeads() {
174
+ builds++;
175
+ return super.buildNoteHeads();
176
+ }
177
+ count() {
178
+ return this.children.length;
179
+ }
180
+ }
181
+ const note = new CountedNote({ keys: ['c/4', 'e/4'], duration: '8' });
182
+ const initialBuilds = builds;
183
+ const initialChildren = note.count();
184
+ for (let i = 0; i < 20; i++)
185
+ note.setStemDirection(i % 2 ? 1 : -1);
186
+ return { empty, durations, invalid, rows, initialBuilds, initialChildren, finalChildren: note.count() };
187
+ });
188
+ assert.deepEqual(result.empty, []);
189
+ assert.deepEqual(result.durations, [
190
+ ['h', 'h'],
191
+ ['h', 'h'],
192
+ ]);
193
+ assert.ok(result.invalid.every(Boolean));
194
+ assert.ok(result.rows[0].overflow > 0);
195
+ assert.equal(result.initialBuilds, 1);
196
+ assert.equal(result.finalChildren, result.initialChildren);
197
+ }));
198
+ }
199
+ finally {
200
+ yield browser.close();
201
+ }
202
+ }));