vexflow 5.2.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 (189) 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 +6502 -1708
  7. package/build/cjs/vexflow-debug-with-tests.js.map +1 -1
  8. package/build/cjs/vexflow-debug.js +5622 -1618
  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 +10 -3
  13. package/build/esm/src/alternatingtremolo.js +68 -0
  14. package/build/esm/src/annotation.js +19 -3
  15. package/build/esm/src/articulation.js +28 -6
  16. package/build/esm/src/beam.js +171 -28
  17. package/build/esm/src/bend.js +79 -23
  18. package/build/esm/src/clef.js +3 -0
  19. package/build/esm/src/continuouslayout.js +681 -0
  20. package/build/esm/src/continuousspan.js +159 -0
  21. package/build/esm/src/curve.js +48 -55
  22. package/build/esm/src/dot.js +13 -4
  23. package/build/esm/src/easyscore/composition.js +52 -2
  24. package/build/esm/src/easyscore/policies.js +39 -8
  25. package/build/esm/src/element.js +4 -0
  26. package/build/esm/src/engravinggeometry.js +157 -0
  27. package/build/esm/src/engravingprofile.js +44 -0
  28. package/build/esm/src/factory.js +31 -11
  29. package/build/esm/src/font.js +9 -1
  30. package/build/esm/src/formatter.js +9 -1
  31. package/build/esm/src/fretdiagram.js +77 -0
  32. package/build/esm/src/gracenote.js +43 -38
  33. package/build/esm/src/gracenotegroup.js +53 -56
  34. package/build/esm/src/guitargesture.js +33 -0
  35. package/build/esm/src/guitarmodifiers.js +26 -0
  36. package/build/esm/src/index.js +10 -0
  37. package/build/esm/src/instrumentprofile.js +123 -0
  38. package/build/esm/src/keysignature.js +24 -2
  39. package/build/esm/src/modifiercontext.js +11 -0
  40. package/build/esm/src/notationspelling.js +73 -0
  41. package/build/esm/src/note.js +3 -0
  42. package/build/esm/src/notehead.js +11 -6
  43. package/build/esm/src/ornament.js +43 -18
  44. package/build/esm/src/pagebreaks.js +58 -0
  45. package/build/esm/src/pedalmarking.js +39 -17
  46. package/build/esm/src/phraselayout.js +503 -0
  47. package/build/esm/src/phraseribbon.js +28 -0
  48. package/build/esm/src/proportionalformatter.js +54 -6
  49. package/build/esm/src/publication.js +402 -0
  50. package/build/esm/src/publicationview.js +114 -0
  51. package/build/esm/src/scorenavigation.js +172 -0
  52. package/build/esm/src/sheet.js +14 -2
  53. package/build/esm/src/stave.js +33 -16
  54. package/build/esm/src/stavebarline.js +5 -7
  55. package/build/esm/src/staveconnector.js +1 -0
  56. package/build/esm/src/stavehairpin.js +53 -27
  57. package/build/esm/src/stavenote.js +134 -116
  58. package/build/esm/src/stavetie.js +66 -9
  59. package/build/esm/src/stem.js +26 -11
  60. package/build/esm/src/strokes.js +4 -0
  61. package/build/esm/src/system.js +19 -4
  62. package/build/esm/src/systembreaks.js +42 -0
  63. package/build/esm/src/tabnote.js +6 -1
  64. package/build/esm/src/textbracket.js +24 -5
  65. package/build/esm/src/tickcontext.js +19 -0
  66. package/build/esm/src/timesignature.js +20 -6
  67. package/build/esm/src/tuplet.js +58 -17
  68. package/build/esm/src/version.js +3 -3
  69. package/build/esm/src/vexflow.js +20 -0
  70. package/build/esm/src/voice.js +7 -3
  71. package/build/esm/tests/bend_tests.js +14 -1
  72. package/build/esm/tests/curve_tests.js +14 -4
  73. package/build/esm/tests/demo_repertoire_tests.js +27 -0
  74. package/build/esm/tests/demos/drums.js +54 -0
  75. package/build/esm/tests/demos/electric.js +63 -0
  76. package/build/esm/tests/demos/greensleeves.js +90 -0
  77. package/build/esm/tests/demos/joy.js +61 -0
  78. package/build/esm/tests/demos/kesh.js +80 -0
  79. package/build/esm/tests/demos/prelude.js +59 -0
  80. package/build/esm/tests/demos/quartertones.js +50 -0
  81. package/build/esm/tests/demos/saints.js +65 -0
  82. package/build/esm/tests/engraving/continuous-studies.mjs +140 -0
  83. package/build/esm/tests/engraving/instrument-studies.mjs +273 -0
  84. package/build/esm/tests/engraving/phrase-studies.mjs +63 -0
  85. package/build/esm/tests/engraving/publication-studies.mjs +87 -0
  86. package/build/esm/tests/engraving/score-layout.mjs +75 -0
  87. package/build/esm/tests/engraving/score-persistence.mjs +262 -0
  88. package/build/esm/tests/engraving/specialist-studies.mjs +347 -0
  89. package/build/esm/tests/engraving/studies.mjs +367 -0
  90. package/build/esm/tests/formatter_tests.js +10 -1
  91. package/build/esm/tests/index.js +1 -0
  92. package/build/esm/tests/node/audit-dependencies-tests.mjs +42 -0
  93. package/build/esm/tests/node/continuous-score-tests.mjs +282 -0
  94. package/build/esm/tests/node/easyscore-tests.mjs +71 -0
  95. package/build/esm/tests/node/engraving-layout-tests.mjs +449 -0
  96. package/build/esm/tests/node/instrument-profile-tests.mjs +224 -0
  97. package/build/esm/tests/node/local-engraving-tests.mjs +128 -0
  98. package/build/esm/tests/node/phrase-layout-tests.mjs +281 -0
  99. package/build/esm/tests/node/proportional-spacing-tests.mjs +64 -0
  100. package/build/esm/tests/node/publication-tests.mjs +219 -0
  101. package/build/esm/tests/node/rendering-tests.mjs +6 -2
  102. package/build/esm/tests/threevoice_tests.js +11 -1
  103. package/build/esm/tests/vexflow_test_helpers.js +19 -10
  104. package/build/esm/tools/audit-dependencies.mjs +61 -0
  105. package/build/esm/tools/easyscore-structure.mjs +1 -1
  106. package/build/esm/tools/explorer/catalog/entries.mjs +2 -1
  107. package/build/esm/tools/explorer/catalog/expression.mjs +14 -9
  108. package/build/esm/tools/explorer/catalog/guitar.mjs +238 -0
  109. package/build/esm/tools/explorer/catalog/layout.mjs +8 -6
  110. package/build/esm/tools/explorer/catalog/notes.mjs +16 -14
  111. package/build/esm/tools/explorer/catalog/staves.mjs +12 -6
  112. package/build/esm/tools/explorer/catalog/strings.mjs +10 -7
  113. package/build/esm/tools/score-fixtures.mjs +23 -6
  114. package/build/types/src/accidental.d.ts +4 -0
  115. package/build/types/src/alternatingtremolo.d.ts +13 -0
  116. package/build/types/src/annotation.d.ts +9 -0
  117. package/build/types/src/articulation.d.ts +9 -1
  118. package/build/types/src/beam.d.ts +16 -0
  119. package/build/types/src/bend.d.ts +8 -0
  120. package/build/types/src/clef.d.ts +3 -0
  121. package/build/types/src/continuouslayout.d.ts +103 -0
  122. package/build/types/src/continuousspan.d.ts +60 -0
  123. package/build/types/src/curve.d.ts +20 -0
  124. package/build/types/src/dot.d.ts +5 -0
  125. package/build/types/src/easyscore/composition.d.ts +27 -0
  126. package/build/types/src/easyscore/policies.d.ts +1 -1
  127. package/build/types/src/element.d.ts +2 -0
  128. package/build/types/src/engravinggeometry.d.ts +31 -0
  129. package/build/types/src/engravingprofile.d.ts +20 -0
  130. package/build/types/src/factory.d.ts +6 -1
  131. package/build/types/src/formatter.d.ts +3 -3
  132. package/build/types/src/fretdiagram.d.ts +23 -0
  133. package/build/types/src/gracenote.d.ts +7 -0
  134. package/build/types/src/gracenotegroup.d.ts +7 -2
  135. package/build/types/src/guitargesture.d.ts +26 -0
  136. package/build/types/src/guitarmodifiers.d.ts +3 -0
  137. package/build/types/src/index.d.ts +12 -0
  138. package/build/types/src/instrumentprofile.d.ts +124 -0
  139. package/build/types/src/keysignature.d.ts +9 -0
  140. package/build/types/src/modifiercontext.d.ts +4 -0
  141. package/build/types/src/notationspelling.d.ts +25 -0
  142. package/build/types/src/note.d.ts +15 -0
  143. package/build/types/src/notehead.d.ts +5 -0
  144. package/build/types/src/ornament.d.ts +10 -1
  145. package/build/types/src/pagebreaks.d.ts +26 -0
  146. package/build/types/src/pedalmarking.d.ts +9 -0
  147. package/build/types/src/phraselayout.d.ts +87 -0
  148. package/build/types/src/phraseribbon.d.ts +7 -0
  149. package/build/types/src/proportionalformatter.d.ts +11 -2
  150. package/build/types/src/publication.d.ts +61 -0
  151. package/build/types/src/publicationview.d.ts +27 -0
  152. package/build/types/src/scorenavigation.d.ts +33 -0
  153. package/build/types/src/sheet.d.ts +5 -0
  154. package/build/types/src/stave.d.ts +13 -0
  155. package/build/types/src/stavehairpin.d.ts +18 -0
  156. package/build/types/src/stavenote.d.ts +20 -2
  157. package/build/types/src/stavetie.d.ts +9 -0
  158. package/build/types/src/stem.d.ts +10 -1
  159. package/build/types/src/system.d.ts +8 -1
  160. package/build/types/src/systembreaks.d.ts +9 -0
  161. package/build/types/src/textbracket.d.ts +7 -0
  162. package/build/types/src/tickcontext.d.ts +5 -0
  163. package/build/types/src/timesignature.d.ts +6 -0
  164. package/build/types/src/tuplet.d.ts +5 -48
  165. package/build/types/src/vexflow.d.ts +20 -0
  166. package/build/types/src/voice.d.ts +2 -0
  167. package/changelog/CHANGELOG.md +25 -0
  168. package/package.json +15 -3
  169. package/tests/all.html +277 -0
  170. package/tests/demo_petzold_tests.ts +435 -0
  171. package/tests/demos/drums.ts +55 -0
  172. package/tests/demos/drums.webp +0 -0
  173. package/tests/demos/electric.ts +70 -0
  174. package/tests/demos/electric.webp +0 -0
  175. package/tests/demos/greensleeves.ts +97 -0
  176. package/tests/demos/greensleeves.webp +0 -0
  177. package/tests/demos/joy.ts +65 -0
  178. package/tests/demos/joy.webp +0 -0
  179. package/tests/demos/kesh.ts +86 -0
  180. package/tests/demos/kesh.webp +0 -0
  181. package/tests/demos/prelude.ts +65 -0
  182. package/tests/demos/prelude.webp +0 -0
  183. package/tests/demos/quartertones.ts +51 -0
  184. package/tests/demos/quartertones.webp +0 -0
  185. package/tests/demos/saints.ts +70 -0
  186. package/tests/demos/saints.webp +0 -0
  187. package/tests/flow.html +550 -239
  188. package/tests/fonts.css +493 -0
  189. package/tests/minuet.webp +0 -0
