vexflow 5.3.0 → 5.4.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 (115) hide show
  1. package/README.md +2 -0
  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 +4189 -772
  7. package/build/cjs/vexflow-debug-with-tests.js.map +1 -1
  8. package/build/cjs/vexflow-debug.js +4323 -906
  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/alternatingtremolo.js +68 -0
  13. package/build/esm/src/annotation.js +19 -3
  14. package/build/esm/src/articulation.js +5 -1
  15. package/build/esm/src/beam.js +13 -0
  16. package/build/esm/src/bend.js +57 -6
  17. package/build/esm/src/clef.js +3 -0
  18. package/build/esm/src/continuouslayout.js +681 -0
  19. package/build/esm/src/continuousspan.js +159 -0
  20. package/build/esm/src/curve.js +21 -2
  21. package/build/esm/src/easyscore/composition.js +13 -2
  22. package/build/esm/src/easyscore/policies.js +6 -3
  23. package/build/esm/src/engravinggeometry.js +8 -1
  24. package/build/esm/src/factory.js +16 -4
  25. package/build/esm/src/font.js +9 -1
  26. package/build/esm/src/fretdiagram.js +77 -0
  27. package/build/esm/src/guitargesture.js +33 -0
  28. package/build/esm/src/guitarmodifiers.js +26 -0
  29. package/build/esm/src/index.js +8 -0
  30. package/build/esm/src/instrumentprofile.js +123 -0
  31. package/build/esm/src/keysignature.js +23 -1
  32. package/build/esm/src/notationspelling.js +73 -0
  33. package/build/esm/src/note.js +3 -0
  34. package/build/esm/src/ornament.js +5 -0
  35. package/build/esm/src/pagebreaks.js +58 -0
  36. package/build/esm/src/pedalmarking.js +39 -17
  37. package/build/esm/src/phraselayout.js +503 -0
  38. package/build/esm/src/phraseribbon.js +28 -0
  39. package/build/esm/src/publication.js +402 -0
  40. package/build/esm/src/publicationview.js +114 -0
  41. package/build/esm/src/scorenavigation.js +172 -0
  42. package/build/esm/src/sheet.js +14 -2
  43. package/build/esm/src/stave.js +33 -16
  44. package/build/esm/src/stavebarline.js +5 -7
  45. package/build/esm/src/staveconnector.js +1 -0
  46. package/build/esm/src/stavehairpin.js +53 -27
  47. package/build/esm/src/stavenote.js +6 -1
  48. package/build/esm/src/stavetie.js +27 -2
  49. package/build/esm/src/strokes.js +4 -0
  50. package/build/esm/src/system.js +19 -4
  51. package/build/esm/src/systembreaks.js +42 -0
  52. package/build/esm/src/tabnote.js +6 -1
  53. package/build/esm/src/textbracket.js +24 -5
  54. package/build/esm/src/timesignature.js +15 -6
  55. package/build/esm/src/tuplet.js +1 -0
  56. package/build/esm/src/version.js +3 -3
  57. package/build/esm/src/vexflow.js +16 -0
  58. package/build/esm/src/voice.js +7 -3
  59. package/build/esm/tests/engraving/continuous-studies.mjs +140 -0
  60. package/build/esm/tests/engraving/instrument-studies.mjs +273 -0
  61. package/build/esm/tests/engraving/phrase-studies.mjs +63 -0
  62. package/build/esm/tests/engraving/publication-studies.mjs +87 -0
  63. package/build/esm/tests/engraving/specialist-studies.mjs +347 -0
  64. package/build/esm/tests/engraving/studies.mjs +88 -0
  65. package/build/esm/tests/node/continuous-score-tests.mjs +282 -0
  66. package/build/esm/tests/node/instrument-profile-tests.mjs +224 -0
  67. package/build/esm/tests/node/phrase-layout-tests.mjs +281 -0
  68. package/build/esm/tests/node/publication-tests.mjs +219 -0
  69. package/build/esm/tools/easyscore-structure.mjs +1 -1
  70. package/build/esm/tools/explorer/catalog/entries.mjs +2 -1
  71. package/build/esm/tools/explorer/catalog/expression.mjs +14 -9
  72. package/build/esm/tools/explorer/catalog/guitar.mjs +238 -0
  73. package/build/esm/tools/explorer/catalog/layout.mjs +8 -6
  74. package/build/esm/tools/explorer/catalog/notes.mjs +16 -14
  75. package/build/esm/tools/explorer/catalog/staves.mjs +12 -6
  76. package/build/esm/tools/explorer/catalog/strings.mjs +10 -7
  77. package/build/types/src/alternatingtremolo.d.ts +13 -0
  78. package/build/types/src/annotation.d.ts +9 -0
  79. package/build/types/src/articulation.d.ts +3 -0
  80. package/build/types/src/beam.d.ts +2 -0
  81. package/build/types/src/bend.d.ts +8 -0
  82. package/build/types/src/clef.d.ts +3 -0
  83. package/build/types/src/continuouslayout.d.ts +103 -0
  84. package/build/types/src/continuousspan.d.ts +60 -0
  85. package/build/types/src/curve.d.ts +11 -0
  86. package/build/types/src/easyscore/composition.d.ts +8 -0
  87. package/build/types/src/easyscore/policies.d.ts +1 -1
  88. package/build/types/src/fretdiagram.d.ts +23 -0
  89. package/build/types/src/guitargesture.d.ts +26 -0
  90. package/build/types/src/guitarmodifiers.d.ts +3 -0
  91. package/build/types/src/index.d.ts +10 -0
  92. package/build/types/src/instrumentprofile.d.ts +124 -0
  93. package/build/types/src/keysignature.d.ts +9 -0
  94. package/build/types/src/notationspelling.d.ts +25 -0
  95. package/build/types/src/note.d.ts +15 -0
  96. package/build/types/src/ornament.d.ts +3 -1
  97. package/build/types/src/pagebreaks.d.ts +26 -0
  98. package/build/types/src/pedalmarking.d.ts +9 -0
  99. package/build/types/src/phraselayout.d.ts +87 -0
  100. package/build/types/src/phraseribbon.d.ts +7 -0
  101. package/build/types/src/publication.d.ts +61 -0
  102. package/build/types/src/publicationview.d.ts +27 -0
  103. package/build/types/src/scorenavigation.d.ts +33 -0
  104. package/build/types/src/sheet.d.ts +5 -0
  105. package/build/types/src/stave.d.ts +13 -0
  106. package/build/types/src/stavehairpin.d.ts +18 -0
  107. package/build/types/src/stavetie.d.ts +5 -0
  108. package/build/types/src/system.d.ts +8 -1
  109. package/build/types/src/systembreaks.d.ts +9 -0
  110. package/build/types/src/textbracket.d.ts +7 -0
  111. package/build/types/src/timesignature.d.ts +4 -0
  112. package/build/types/src/vexflow.d.ts +16 -0
  113. package/build/types/src/voice.d.ts +2 -0
  114. package/changelog/CHANGELOG.md +8 -0
  115. package/package.json +9 -2
