vexflow 5.1.1 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +8 -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 +2916 -484
  7. package/build/cjs/vexflow-debug-with-tests.js.map +1 -1
  8. package/build/cjs/vexflow-debug.js +2761 -451
  9. package/build/cjs/vexflow-debug.js.map +1 -1
  10. package/build/cjs/vexflow.js +2 -2
  11. package/build/cjs/vexflow.js.map +1 -1
  12. package/build/esm/src/accidental.js +3 -0
  13. package/build/esm/src/articulation.js +27 -14
  14. package/build/esm/src/beam.js +12 -2
  15. package/build/esm/src/chordkerning.js +98 -0
  16. package/build/esm/src/chordsymbol.js +108 -27
  17. package/build/esm/src/clef.js +3 -0
  18. package/build/esm/src/clefnote.js +5 -1
  19. package/build/esm/src/dot.js +1 -1
  20. package/build/esm/src/easyscore/composition.js +297 -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 +69 -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 +13 -2
  27. package/build/esm/src/factory.js +256 -60
  28. package/build/esm/src/formatter.js +32 -4
  29. package/build/esm/src/keysignature.js +9 -1
  30. package/build/esm/src/keysignote.js +2 -2
  31. package/build/esm/src/note.js +5 -0
  32. package/build/esm/src/parenthesis.js +1 -1
  33. package/build/esm/src/parser.js +6 -1
  34. package/build/esm/src/proportionalformatter.js +186 -0
  35. package/build/esm/src/registry.js +27 -0
  36. package/build/esm/src/sheet.js +20 -3
  37. package/build/esm/src/stave.js +9 -2
  38. package/build/esm/src/stavenote.js +12 -12
  39. package/build/esm/src/stemmablenote.js +6 -1
  40. package/build/esm/src/tickable.js +5 -0
  41. package/build/esm/src/tuplet.js +3 -2
  42. package/build/esm/src/version.js +3 -3
  43. package/build/esm/src/vexflow.js +2 -1
  44. package/build/esm/tests/beam_tests.js +35 -0
  45. package/build/esm/tests/easyscore_tests.js +40 -0
  46. package/build/esm/tests/easyscore_types.js +65 -0
  47. package/build/esm/tests/formatter_tests.js +41 -0
  48. package/build/esm/tests/node/chord-kerning-tests.mjs +173 -0
  49. package/build/esm/tests/node/easyscore-rendering-tests.mjs +332 -0
  50. package/build/esm/tests/node/easyscore-tests.mjs +953 -0
  51. package/build/esm/tests/node/proportional-spacing-tests.mjs +214 -0
  52. package/build/esm/tests/node/tool-security-tests.mjs +85 -0
  53. package/build/esm/tools/easyscore-api-audit.mjs +58 -0
  54. package/build/esm/tools/easyscore-composition.mjs +62 -0
  55. package/build/esm/tools/easyscore-example.mjs +16 -0
  56. package/build/esm/tools/easyscore-families.mjs +61 -0
  57. package/build/esm/tools/easyscore-references-example.mjs +26 -0
  58. package/build/esm/tools/easyscore-rhythm.mjs +58 -0
  59. package/build/esm/tools/easyscore-structure.mjs +88 -0
  60. package/build/esm/tools/explorer/catalog/entries.mjs +6 -0
  61. package/build/esm/tools/explorer/catalog/expression.mjs +68 -0
  62. package/build/esm/tools/explorer/catalog/helpers.mjs +29 -0
  63. package/build/esm/tools/explorer/catalog/layout.mjs +109 -0
  64. package/build/esm/tools/explorer/catalog/notes.mjs +61 -0
  65. package/build/esm/tools/explorer/catalog/staves.mjs +85 -0
  66. package/build/esm/tools/explorer/catalog/strings.mjs +25 -0
  67. package/build/esm/tools/explorer/catalog.mjs +14 -0
  68. package/build/types/src/accidental.d.ts +2 -0
  69. package/build/types/src/articulation.d.ts +6 -0
  70. package/build/types/src/beam.d.ts +2 -0
  71. package/build/types/src/chordkerning.d.ts +42 -0
  72. package/build/types/src/chordsymbol.d.ts +19 -0
  73. package/build/types/src/clef.d.ts +2 -0
  74. package/build/types/src/easyscore/composition.d.ts +107 -0
  75. package/build/types/src/easyscore/elementindex.d.ts +30 -0
  76. package/build/types/src/easyscore/elements.d.ts +156 -0
  77. package/build/types/src/easyscore/policies.d.ts +12 -0
  78. package/build/types/src/easyscore/rhythm.d.ts +9 -0
  79. package/build/types/src/easyscore.d.ts +153 -11
  80. package/build/types/src/element.d.ts +5 -1
  81. package/build/types/src/factory.d.ts +91 -8
  82. package/build/types/src/formatter.d.ts +7 -1
  83. package/build/types/src/keysignature.d.ts +3 -0
  84. package/build/types/src/keysignote.d.ts +1 -1
  85. package/build/types/src/note.d.ts +2 -0
  86. package/build/types/src/parser.d.ts +5 -0
  87. package/build/types/src/proportionalformatter.d.ts +30 -0
  88. package/build/types/src/registry.d.ts +4 -0
  89. package/build/types/src/stave.d.ts +2 -0
  90. package/build/types/src/stavenote.d.ts +1 -1
  91. package/build/types/src/stemmablenote.d.ts +6 -1
  92. package/build/types/src/tickable.d.ts +2 -0
  93. package/build/types/src/vexflow.d.ts +2 -1
  94. package/changelog/CHANGELOG.md +57 -0
  95. package/package.json +19 -7
  96. package/tests/flow.html +10 -3