@@ -66,13 +66,14 @@ export class ProportionalFormatter {
66
66
  anchor.prefixes.forEach((prefix) => array.push(...prefix.contexts));
67
67
  array.push(anchor.context);
68
68
  }
69
+ TickContext.linkTimeline(this.anchors.map((anchor) => anchor.context));
69
70
  array.forEach((context) => (context.tContexts = array));
70
71
  this.contexts = { map, array, list: this.anchors.map((anchor) => anchor.tick), resolutionMultiplier };
71
72
  }
72
73
  quarters(anchor) {
73
74
  return anchor.tick / this.contexts.resolutionMultiplier / this.quarterTicks;
74
75
  }
75
- measure() {
76
+ measure(proportional = true) {
76
77
  var _a, _b, _c, _d;
77
78
  this.origin = PADDING;
78
79
  this.tail = PADDING;
@@ -115,6 +116,8 @@ export class ProportionalFormatter {
115
116
  this.tail = Math.max(this.tail, extent.right + PADDING);
116
117
  }
117
118
  }
119
+ if (!proportional)
120
+ return;
118
121
  const previous = new Map();
119
122
  for (const anchor of this.anchors) {
120
123
  const time = this.quarters(anchor);
@@ -155,16 +158,61 @@ export class ProportionalFormatter {
155
158
  }
156
159
  return { scale, width: neededWidth };
157
160
  }
161
+ opticalLayout(width) {
162
+ var _a;
163
+ if (!Number.isFinite(width) || width < 0)
164
+ throw new RuntimeError('BadArgument', 'Width must be finite and nonnegative.');
165
+ this.measure(false);
166
+ const rightEdges = new Map();
167
+ const positions = [];
168
+ const weights = [];
169
+ let priorX = 0;
170
+ let time = 0;
171
+ let weight = 0;
172
+ for (const anchor of this.anchors) {
173
+ const onset = this.quarters(anchor);
174
+ let x = priorX + PADDING;
175
+ for (const [stave, extent] of anchor.extents)
176
+ x = Math.max(x, ((_a = rightEdges.get(stave)) !== null && _a !== void 0 ? _a : 0) + PADDING + extent.left);
177
+ for (const [stave, extent] of anchor.extents)
178
+ rightEdges.set(stave, x + extent.right);
179
+ weight += Math.sqrt(onset - time);
180
+ weights.push(weight);
181
+ positions.push(x);
182
+ priorX = x;
183
+ time = onset;
184
+ }
185
+ weight += Math.sqrt(this.duration - time);
186
+ const minimum = Math.max(this.centeredWidth + 2 * PADDING, priorX + PADDING, ...Array.from(rightEdges.values(), (x) => x + PADDING));
187
+ if (width > 0 && width + EPSILON < minimum)
188
+ throw new RuntimeError('InsufficientOpticalSpace', `Optical spacing requires at least ${required(minimum)} px width; received ${width.toFixed(2)} px.`);
189
+ const available = width || minimum;
190
+ return {
191
+ width: available,
192
+ center: available / 2,
193
+ positions: positions.map((x, i) => x + (weight ? weights[i] / weight : 0) * (available - minimum)),
194
+ };
195
+ }
158
196
  minimumWidth(spacing) {
197
+ if (spacing.mode === 'optical')
198
+ return this.opticalLayout(0).width;
159
199
  return this.dimensions(spacing, 0).width;
160
200
  }
161
- format(spacing, width) {
201
+ proportionalLayout(spacing, width) {
162
202
  const dimensions = this.dimensions(spacing, width);
163
- for (const anchor of this.anchors) {
164
- const x = this.origin + this.quarters(anchor) * dimensions.scale;
203
+ return {
204
+ width: dimensions.width,
205
+ center: this.origin + (this.duration * dimensions.scale) / 2,
206
+ positions: this.anchors.map((anchor) => this.origin + this.quarters(anchor) * dimensions.scale),
207
+ };
208
+ }
209
+ format(spacing, width) {
210
+ const { positions, center, width: usedWidth, } = spacing.mode === 'optical' ? this.opticalLayout(width) : this.proportionalLayout(spacing, width);
211
+ for (const [i, anchor] of this.anchors.entries()) {
212
+ const x = positions[i];
165
213
  anchor.context.setX(x);
166
214
  anchor.context.getCenterAlignedTickables().forEach((note) => {
167
- note.setCenterXShift(this.origin + (this.duration * dimensions.scale) / 2 - x);
215
+ note.setCenterXShift(center - x);
168
216
  });
169
217
  anchor.prefixes.forEach((prefix) => {
170
218
  const stave = prefix.contexts[0].getTickables()[0].getStave();
@@ -181,6 +229,6 @@ export class ProportionalFormatter {
181
229
  }
182
230
  });
183
231
  }
184
- return dimensions.width;
232
+ return usedWidth;
185
233
  }
186
234
  }
@@ -0,0 +1,402 @@
1
+ import { Factory } from './factory.js';
2
+ import { Metrics } from './metrics.js';
3
+ import { Note } from './note.js';
4
+ import { paginate } from './pagebreaks.js';
5
+ import { checkView, insetStaff, invalidPage, projectScore, restingMeasure } from './publicationview.js';
6
+ import { Registry } from './registry.js';
7
+ import { SVGContext } from './svgcontext.js';
8
+ import { Tables } from './tables.js';
9
+ const NS = 'http://www.w3.org/2000/svg';
10
+ function node(tag, attrs = {}) {
11
+ const el = document.createElementNS(NS, tag);
12
+ for (const [k, v] of Object.entries(attrs))
13
+ el.setAttribute(k, String(v));
14
+ return el;
15
+ }
16
+ function dimensions(o) {
17
+ var _a, _b, _c, _d;
18
+ const paper = (_a = o.paper) !== null && _a !== void 0 ? _a : 'A4';
19
+ const size = typeof paper === 'object'
20
+ ? paper
21
+ : paper === 'A4'
22
+ ? { width: 210, height: 297 }
23
+ : paper === 'Letter'
24
+ ? { width: 215.9, height: 279.4 }
25
+ : invalidPage('Unknown paper size.');
26
+ const margin = Object.assign({ top: 15, bottom: 15, left: 16, right: 16 }, o.margins);
27
+ const staff = (_b = o.staffSize) !== null && _b !== void 0 ? _b : 7, gap = (_c = o.systemGap) !== null && _c !== void 0 ? _c : 6, extra = (_d = o.maxExtraGap) !== null && _d !== void 0 ? _d : 12;
28
+ if ([...Object.values(margin), gap, extra].some((n) => !Number.isFinite(n) || n < 0) ||
29
+ [staff, size.width, size.height].some((n) => !Number.isFinite(n) || n <= 0))
30
+ invalidPage('Invalid print dimensions.');
31
+ const width = size.width - margin.left - margin.right;
32
+ if (width <= 0 || size.height <= margin.top + margin.bottom)
33
+ invalidPage('Margins consume the paper.');
34
+ return Object.assign(Object.assign({}, size), { margin, musicWidth: width, scale: staff / (4 * Tables.STAVE_LINE_DISTANCE), gap, extra });
35
+ }
36
+ function compose(host, spec) {
37
+ const ctx = new SVGContext(host);
38
+ const factory = new Factory({ renderer: { elementId: null, width: 1, height: 1 } }).setContext(ctx);
39
+ const score = factory.EasyScore().compose(spec);
40
+ return { ctx, factory, score };
41
+ }
42
+ function musicGroup(svg) {
43
+ const g = node('g');
44
+ for (const attr of Array.from(svg.attributes))
45
+ if (!['width', 'height', 'style', 'viewBox', 'xmlns', 'id', 'pointer-events'].includes(attr.name))
46
+ g.setAttribute(attr.name, attr.value);
47
+ return g;
48
+ }
49
+ function inkBox(el, context) {
50
+ var _a, _b;
51
+ let box;
52
+ if (el.tagName === 'g') {
53
+ const children = Array.from(el.children).flatMap((c) => { var _a; return (_a = inkBox(c, context)) !== null && _a !== void 0 ? _a : []; });
54
+ if (!children.length)
55
+ return;
56
+ const x = Math.min(...children.map((c) => c.x)), y = Math.min(...children.map((c) => c.y));
57
+ box = new DOMRect(x, y, Math.max(...children.map((c) => c.right)) - x, Math.max(...children.map((c) => c.bottom)) - y);
58
+ }
59
+ else if (el.tagName === 'text') {
60
+ const style = getComputedStyle(el);
61
+ context.font = style.fontStyle + ' ' + style.fontWeight + ' ' + style.fontSize + ' ' + style.fontFamily;
62
+ const m = context.measureText((_a = el.textContent) !== null && _a !== void 0 ? _a : '');
63
+ box = new DOMRect(Number(el.getAttribute('x')) - m.actualBoundingBoxLeft, Number(el.getAttribute('y')) - m.actualBoundingBoxAscent, m.actualBoundingBoxLeft + m.actualBoundingBoxRight, m.actualBoundingBoxAscent + m.actualBoundingBoxDescent);
64
+ }
65
+ else {
66
+ const native = el.getBBox();
67
+ box = new DOMRect(native.x, native.y, native.width, native.height);
68
+ }
69
+ if (![box.x, box.y, box.width, box.height].every(Number.isFinite))
70
+ invalidPage('Nonfinite SVG ink bounds.');
71
+ const matrix = (_b = el.transform.baseVal.consolidate()) === null || _b === void 0 ? void 0 : _b.matrix;
72
+ if (!matrix)
73
+ return box;
74
+ const corners = [
75
+ [box.x, box.y],
76
+ [box.right, box.y],
77
+ [box.x, box.bottom],
78
+ [box.right, box.bottom],
79
+ ].map(([x, y]) => new DOMPoint(x, y).matrixTransform(matrix));
80
+ const x = Math.min(...corners.map((p) => p.x)), y = Math.min(...corners.map((p) => p.y));
81
+ return new DOMRect(x, y, Math.max(...corners.map((p) => p.x)) - x, Math.max(...corners.map((p) => p.y)) - y);
82
+ }
83
+ function splitRows(svg, rows, score) {
84
+ const result = rows.map((row) => ({
85
+ measures: row.measures,
86
+ music: musicGroup(svg),
87
+ top: row.y,
88
+ bottom: row.y + row.height,
89
+ left: row.x,
90
+ right: row.x + row.width,
91
+ restAtEnd: restingMeasure(score, row.measures[row.measures.length - 1]),
92
+ insetHeight: 0,
93
+ insets: node('g'),
94
+ references: [],
95
+ }));
96
+ const edges = rows.slice(1).map((r, i) => (r.y + rows[i].y + rows[i].height) / 2);
97
+ const context = document.createElement('canvas').getContext('2d');
98
+ const elements = Array.from(svg.children, (child) => {
99
+ const el = child;
100
+ return { el, box: inkBox(el, context) };
101
+ });
102
+ for (const { el, box } of elements) {
103
+ if (!box)
104
+ continue;
105
+ const { top, bottom } = box;
106
+ let low = 0, high = edges.length;
107
+ while (low < high) {
108
+ const mid = (low + high) >>> 1;
109
+ if ((top + bottom) / 2 < edges[mid])
110
+ high = mid;
111
+ else
112
+ low = mid + 1;
113
+ }
114
+ const row = result[low];
115
+ row.top = Math.min(row.top, top);
116
+ row.bottom = Math.max(row.bottom, bottom);
117
+ row.left = Math.min(row.left, box.left);
118
+ row.right = Math.max(row.right, box.right);
119
+ row.music.append(el);
120
+ }
121
+ return result;
122
+ }
123
+ function label(host, text, size) {
124
+ var _a;
125
+ const el = node('text', {
126
+ 'font-family': (_a = Metrics.getFontInfo('Annotation').family) !== null && _a !== void 0 ? _a : 'Academico',
127
+ 'font-size': size + 'px',
128
+ fill: 'black',
129
+ stroke: 'none',
130
+ x: 0,
131
+ y: 0,
132
+ });
133
+ el.textContent = text;
134
+ host.append(el);
135
+ return { el, box: el.getBBox() };
136
+ }
137
+ function furniture(host, size, o, number) {
138
+ const group = node('g', { 'data-page-furniture': '' });
139
+ host.append(group);
140
+ const { margin, musicWidth } = size;
141
+ let y = margin.top;
142
+ let overflow = false;
143
+ function place(text, font, top, align) {
144
+ const { el, box } = label(group, text, font);
145
+ const x = margin.left +
146
+ (align === 'center' ? (musicWidth - box.width) / 2 : align === 'right' ? musicWidth - box.width : 0);
147
+ el.setAttribute('x', String(x - box.x));
148
+ el.setAttribute('y', String(top - box.y));
149
+ overflow || (overflow = box.width > musicWidth);
150
+ return box;
151
+ }
152
+ if (number === 1 && o.title)
153
+ y += place(o.title, 7, y, 'center').height + 2;
154
+ if (number === 1 && o.subtitle)
155
+ y += place(o.subtitle, 4, y, 'center').height + 2;
156
+ if (number > 1 && o.header)
157
+ y += place(o.header, 3.5, y, 'left').height + 2;
158
+ if (y !== margin.top)
159
+ y += 3;
160
+ let end = size.height - margin.bottom;
161
+ if (o.footer || o.pageNumbers !== false) {
162
+ const items = [];
163
+ if (o.footer)
164
+ items.push(place(o.footer, 3.3, 0, 'left'));
165
+ if (o.pageNumbers !== false)
166
+ items.push(place(String(number), 3.3, 0, 'right'));
167
+ const h = Math.max(...items.map((b) => b.height));
168
+ if (items.length > 1 && items[0].width + items[1].width + 2 > musicWidth)
169
+ overflow = true;
170
+ for (const el of Array.from(group.children).slice(-items.length)) {
171
+ el.setAttribute('y', String(Number(el.getAttribute('y')) + end - h));
172
+ }
173
+ end -= h + 4;
174
+ }
175
+ if (end <= y)
176
+ invalidPage('Title, margins and running furniture leave no music area.');
177
+ return { group, top: y, height: end - y, overflow };
178
+ }
179
+ function addInsets(host, spec, o, score, rows, diagnostics) {
180
+ var _a, _b;
181
+ for (const r of (_a = o.regions) !== null && _a !== void 0 ? _a : []) {
182
+ const row = rows.find((p) => p.measures.includes(r.measure));
183
+ const stave = score.staves[r.measure - 1][0], scale = (_b = r.scale) !== null && _b !== void 0 ? _b : 0.7;
184
+ const staff = insetStaff(spec.staves.find((s) => s.id === r.staff), r.measure);
185
+ const insetSpec = {
186
+ staves: [staff],
187
+ accidentals: spec.accidentals,
188
+ graceAccidentals: spec.graceAccidentals,
189
+ sheet: { x: 0, y: 0, width: stave.getWidth() / scale, measurePadding: 4 },
190
+ continuous: {},
191
+ };
192
+ const inset = compose(host, insetSpec);
193
+ inset.factory.draw();
194
+ row.references.push(Object.assign(Object.assign({}, r), { events: semanticEvents(inset.score, insetSpec, 1).map((e) => (Object.assign(Object.assign({}, e), { measure: r.measure }))) }));
195
+ const g = musicGroup(inset.ctx.svg);
196
+ while (inset.ctx.svg.firstChild)
197
+ g.append(inset.ctx.svg.firstChild);
198
+ inset.ctx.svg.append(g);
199
+ const ink = inkBox(g, document.createElement('canvas').getContext('2d'));
200
+ const caption = label(inset.ctx.svg, r.label, 12);
201
+ const wrap = node('g', { 'data-region': r.kind, 'data-source-staff': r.staff, 'data-measure': r.measure });
202
+ wrap.setAttribute('transform', `translate(${stave.getX()},${row.insetHeight})`);
203
+ caption.el.setAttribute('y', String(-caption.box.y));
204
+ g.setAttribute('transform', `translate(0,${caption.box.height + 2 - ink.y * scale}) scale(${scale})`);
205
+ const right = Math.max(ink.width * scale, caption.box.width);
206
+ if (right > stave.getWidth() + 1)
207
+ diagnostics.push({
208
+ code: 'SystemOverflow',
209
+ measures: [r.measure],
210
+ detail: r.kind + ' exceeds its measure width.',
211
+ });
212
+ wrap.append(caption.el, g);
213
+ row.insets.append(wrap);
214
+ row.insetHeight += caption.box.height + ink.height * scale + 8;
215
+ inset.ctx.svg.remove();
216
+ }
217
+ }
218
+ let nextView = 0;
219
+ function scopeIds(root, prefix) {
220
+ for (const [index, e] of Array.from(root.querySelectorAll('[id]')).entries()) {
221
+ const id = e.id;
222
+ e.setAttribute('data-vf-id', id);
223
+ e.id = prefix + '-' + index;
224
+ }
225
+ }
226
+ export class PublicationResult {
227
+ constructor(pages, diagnostics, paper) {
228
+ this.pages = pages;
229
+ this.diagnostics = diagnostics;
230
+ this.paper = paper;
231
+ }
232
+ toSVG(pageNumber, fonts) {
233
+ const page = this.pages[pageNumber - 1];
234
+ if (!Number.isInteger(pageNumber) || !page)
235
+ invalidPage('Unknown publication page.');
236
+ return SVGContext.toSVG(page.svg, fonts);
237
+ }
238
+ toPrintHTML(fonts) {
239
+ if (!(fonts === null || fonts === void 0 ? void 0 : fonts.length))
240
+ invalidPage('Supply outline fonts for portable print.');
241
+ if (this.diagnostics.some((d) => ['PageOverflow', 'TextOverflow', 'SystemOverflow'].includes(d.code)))
242
+ invalidPage('Resolve publication overflow before printing.');
243
+ const css = `@page{size:${this.paper.width}mm ${this.paper.height}mm;margin:0}html,body{margin:0}svg{display:block;break-after:page}svg:last-child{break-after:auto}`;
244
+ return ('<!doctype html><html><head><meta charset="utf-8"><title>Score</title><style>' +
245
+ css +
246
+ '</style></head><body>' +
247
+ this.pages.map((p) => this.toSVG(p.number, fonts)).join('') +
248
+ '</body></html>');
249
+ }
250
+ }
251
+ function semanticEvents(score, spec, measure) {
252
+ return score.notes[measure - 1].flatMap((voices, j) => voices.flatMap((ticks, voice) => ticks
253
+ .filter((t) => !t.shouldIgnoreTicks())
254
+ .flatMap((n, event) => n instanceof Note
255
+ ? [
256
+ Object.assign(Object.assign({ id: n.getAttribute('id'), measure, staff: spec.staves[j].id, voice,
257
+ event, keys: n.getKeys() }, (n.notation.length && { notation: n.notation })), { ticks: n.getTicks().toString(), rest: n.isRest() }),
258
+ ]
259
+ : [])));
260
+ }
261
+ function pageSurface(host, size) {
262
+ const svg = node('svg', {
263
+ width: size.width + 'mm',
264
+ height: size.height + 'mm',
265
+ viewBox: `0 0 ${size.width} ${size.height}`,
266
+ role: 'img',
267
+ });
268
+ host.append(svg);
269
+ return svg;
270
+ }
271
+ function buildPages(host, size, options, spec, score, measured, breaks, diagnostics) {
272
+ const uid = ++nextView;
273
+ return breaks.map((b, index) => {
274
+ var _a;
275
+ const number = index + 1;
276
+ const svg = pageSurface(host, size);
277
+ svg.append(node('rect', { width: size.width, height: size.height, fill: 'white' }));
278
+ const title = node('title');
279
+ title.textContent = ((_a = options.title) !== null && _a !== void 0 ? _a : 'Score') + ' · ' + number;
280
+ svg.append(title);
281
+ const f = furniture(svg, size, options, number);
282
+ const systems = b.offsets.map((offset, i) => {
283
+ const r = measured[b.first + i];
284
+ const x = size.margin.left + size.scale, y = f.top + offset;
285
+ const group = node('g', {
286
+ transform: `translate(${x},${y}) scale(${size.scale})`,
287
+ 'data-system': r.measures[0],
288
+ });
289
+ r.music.setAttribute('transform', `translate(0,${r.insetHeight - r.top})`);
290
+ group.append(r.insets, r.music);
291
+ svg.append(group);
292
+ if (r.left < -1.001 || x + r.right * size.scale > size.width - size.margin.right + 0.001)
293
+ diagnostics.push({
294
+ code: 'SystemOverflow',
295
+ page: number,
296
+ measures: r.measures,
297
+ detail: 'Ink outside the music width.',
298
+ });
299
+ return { measures: r.measures, x, y, width: (r.right - r.left) * size.scale, height: r.height };
300
+ });
301
+ const measures = systems.flatMap((s) => s.measures);
302
+ if (f.overflow)
303
+ diagnostics.push({
304
+ code: 'TextOverflow',
305
+ page: number,
306
+ measures,
307
+ detail: 'Page furniture exceeds the margin.',
308
+ });
309
+ if (b.overflow > 0.00001)
310
+ diagnostics.push({
311
+ code: 'PageOverflow',
312
+ page: number,
313
+ measures,
314
+ detail: `System exceeds music area by ${b.overflow.toFixed(2)} mm.`,
315
+ });
316
+ if (b.forbiddenTurn)
317
+ diagnostics.push({
318
+ code: 'ForbiddenTurn',
319
+ page: number,
320
+ measures: [measures[measures.length - 1]],
321
+ detail: 'No feasible pagination avoids this turn.',
322
+ });
323
+ const metadata = node('metadata');
324
+ metadata.textContent = JSON.stringify({
325
+ page: number,
326
+ measures,
327
+ staves: spec.staves.map((s) => s.id),
328
+ events: measures.flatMap((m) => semanticEvents(score, spec, m)),
329
+ regions: measured.slice(b.first, b.end).flatMap((row) => row.references),
330
+ spans: score.sheet
331
+ .getContinuousLayout()
332
+ .fragments.filter((f) => f.row >= b.first && f.row < b.end)
333
+ .map((f) => (Object.assign({ id: f.id, kind: f.kind, part: f.part }, (f.strings && { strings: f.strings, from: f.from, to: f.to })))),
334
+ text: Array.from(svg.querySelectorAll('text')).map((e) => e.textContent),
335
+ });
336
+ svg.append(metadata);
337
+ scopeIds(svg, 'vf-pub-' + uid + '-' + number);
338
+ return { number, svg, systems };
339
+ });
340
+ }
341
+ export class Publication {
342
+ constructor(source) {
343
+ this.source = source;
344
+ }
345
+ render(target, options = {}) {
346
+ var _a, _b, _c, _d, _e, _f;
347
+ checkView(this.source, options);
348
+ const size = dimensions(options);
349
+ const host = document.createElement('div');
350
+ host.style.cssText = 'position:absolute;left:0;top:0;visibility:hidden;pointer-events:none';
351
+ document.body.append(host);
352
+ const registry = Registry.getDefaultRegistry();
353
+ Registry.disableDefaultRegistry();
354
+ try {
355
+ const diagnostics = [];
356
+ const ref = options.staves &&
357
+ (((_a = this.source.spans) === null || _a === void 0 ? void 0 : _a.length) ||
358
+ ((_c = (_b = this.source.continuous) === null || _b === void 0 ? void 0 : _b.spans) === null || _c === void 0 ? void 0 : _c.length) ||
359
+ ((_e = (_d = this.source.continuous) === null || _d === void 0 ? void 0 : _d.splitChords) === null || _e === void 0 ? void 0 : _e.length))
360
+ ? compose(host, this.source).score
361
+ : undefined;
362
+ const width = size.musicWidth / size.scale - 2;
363
+ const spec = projectScore(this.source, options, width, ref, (id, measures) => diagnostics.push({ code: 'ExcludedAnchor', measures, detail: id }));
364
+ const { ctx, factory, score } = compose(host, spec);
365
+ factory.draw();
366
+ const layout = score.sheet.getContinuousLayout();
367
+ for (const d of layout.diagnostics)
368
+ diagnostics.push({
369
+ code: d.code === 'RowOverflow' ? 'SystemOverflow' : 'Engraving',
370
+ measures: d.measures,
371
+ detail: d.source ? d.code + ' ' + d.source : d.code,
372
+ });
373
+ const rows = splitRows(ctx.svg, layout.rows, score);
374
+ addInsets(host, this.source, options, score, rows, diagnostics);
375
+ const measured = rows.map((r) => (Object.assign(Object.assign({}, r), { height: (r.bottom - r.top + r.insetHeight) * size.scale })));
376
+ const surface = pageSurface(host, size);
377
+ const first = furniture(surface, size, options, 1);
378
+ first.group.remove();
379
+ const later = furniture(surface, size, options, 2);
380
+ surface.remove();
381
+ const breaks = paginate(measured, {
382
+ firstHeight: first.height,
383
+ laterHeight: later.height,
384
+ gap: size.gap,
385
+ maxExtraGap: size.extra,
386
+ justifyLast: (_f = options.justifyLast) !== null && _f !== void 0 ? _f : false,
387
+ part: !!options.staves,
388
+ forceBefore: new Set(options.pageBreaks),
389
+ preferAfter: new Set(options.preferredTurns),
390
+ forbidAfter: new Set(options.forbiddenTurns),
391
+ });
392
+ const pages = buildPages(host, size, options, spec, score, measured, breaks, diagnostics);
393
+ target.replaceChildren(...pages.map((p) => p.svg));
394
+ return new PublicationResult(pages, diagnostics, { width: size.width, height: size.height });
395
+ }
396
+ finally {
397
+ if (registry)
398
+ Registry.enableDefaultRegistry(registry);
399
+ host.remove();
400
+ }
401
+ }
402
+ }
@@ -0,0 +1,114 @@
1
+ import { Note } from './note.js';
2
+ import { Tickable } from './tickable.js';
3
+ import { RuntimeError } from './util.js';
4
+ export function invalidPage(message) {
5
+ throw new RuntimeError('BadPublication', message);
6
+ }
7
+ export function checkView(source, view) {
8
+ var _a, _b, _c, _d;
9
+ const staffIds = new Set(source.staves.map((s) => s.id));
10
+ const count = (_b = (_a = source.staves[0]) === null || _a === void 0 ? void 0 : _a.measures.length) !== null && _b !== void 0 ? _b : 0;
11
+ if (!count)
12
+ invalidPage('Expected at least one measure.');
13
+ const validMeasure = (n) => Number.isInteger(n) && n >= 1 && n <= count;
14
+ for (const values of [view.systemBreaks, view.pageBreaks, view.preferredTurns, view.forbiddenTurns])
15
+ if (values === null || values === void 0 ? void 0 : values.some((n) => !validMeasure(n)))
16
+ invalidPage('Break or turn outside the score.');
17
+ if (view.staves &&
18
+ (!view.staves.length ||
19
+ new Set(view.staves).size !== view.staves.length ||
20
+ view.staves.some((id) => !staffIds.has(id))))
21
+ invalidPage('Expected distinct source staff IDs.');
22
+ for (const region of (_c = view.regions) !== null && _c !== void 0 ? _c : []) {
23
+ const scale = (_d = region.scale) !== null && _d !== void 0 ? _d : 0.7;
24
+ if (!validMeasure(region.measure) ||
25
+ !staffIds.has(region.staff) ||
26
+ !region.label.trim() ||
27
+ !['cue', 'ossia'].includes(region.kind) ||
28
+ !Number.isFinite(scale) ||
29
+ scale <= 0 ||
30
+ scale > 1)
31
+ invalidPage('Expected a labeled cue or ossia on a source staff and measure with scale in (0, 1].');
32
+ }
33
+ for (const staff of source.staves)
34
+ for (const measure of staff.measures)
35
+ for (const voice of measure.voices)
36
+ if (typeof voice.notes !== 'string' && voice.notes.some((n) => n instanceof Tickable))
37
+ invalidPage('Use declarative events for independently rendered publication views.');
38
+ }
39
+ export function projectScore(source, view, width, reference, omitted) {
40
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
41
+ const selected = new Set((_a = view.staves) !== null && _a !== void 0 ? _a : source.staves.map((s) => s.id));
42
+ const staves = source.staves.filter((s) => selected.has(s.id)).map((s) => (view.staves ? homeStaff(s, selected) : s));
43
+ const owners = new Map();
44
+ reference === null || reference === void 0 ? void 0 : reference.notes.forEach((parts, m) => parts.forEach((voices, j) => {
45
+ for (const event of voices.flat())
46
+ owners.set(event, { staff: source.staves[j].id, measure: m + 1 });
47
+ }));
48
+ const keep = (a, b, id) => {
49
+ var _a, _b;
50
+ if (!reference)
51
+ return true;
52
+ const ends = [a, b].flatMap((name) => (name ? [owners.get(reference.getNote(name))] : []));
53
+ const included = ends.filter((e) => selected.has(e.staff));
54
+ if (included.length && included.length < ends.length)
55
+ omitted === null || omitted === void 0 ? void 0 : omitted((_b = (_a = id !== null && id !== void 0 ? id : a) !== null && _a !== void 0 ? _a : b) !== null && _b !== void 0 ? _b : '', ends.map((e) => e.measure));
56
+ return ends.length === included.length;
57
+ };
58
+ const original = (_b = source.continuous) !== null && _b !== void 0 ? _b : {};
59
+ const boundaries = new Map(((_c = original.boundaries) !== null && _c !== void 0 ? _c : []).map((b) => [b.measure, Object.assign({}, b)]));
60
+ if (boundaries.size !== ((_e = (_d = original.boundaries) === null || _d === void 0 ? void 0 : _d.length) !== null && _e !== void 0 ? _e : 0))
61
+ invalidPage('Expected unique source boundary measures.');
62
+ function boundary(n) {
63
+ let b = boundaries.get(n);
64
+ if (!b) {
65
+ b = { measure: n };
66
+ boundaries.set(n, b);
67
+ }
68
+ return b;
69
+ }
70
+ for (const n of [...((_f = view.systemBreaks) !== null && _f !== void 0 ? _f : []), ...((_g = view.pageBreaks) !== null && _g !== void 0 ? _g : [])])
71
+ boundary(n).breakBefore = 'force';
72
+ for (const region of (_h = view.regions) !== null && _h !== void 0 ? _h : [])
73
+ boundary(region.measure).keepRest = true;
74
+ return Object.assign(Object.assign({}, source), { staves, sheet: Object.assign(Object.assign({}, source.sheet), { x: 0, y: 0, rowGap: 150, width }), spans: (_j = source.spans) === null || _j === void 0 ? void 0 : _j.filter((s) => keep(s.from, s.to)), continuous: Object.assign(Object.assign({}, original), { boundaries: [...boundaries.values()], spans: (_k = original.spans) === null || _k === void 0 ? void 0 : _k.filter((s) => keep(s.from, s.to, s.id)), splitChords: (_l = original.splitChords) === null || _l === void 0 ? void 0 : _l.filter((c) => keep(c.upper, c.lower, c.id)), groups: !view.staves
75
+ ? original.groups
76
+ : (_m = original.groups) === null || _m === void 0 ? void 0 : _m.flatMap((g) => {
77
+ const start = source.staves.findIndex((s) => s.id === g.first), end = source.staves.findIndex((s) => s.id === g.last);
78
+ const members = source.staves.slice(start, end + 1).filter((s) => selected.has(s.id));
79
+ return members.length >= 2 ? [Object.assign(Object.assign({}, g), { first: members[0].id, last: members[members.length - 1].id })] : [];
80
+ }) }) });
81
+ }
82
+ function homeStaff(staff, selected) {
83
+ return Object.assign(Object.assign({}, staff), { measures: staff.measures.map((m) => (Object.assign(Object.assign({}, m), { voices: m.voices.map((v) => (Object.assign(Object.assign({}, v), { notes: typeof v.notes === 'string'
84
+ ? v.notes
85
+ : v.notes.map((n) => {
86
+ if (typeof n !== 'object' || !('stave' in n) || !n.stave || selected.has(n.stave))
87
+ return n;
88
+ if ('note' in n) {
89
+ const note = Object.assign({}, n.note);
90
+ delete note.clef;
91
+ return Object.assign(Object.assign({}, n), { stave: staff.id, note });
92
+ }
93
+ return Object.assign(Object.assign({}, n), { stave: staff.id });
94
+ }) }))) }))) });
95
+ }
96
+ export function insetStaff(staff, measure) {
97
+ var _a, _b, _c;
98
+ const state = { clef: staff.clef, key: staff.key, time: staff.time };
99
+ for (const m of staff.measures.slice(0, measure - 1)) {
100
+ state.clef = (_a = m.clef) !== null && _a !== void 0 ? _a : state.clef;
101
+ state.key = (_b = m.key) !== null && _b !== void 0 ? _b : state.key;
102
+ state.time = (_c = m.time) !== null && _c !== void 0 ? _c : state.time;
103
+ for (const v of m.voices.slice(0, 1))
104
+ if (typeof v.notes !== 'string')
105
+ for (const item of v.notes)
106
+ if (typeof item === 'object' && 'change' in item)
107
+ Object.assign(state, item.change);
108
+ }
109
+ return homeStaff(Object.assign(Object.assign(Object.assign({}, staff), state), { name: undefined, shortName: undefined, measures: [staff.measures[measure - 1]] }), new Set([staff.id]));
110
+ }
111
+ export function restingMeasure(score, number) {
112
+ const notes = score.notes[number - 1].flat(2).filter((n) => !n.shouldIgnoreTicks());
113
+ return notes.length > 0 && notes.every((n) => n instanceof Note && n.isRest());
114
+ }