@@ -0,0 +1,281 @@
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 test from 'node:test';
12
+ import { createCanvas, registerFont } from 'canvas';
13
+ import { readFile } from 'node:fs/promises';
14
+ import puppeteer from 'puppeteer';
15
+ import { makePhraseStudy } from '../engraving/phrase-studies.mjs';
16
+ const VF = await import(new URL('../../build/esm/entry/vexflow-core.js', import.meta.url));
17
+ for (const family of ['Bravura', 'Academico']) {
18
+ const n = family.toLowerCase();
19
+ registerFont(new URL('../../node_modules/@vexflow-fonts/' + n + '/' + n + '.otf', import.meta.url).pathname, {
20
+ family,
21
+ });
22
+ }
23
+ VF.Element.setTextMeasurementCanvas(createCanvas(1, 1));
24
+ function factory() {
25
+ return new VF.Factory({ renderer: { elementId: null } }).setContext(new VF.CanvasContext(createCanvas(720, 420).getContext('2d')));
26
+ }
27
+ function score(text = 'G4/q, A4/q, B4/q, A4/q, G4/q') {
28
+ const f = factory(), es = f.EasyScore(), notes = es.notes(text, { stem: 'down' });
29
+ const system = f.System({ width: 510, y: 30, spaceBetweenStaves: 4 });
30
+ const staff = system.addStave({ voices: [es.voice(notes, { mode: 'soft' })] });
31
+ return { f, notes, system, staff, layout: system.getPhraseLayout() };
32
+ }
33
+ function measured(mark) {
34
+ const g = VF.measureEngraving(mark);
35
+ assert.deepEqual(g.diagnostics, []);
36
+ return g;
37
+ }
38
+ function intersects(a, b) {
39
+ return a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
40
+ }
41
+ test('whole syllables, hyphens and extenders stay in their verses across retained reflow', () => {
42
+ const f = factory(), { layout, system, lyrics, notes, bass } = makePhraseStudy(VF.VexFlow, f, 'choir');
43
+ const inspect = () => {
44
+ const rows = lyrics.map((verse) => verse.map((mark) => measured(mark)));
45
+ const baselines = rows.map((row) => row[0].anchors.baseline.y);
46
+ rows.forEach((row, i) => assert.ok(row.every((g) => g.anchors.baseline.y === baselines[i])));
47
+ assert.ok(rows[0].every((a) => rows[1].every((b) => a.ink.y + a.ink.h < b.ink.y)));
48
+ const links = layout.getLyricConnectors();
49
+ assert.equal(links.length, 5);
50
+ const [hyphen, extender] = links;
51
+ assert.ok(hyphen.x > rows[0][0].ink.x + rows[0][0].ink.w && hyphen.x + hyphen.w < rows[0][1].ink.x);
52
+ assert.equal(extender.x + extender.w, notes[3].getNoteHeadBeginX() + notes[3].getGlyphWidth());
53
+ assert.ok(links.every((link) => rows.flat().every((g) => !intersects(link, g.ink))));
54
+ assert.ok(bass.getYForLine(0) > Math.max(...links.map((b) => b.y + b.h)));
55
+ assert.deepEqual(layout.diagnostics, []);
56
+ return { rows, links, gap: bass.getY(), bounds: layout.bounds };
57
+ };
58
+ system.format();
59
+ const wide = inspect();
60
+ f.draw({ retain: true });
61
+ assert.deepEqual(inspect(), wide);
62
+ system.setWidth(390).format();
63
+ assert.notDeepEqual(inspect(), wide);
64
+ system.setWidth(615).format();
65
+ assert.deepEqual(inspect(), wide);
66
+ });
67
+ test('a cubic slur clears internal accents while the wedge, pedal and ottava retain their anchors', () => {
68
+ const f = factory(), { system, layout, notes, slur, hairpin, octave, pedal, dynamics, bass } = makePhraseStudy(VF.VexFlow, f, 'piano');
69
+ for (const width of [615, 390, 615]) {
70
+ system.setWidth(width).format();
71
+ f.draw({ retain: true });
72
+ assert.deepEqual(layout.diagnostics, []);
73
+ const routed = slur.getRouteParts(), anchors = slur.getAnchors();
74
+ const accent = measured(notes[1].getModifiers()[0]).ink;
75
+ assert.ok(routed.every((b) => !intersects(b, accent)));
76
+ const ottava = measured(octave).ink;
77
+ assert.ok(ottava.y + ottava.h < Math.min(...routed.map((b) => b.y)));
78
+ const [p, forte] = dynamics.map((m) => measured(m).ink), wedge = measured(hairpin).ink;
79
+ assert.ok(p.x + p.w < wedge.x && wedge.x + wedge.w < forte.x);
80
+ assert.ok(measured(pedal).ink.y > bass.getYForLine(4));
81
+ slur.setLayoutRise(0);
82
+ assert.deepEqual(slur.getAnchors(), anchors);
83
+ assert.notDeepEqual(routed, slur.getRouteParts());
84
+ }
85
+ });
86
+ test('pinned verse and staff collisions name their owners and terminate', () => {
87
+ const { system, layout, notes, staff } = score();
88
+ const bottom = system.addStave({ voices: [] });
89
+ layout.lockStaffGap(bottom);
90
+ const ids = ['one', 'two'];
91
+ ids.forEach((id) => layout.addVerse(staff, [{ note: notes[0], text: 'word' }], { baselineSpaces: 7 })[0].setAttribute('id', id));
92
+ system.format();
93
+ assert.ok(layout.diagnostics.some((d) => d.code === 'PinnedCollision' && ids.every((id) => d.sources.includes(id))));
94
+ assert.ok(layout.diagnostics.some((d) => d.code === 'PinnedCollision' && d.sources.includes(bottom.getAttribute('id'))));
95
+ for (const m of notes[0].getModifiers())
96
+ assert.equal(measured(m).anchors.baseline.y, staff.getYForLine(7));
97
+ assert.equal(layout.passes, 1);
98
+ });
99
+ test('a restricted pass budget leaves finite repeatable evidence', () => {
100
+ const f = factory(), { system, layout } = makePhraseStudy(VF.VexFlow, f, 'choir');
101
+ layout.setPassLimit(1);
102
+ const inspect = () => {
103
+ system.format();
104
+ return { diagnostics: structuredClone(layout.diagnostics), bounds: layout.bounds, passes: layout.passes };
105
+ };
106
+ const first = inspect();
107
+ assert.equal(first.passes, 1);
108
+ assert.ok(first.diagnostics.some((d) => d.code === 'IterationLimit'));
109
+ assert.ok(Object.values(first.bounds).every(Number.isFinite));
110
+ assert.deepEqual(inspect(), first);
111
+ layout.setPassLimit(4);
112
+ system.format();
113
+ assert.deepEqual(layout.diagnostics, []);
114
+ });
115
+ test('whole Latin combining sequences and CJK keep their text, unsupported script and invalid anchors name the mark', () => {
116
+ const { f, system, layout, notes, staff } = score();
117
+ const texts = ['E\u0301', '歌', 'سلام'];
118
+ const marks = layout.addVerse(staff, texts.map((text, i) => ({ note: notes[i], text })));
119
+ const detached = f.Annotation({ text: 'detached' });
120
+ layout.addLane(staff, [detached]);
121
+ const truncated = f.StaveTie({ from: notes[3] });
122
+ layout.route(truncated);
123
+ system.format();
124
+ assert.deepEqual(marks.map((m) => m.text), texts);
125
+ assert.deepEqual(layout.diagnostics.filter((d) => d.code === 'UnsupportedScript').map((d) => d.sources), [[marks[2].getAttribute('id')]]);
126
+ for (const m of [detached, truncated])
127
+ assert.ok(layout.diagnostics.some((d) => d.code === 'InvalidAnchor' && d.sources.includes(m.getAttribute('id'))));
128
+ });
129
+ test('nested quadratic and cubic routes preserve tied chord indices, manual controls and crossing diagnostics', () => {
130
+ const { f, system, layout, notes } = score('(G4 B4)/q, (G4 B4)/q, (G4 B4)/q, (G4 B4)/q, (G4 B4)/q');
131
+ const tie = f.StaveTie({
132
+ from: notes[1],
133
+ to: notes[3],
134
+ firstIndexes: [1],
135
+ lastIndexes: [1],
136
+ options: { direction: -1 },
137
+ });
138
+ const slur = f.Curve({
139
+ from: notes[0],
140
+ to: notes[4],
141
+ options: {
142
+ openingDirection: 'down',
143
+ cps: [
144
+ { x: 2, y: 39 },
145
+ { x: 3, y: 43 },
146
+ ],
147
+ },
148
+ });
149
+ system.format();
150
+ const manual = slur.getRouteParts();
151
+ layout.route(slur).route(tie);
152
+ system.format();
153
+ assert.deepEqual(slur.getRouteParts(), manual);
154
+ assert.deepEqual(tie.getNotes().firstIndexes, [1]);
155
+ assert.ok(tie.getRouteParts().length > 1);
156
+ assert.ok(!layout.diagnostics.some((d) => d.code === 'CrossingSpans'));
157
+ const cross = f.Curve({ from: notes[0], to: notes[2] });
158
+ layout.route(cross);
159
+ system.format();
160
+ assert.ok(layout.diagnostics.some((d) => d.code === 'CrossingSpans' && d.sources.includes(cross.getAttribute('id'))));
161
+ });
162
+ test('a rest clears ink anchored at an earlier attack and reports a collision when pinned', () => {
163
+ function restCase(pin) {
164
+ const { f, system, staff, layout, notes } = score('G4/q, B4/q/r, G4/q');
165
+ const [host, rest] = notes, obstruction = f.Annotation({ text: 'x' });
166
+ host.addModifier(obstruction, 0);
167
+ system.format();
168
+ const b = measured(rest).ink, a = measured(obstruction).ink;
169
+ obstruction.setXShift(a.x - b.x).setTextBaseline(obstruction.computeY().y + b.y - a.y);
170
+ assert.ok(rest.isRest());
171
+ const original = rest.getKeyLine(0);
172
+ if (pin)
173
+ layout.pin(rest);
174
+ system.format();
175
+ assert.equal(intersects(measured(rest).ink, measured(obstruction).ink), pin);
176
+ assert.equal(rest.getKeyLine(0) === original, pin);
177
+ assert.equal(layout.diagnostics.some((d) => d.code === 'PinnedCollision'), pin);
178
+ const line = rest.getKeyLine(0);
179
+ system.format();
180
+ assert.equal(rest.getKeyLine(0), line);
181
+ assert.equal(host.getStave(), staff);
182
+ }
183
+ restCase(false);
184
+ restCase(true);
185
+ });
186
+ test('staff separation refits cross-staff beams to the visible stem tips after resizing', () => {
187
+ const { f, system, staff, layout, notes } = score('G4/8, C5/8, G4/q');
188
+ const bottom = system.addStave({ voices: [] }).addClef('bass');
189
+ notes[1].setStave(bottom);
190
+ const beam = f.Beam({ notes: notes.slice(0, 2) });
191
+ layout.addVerse(staff, [{ note: notes[2], text: 'glow' }]);
192
+ const inspect = () => {
193
+ system.format();
194
+ assert.deepEqual(layout.diagnostics, []);
195
+ assert.ok(layout.passes >= 2 && layout.passes <= 4);
196
+ const geometry = measured(beam);
197
+ for (const [i, n] of notes.slice(0, 2).entries())
198
+ assert.equal(geometry.anchors['stem' + i].y, measured(n).anchors.stemTip.y + VF.Stem.WIDTH / 2);
199
+ return { beam: geometry.ink, stave: bottom.getY() };
200
+ };
201
+ const before = inspect();
202
+ system.setWidth(340);
203
+ assert.notDeepEqual(inspect(), before);
204
+ system.setWidth(510);
205
+ assert.deepEqual(inspect(), before);
206
+ });
207
+ test('clefs, key and time signatures follow the lower stave on each staff refit', () => {
208
+ const f = factory();
209
+ const { system, layout, bass } = makePhraseStudy(VF.VexFlow, f, 'choir');
210
+ bass.addKeySignature('E').addTimeSignature('6/8');
211
+ const key = bass.getModifiers().find((m) => m instanceof VF.KeySignature);
212
+ const meter = bass.getModifiers().find((m) => m instanceof VF.TimeSignature);
213
+ const inspect = () => {
214
+ system.format();
215
+ assert.deepEqual(layout.diagnostics, []);
216
+ return [...key.getInkParts(), meter.getInkBounds()].map((b) => b.y - bass.getY());
217
+ };
218
+ const initial = inspect();
219
+ assert.equal(initial.length, 5);
220
+ system.setY(system.getY() + 80);
221
+ assert.deepEqual(inspect(), initial);
222
+ });
223
+ test('choir and piano phrases render through SVG and Canvas with Bravura and Petaluma', () => __awaiter(void 0, void 0, void 0, function* () {
224
+ const browser = yield puppeteer.launch({ headless: true, args: process.env.CI ? ['--no-sandbox'] : [] });
225
+ try {
226
+ const page = yield browser.newPage();
227
+ yield page.setContent('<body></body>');
228
+ yield page.addScriptTag({ path: new URL('../../build/cjs/vexflow-debug.js', import.meta.url).pathname });
229
+ yield page.addScriptTag({ content: 'window.makePhraseStudy = ' + makePhraseStudy.toString() });
230
+ for (const family of ['Bravura', 'Academico', 'Petaluma', 'Petaluma Script']) {
231
+ const name = family.toLowerCase().replaceAll(' ', '');
232
+ const data = yield readFile(new URL('../../node_modules/@vexflow-fonts/' + name + '/' + name + '.woff2', import.meta.url));
233
+ yield page.evaluate((family, base64) => __awaiter(void 0, void 0, void 0, function* () {
234
+ document.fonts.add(yield new FontFace(family, 'url(data:font/woff2;base64,' + base64 + ')').load());
235
+ }), family, data.toString('base64'));
236
+ }
237
+ for (const [family, textFamily] of [
238
+ ['Bravura', 'Academico'],
239
+ ['Petaluma', 'Petaluma Script'],
240
+ ])
241
+ for (const kind of ['choir', 'piano'])
242
+ for (const backend of ['SVG', 'Canvas']) {
243
+ const result = yield page.evaluate(({ family, textFamily, kind, backend }) => {
244
+ var _a;
245
+ const VF = window.VexFlow;
246
+ VF.setFonts(family, textFamily);
247
+ const target = document.createElement(backend === 'SVG' ? 'div' : 'canvas');
248
+ target.id = 'phrase';
249
+ document.body.replaceChildren(target);
250
+ const f = new VF.Factory({ renderer: { elementId: 'phrase', width: 670, height: 380 } });
251
+ const { system, layout, lyrics } = window.makePhraseStudy(VF, f, kind);
252
+ const widths = [615, 390, 615];
253
+ const results = widths.map((w) => {
254
+ system.setWidth(w);
255
+ f.draw({ retain: true });
256
+ return {
257
+ diagnostics: structuredClone(layout.diagnostics),
258
+ bounds: layout.bounds,
259
+ connectors: layout.getLyricConnectors(),
260
+ };
261
+ });
262
+ const ink = backend === 'SVG'
263
+ ? target.querySelectorAll('svg path').length > 0
264
+ : target
265
+ .getContext('2d')
266
+ .getImageData(0, 0, target.width, target.height)
267
+ .data.some((v, i) => i % 4 === 3 && v > 0);
268
+ return { results, ink, syllables: (_a = lyrics === null || lyrics === void 0 ? void 0 : lyrics.flat().length) !== null && _a !== void 0 ? _a : 0 };
269
+ }, { family, textFamily, kind, backend });
270
+ assert.ok(result.ink, family + ' ' + kind + ' ' + backend);
271
+ for (const row of result.results)
272
+ assert.deepEqual(row.diagnostics, [], family + ' ' + kind + ' ' + backend);
273
+ assert.deepEqual(result.results[0], result.results[2]);
274
+ assert.notDeepEqual(result.results[0], result.results[1]);
275
+ assert.equal(result.results[0].connectors.length, kind === 'choir' ? 5 : 0);
276
+ }
277
+ }
278
+ finally {
279
+ yield browser.close();
280
+ }
281
+ }));
@@ -0,0 +1,219 @@
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 { readFile } from 'node:fs/promises';
12
+ import { test } from 'node:test';
13
+ import puppeteer from 'puppeteer';
14
+ import { publicationStudy } from '../engraving/publication-studies.mjs';
15
+ test('publication views, pagination and portable printing', (t) => __awaiter(void 0, void 0, void 0, function* () {
16
+ const browser = yield puppeteer.launch({ headless: true, args: process.env.CI ? ['--no-sandbox'] : [] });
17
+ try {
18
+ const page = yield browser.newPage();
19
+ yield page.setContent('<main></main><aside></aside>');
20
+ yield page.addScriptTag({ path: 'build/cjs/vexflow-debug.js' });
21
+ yield page.addScriptTag({ path: 'node_modules/opentype.js/dist/opentype.js' });
22
+ yield page.addScriptTag({ content: 'window.study=' + publicationStudy });
23
+ for (const [family, file] of [
24
+ ['Bravura', 'bravura'],
25
+ ['Academico', 'academico'],
26
+ ]) {
27
+ const data = yield readFile('node_modules/@vexflow-fonts/' + file + '/' + file + '.otf');
28
+ yield page.evaluate((_a) => __awaiter(void 0, [_a], void 0, function* ({ family, data }) {
29
+ var _b;
30
+ const bytes = Uint8Array.from(atob(data), (c) => c.charCodeAt(0));
31
+ document.fonts.add(yield new FontFace(family, bytes).load());
32
+ ((_b = window.faces) !== null && _b !== void 0 ? _b : (window.faces = [])).push({ family, font: opentype.parse(bytes.buffer) });
33
+ }), { family, data: data.toString('base64') });
34
+ }
35
+ yield page.evaluate(() => VexFlow.setFonts('Bravura', 'Academico'));
36
+ for (const paper of ['A4', 'Letter'])
37
+ for (const part of [false, true]) {
38
+ yield t.test((part ? 'cello' : 'score') + ' on ' + paper, () => __awaiter(void 0, void 0, void 0, function* () {
39
+ var _a;
40
+ const { diagnostics, ranges, media, metadata, ids, boxes, printed, geometry, svg } = yield page.evaluate(({ part, paper }) => {
41
+ const { source, options } = study(part, paper), target = document.querySelector('main');
42
+ const result = new VexFlow.Publication(source).render(target, options);
43
+ const roots = result.pages.map((p) => p.svg);
44
+ const ids = roots.flatMap((s) => [...s.querySelectorAll('[id]')].map((el) => el.id));
45
+ const p = result.pages[0];
46
+ const xml = result.toSVG(1), outlined = result.toSVG(1, faces);
47
+ const parse = (s) => new DOMParser().parseFromString(s, 'image/svg+xml');
48
+ return {
49
+ diagnostics: result.diagnostics,
50
+ ranges: result.pages.map((p) => p.systems.flatMap((s) => s.measures)),
51
+ media: roots.map((el) => [el.getAttribute('width'), el.getAttribute('height')]),
52
+ metadata: roots.map((s) => JSON.parse(s.querySelector('metadata').textContent)),
53
+ ids: ids.length === new Set(ids).size,
54
+ boxes: result.pages.map((p) => p.systems),
55
+ printed: result.toPrintHTML(faces),
56
+ geometry: [...parse(outlined).querySelectorAll('[data-system]')].map((g) => g.getAttribute('transform')),
57
+ svg: {
58
+ transforms: [...p.svg.querySelectorAll('[data-system]')].map((g) => g.getAttribute('transform')),
59
+ source: parse(xml).querySelectorAll('text').length,
60
+ outlined: parse(outlined).querySelectorAll('text').length,
61
+ meta: parse(outlined).querySelector('metadata').textContent ===
62
+ p.svg.querySelector('metadata').textContent,
63
+ },
64
+ };
65
+ }, { part, paper });
66
+ assert.deepEqual(diagnostics, []);
67
+ assert.deepEqual(ranges.flat(), Array.from({ length: 26 }, (_, i) => i + 1));
68
+ assert.deepEqual(ranges.map((r) => r.at(-1)), part ? [16, 26] : paper === 'A4' ? [12, 24, 26] : [8, 20, 26]);
69
+ const [w, h] = paper === 'A4' ? [210, 297] : [215.9, 279.4];
70
+ assert.ok(media.every((m) => m[0] === w + 'mm' && m[1] === h + 'mm'));
71
+ for (const systems of boxes)
72
+ for (const [i, s] of systems.entries()) {
73
+ assert.ok(s.x >= 16 && s.x + s.width <= w - 16 + 0.001);
74
+ assert.ok(s.y >= 15 && s.y + s.height < h - 15);
75
+ if (i)
76
+ assert.ok(s.y >= systems[i - 1].y + systems[i - 1].height + 5.99);
77
+ }
78
+ assert.ok(ids && svg.meta && svg.source > 0 && !svg.outlined);
79
+ assert.deepEqual(geometry, svg.transforms);
80
+ const events = metadata.flatMap((m) => m.events);
81
+ assert.ok(events.some((n) => n.id === 'vc-16-1' && n.rest));
82
+ if (part) {
83
+ const cue = metadata.flatMap((m) => m.regions).find((r) => r.kind === 'cue');
84
+ assert.ok(cue.events.some((e) => e.id === 'fl-16-1' && e.measure === 16 && e.staff === 'fl'));
85
+ assert.ok(events.every((e) => e.staff === 'vc'));
86
+ assert.deepEqual(metadata.flatMap((m) => m.regions).map((r) => [r.kind, r.measure]), [
87
+ ['cue', 16],
88
+ ['ossia', 21],
89
+ ]);
90
+ }
91
+ const print = yield browser.newPage();
92
+ try {
93
+ yield print.setContent(printed);
94
+ const pdf = Buffer.from(yield print.pdf({ preferCSSPageSize: true, printBackground: true }));
95
+ const bytes = pdf.toString('latin1');
96
+ const pages = (_a = bytes.match(/\/Type\s*\/Page\b/g)) !== null && _a !== void 0 ? _a : [];
97
+ assert.equal(pages.length, ranges.length);
98
+ const media = [...bytes.matchAll(/\/MediaBox\s*\[\s*0\s+0\s+([\d.]+)\s+([\d.]+)/g)];
99
+ assert.equal(media.length, ranges.length);
100
+ assert.ok(media.every((m) => Math.abs(Number(m[1]) - (w * 72) / 25.4) < 1 && Math.abs(Number(m[2]) - (h * 72) / 25.4) < 1));
101
+ }
102
+ finally {
103
+ yield print.close();
104
+ }
105
+ }));
106
+ }
107
+ yield t.test('pagination reserves running text at the final page scale', () => __awaiter(void 0, void 0, void 0, function* () {
108
+ const result = yield page.evaluate(() => {
109
+ const style = document.createElement('style');
110
+ style.textContent = 'svg[role="img"] [data-page-furniture] text { font-size: 7px }';
111
+ document.head.append(style);
112
+ try {
113
+ const { source, options } = study(false, 'Letter');
114
+ const book = new VexFlow.Publication(source).render(document.querySelector('main'), options);
115
+ return book.pages.map((p) => {
116
+ const footer = Array.from(p.svg.querySelector('[data-page-furniture]').children).slice(-2);
117
+ const bottom = Math.min(...footer.map((el) => el.getBBox().y));
118
+ const last = p.systems.at(-1);
119
+ return { end: last.measures.at(-1), clearance: bottom - last.y - last.height };
120
+ });
121
+ }
122
+ finally {
123
+ style.remove();
124
+ }
125
+ });
126
+ assert.deepEqual(result.map((p) => p.end), [8, 16, 24, 26]);
127
+ assert.ok(result.every((p) => p.clearance >= 3.99), 'Every system clears the footer reservation');
128
+ }));
129
+ yield t.test('an extracted cross-staff voice keeps its notes and reports a spanner ending in another part', () => __awaiter(void 0, void 0, void 0, function* () {
130
+ const data = yield page.evaluate(() => {
131
+ const { source } = study(false, 'A4');
132
+ const note = source.staves[0].measures[0].voices[0].notes[0];
133
+ note.stave = 'va';
134
+ note.note.clef = 'alto';
135
+ source.continuous.spans.push({ kind: 'slur', id: 'between', from: 'fl-1-1', to: 'vc-2-2' });
136
+ const registry = new VexFlow.Registry();
137
+ VexFlow.Registry.enableDefaultRegistry(registry);
138
+ try {
139
+ const r = new VexFlow.Publication(source).render(document.querySelector('aside'), { staves: ['fl'] });
140
+ const metadata = JSON.parse(r.pages[0].svg.querySelector('metadata').textContent);
141
+ return {
142
+ notes: metadata.events.filter((n) => n.id === 'fl-1-1'),
143
+ omitted: r.diagnostics.filter((d) => d.code === 'ExcludedAnchor'),
144
+ registry: VexFlow.Registry.getDefaultRegistry() === registry && !registry.getElementById('fl-1-1'),
145
+ };
146
+ }
147
+ finally {
148
+ VexFlow.Registry.disableDefaultRegistry();
149
+ }
150
+ });
151
+ assert.equal(data.notes[0].staff, 'fl');
152
+ assert.deepEqual(data.omitted, [{ code: 'ExcludedAnchor', measures: [1, 2], detail: 'between' }]);
153
+ assert.ok(data.registry);
154
+ }));
155
+ yield t.test('part-only breaks, forced and forbidden turns, oversize diagnostics and transactional redraw', () => __awaiter(void 0, void 0, void 0, function* () {
156
+ const checks = yield page.evaluate(() => {
157
+ const { source, options } = study(false, 'A4'), part = study(true, 'A4').options;
158
+ const base = JSON.stringify(source), pub = new VexFlow.Publication(source);
159
+ const main = document.querySelector('main'), other = document.querySelector('aside');
160
+ const score = pub.render(main, options), before = main.innerHTML;
161
+ const forced = pub.render(other, Object.assign(Object.assign({}, part), { pageBreaks: [5], forbiddenTurns: [4] }));
162
+ const last = other.innerHTML;
163
+ let invalid = false;
164
+ try {
165
+ pub.render(other, Object.assign(Object.assign({}, part), { regions: [{ kind: 'cue', staff: 'missing', measure: 4, label: 'Cue' }] }));
166
+ }
167
+ catch (_a) {
168
+ invalid = true;
169
+ }
170
+ const intact = other.innerHTML === last;
171
+ const narrow = pub.render(other, Object.assign(Object.assign({}, part), { paper: { width: 130, height: 68 }, title: 'A '.repeat(100) }));
172
+ let refused = false;
173
+ try {
174
+ narrow.toPrintHTML(faces);
175
+ }
176
+ catch (_b) {
177
+ refused = true;
178
+ }
179
+ return {
180
+ invalid,
181
+ intact,
182
+ refused,
183
+ unchanged: before === main.innerHTML && base === JSON.stringify(source),
184
+ turn: forced.diagnostics.filter((d) => d.code === 'ForbiddenTurn').map((d) => d.measures),
185
+ first: forced.pages[1].systems[0].measures[0],
186
+ codes: narrow.diagnostics.map((d) => d.code),
187
+ score: score.pages.length,
188
+ };
189
+ });
190
+ assert.ok(checks.invalid && checks.intact && checks.refused && checks.unchanged);
191
+ assert.equal(checks.first, 5);
192
+ assert.deepEqual(checks.turn, [[4]]);
193
+ assert.ok(checks.codes.includes('PageOverflow') && checks.codes.includes('TextOverflow'));
194
+ }));
195
+ }
196
+ finally {
197
+ yield browser.close();
198
+ }
199
+ }));
200
+ test('equally feasible pages prefer a performing rest and respect a forbidden turn and last-page spacing', () => __awaiter(void 0, void 0, void 0, function* () {
201
+ const { paginate } = yield import('../../build/esm/src/pagebreaks.js');
202
+ const rows = Array.from({ length: 5 }, (_, i) => ({ measures: [i + 1], height: 10, restAtEnd: i === 1 }));
203
+ const rules = {
204
+ firstHeight: 34,
205
+ laterHeight: 34,
206
+ gap: 1,
207
+ maxExtraGap: 8,
208
+ justifyLast: false,
209
+ part: true,
210
+ forceBefore: new Set(),
211
+ preferAfter: new Set(),
212
+ forbidAfter: new Set(),
213
+ };
214
+ const natural = paginate(rows, rules);
215
+ assert.deepEqual(natural.map((p) => p.end), [2, 5]);
216
+ assert.deepEqual(natural[1].offsets, [0, 11, 22]);
217
+ assert.deepEqual(paginate(rows, Object.assign(Object.assign({}, rules), { justifyLast: true }))[1].offsets, [0, 12, 24]);
218
+ assert.deepEqual(paginate(rows, Object.assign(Object.assign({}, rules), { forbidAfter: new Set([2]) })).map((p) => p.end), [3, 5]);
219
+ }));
@@ -12,7 +12,7 @@ export function renderEasyScoreStructure(VF, renderer, kind = 'tab', ink = '#243
12
12
  marks.push(mark);
13
13
  };
14
14
  if (tab) {
15
- notes = [3, 5, 7, 7].map((fret) => score.make.tabNote({ positions: [{ str: 2, fret }], duration: 'q' }));
15
+ notes = [3, 5, 7, 8].map((fret) => score.make.tabNote({ positions: [{ str: 2, fret }], duration: 'q' }));
16
16
  attach(score.make.clef('tab'));
17
17
  if (kind === 'tab') {
18
18
  const bend = score.make.bend([
@@ -1,6 +1,7 @@
1
1
  import { expression } from './expression.mjs';
2
+ import { guitar } from './guitar.mjs';
2
3
  import { layout } from './layout.mjs';
3
4
  import { notes } from './notes.mjs';
4
5
  import { staves } from './staves.mjs';
5
6
  import { strings } from './strings.mjs';
6
- export const entries = [...notes, ...staves, ...expression, ...strings, ...layout];
7
+ export const entries = [...notes, ...staves, ...expression, ...strings, ...guitar, ...layout];
@@ -1,10 +1,12 @@
1
1
  import { example as e, number, select, setup, staff, text } from './helpers.mjs';
2
2
  const group = 'Marks & expression';
3
3
  export const expression = [
4
- e('annotations', 'Lyrics & annotations', group, 'Align lyrics below notes or annotations above them.', 'Annotation', staff("score.notes('C5/q, E5, G5, C6')", `params.words.split(' ').slice(0, notes.length).forEach((word, i) => {
4
+ e('annotations', 'Lyrics & annotations', group, 'Align lyrics below notes or annotations above them.', 'Annotation', staff("score.notes('C5/q, E5, G5, C6')", `// Pair each word with the note at the same position in the melody.
5
+ params.words.split(' ').slice(0, notes.length).forEach((word, i) => {
5
6
  notes[i].addModifier(factory.Annotation({ text: word, vJustify: params.position }), 0);
6
7
  });`), [text('words', 'Words', 'One two three four'), select('position', 'Position', 'bottom', ['bottom', 'top'])]),
7
- e('chord-symbols', 'Chord symbols', group, 'Build harmonic labels from text, accidentals, and superscripts.', 'ChordSymbol', staff("score.notes('C5/h, G4')", `notes[0].addModifier(factory.ChordSymbol().addText(params.root).addGlyphOrText('maj7'), 0);
8
+ e('chord-symbols', 'Chord symbols', group, 'Build harmonic labels from text, accidentals, and superscripts.', 'ChordSymbol', staff("score.notes('C5/h, G4')", `// Build the label in reading order. Raise the flat ninth on the second symbol.
9
+ notes[0].addModifier(factory.ChordSymbol().addText(params.root).addGlyphOrText('maj7'), 0);
8
10
  notes[1].addModifier(factory.ChordSymbol().addText('G').addGlyphOrText('7').addGlyphOrText('b9', { symbolModifier: VF.ChordSymbol.symbolModifiers.SUPERSCRIPT }), 0);`), [text('root', 'Root', 'C')]),
9
11
  e('chord-kerning', 'Chord kerning', group, 'Compare default spacing with opt-in font-specific kerning and stacked scripts.', 'ChordSymbol', `${setup}
10
12
  // The two rows use identical notes and chord content. Only the kerning mode changes.
@@ -46,23 +48,26 @@ if (params.bounds === 'yes') {
46
48
  select('bounds', 'Chord bounds', 'no', ['no', 'yes']),
47
49
  ], 'Auto supports regular Academico/Bravura and Petaluma Script/Petaluma. Other font combinations keep the default layout. Set the chord font before formatting.'),
48
50
  e('dynamics', 'Dynamics', group, 'From pianissimo to fortissimo, draw music-font dynamic marks.', 'TextDynamics', `${setup}
51
+ // Give each dynamic a beat so the voice can space the markings from softest to loudest.
49
52
  const dynamics = ['pp', 'p', 'mp', 'mf', 'f', 'ff'].map(text => factory.TextDynamics({ text, duration: 'q' }));
50
53
  const voice = factory.Voice().setMode(VF.Voice.Mode.SOFT).addTickables(dynamics);
51
54
  factory.System({ x: 30, y: 55, width: width - 60 }).addStave({ voices: [voice] });
52
55
  factory.draw();`),
53
56
  e('text-notes', 'Text notes', group, 'Place rhythmically aligned text alongside music.', 'TextNote', `${setup}
57
+ // Each word takes a quarter note of time, even though it has no notehead.
54
58
  const notes = ['dolce', 'poco', 'a', 'poco'].map(text => factory.TextNote({ text, duration: 'q', line: params.line }));
55
59
  const voice = factory.Voice().addTickables(notes);
56
60
  factory.System({ x: 30, y: 65, width: width - 60 }).addStave({ voices: [voice] });
57
61
  factory.draw();`, [number('line', 'Text line', 2, -2, 6)]),
58
- e('ties', 'Ties', group, 'Connect the same pitch across successive notes. Chord ties can select individual keys.', 'StaveTie', staff("score.notes('(C5 E5)/h, (C5 E5)')", 'factory.StaveTie({ from: notes[0], to: notes[1], firstIndexes: [0, 1], lastIndexes: [0, 1] });')),
59
- e('slurs', 'Slurs & curves', group, 'Connect notes with a slur and adjust its thickness.', 'Curve', staff("score.notes('C5/q, D5, E5, G5')", 'factory.Curve({ from: notes[0], to: notes[3], options: { thickness: params.thickness } });'), [number('thickness', 'Thickness', 2, 1, 6, 0.5)]),
60
- e('hairpins', 'Hairpins', group, 'Draw crescendo and decrescendo hairpins below the staff.', 'StaveHairpin', staff("score.notes('C5/q, D5, E5, G5')", '', `new VF.StaveHairpin({ firstNote: notes[0], lastNote: notes[3] }, params.direction === 'crescendo' ? 1 : 2)
62
+ e('ties', 'Ties', group, 'Connect the same pitch across successive notes. Chord ties can select individual keys.', 'StaveTie', staff("score.notes('(C5 E5)/h, (C5 E5)')", '// Connect both matching pitches. Leave only index zero on each side to sustain just C.\nfactory.StaveTie({ from: notes[0], to: notes[1], firstIndexes: [0, 1], lastIndexes: [0, 1] });')),
63
+ e('slurs', 'Slurs & curves', group, 'Connect notes with a slur and adjust its thickness.', 'Curve', staff("score.notes('C5/q, D5, E5, G5')", '// The middle two notes belong to the phrase even though only its endpoints are named.\nfactory.Curve({ from: notes[0], to: notes[3], options: { thickness: params.thickness } });'), [number('thickness', 'Thickness', 2, 1, 6, 0.5)]),
64
+ e('hairpins', 'Hairpins', group, 'Draw crescendo and decrescendo hairpins below the staff.', 'StaveHairpin', staff("score.notes('C5/q, D5, E5, G5')", '', `// The opening or closing wedge occupies the space between the first and last attacks.
65
+ new VF.StaveHairpin({ firstNote: notes[0], lastNote: notes[3] }, params.direction === 'crescendo' ? 1 : 2)
61
66
  .setPosition(VF.Modifier.Position.BELOW)
62
67
  .setStyle({ fillStyle: ink, strokeStyle: ink })
63
68
  .setContext(factory.getContext()).drawWithStyle();`), [select('direction', 'Direction', 'crescendo', ['crescendo', 'decrescendo'])]),
64
- e('pedal', 'Pedal markings', group, 'Choose between text, brackets, and a mixture of the two.', 'PedalMarking', staff("score.notes('C5/q, E5, G5, C6')", 'factory.PedalMarking({ notes: [notes[0], notes[3]], options: { style: params.style } });'), [select('style', 'Style', 'mixed', ['mixed', 'bracket', 'text'])]),
65
- e('octaves', 'Octave brackets', group, 'An octave instruction spans a passage without changing its written pitches.', 'TextBracket', staff("score.notes('C5/q, E5, G5, C6')", "factory.TextBracket({ from: notes[0], to: notes[3], text: params.text, options: { superscript: 'va', position: 'top', line: 2 } });"), [select('text', 'Interval', '8', ['8', '15'])]),
66
- e('glissando', 'Glissando lines', group, 'Draw a line between selected pitches and add a label.', 'StaveLine', staff("score.notes('C4/h, C6')", "factory.StaveLine({ from: notes[0], to: notes[1], firstIndexes: [0], lastIndexes: [0], options: { text: 'gliss.' } });")),
67
- e('vibrato-bracket', 'Vibrato brackets', group, 'Draw a vibrato bracket spanning several notes.', 'VibratoBracket', staff("score.notes('C5/q, D5, E5, G5')", 'factory.VibratoBracket({ from: notes[0], to: notes[3], options: { line: 2 } });')),
69
+ e('pedal', 'Pedal markings', group, 'Choose between text, brackets, and a mixture of the two.', 'PedalMarking', staff("score.notes('C5/q, E5, G5, C6')", '// The first note tells the pianist to depress the pedal and the last to release it.\nfactory.PedalMarking({ notes: [notes[0], notes[3]], options: { style: params.style } });'), [select('style', 'Style', 'mixed', ['mixed', 'bracket', 'text'])]),
70
+ e('octaves', 'Octave brackets', group, 'An octave instruction spans a passage without changing its written pitches.', 'TextBracket', staff("score.notes('C5/q, E5, G5, C6')", "// The bracket tells the player to transpose every note under it.\nfactory.TextBracket({ from: notes[0], to: notes[3], text: params.text, options: { superscript: 'va', position: 'top', line: 2 } });"), [select('text', 'Interval', '8', ['8', '15'])]),
71
+ e('glissando', 'Glissando lines', group, 'Draw a line between selected pitches and add a label.', 'StaveLine', staff("score.notes('C4/h, C6')", "// Each index picks the head where the sliding line starts or ends.\nfactory.StaveLine({ from: notes[0], to: notes[1], firstIndexes: [0], lastIndexes: [0], options: { text: 'gliss.' } });")),
72
+ e('vibrato-bracket', 'Vibrato brackets', group, 'Draw a vibrato bracket spanning several notes.', 'VibratoBracket', staff("score.notes('C5/q, D5, E5, G5')", '// The wavy line lasts across the phrase. Its line setting controls its height.\nfactory.VibratoBracket({ from: notes[0], to: notes[3], options: { line: 2 } });')),
68
73
  ];