@@ -0,0 +1,214 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import { createCanvas, registerFont } from 'canvas';
4
+ import { JSDOM } from 'jsdom';
5
+ const VF = await import(new URL('../../build/esm/entry/vexflow-core.js', import.meta.url));
6
+ for (const [family, file] of [
7
+ ['Bravura', 'bravura/bravura'],
8
+ ['Academico', 'academico/academico'],
9
+ ]) {
10
+ registerFont(new URL(`../../node_modules/@vexflow-fonts/${file}.otf`, import.meta.url).pathname, { family });
11
+ }
12
+ VF.Element.setTextMeasurementCanvas(createCanvas(1, 1));
13
+ const documentFixture = new JSDOM('<div></div>');
14
+ globalThis.document = documentFixture.window.document;
15
+ test.after(() => {
16
+ delete globalThis.document;
17
+ documentFixture.window.close();
18
+ });
19
+ const { Formatter, Voice, Stave, StaveNote, Tuplet, ClefNote, Accidental, Dot, GraceNote, GraceNoteGroup } = VF;
20
+ const rhythm = ['16', '16', '16', '16', '8', '8', 'q', 'q'];
21
+ const close = (actual, expected) => assert.ok(Math.abs(actual - expected) < 1e-7, `${actual} ≈ ${expected}`);
22
+ function voice(durations = rhythm, meter = '4/4', stave = new Stave(10, 50, 900)) {
23
+ const notes = durations.map((duration) => new StaveNote({ keys: ['c/5'], duration }).setStave(stave));
24
+ VF.Beam.generateBeams(notes);
25
+ return new Voice(meter).setMode(Voice.Mode.SOFT).addTickables(notes).setMode(Voice.Mode.STRICT);
26
+ }
27
+ const proportional = (pixelsPerQuarter) => new Formatter({ spacing: { mode: 'proportional', pixelsPerQuarter } });
28
+ const positions = (voice) => voice
29
+ .getTickables()
30
+ .filter((n) => !n.shouldIgnoreTicks())
31
+ .map((n) => n.getTickContext().getX());
32
+ function onsets(v, expected) {
33
+ const x = positions(v);
34
+ expected.forEach((offset, i) => close(x[i] - x[0], offset));
35
+ }
36
+ test('mixed durations retain exact scale, final duration, trailing space, and tuning invariance', () => {
37
+ const v = voice();
38
+ const f = proportional(100).joinVoices([v]).format([v], 800);
39
+ onsets(v, [0, 25, 50, 75, 100, 150, 200, 300]);
40
+ close(f.getMinTotalWidth(), 404);
41
+ const before = positions(v);
42
+ for (let i = 0; i < 10; i++)
43
+ f.tune();
44
+ assert.deepEqual(positions(v), before);
45
+ f.format([v], 500);
46
+ assert.deepEqual(positions(v), before);
47
+ });
48
+ test('omitted scale fits the full measure; omitted width uses measured minimum', () => {
49
+ const v = voice();
50
+ const f = proportional().joinVoices([v]).format([v], 504);
51
+ onsets(v, [0, 31.25, 62.5, 93.75, 125, 187.5, 250, 375]);
52
+ const minimum = f.preCalculateMinTotalWidth([v]);
53
+ f.format([v], minimum);
54
+ const expected = positions(v);
55
+ f.format([v]);
56
+ assert.deepEqual(positions(v), expected);
57
+ });
58
+ test('7/8 and dotted rhythms retain duration ratios', () => {
59
+ const v = voice(Array(7).fill('8'), '7/8');
60
+ proportional(100).joinVoices([v]).format([v]);
61
+ onsets(v, [0, 50, 100, 150, 200, 250, 300]);
62
+ const dotted = voice(['qd', '8', 'h']);
63
+ Dot.buildAndAttach([dotted.getTickables()[0]]);
64
+ proportional(100).joinVoices([dotted]).format([dotted]);
65
+ onsets(dotted, [0, 150, 200]);
66
+ });
67
+ test('shared onsets align in multiple voices on the same stave', () => {
68
+ const stave = new Stave(10, 50, 900);
69
+ const upper = voice(rhythm, '4/4', stave);
70
+ const lower = voice(['q', 'q', 'q', 'q'], '4/4', stave);
71
+ lower.getTickables().forEach((note) => note.setStemDirection(-1));
72
+ const f = proportional(140).joinVoices([upper, lower]).format([upper, lower]);
73
+ [0, 4, 6, 7].forEach((index, beat) => close(positions(upper)[index], positions(lower)[beat]));
74
+ assert.ok(f.getMinTotalWidth() >= 560);
75
+ });
76
+ test('triplets and septuplets on separate staves share rational endpoints without false collisions', () => {
77
+ const first = voice([...Array(3).fill('8'), 'q', 'h']);
78
+ const second = voice([...Array(7).fill('8'), 'h']);
79
+ new Tuplet(first.getTickables().slice(0, 3), { numNotes: 3, notesOccupied: 2 });
80
+ new Tuplet(second.getTickables().slice(0, 7), { numNotes: 7, notesOccupied: 4 });
81
+ const f = proportional(140).joinVoices([first, second]).format([first, second]);
82
+ onsets(first, [0, 140 / 3, 280 / 3, 140, 280]);
83
+ onsets(second, [...Array.from({ length: 7 }, (_, i) => (i * 280) / 7), 280]);
84
+ close(positions(first)[4], positions(second)[7]);
85
+ assert.equal(f.getTickContexts().resolutionMultiplier % 21, 0);
86
+ });
87
+ test('inline clefs and trailing barlines occupy space without consuming time', () => {
88
+ const stave = new Stave(10, 50, 900);
89
+ const notes = voice(['q', 'q', 'q', 'q'], '4/4', stave).getTickables();
90
+ const clefs = [new ClefNote('bass', 'small'), new ClefNote('treble', 'small')].map((c) => c.setStave(stave));
91
+ const end = new VF.BarNote().setStave(stave);
92
+ const v = new Voice('4/4').addTickables([notes[0], ...clefs, ...notes.slice(1), end]);
93
+ const f = proportional(130).joinVoices([v]).format([v]);
94
+ onsets(v, [0, 130, 260, 390]);
95
+ assert.ok(clefs[0].getAbsoluteX() < clefs[1].getAbsoluteX());
96
+ assert.ok(clefs[1].getAbsoluteX() + clefs[1].getWidth() <= notes[1].getAbsoluteX());
97
+ close(end.getTickContext().getX() - positions(v)[0], 520 - 1 - end.getTickContext().getMetrics().notePx);
98
+ const before = v.getTickables().map((n) => n.getAbsoluteX());
99
+ f.format([v]);
100
+ assert.deepEqual(v.getTickables().map((n) => n.getAbsoluteX()), before);
101
+ });
102
+ test('grace groups and accidentals reserve space before the first rhythmic anchor', () => {
103
+ const v = voice(['q', 'q', 'q', 'q']);
104
+ const first = v.getTickables()[0];
105
+ first.addModifier(new Accidental('##'), 0);
106
+ first.addModifier(new GraceNoteGroup([new GraceNote({ keys: ['d/5'], duration: '8' })]), 0);
107
+ const f = proportional(150).joinVoices([v]).format([v]);
108
+ onsets(v, [0, 150, 300, 450]);
109
+ assert.ok(positions(v)[0] > 20);
110
+ assert.ok(f.getMinTotalWidth() > 620);
111
+ });
112
+ test('crowded chords and insufficient stave width fail with actionable dimensions', () => {
113
+ const v = voice();
114
+ v.getTickables()[1].addModifier(new Accidental('##'), 0);
115
+ assert.throws(() => proportional(10).joinVoices([v]).format([v]), /InsufficientProportionalSpace.*px\/quarter.*px width/);
116
+ const f = proportional(200).joinVoices([v]);
117
+ assert.throws(() => f.format([v], 100), /InsufficientProportionalSpace/);
118
+ f.format([v], 1000);
119
+ onsets(v, [0, 50, 100, 150, 200, 300, 400, 600]);
120
+ });
121
+ test('partial voices keep the declared span and SOFT overflow extends it', () => {
122
+ const partial = new Voice('4/4').setMode(Voice.Mode.SOFT).addTickables(voice(['q'], '1/4').getTickables());
123
+ const f = proportional(100).joinVoices([partial]).format([partial]);
124
+ close(f.getMinTotalWidth(), 404);
125
+ const overflow = new Voice('4/4')
126
+ .setMode(Voice.Mode.SOFT)
127
+ .addTickables(voice(Array(5).fill('q'), '5/4').getTickables());
128
+ const g = proportional(100).joinVoices([overflow]).format([overflow]);
129
+ close(g.getMinTotalWidth(), 504);
130
+ });
131
+ test('invalid scales and widths are rejected, and default spacing remains available', () => {
132
+ for (const scale of [0, -1, NaN, Infinity]) {
133
+ const v = voice();
134
+ assert.throws(() => proportional(scale).joinVoices([v]).format([v]), /pixelsPerQuarter/);
135
+ }
136
+ for (const width of [-1, Infinity, NaN]) {
137
+ const v = voice();
138
+ assert.throws(() => proportional(100).joinVoices([v]).format([v], width), /Width must/);
139
+ }
140
+ const v = voice();
141
+ new Formatter().joinVoices([v]).format([v], 500);
142
+ assert.notEqual(positions(v)[4] - positions(v)[0], positions(v)[6] - positions(v)[4]);
143
+ });
144
+ test('centered whole-measure rests retain centering', () => {
145
+ const v = voice(['wr']);
146
+ v.getTickables()[0].setCenterAlignment(true);
147
+ proportional(100).joinVoices([v]).format([v], 800);
148
+ close(v.getTickables()[0].getCenterXShift(), 200);
149
+ });
150
+ test('System autoWidth and tuning preserve fixed spacing on Canvas and SVG', () => {
151
+ const dom = new JSDOM('<div id="score"></div>');
152
+ const oldDocument = globalThis.document;
153
+ globalThis.document = dom.window.document;
154
+ try {
155
+ for (const backend of [VF.Renderer.Backends.CANVAS, VF.Renderer.Backends.SVG]) {
156
+ const host = document.getElementById('score');
157
+ host.replaceChildren();
158
+ const target = backend === VF.Renderer.Backends.CANVAS ? host.appendChild(document.createElement('canvas')) : host;
159
+ target.id = 'target';
160
+ const factory = new VF.Factory({ renderer: { elementId: target, backend, width: 900, height: 300 } });
161
+ const notes = factory.EasyScore().notes('C5/16, D5, E5, F5, G5/8, A5, B5/q, C6');
162
+ const v = factory.Voice().addTickables(notes);
163
+ const system = factory.System({
164
+ details: { spacing: { mode: 'proportional', pixelsPerQuarter: 120 } },
165
+ formatIterations: 5,
166
+ });
167
+ system.addStave({ voices: [v] }).addClef('treble');
168
+ factory.draw({ retain: true });
169
+ onsets(v, [0, 30, 60, 90, 120, 180, 240, 360]);
170
+ assert.ok(system.getWidth() > 480);
171
+ const before = positions(v);
172
+ factory.draw({ retain: true });
173
+ assert.deepEqual(positions(v), before);
174
+ target.id = 'score';
175
+ }
176
+ }
177
+ finally {
178
+ globalThis.document = oldDocument;
179
+ dom.window.close();
180
+ }
181
+ });
182
+ test('dense chord bounds remain separated at the automatic minimum width', () => {
183
+ const stave = new Stave(10, 50, 900);
184
+ const notes = Array.from({ length: 8 }, () => new StaveNote({ keys: ['c/5', 'd/5', 'e/5'], duration: '8' }).setStave(stave));
185
+ notes.forEach((note) => note.addModifier(new Accidental('##'), 0).addModifier(new Accidental('b'), 1));
186
+ VF.Beam.generateBeams(notes);
187
+ const v = new Voice('4/4').addTickables(notes);
188
+ const f = proportional().joinVoices([v]).format([v]);
189
+ for (let i = 1; i < notes.length; i++) {
190
+ const previous = notes[i - 1].getMetrics();
191
+ const current = notes[i].getMetrics();
192
+ const right = notes[i - 1].getTickContext().getX() + previous.notePx + previous.modRightPx + previous.rightDisplacedHeadPx;
193
+ const left = notes[i].getTickContext().getX() - current.modLeftPx - current.leftDisplacedHeadPx;
194
+ assert.ok(left - right >= 2 - 1e-7);
195
+ }
196
+ const scale = positions(v)[1] - positions(v)[0];
197
+ onsets(v, notes.map((_, i) => scale * i));
198
+ assert.ok(Number.isFinite(f.getMinTotalWidth()));
199
+ });
200
+ test('staves supplied during format also apply to inline prefixes', () => {
201
+ const notes = ['q', 'q', 'q', 'q'].map((duration) => new StaveNote({ keys: ['c/5'], duration }));
202
+ const clef = new ClefNote('bass', 'small');
203
+ const v = new Voice('4/4').addTickables([clef, ...notes]);
204
+ const stave = new Stave(10, 50, 900);
205
+ proportional(120).joinVoices([v]).format([v], 600, { stave });
206
+ onsets(v, [0, 120, 240, 360]);
207
+ assert.ok(clef.getAbsoluteX() + clef.getWidth() <= notes[0].getAbsoluteX());
208
+ });
209
+ test('unsupported numeric ranges fail before producing infinite coordinates', () => {
210
+ assert.throws(() => proportional().preCalculateMinTotalWidth([]), /No voices/);
211
+ assert.throws(() => proportional().format([]), /No voices/);
212
+ const v = voice();
213
+ assert.throws(() => proportional(Number.MAX_VALUE).joinVoices([v]).format([v]), /pixel range/);
214
+ });
@@ -0,0 +1,85 @@
1
+ import assert from 'node:assert/strict';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, 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
+ import { JSDOM } from 'jsdom';
9
+ const root = fileURLToPath(new URL('../../', import.meta.url));
10
+ test('release downloads reject paths, flags, and shell fragments before prompting', () => {
11
+ for (const version of ['../outside', '--help', '4.0.0;echo injected', '4.0.0$(echo injected)', '4.0.0\n', 'latest']) {
12
+ const result = spawnSync(process.execPath, ['tools/get_releases.mjs', version], {
13
+ cwd: root,
14
+ encoding: 'utf8',
15
+ timeout: 3000,
16
+ });
17
+ assert.ifError(result.error);
18
+ assert.notEqual(result.status, 0);
19
+ assert.match(result.stderr, /Invalid release version/);
20
+ assert.doesNotMatch(result.stdout, /Press any key/);
21
+ }
22
+ });
23
+ test('release download commands preserve spaces and shell punctuation in checkout paths', () => {
24
+ const directory = realpathSync(mkdtempSync(join(tmpdir(), "release tools '$literal' ")));
25
+ try {
26
+ mkdirSync(join(directory, 'tools'));
27
+ mkdirSync(join(directory, 'bin'));
28
+ symlinkSync(join(root, 'node_modules'), join(directory, 'node_modules'), 'dir');
29
+ copyFileSync(join(root, 'tools/get_releases.mjs'), join(directory, 'tools/get_releases.mjs'));
30
+ const command = `#!${process.execPath}
31
+ const fs = require('node:fs');
32
+ const path = require('node:path');
33
+ const name = path.basename(process.argv[1]);
34
+ const args = process.argv.slice(2);
35
+ fs.appendFileSync(process.env.COMMAND_LOG, JSON.stringify({name,args}) + '\\n');
36
+ if (name === 'tar') {
37
+ const build = path.join(args[args.indexOf('-C') + 1], 'package', 'build');
38
+ fs.mkdirSync(build, {recursive:true});
39
+ fs.writeFileSync(path.join(build, 'fixture.js'), 'release fixture');
40
+ }
41
+ `;
42
+ for (const name of ['git', 'npm', 'tar'])
43
+ writeFileSync(join(directory, 'bin', name), command, { mode: 0o755 });
44
+ writeFileSync(join(directory, 'stdin.mjs'), 'process.stdin.setRawMode = () => {};');
45
+ const log = join(directory, 'commands.jsonl');
46
+ const result = spawnSync(process.execPath, ['--import', './stdin.mjs', 'tools/get_releases.mjs', '5.0.0-beta.1'], {
47
+ cwd: directory,
48
+ env: Object.assign(Object.assign({}, process.env), { PATH: `${join(directory, 'bin')}:${process.env.PATH}`, COMMAND_LOG: log }),
49
+ input: 'y',
50
+ encoding: 'utf8',
51
+ timeout: 5000,
52
+ });
53
+ assert.ifError(result.error);
54
+ assert.equal(result.status, 0, result.stderr || result.stdout);
55
+ assert.equal(readFileSync(join(directory, 'releases/5.0.0-beta.1/fixture.js'), 'utf8'), 'release fixture');
56
+ const calls = readFileSync(log, 'utf8').trim().split('\n').map(JSON.parse);
57
+ const pack = calls.find(({ name }) => name === 'npm').args;
58
+ assert.equal(pack[pack.indexOf('--pack-destination') + 1], join(directory, 'releases/5.0.0-beta.1-delete-me-later'));
59
+ assert.ok(pack.includes('--ignore-scripts'));
60
+ }
61
+ finally {
62
+ rmSync(directory, { recursive: true, force: true });
63
+ }
64
+ });
65
+ test('font metadata stays literal text while labels retain their formatting', () => {
66
+ const html = readFileSync(join(root, 'demos/opentype/load.html'), 'utf8');
67
+ const dom = new JSDOM(html, { runScripts: 'outside-only' });
68
+ try {
69
+ const { window } = dom;
70
+ window.console.log = () => { };
71
+ const name = '<img src=x onerror="globalThis.injected = true"> & Test';
72
+ window.opentype = { parse: () => ({ names: { fontFamily: { en: name } }, glyphs: { length: 12 } }) };
73
+ window.eval(window.document.querySelector('script:not([src])').textContent);
74
+ assert.equal(window.parseFont(new Uint8Array([0]), 'music'), name);
75
+ const target = window.document.getElementById('musicFontInfo');
76
+ assert.equal(target.querySelector('img'), null);
77
+ assert.equal(window.injected, undefined);
78
+ assert.ok(target.textContent.includes(name));
79
+ assert.deepEqual([...target.querySelectorAll('b')].map((node) => node.textContent), ['Font Family Name:', 'Num Glyphs:']);
80
+ assert.equal(target.querySelectorAll('br').length, 2);
81
+ }
82
+ finally {
83
+ dom.window.close();
84
+ }
85
+ });
@@ -0,0 +1,58 @@
1
+ import assert from 'node:assert/strict';
2
+ import { readFileSync, writeFileSync } from 'node:fs';
3
+ import { fileURLToPath, pathToFileURL } from 'node:url';
4
+ import ts from 'typescript';
5
+ const root = new URL('../', import.meta.url);
6
+ const snapshot = new URL('docs/easyscore-native-api.json', root);
7
+ const text = (node) => node === null || node === void 0 ? void 0 : node.getText().replace(/\s+/g, ' ').trim();
8
+ const has = (node, kind) => { var _a; return (_a = node.modifiers) === null || _a === void 0 ? void 0 : _a.some((modifier) => modifier.kind === kind); };
9
+ export function nativeSurface() {
10
+ const index = readFileSync(new URL('src/index.ts', root), 'utf8');
11
+ const modules = [...index.matchAll(/^export \* from '\.\/([^']+)';/gm)].map((match) => match[1]);
12
+ modules.push('easyscore/elements', 'easyscore/composition', 'easyscore/rhythm');
13
+ return Object.fromEntries(modules.map((module) => {
14
+ var _a, _b, _c;
15
+ const path = new URL(`src/${module}.ts`, root);
16
+ const file = ts.createSourceFile(fileURLToPath(path), readFileSync(path, 'utf8'), ts.ScriptTarget.Latest, true);
17
+ const declarations = {};
18
+ for (const node of file.statements) {
19
+ if (!has(node, ts.SyntaxKind.ExportKeyword))
20
+ continue;
21
+ const name = text(node.name);
22
+ if (ts.isInterfaceDeclaration(node)) {
23
+ declarations[name] = { extends: (_b = (_a = node.heritageClauses) === null || _a === void 0 ? void 0 : _a.map(text)) !== null && _b !== void 0 ? _b : [], fields: node.members.map(text) };
24
+ }
25
+ else if (ts.isTypeAliasDeclaration(node) || ts.isEnumDeclaration(node)) {
26
+ declarations[name] = text(node);
27
+ }
28
+ else if (ts.isClassDeclaration(node)) {
29
+ declarations[name] = node.members
30
+ .filter((member) => !has(member, ts.SyntaxKind.PrivateKeyword) && !has(member, ts.SyntaxKind.ProtectedKeyword))
31
+ .map((member) => {
32
+ var _a;
33
+ const name = (_a = text(member.name)) !== null && _a !== void 0 ? _a : 'constructor';
34
+ if (member.parameters)
35
+ return `${name}(${member.parameters.map(text).join(', ')})${member.type ? ': ' + text(member.type) : ''}`;
36
+ return `${name}${member.type ? ': ' + text(member.type) : ''}`;
37
+ });
38
+ }
39
+ else if (ts.isFunctionDeclaration(node)) {
40
+ declarations[name] = `(${node.parameters.map(text).join(', ')})${node.type ? ': ' + text(node.type) : ''}`;
41
+ }
42
+ else if (ts.isVariableStatement(node)) {
43
+ for (const declaration of node.declarationList.declarations)
44
+ declarations[text(declaration.name)] = (_c = text(declaration.type)) !== null && _c !== void 0 ? _c : 'inferred';
45
+ }
46
+ }
47
+ return [module, declarations];
48
+ }));
49
+ }
50
+ export function checkNativeSurface() {
51
+ assert.deepEqual(nativeSurface(), JSON.parse(readFileSync(snapshot, 'utf8')), 'Native API changed. Review EasyScore coverage, then run node tools/easyscore-api-audit.mjs --update.');
52
+ }
53
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
54
+ if (process.argv.includes('--update'))
55
+ writeFileSync(snapshot, JSON.stringify(nativeSurface(), null, 2) + '\n');
56
+ else
57
+ checkNativeSurface();
58
+ }
@@ -0,0 +1,62 @@
1
+ export function renderEasyScoreComposition(VF, renderer, spacing = 'engraving', ink = '#24312c') {
2
+ const score = VF.EasyScore.create({ renderer });
3
+ score.setStyle({ fillStyle: ink, strokeStyle: ink });
4
+ const result = score.compose({
5
+ sheet: { width: renderer.width - 40, x: 20, y: 20, rowGap: 55 },
6
+ system: {
7
+ spaceBetweenStaves: 10,
8
+ details: spacing === 'proportional' ? { spacing: { mode: 'proportional', pixelsPerQuarter: 70 } } : {},
9
+ },
10
+ accidentals: 'key-aware',
11
+ signatures: 'every-measure',
12
+ staves: [
13
+ {
14
+ id: 'right',
15
+ key: 'G',
16
+ measures: [
17
+ { span: '1/4', voices: [{ notes: 'D5/q' }] },
18
+ {
19
+ time: '2/4',
20
+ voices: [
21
+ {
22
+ notes: 'F#5/8[id="start"], E5, D5, C5, B4, A4[id="end"]',
23
+ stem: 'up',
24
+ tuplets: [
25
+ { start: 0, count: 3 },
26
+ { start: 3, count: 3 },
27
+ ],
28
+ autoBeam: true,
29
+ },
30
+ { notes: 'G4/h', stem: 'down' },
31
+ ],
32
+ },
33
+ { time: '3/4', voices: [{ notes: 'F#5/q, F5, F5' }] },
34
+ { time: '4/4', voices: [{ notes: ['F#5/h', { change: { key: 'C', clef: 'bass' } }, 'G3/q, C4'] }] },
35
+ ],
36
+ },
37
+ {
38
+ id: 'left',
39
+ clef: 'bass',
40
+ key: 'G',
41
+ measures: [
42
+ { span: '1/4', voices: [{ notes: 'G2/q' }] },
43
+ { time: '2/4', voices: [{ notes: '(G2 D3)/h' }] },
44
+ { time: '3/4', voices: [{ notes: 'G2/h.' }] },
45
+ { time: '4/4', voices: [{ notes: 'C3/w' }] },
46
+ ],
47
+ },
48
+ ],
49
+ spans: [{ kind: 'curve', from: 'start', to: 'end' }],
50
+ });
51
+ result.systems.forEach((system) => system.addConnector('brace'));
52
+ const redraw = (width) => {
53
+ result.sheet.setWidth(width - 40).format();
54
+ const context = score.factory.getContext();
55
+ context.resize(width, result.sheet.getHeight() + 35);
56
+ context.clear();
57
+ score.draw({ retain: true });
58
+ return result.sheet.getRows().map((row) => ({ width: row.width, height: row.height, overflow: row.overflow }));
59
+ };
60
+ redraw(renderer.width);
61
+ return { score, result, redraw };
62
+ }
@@ -0,0 +1,16 @@
1
+ export function createEasyScoreExample(VF, renderer, ink = '#24312c') {
2
+ const score = VF.EasyScore.create({ renderer });
3
+ score.setStyle({ fillStyle: ink, strokeStyle: ink });
4
+ const notes = score.notes('(C4 E4 G4)/h, (C4 F4 A4)');
5
+ const annotation = score.make.annotation({ text: 'dolce', vJustify: 'top' });
6
+ score.attach(notes[0], annotation, 0);
7
+ const tie = score.make.tie({ from: notes[0], to: notes[1], firstIndexes: [0], lastIndexes: [0] });
8
+ const voice = score.voice(notes, { time: '4/4', mode: 'strict' });
9
+ const system = score.system({ x: 20, y: 70, width: renderer.width - 40 });
10
+ system
11
+ .addStave({ voices: [voice] })
12
+ .addClef('treble')
13
+ .addTimeSignature('4/4');
14
+ score.draw({ retain: true });
15
+ return { score, notes, annotation, tie, voice, system };
16
+ }
@@ -0,0 +1,61 @@
1
+ export function renderEasyScoreFamilies(VF, renderer, kind = 'modifiers', ink = '#24312c') {
2
+ const score = VF.EasyScore.create({ renderer });
3
+ score.setStyle({ fillStyle: ink, strokeStyle: ink });
4
+ const notes = (['percussion', 'sequence'].includes(kind) ? [] : ['c/5', 'd/5', 'e/5', 'f/5']).map((key) => score.make.note({ keys: [key], duration: 'q' }));
5
+ const marks = [];
6
+ const attach = (index, modifier) => {
7
+ marks.push(modifier);
8
+ score.attach(notes[index], modifier);
9
+ };
10
+ let clef = 'treble';
11
+ if (kind === 'modifiers') {
12
+ attach(0, score.make.articulation({ type: 'fermata' }));
13
+ attach(1, score.make.ornament('tr'));
14
+ attach(2, score.make.tremolo(3));
15
+ attach(3, score.make.vibrato().setVibratoWidth(24));
16
+ }
17
+ else if (kind === 'accidentals') {
18
+ attach(0, score.make.accidental({ type: '#' }).setAsCautionary());
19
+ attach(1, score.make.accidental({ type: '++' }));
20
+ attach(2, score.make.parenthesis(VF.Modifier.Position.LEFT));
21
+ attach(2, score.make.parenthesis(VF.Modifier.Position.RIGHT));
22
+ attach(3, score.make.dot());
23
+ }
24
+ else if (kind === 'text') {
25
+ attach(0, score.make.annotation({ text: 'dolce', vJustify: 'top' }));
26
+ attach(1, score.make.chordSymbol().setKerning('auto').addText('Dm7'));
27
+ attach(2, score.make.fingering({ number: '2', position: 'left' }));
28
+ attach(3, score.make.stringNumber({ number: '3', position: 'above' }));
29
+ }
30
+ else if (kind === 'grace') {
31
+ const grace = ['b/4', 'c/5'].map((key) => score.make.graceNote({ keys: [key], duration: '16', slash: true }));
32
+ attach(0, score.make.graceNoteGroup({ notes: grace, slur: true }).beamNotes());
33
+ attach(2, score.make.noteSubGroup({ notes: [score.make.graceNote({ keys: ['d/5'], duration: '8' })] }));
34
+ attach(3, score.make.stroke(VF.Stroke.Type.ROLL_UP));
35
+ }
36
+ else if (kind === 'sequence') {
37
+ notes.push(...score.sequence([
38
+ 'C5/q',
39
+ score.make.ghostNote('q'),
40
+ score.make.textNote({ text: 'rit.', duration: 'q', smooth: true }),
41
+ { keys: ['f/5'], duration: 'q' },
42
+ ]));
43
+ }
44
+ else if (kind === 'percussion') {
45
+ clef = 'percussion';
46
+ notes.splice(0, notes.length, ...score.sequence([
47
+ { keys: ['g/5/x'], duration: 'q', clef, stemDirection: VF.Stem.UP },
48
+ { keys: ['c/5'], duration: 'q', clef, stemDirection: VF.Stem.DOWN },
49
+ { keys: ['g/5/x', 'c/5'], duration: 'q', clef, stemDirection: VF.Stem.UP },
50
+ { keys: ['b/4'], duration: 'q', type: 'r', clef, line: 2 },
51
+ ]));
52
+ }
53
+ const voice = score.voice(notes, { time: '4/4' });
54
+ const system = score.system({ x: 20, y: 65, width: renderer.width - 40 });
55
+ system
56
+ .addStave({ voices: [voice] })
57
+ .addClef(clef)
58
+ .addTimeSignature('4/4');
59
+ score.draw({ retain: true });
60
+ return { score, notes, marks, voice, system };
61
+ }
@@ -0,0 +1,26 @@
1
+ export function createEasyScoreReferencesExample(VF, renderer, ink = '#24312c') {
2
+ const score = VF.EasyScore.create({ renderer });
3
+ score.setStyle({ fillStyle: ink, strokeStyle: ink });
4
+ const notes = score.notes('C4/h[id="start"], C4/q[id="end"]');
5
+ const native = score.adopt(new VF.StaveNote({ keys: ['e/4'], duration: 'q', autoStem: true }), 'note');
6
+ native.setAttribute('id', 'native');
7
+ notes.push(native);
8
+ class PhraseLabel extends VF.Annotation {
9
+ constructor() {
10
+ super('dolce');
11
+ this.setVerticalJustification(VF.Annotation.VerticalJustify.TOP);
12
+ }
13
+ }
14
+ const label = score.adopt(new PhraseLabel(), 'modifier');
15
+ score.attach(score.getNote('start'), label);
16
+ const tie = score.make.tie({ from: score.getNote('start'), to: score.getNote('end') });
17
+ const curve = score.adopt(new VF.Curve(score.getNote('end'), native), 'drawable');
18
+ const voice = score.voice(notes, { time: '4/4' });
19
+ const system = score.system({ x: 20, y: 70, width: renderer.width - 40 });
20
+ system
21
+ .addStave({ voices: [voice] })
22
+ .addClef('treble')
23
+ .addTimeSignature('4/4');
24
+ score.draw({ retain: true });
25
+ return { score, notes, label, tie, curve, voice, system };
26
+ }
@@ -0,0 +1,58 @@
1
+ export function renderEasyScoreRhythm(VF, renderer, kind = 'odd-meter', ink = '#24312c') {
2
+ const score = VF.EasyScore.create({ renderer });
3
+ score.setStyle({ fillStyle: ink, strokeStyle: ink });
4
+ const marks = [];
5
+ let notes, voices, time = '4/4';
6
+ if (kind === 'odd-meter') {
7
+ time = '7/8';
8
+ score.set({ time });
9
+ notes = score.notes('C5/8, D5, E5, F5, G5, A5, B5', { stem: 'up' });
10
+ marks.push(...score.autoBeam(notes, { groups: [new VF.Fraction(2, 8), new VF.Fraction(2, 8), new VF.Fraction(3, 8)] }));
11
+ const bass = score.notes('C4/h, G3/q.', { stem: 'down' });
12
+ voices = [score.voice(notes), score.voice(bass)];
13
+ }
14
+ else if (kind === 'tuplets') {
15
+ time = '2/4';
16
+ notes = score.notes('C5/8, D5, E5, F5, G5, A5');
17
+ marks.push(score.make.tuplet({ notes: notes.slice(0, 3), options: { numNotes: 3, notesOccupied: 2 } }));
18
+ marks.push(score.make.tuplet({ notes, options: { numNotes: 5, notesOccupied: 4, ratioed: true } }));
19
+ marks.push(...score.autoBeam(notes, { groups: [new VF.Fraction(1, 4)] }));
20
+ voices = [score.voice(notes, { time })];
21
+ }
22
+ else if (kind === 'dynamics') {
23
+ notes = [
24
+ score.make.textDynamics({ text: 'p', duration: 'q', line: 2 }),
25
+ score.make.crescendo({ duration: 'h', line: 2 }).setHeight(8),
26
+ score.make.textDynamics({ text: 'ff', duration: 'q', line: 2 }),
27
+ ];
28
+ voices = [score.voice(notes)];
29
+ }
30
+ else {
31
+ notes = score.notes(kind === 'ties' ? 'C5/q, C5, E5, G5' : 'C5/q, D5, E5, G5');
32
+ const [from, , , to] = notes;
33
+ if (kind === 'ties')
34
+ marks.push(score.make.tie({ from: notes[0], to: notes[1] }));
35
+ if (kind === 'curves')
36
+ marks.push(score.make.curve({ from, to, options: { thickness: 2 } }));
37
+ if (kind === 'hairpins')
38
+ marks.push(score.make.hairpin({ from, to, type: 1, options: { height: 10 } }));
39
+ if (kind === 'lines')
40
+ marks.push(score.make.line({ from, to, firstIndexes: [0], lastIndexes: [0], options: { text: 'gliss.' } }));
41
+ if (kind === 'brackets') {
42
+ marks.push(score.make.textBracket({ from, to, text: '8', options: { superscript: 'va', position: 'top', line: 1 } }));
43
+ marks.push(score.make.vibratoBracket({ from, to, options: { line: 3 } }));
44
+ }
45
+ if (kind === 'pedal')
46
+ marks.push(score.make.pedalMarking({ notes: [from, to], options: { style: 'mixed' } }));
47
+ if (kind === 'partial-spans') {
48
+ marks.push(score.make.tie({ to: from }), score.make.tie({ from: to }));
49
+ marks.push(score.make.curve({ from: to }));
50
+ marks.push(score.make.vibratoBracket({ from: null, to: from, options: { line: 2 } }));
51
+ }
52
+ voices = [score.voice(notes)];
53
+ }
54
+ const system = score.system({ x: 20, y: 75, width: renderer.width - 40 });
55
+ system.addStave({ voices }).addClef('treble').addTimeSignature(time);
56
+ score.draw({ retain: true });
57
+ return { score, notes, marks, voices, system };
58
+ }