@barmark/score 0.0.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +96 -0
- package/LICENSE +21 -0
- package/README.md +144 -1
- package/dist/element.d.ts +13 -0
- package/dist/element.js +435 -0
- package/dist/engine.d.ts +43 -0
- package/dist/engine.js +54 -0
- package/dist/engrave.d.ts +41 -0
- package/dist/engrave.js +78 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/markup.d.ts +25 -0
- package/dist/markup.js +242 -0
- package/dist/server.d.ts +14 -0
- package/dist/server.js +26 -0
- package/dist/shell.d.ts +9 -0
- package/dist/shell.js +16 -0
- package/dist/switch.d.ts +18 -0
- package/dist/switch.js +32 -0
- package/dist/worker.d.ts +8 -0
- package/dist/worker.js +52 -0
- package/package.json +59 -5
package/dist/element.js
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `<barmark-score>`: a chart as barmark's bar grid or as a full score, with a
|
|
3
|
+
* Grid / Score switch. Its chart comes from the `text` property, a `src` URL or
|
|
4
|
+
* a child `<script type="text/barmark">`, as `<barmark-chart>`'s does. A shadow
|
|
5
|
+
* root drawn by `renderScoreHtml` is reused. The score engine (Verovio, in a
|
|
6
|
+
* worker) loads on the first switch to the score, never before. Importing
|
|
7
|
+
* this module registers the element (once) and the font (once per document).
|
|
8
|
+
*/
|
|
9
|
+
import { FONT_FAMILY, fontFaceCss, renderChartUnwrapped, } from "@barmark/render";
|
|
10
|
+
import { chartSource, inlineChartText, optionsFromAttributes, } from "@barmark/render/element";
|
|
11
|
+
import { parseChart } from "barmark";
|
|
12
|
+
import { isLeipzigFace, scorePane } from "./markup.js";
|
|
13
|
+
import { decodeCarried, gridError, scoreShell } from "./shell.js";
|
|
14
|
+
import { viewOf } from "./switch.js";
|
|
15
|
+
let testEngine = null;
|
|
16
|
+
/** For tests only: an engine to use in place of the worker's, or null for the real one. */
|
|
17
|
+
export function setEngineForTests(factory) {
|
|
18
|
+
testEngine = factory;
|
|
19
|
+
}
|
|
20
|
+
let loading = null;
|
|
21
|
+
/** The page's engine, imported on first use; a failed import is tried again next time. */
|
|
22
|
+
function loadEngine() {
|
|
23
|
+
const factory = testEngine;
|
|
24
|
+
if (factory)
|
|
25
|
+
return Promise.resolve().then(factory);
|
|
26
|
+
loading ??= import("./engine.js").then((m) => m.engine(), (e) => {
|
|
27
|
+
loading = null;
|
|
28
|
+
throw e;
|
|
29
|
+
});
|
|
30
|
+
return loading;
|
|
31
|
+
}
|
|
32
|
+
const LOADING = "Loading score…";
|
|
33
|
+
/** The score's accessible name when the chart has no title. */
|
|
34
|
+
const UNTITLED = "Score";
|
|
35
|
+
const NOTE = "The score couldn't be drawn";
|
|
36
|
+
/** A width change smaller than this keeps the score as engraved. */
|
|
37
|
+
const SLACK = 8;
|
|
38
|
+
const RESIZE_DELAY = 150;
|
|
39
|
+
const ARROWS = new Set(["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"]);
|
|
40
|
+
/** Edwin, once per document, under the same marker `<barmark-chart>` uses, so either element adds it once. */
|
|
41
|
+
function addFont(doc) {
|
|
42
|
+
if (doc.querySelector("style[data-barmark-font]") !== null)
|
|
43
|
+
return;
|
|
44
|
+
// From dist/ (or src/), ../../render is @barmark/render, in the workspace and under node_modules/@barmark/.
|
|
45
|
+
const url = new URL("../../render/fonts/Edwin-Roman.otf", import.meta.url);
|
|
46
|
+
const font = Object.assign(doc.createElement("style"), { textContent: fontFaceCss(url.href) });
|
|
47
|
+
font.setAttribute("data-barmark-font", FONT_FAMILY);
|
|
48
|
+
doc.head.append(font);
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Verovio's Leipzig face (the ♯, ♭ and ♩ of chord symbols and tempo marks), once per
|
|
52
|
+
* document. Verovio declares it in a `<style>` inside the score's SVG, in the shadow
|
|
53
|
+
* root, where Chromium never registers a font face, so "C♯m7" drew as "C m7". The
|
|
54
|
+
* copy is the face `cleanSvg` already let through, checked again here.
|
|
55
|
+
*/
|
|
56
|
+
function addScoreFont(doc, pane) {
|
|
57
|
+
if (doc.querySelector("style[data-barmark-score-font]") !== null)
|
|
58
|
+
return;
|
|
59
|
+
const css = [...pane.querySelectorAll("style")]
|
|
60
|
+
.map((s) => s.textContent ?? "")
|
|
61
|
+
.find(isLeipzigFace);
|
|
62
|
+
if (!css)
|
|
63
|
+
return;
|
|
64
|
+
const font = Object.assign(doc.createElement("style"), { textContent: css });
|
|
65
|
+
font.setAttribute("data-barmark-score-font", "Leipzig");
|
|
66
|
+
doc.head.append(font);
|
|
67
|
+
}
|
|
68
|
+
const load = (src) => fetch(src).then((r) => r.ok ? r.text() : Promise.reject(new Error(`${r.status} ${r.statusText}`.trim())));
|
|
69
|
+
/** Text set on the element before it was defined is an own property; it is taken off and returned. */
|
|
70
|
+
function takeEarlyText(el) {
|
|
71
|
+
if (!Object.hasOwn(el, "text"))
|
|
72
|
+
return null;
|
|
73
|
+
const early = el.text;
|
|
74
|
+
Reflect.deleteProperty(el, "text");
|
|
75
|
+
return { text: early === null || early === undefined ? null : String(early) };
|
|
76
|
+
}
|
|
77
|
+
/** The grid's attributes, as `<barmark-chart>` observes them, then the score's own. */
|
|
78
|
+
const OBSERVED = [
|
|
79
|
+
...["src", "theme", "bar-numbers", "rehearsal-letters", "numerals", "wrap", "show-part"],
|
|
80
|
+
...["view", "verovio-url"],
|
|
81
|
+
];
|
|
82
|
+
const messageOf = (e) => (e instanceof Error ? e.message : String(e));
|
|
83
|
+
/** The radio a click or key landed on. */
|
|
84
|
+
const radioOf = (target) => target?.closest?.("[data-view]") ?? null;
|
|
85
|
+
const same = (a, b) => a !== null && a.text === b.text && Math.abs(a.width - b.width) <= SLACK;
|
|
86
|
+
const URL_REASON = "verovio-url must be an http(s) URL";
|
|
87
|
+
/** `verovio-url` resolved against the page: undefined when absent, null unless http(s). */
|
|
88
|
+
function verovioHref(value, base) {
|
|
89
|
+
if (value === null)
|
|
90
|
+
return undefined;
|
|
91
|
+
try {
|
|
92
|
+
const url = new URL(value, base);
|
|
93
|
+
return url.protocol === "http:" || url.protocol === "https:" ? url.href : null;
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
function defineElement() {
|
|
100
|
+
class BarmarkScore extends HTMLElement {
|
|
101
|
+
static observedAttributes = OBSERVED;
|
|
102
|
+
// Only the children are observed; some DOMs report attribute changes anyway, which are not the chart's.
|
|
103
|
+
#observer = new MutationObserver((records) => {
|
|
104
|
+
if (records.some((r) => r.type !== "attributes"))
|
|
105
|
+
this.#chartChanged();
|
|
106
|
+
});
|
|
107
|
+
#resize = null;
|
|
108
|
+
#resizeTimer;
|
|
109
|
+
#queued = null;
|
|
110
|
+
#renders = 0;
|
|
111
|
+
#engraves = 0;
|
|
112
|
+
#fetched = null;
|
|
113
|
+
#text = null;
|
|
114
|
+
/** The chart the grid shows: null when it could not be loaded, undefined until there is a source. */
|
|
115
|
+
#chart;
|
|
116
|
+
/** Whether the shadow root has been drawn (or a server-drawn one taken over). */
|
|
117
|
+
#drawn = false;
|
|
118
|
+
/** The view last shown, null before the first: a change from it fires `viewchange`. */
|
|
119
|
+
#shown = null;
|
|
120
|
+
#failed = false;
|
|
121
|
+
#engraved = null;
|
|
122
|
+
/** The engraving and theme the pane holds, so an unchanged one is not written again. */
|
|
123
|
+
#revealed = null;
|
|
124
|
+
#asked = null;
|
|
125
|
+
connectedCallback() {
|
|
126
|
+
const early = takeEarlyText(this);
|
|
127
|
+
if (early)
|
|
128
|
+
this.#text = early.text;
|
|
129
|
+
addFont(this.ownerDocument);
|
|
130
|
+
this.#observer.observe(this, { childList: true, subtree: true, characterData: true });
|
|
131
|
+
if (typeof ResizeObserver !== "undefined") {
|
|
132
|
+
this.#resize = new ResizeObserver(() => this.#resized());
|
|
133
|
+
this.#resize.observe(this);
|
|
134
|
+
}
|
|
135
|
+
this.#schedule();
|
|
136
|
+
}
|
|
137
|
+
disconnectedCallback() {
|
|
138
|
+
this.#observer.disconnect();
|
|
139
|
+
this.#resize?.disconnect();
|
|
140
|
+
this.#resize = null;
|
|
141
|
+
clearTimeout(this.#resizeTimer);
|
|
142
|
+
}
|
|
143
|
+
attributeChangedCallback(name, old, value) {
|
|
144
|
+
if (!this.isConnected || old === value)
|
|
145
|
+
return;
|
|
146
|
+
// A new URL may be the fix: the Score radio works again, as after a new chart.
|
|
147
|
+
if (name === "verovio-url")
|
|
148
|
+
this.#clearFailure();
|
|
149
|
+
else if (name === "view")
|
|
150
|
+
this.#applyView();
|
|
151
|
+
else if (name === "src")
|
|
152
|
+
this.#chartChanged();
|
|
153
|
+
else
|
|
154
|
+
this.#schedule();
|
|
155
|
+
}
|
|
156
|
+
/** Chart text to draw; while it is a string it wins over `src` and a script child. */
|
|
157
|
+
get text() {
|
|
158
|
+
return this.#text;
|
|
159
|
+
}
|
|
160
|
+
set text(value) {
|
|
161
|
+
this.#text = value == null ? null : `${value}`;
|
|
162
|
+
if (this.isConnected)
|
|
163
|
+
this.#chartChanged();
|
|
164
|
+
}
|
|
165
|
+
/** "grid" or "score"; anything else is the grid. */
|
|
166
|
+
get view() {
|
|
167
|
+
return viewOf(this.getAttribute("view"));
|
|
168
|
+
}
|
|
169
|
+
set view(v) {
|
|
170
|
+
this.setAttribute("view", viewOf(v));
|
|
171
|
+
}
|
|
172
|
+
#chartChanged() {
|
|
173
|
+
this.#clearFailure();
|
|
174
|
+
this.#schedule();
|
|
175
|
+
}
|
|
176
|
+
/** The `src` attribute, "" when absent. */
|
|
177
|
+
#src() {
|
|
178
|
+
return this.getAttribute("src") ?? "";
|
|
179
|
+
}
|
|
180
|
+
/** Changes made in one task (an upgrade sets each attribute in turn) draw once, in a microtask. */
|
|
181
|
+
#schedule() {
|
|
182
|
+
this.#queued ??= Promise.resolve().then(() => {
|
|
183
|
+
this.#queued = null;
|
|
184
|
+
return this.#render();
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
async #render() {
|
|
188
|
+
const ticket = ++this.#renders;
|
|
189
|
+
const options = optionsFromAttributes(this);
|
|
190
|
+
const script = this.querySelector('script[type="text/barmark"]');
|
|
191
|
+
const from = { text: this.#text, src: this.#src(), script: script !== null };
|
|
192
|
+
const source = chartSource(from);
|
|
193
|
+
const grid = await this.#grid(source, script, options);
|
|
194
|
+
if (ticket === this.#renders) {
|
|
195
|
+
this.#draw(source, grid, options);
|
|
196
|
+
this.#chart = grid.text;
|
|
197
|
+
this.#applyView();
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
async #grid(source, script, options) {
|
|
201
|
+
if (source === "none")
|
|
202
|
+
return { text: undefined, html: null };
|
|
203
|
+
try {
|
|
204
|
+
const text = await this.#chartText(source, script);
|
|
205
|
+
return { text, html: renderChartUnwrapped(text, options) };
|
|
206
|
+
}
|
|
207
|
+
catch (e) {
|
|
208
|
+
this.#fetched = null;
|
|
209
|
+
const message = `Could not load ${this.#src()}: ${messageOf(e)}`;
|
|
210
|
+
return { text: null, html: gridError(message, options.theme ?? "auto") };
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
#chartText(source, script) {
|
|
214
|
+
if (source === "text")
|
|
215
|
+
return this.#text ?? "";
|
|
216
|
+
if (source === "script")
|
|
217
|
+
return inlineChartText(decodeCarried(script?.textContent ?? ""));
|
|
218
|
+
const src = this.#src();
|
|
219
|
+
if (this.#fetched?.src !== src)
|
|
220
|
+
this.#fetched = { src, text: load(src) };
|
|
221
|
+
return this.#fetched.text;
|
|
222
|
+
}
|
|
223
|
+
/** Draws the grid, keeping a server-drawn one on upgrade (its script child is what it drew). */
|
|
224
|
+
#draw(source, grid, options) {
|
|
225
|
+
const hydrating = !this.#drawn && source === "script";
|
|
226
|
+
this.#drawn = true;
|
|
227
|
+
const { switcher, grid: pane, pane: score } = this.#parts();
|
|
228
|
+
if (pane && switcher && score) {
|
|
229
|
+
if (!hydrating)
|
|
230
|
+
this.#redraw(pane, grid.html, options);
|
|
231
|
+
}
|
|
232
|
+
else {
|
|
233
|
+
const root = this.shadowRoot ?? this.attachShadow({ mode: "open" });
|
|
234
|
+
// Grid is checked, as the server draws it: #applyView checks the view actually shown.
|
|
235
|
+
root.innerHTML = scoreShell(grid.html ?? renderChartUnwrapped("", options), "grid");
|
|
236
|
+
}
|
|
237
|
+
this.#wire();
|
|
238
|
+
}
|
|
239
|
+
/** New grid markup, or with no source of its own, the drawn grid takes the theme. */
|
|
240
|
+
#redraw(pane, html, options) {
|
|
241
|
+
if (html !== null)
|
|
242
|
+
pane.innerHTML = html;
|
|
243
|
+
else
|
|
244
|
+
pane.querySelector(".bm-chart")?.setAttribute("data-theme", options.theme ?? "auto");
|
|
245
|
+
}
|
|
246
|
+
#parts() {
|
|
247
|
+
const root = this.shadowRoot;
|
|
248
|
+
return {
|
|
249
|
+
switcher: root?.querySelector(".bms-switch") ?? null,
|
|
250
|
+
grid: root?.querySelector(".bms-grid") ?? null,
|
|
251
|
+
pane: root?.querySelector(".bms-pane") ?? null,
|
|
252
|
+
radios: [...(root?.querySelectorAll(".bms-switch [data-view]") ?? [])],
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
#wired = null;
|
|
256
|
+
#wire() {
|
|
257
|
+
const { switcher } = this.#parts();
|
|
258
|
+
if (!switcher || switcher === this.#wired)
|
|
259
|
+
return;
|
|
260
|
+
this.#wired = switcher;
|
|
261
|
+
switcher.addEventListener("click", (e) => this.#pick(radioOf(e.target)));
|
|
262
|
+
switcher.addEventListener("keydown", (e) => this.#key(e));
|
|
263
|
+
}
|
|
264
|
+
#pick(radio) {
|
|
265
|
+
if (!radio || radio.getAttribute("aria-disabled") === "true")
|
|
266
|
+
return;
|
|
267
|
+
this.view = viewOf(radio.getAttribute("data-view"));
|
|
268
|
+
}
|
|
269
|
+
/** The radio-group keys: an arrow moves to the other view and selects it; Space and Enter select. */
|
|
270
|
+
#key(e) {
|
|
271
|
+
const radio = radioOf(e.target);
|
|
272
|
+
if (!radio)
|
|
273
|
+
return;
|
|
274
|
+
if (e.key === " " || e.key === "Enter") {
|
|
275
|
+
e.preventDefault();
|
|
276
|
+
this.#pick(radio);
|
|
277
|
+
}
|
|
278
|
+
else if (ARROWS.has(e.key)) {
|
|
279
|
+
e.preventDefault();
|
|
280
|
+
const other = this.#parts().radios.find((r) => r !== radio) ?? null;
|
|
281
|
+
other?.focus?.();
|
|
282
|
+
this.#pick(other);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
/** Shows the view the attribute names, firing `viewchange` when it differs from the last. */
|
|
286
|
+
#applyView() {
|
|
287
|
+
if (!this.#drawn)
|
|
288
|
+
return;
|
|
289
|
+
const view = this.view;
|
|
290
|
+
if (view === "score" && this.#failed) {
|
|
291
|
+
this.view = "grid";
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
// A score waiting for its chart shows the grid, so Grid is the radio checked.
|
|
295
|
+
this.#check(view === "score" && this.#chart === undefined ? "grid" : view);
|
|
296
|
+
const was = this.#shown;
|
|
297
|
+
this.#shown = view;
|
|
298
|
+
if (was !== null && was !== view)
|
|
299
|
+
this.dispatchEvent(new CustomEvent("viewchange", { detail: { view }, bubbles: true, composed: true }));
|
|
300
|
+
if (view === "score")
|
|
301
|
+
this.#showScore();
|
|
302
|
+
else
|
|
303
|
+
this.#showGrid();
|
|
304
|
+
}
|
|
305
|
+
/** Checks the radio for `view` and makes it the one Tab reaches. */
|
|
306
|
+
#check(view) {
|
|
307
|
+
for (const r of this.#parts().radios) {
|
|
308
|
+
const on = r.getAttribute("data-view") === view;
|
|
309
|
+
r.setAttribute("aria-checked", String(on));
|
|
310
|
+
if (on)
|
|
311
|
+
r.removeAttribute("tabindex");
|
|
312
|
+
else
|
|
313
|
+
r.setAttribute("tabindex", "-1");
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
#showGrid() {
|
|
317
|
+
const { grid, pane } = this.#parts();
|
|
318
|
+
pane?.toggleAttribute("hidden", true);
|
|
319
|
+
grid?.toggleAttribute("hidden", false);
|
|
320
|
+
}
|
|
321
|
+
/** Shows the score, engraving it first unless the one in hand is for this chart and width. */
|
|
322
|
+
#showScore() {
|
|
323
|
+
// No source yet: the grid stays and the score is engraved once the chart arrives.
|
|
324
|
+
if (this.#chart === undefined)
|
|
325
|
+
return this.#showGrid();
|
|
326
|
+
if (this.#chart === null)
|
|
327
|
+
return this.#fail("there is no chart to engrave");
|
|
328
|
+
const want = { text: this.#chart, width: this.clientWidth || 0 };
|
|
329
|
+
if (this.#engraved && same(this.#engraved, want))
|
|
330
|
+
return this.#reveal(this.#engraved);
|
|
331
|
+
if (same(this.#asked, want))
|
|
332
|
+
return this.#busy();
|
|
333
|
+
const url = verovioHref(this.getAttribute("verovio-url"), this.ownerDocument.baseURI);
|
|
334
|
+
if (url === null)
|
|
335
|
+
return this.#fail(URL_REASON);
|
|
336
|
+
void this.#engrave(want, url);
|
|
337
|
+
}
|
|
338
|
+
/** Engraves `want`; only the newest request this element made is shown. */
|
|
339
|
+
async #engrave(want, url) {
|
|
340
|
+
this.#busy();
|
|
341
|
+
this.#asked = want;
|
|
342
|
+
const ask = ++this.#engraves;
|
|
343
|
+
let reply;
|
|
344
|
+
try {
|
|
345
|
+
reply = await (await loadEngine()).engrave(this, want.text, want.width, url);
|
|
346
|
+
}
|
|
347
|
+
catch (e) {
|
|
348
|
+
reply = { id: 0, ok: false, reason: messageOf(e) };
|
|
349
|
+
}
|
|
350
|
+
if (reply === null || ask !== this.#engraves)
|
|
351
|
+
return;
|
|
352
|
+
this.#asked = null;
|
|
353
|
+
if (!reply.ok)
|
|
354
|
+
return this.#fail(reply.reason);
|
|
355
|
+
const label = parseChart(want.text).title ?? UNTITLED;
|
|
356
|
+
this.#engraved = { ...want, svg: reply.svg, label };
|
|
357
|
+
if (this.view === "score")
|
|
358
|
+
this.#reveal(this.#engraved);
|
|
359
|
+
}
|
|
360
|
+
/** A score on its way: a shown one stays (busy) until the new one lands, else "Loading score…". */
|
|
361
|
+
#busy() {
|
|
362
|
+
const { grid, pane } = this.#parts();
|
|
363
|
+
if (!pane)
|
|
364
|
+
return;
|
|
365
|
+
if (this.#revealed === null)
|
|
366
|
+
pane.textContent = LOADING;
|
|
367
|
+
pane.setAttribute("aria-busy", "true");
|
|
368
|
+
pane.toggleAttribute("hidden", false);
|
|
369
|
+
grid?.toggleAttribute("hidden", true);
|
|
370
|
+
}
|
|
371
|
+
#reveal({ svg, label }) {
|
|
372
|
+
const { grid, pane } = this.#parts();
|
|
373
|
+
if (!pane)
|
|
374
|
+
return;
|
|
375
|
+
const theme = optionsFromAttributes(this).theme ?? "auto";
|
|
376
|
+
if (this.#revealed?.svg !== svg || this.#revealed.theme !== theme) {
|
|
377
|
+
try {
|
|
378
|
+
pane.innerHTML = scorePane(svg, theme, label);
|
|
379
|
+
addScoreFont(this.ownerDocument, pane);
|
|
380
|
+
}
|
|
381
|
+
catch (e) {
|
|
382
|
+
return this.#fail(messageOf(e));
|
|
383
|
+
}
|
|
384
|
+
this.#revealed = { svg, theme };
|
|
385
|
+
}
|
|
386
|
+
pane.removeAttribute("aria-busy");
|
|
387
|
+
pane.toggleAttribute("hidden", false);
|
|
388
|
+
grid?.toggleAttribute("hidden", true);
|
|
389
|
+
}
|
|
390
|
+
/** The score could not be drawn: the grid again, a note by the switch, Score disabled. */
|
|
391
|
+
#fail(reason) {
|
|
392
|
+
console.warn(`<barmark-score>: the score couldn't be drawn: ${reason}`);
|
|
393
|
+
this.#failed = true;
|
|
394
|
+
this.#asked = null;
|
|
395
|
+
this.#engraved = null;
|
|
396
|
+
this.#engraves++;
|
|
397
|
+
const { switcher, pane, radios } = this.#parts();
|
|
398
|
+
if (switcher && !this.shadowRoot?.querySelector(".bms-note")) {
|
|
399
|
+
const note = this.ownerDocument.createElement("p");
|
|
400
|
+
note.className = "bms-note";
|
|
401
|
+
note.setAttribute("role", "status");
|
|
402
|
+
note.textContent = NOTE;
|
|
403
|
+
switcher.after(note);
|
|
404
|
+
}
|
|
405
|
+
radios
|
|
406
|
+
.find((r) => r.getAttribute("data-view") === "score")
|
|
407
|
+
?.setAttribute("aria-disabled", "true");
|
|
408
|
+
this.#revealed = null;
|
|
409
|
+
pane?.replaceChildren();
|
|
410
|
+
pane?.removeAttribute("aria-busy");
|
|
411
|
+
this.#showGrid();
|
|
412
|
+
if (this.view === "score")
|
|
413
|
+
this.view = "grid";
|
|
414
|
+
}
|
|
415
|
+
#clearFailure() {
|
|
416
|
+
if (!this.#failed)
|
|
417
|
+
return;
|
|
418
|
+
this.#failed = false;
|
|
419
|
+
this.shadowRoot?.querySelector(".bms-note")?.remove();
|
|
420
|
+
for (const r of this.#parts().radios)
|
|
421
|
+
r.removeAttribute("aria-disabled");
|
|
422
|
+
}
|
|
423
|
+
/** A resize engraves again (if the width moved more than SLACK) once it settles. */
|
|
424
|
+
#resized() {
|
|
425
|
+
clearTimeout(this.#resizeTimer);
|
|
426
|
+
this.#resizeTimer = setTimeout(() => {
|
|
427
|
+
if (this.#shown === "score")
|
|
428
|
+
this.#showScore();
|
|
429
|
+
}, RESIZE_DELAY);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
customElements.define("barmark-score", BarmarkScore);
|
|
433
|
+
}
|
|
434
|
+
if (typeof customElements !== "undefined" && !customElements.get("barmark-score"))
|
|
435
|
+
defineElement();
|
package/dist/engine.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/** What a page asks the worker for: one chart, laid out for a width. */
|
|
2
|
+
export type Request = {
|
|
3
|
+
id: number;
|
|
4
|
+
text: string;
|
|
5
|
+
width: number;
|
|
6
|
+
verovioUrl?: string;
|
|
7
|
+
};
|
|
8
|
+
/** What the worker answers. No `xml` or `diagnostics` cross the boundary. */
|
|
9
|
+
export type Reply = {
|
|
10
|
+
id: number;
|
|
11
|
+
ok: true;
|
|
12
|
+
svg: string;
|
|
13
|
+
pages: number;
|
|
14
|
+
} | {
|
|
15
|
+
id: number;
|
|
16
|
+
ok: false;
|
|
17
|
+
reason: string;
|
|
18
|
+
};
|
|
19
|
+
/** An `EngraveReply` is a reply a page may show. */
|
|
20
|
+
export type EngraveReply = Reply;
|
|
21
|
+
/**
|
|
22
|
+
* The part of a `Worker` the engine uses, so a test can pass a fake. It is
|
|
23
|
+
* driven by the `onmessage` and `onerror` properties (a real `Worker`
|
|
24
|
+
* satisfies this), not by `addEventListener`.
|
|
25
|
+
*/
|
|
26
|
+
export interface WorkerLike {
|
|
27
|
+
postMessage(request: Request): void;
|
|
28
|
+
terminate(): void;
|
|
29
|
+
onmessage: ((e: MessageEvent<Reply>) => void) | null;
|
|
30
|
+
onerror: ((e: ErrorEvent) => void) | null;
|
|
31
|
+
}
|
|
32
|
+
export type Engine = {
|
|
33
|
+
/**
|
|
34
|
+
* Engrave `text` for `width`. Per `key` (the element) only the newest
|
|
35
|
+
* request resolves with a reply; an older one resolves `null`. Rejects
|
|
36
|
+
* with "The score engine failed" if the worker crashes.
|
|
37
|
+
*/
|
|
38
|
+
engrave(key: object, text: string, width: number, verovioUrl?: string): Promise<EngraveReply | null>;
|
|
39
|
+
};
|
|
40
|
+
/** An engine over one worker made on first use; a crashed worker is replaced on the next call. */
|
|
41
|
+
export declare function createEngine(makeWorker: () => WorkerLike): Engine;
|
|
42
|
+
/** The page's single shared engine, over one real module `Worker` made on first use. */
|
|
43
|
+
export declare function engine(): Engine;
|
package/dist/engine.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/** An engine over one worker made on first use; a crashed worker is replaced on the next call. */
|
|
2
|
+
export function createEngine(makeWorker) {
|
|
3
|
+
let worker = null;
|
|
4
|
+
let nextId = 0;
|
|
5
|
+
const pending = new Map();
|
|
6
|
+
const newest = new WeakMap();
|
|
7
|
+
const fail = (w) => {
|
|
8
|
+
if (worker !== w)
|
|
9
|
+
return;
|
|
10
|
+
worker = null;
|
|
11
|
+
w.terminate();
|
|
12
|
+
const all = [...pending.values()];
|
|
13
|
+
pending.clear();
|
|
14
|
+
for (const p of all)
|
|
15
|
+
p.reject(new Error("The score engine failed"));
|
|
16
|
+
};
|
|
17
|
+
const start = () => {
|
|
18
|
+
if (worker)
|
|
19
|
+
return worker;
|
|
20
|
+
const w = makeWorker();
|
|
21
|
+
w.onmessage = (e) => {
|
|
22
|
+
const p = pending.get(e.data.id);
|
|
23
|
+
if (!p)
|
|
24
|
+
return;
|
|
25
|
+
pending.delete(e.data.id);
|
|
26
|
+
p.resolve(newest.get(p.key) === e.data.id ? e.data : null);
|
|
27
|
+
};
|
|
28
|
+
w.onerror = () => fail(w);
|
|
29
|
+
worker = w;
|
|
30
|
+
return w;
|
|
31
|
+
};
|
|
32
|
+
return {
|
|
33
|
+
engrave(key, text, width, verovioUrl) {
|
|
34
|
+
const w = start();
|
|
35
|
+
const id = ++nextId;
|
|
36
|
+
const before = newest.get(key);
|
|
37
|
+
if (before !== undefined) {
|
|
38
|
+
pending.get(before)?.resolve(null);
|
|
39
|
+
pending.delete(before);
|
|
40
|
+
}
|
|
41
|
+
newest.set(key, id);
|
|
42
|
+
return new Promise((resolve, reject) => {
|
|
43
|
+
pending.set(id, { key, resolve, reject });
|
|
44
|
+
w.postMessage(verovioUrl === undefined ? { id, text, width } : { id, text, width, verovioUrl });
|
|
45
|
+
});
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
let shared;
|
|
50
|
+
/** The page's single shared engine, over one real module `Worker` made on first use. */
|
|
51
|
+
export function engine() {
|
|
52
|
+
shared ??= createEngine(() => new Worker(new URL("./worker.js", import.meta.url), { type: "module" }));
|
|
53
|
+
return shared;
|
|
54
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { ChartDiagnostic } from "barmark";
|
|
2
|
+
import type { VerovioToolkit } from "verovio/esm";
|
|
3
|
+
export type EngraveOptions = {
|
|
4
|
+
/** The width available, in CSS pixels; below 320 it is 320. */
|
|
5
|
+
width: number;
|
|
6
|
+
/** Verovio's scale (default 40). */
|
|
7
|
+
scale?: number;
|
|
8
|
+
};
|
|
9
|
+
export type Engraved = {
|
|
10
|
+
ok: true;
|
|
11
|
+
svg: string;
|
|
12
|
+
pages: number;
|
|
13
|
+
xml: string;
|
|
14
|
+
} | {
|
|
15
|
+
ok: false;
|
|
16
|
+
reason: string;
|
|
17
|
+
diagnostics: ChartDiagnostic[];
|
|
18
|
+
};
|
|
19
|
+
/** Verovio's options for a score, all but `pageWidth` and `scale`. */
|
|
20
|
+
export declare const LAYOUT: {
|
|
21
|
+
readonly pageHeight: 60000;
|
|
22
|
+
readonly adjustPageHeight: true;
|
|
23
|
+
readonly breaks: "auto";
|
|
24
|
+
readonly svgViewBox: true;
|
|
25
|
+
readonly footer: "none";
|
|
26
|
+
readonly header: "auto";
|
|
27
|
+
readonly justifyVertically: false;
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* The MusicXML as Verovio should read it. Verovio 6.4 appends every chord <degree> to the
|
|
31
|
+
* kind text, `print-object="no"` or not, so a degree the text already spells is drawn twice
|
|
32
|
+
* (`D7sus4(7)`); a degree that is not printed is dropped, which changes nothing it draws.
|
|
33
|
+
*/
|
|
34
|
+
export declare function forVerovio(xml: string): string;
|
|
35
|
+
/** MusicXML laid out for a width, every page as SVG in a `bms-score-page` div. Throws on unreadable XML. */
|
|
36
|
+
export declare function engraveXml(vrv: VerovioToolkit, xml: string, options: EngraveOptions): {
|
|
37
|
+
svg: string;
|
|
38
|
+
pages: number;
|
|
39
|
+
};
|
|
40
|
+
/** A chart as a full score, or why it cannot be one. */
|
|
41
|
+
export declare function engraveChart(vrv: VerovioToolkit, text: string, options: EngraveOptions): Engraved;
|
package/dist/engrave.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { exportMusicXml } from "@barmark/musicxml";
|
|
2
|
+
import { cleanSvg } from "./markup.js";
|
|
3
|
+
/** Verovio's options for a score, all but `pageWidth` and `scale`. */
|
|
4
|
+
export const LAYOUT = {
|
|
5
|
+
pageHeight: 60000,
|
|
6
|
+
adjustPageHeight: true,
|
|
7
|
+
breaks: "auto",
|
|
8
|
+
svgViewBox: true,
|
|
9
|
+
footer: "none",
|
|
10
|
+
header: "auto",
|
|
11
|
+
justifyVertically: false,
|
|
12
|
+
};
|
|
13
|
+
const DEFAULT_SCALE = 40;
|
|
14
|
+
const MIN_WIDTH = 320;
|
|
15
|
+
const HIDDEN_DEGREE = '<degree print-object="no">';
|
|
16
|
+
const DEGREE_END = "</degree>";
|
|
17
|
+
/**
|
|
18
|
+
* The MusicXML as Verovio should read it. Verovio 6.4 appends every chord <degree> to the
|
|
19
|
+
* kind text, `print-object="no"` or not, so a degree the text already spells is drawn twice
|
|
20
|
+
* (`D7sus4(7)`); a degree that is not printed is dropped, which changes nothing it draws.
|
|
21
|
+
*/
|
|
22
|
+
export function forVerovio(xml) {
|
|
23
|
+
// One pass with indexOf, never a backtracking regex: an opener with no closer ends the
|
|
24
|
+
// search, so a hostile file of openers costs linear time, not a rescan per opener.
|
|
25
|
+
const parts = [];
|
|
26
|
+
let from = 0;
|
|
27
|
+
for (;;) {
|
|
28
|
+
const open = xml.indexOf(HIDDEN_DEGREE, from);
|
|
29
|
+
if (open < 0)
|
|
30
|
+
break;
|
|
31
|
+
const close = xml.indexOf(DEGREE_END, open + HIDDEN_DEGREE.length);
|
|
32
|
+
if (close < 0)
|
|
33
|
+
break;
|
|
34
|
+
parts.push(xml.slice(from, open));
|
|
35
|
+
from = close + DEGREE_END.length;
|
|
36
|
+
}
|
|
37
|
+
parts.push(xml.slice(from));
|
|
38
|
+
return parts.join("");
|
|
39
|
+
}
|
|
40
|
+
/** MusicXML laid out for a width, every page as SVG in a `bms-score-page` div. Throws on unreadable XML. */
|
|
41
|
+
export function engraveXml(vrv, xml, options) {
|
|
42
|
+
const scale = options.scale ?? DEFAULT_SCALE;
|
|
43
|
+
vrv.setOptions({
|
|
44
|
+
...LAYOUT,
|
|
45
|
+
scale,
|
|
46
|
+
// Verovio's page width is in its own units at scale 100.
|
|
47
|
+
pageWidth: Math.round((Math.max(MIN_WIDTH, options.width) * 100) / scale),
|
|
48
|
+
});
|
|
49
|
+
if (!vrv.loadData(forVerovio(xml)))
|
|
50
|
+
throw new Error("Verovio could not read the score");
|
|
51
|
+
const pages = vrv.getPageCount();
|
|
52
|
+
if (pages < 1)
|
|
53
|
+
throw new Error("The score has no pages");
|
|
54
|
+
const svgs = [];
|
|
55
|
+
for (let p = 1; p <= pages; p++)
|
|
56
|
+
svgs.push(`<div class="bms-score-page">${vrv.renderToSVG(p)}</div>`);
|
|
57
|
+
return { svg: svgs.join(""), pages };
|
|
58
|
+
}
|
|
59
|
+
function refusal(diagnostics) {
|
|
60
|
+
const first = diagnostics.find((d) => d.severity === "error") ?? diagnostics[0];
|
|
61
|
+
if (!first)
|
|
62
|
+
return "The chart has no bars";
|
|
63
|
+
// A diagnostic about the whole chart has line 0: there is no line to name.
|
|
64
|
+
return first.line > 0 ? `Line ${first.line}: ${first.message}` : first.message;
|
|
65
|
+
}
|
|
66
|
+
/** A chart as a full score, or why it cannot be one. */
|
|
67
|
+
export function engraveChart(vrv, text, options) {
|
|
68
|
+
const exported = exportMusicXml(text);
|
|
69
|
+
if (!exported.ok)
|
|
70
|
+
return { ok: false, reason: refusal(exported.diagnostics), diagnostics: exported.diagnostics };
|
|
71
|
+
try {
|
|
72
|
+
const engraved = engraveXml(vrv, exported.xml, options);
|
|
73
|
+
return { ok: true, xml: exported.xml, pages: engraved.pages, svg: cleanSvg(engraved.svg) };
|
|
74
|
+
}
|
|
75
|
+
catch (e) {
|
|
76
|
+
return { ok: false, reason: e instanceof Error ? e.message : String(e), diagnostics: [] };
|
|
77
|
+
}
|
|
78
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { createEngine, type Engine, type EngraveReply, engine, type Reply, type Request, type WorkerLike, } from "./engine.js";
|
|
2
|
+
export { type Engraved, type EngraveOptions, engraveChart, engraveXml, LAYOUT } from "./engrave.js";
|
|
3
|
+
export { cleanSvg, type ScoreTheme, scorePane, scoreStyles } from "./markup.js";
|
package/dist/index.js
ADDED