@barmark/score 0.2.0 → 0.3.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.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,47 @@ package uses [semantic versioning](https://semver.org/).
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.3.0] - 2026-11-10
10
+
11
+ ### Added
12
+
13
+ - **Loading progress.** While its first score waits, `<barmark-score>`
14
+ shows a themed status region (`role="status"`) and progress bar in
15
+ three phases: "Loading the score engine…" (with a percentage while the
16
+ download can be measured, and "X of Y MB" only when Y is the size
17
+ actually transferred), "Preparing…" while Verovio's WebAssembly
18
+ compiles and "Engraving…". Each phase is announced once; the bar
19
+ carries the percentage and stands still under `prefers-reduced-motion`.
20
+ A `verovio-url` is now downloaded by the worker with progress and
21
+ imported from a `blob:` URL. A compressed response is measured against
22
+ Verovio's decoded size (`VEROVIO_MODULE_BYTES`), never against its
23
+ compressed `Content-Length`, so the bar never runs past 100%. The
24
+ worker's new `Progress` message carries it (`LoadStatus`), and
25
+ `Engine.engrave` takes an `EngraveCall` with `onStatus`
26
+ (`EngineStatus`).
27
+ - **`verovio-integrity`.** With an SRI digest (`sha256-`, `sha384-` or
28
+ `sha512-`), the worker checks the `verovio-url` copy with
29
+ `crypto.subtle` before importing it, and on a mismatch or any failure
30
+ to load it warns, naming the reason, and loads the package's own copy
31
+ instead, once. `VEROVIO_CDN_URL` and `VEROVIO_CDN_INTEGRITY` are
32
+ Verovio 6.4.1 on jsDelivr and its sha384, with `VEROVIO_VERSION` and
33
+ the `VerovioSource` type.
34
+ - **`preload`.** `"intent"` starts loading Verovio on the first pointer,
35
+ focus or touch on the Score switch; `"idle"` once the page is idle
36
+ (`requestIdleCallback`, or half a second later), or on intent when the
37
+ reader saves data or is on 2G. `"none"`, the default, keeps today's
38
+ behaviour. A preload loads the engine only, shares the page's one load
39
+ and does nothing the second time (`Engine.preload`).
40
+
41
+ ### Changed
42
+
43
+ - **Verovio is pinned exactly at 6.4.1** (was `^6.4.1`): the decoded size
44
+ and the CDN digest are those of that build.
45
+ - **A `verovio-url` is fetched, then imported from a `blob:` URL**, with
46
+ or without `verovio-integrity`, where the worker used to `import()` it
47
+ directly. A worker served with its own Content-Security-Policy needs
48
+ the module's origin in `connect-src` and `blob:` in `script-src`.
49
+
9
50
  ## [0.2.0] - 2026-11-09
10
51
 
11
52
  ### Added
@@ -146,7 +187,8 @@ First release.
146
187
  needs no config; Vite 7 needs `optimizeDeps.exclude` and
147
188
  `worker.format: "es"`.
148
189
 
149
- [Unreleased]: https://github.com/kevinpeckham/barmark/compare/score-v0.2.0...HEAD
190
+ [Unreleased]: https://github.com/kevinpeckham/barmark/compare/score-v0.3.0...HEAD
191
+ [0.3.0]: https://github.com/kevinpeckham/barmark/compare/score-v0.2.0...score-v0.3.0
150
192
  [0.2.0]: https://github.com/kevinpeckham/barmark/compare/score-v0.1.1...score-v0.2.0
151
193
  [0.1.1]: https://github.com/kevinpeckham/barmark/compare/score-v0.1.0...score-v0.1.1
152
194
  [0.1.0]: https://github.com/kevinpeckham/barmark/releases/tag/score-v0.1.0
package/README.md CHANGED
@@ -14,9 +14,9 @@ npm install @barmark/score
14
14
  - **`<barmark-chart>`** from [`@barmark/render`](../render/) is the light
15
15
  one: the bar grid, no Verovio.
16
16
  - **`<barmark-score>`** from this package is the heavier one: the same grid,
17
- plus a Grid / Score switch to a full score. Verovio (about 7 MB) loads
18
- only on the first switch to the score, never on page load, and one copy
19
- serves every score on the page.
17
+ plus a Grid / Score switch to a full score. Verovio (about 7 MB, 2.4 MB
18
+ gzipped) loads on the first switch to the score, never on page load
19
+ unless you ask (`preload`), and one copy serves every score on the page.
20
20
 
21
21
  Use `<barmark-chart>` when the grid is enough.
22
22
 
@@ -49,6 +49,8 @@ technology the score is one image named for the chart's title, or "Score".
49
49
  | `src`, `theme`, `bar-numbers`, `rehearsal-letters`, `numerals`, `wrap`, `show-part` | the grid's own, as in [`@barmark/render`](../render/README.md#options-and-attributes) |
50
50
  | `view` (`view`) | `"grid"` (default) or `"score"`; the view being shown. Set before the chart arrives, `"score"` waits for it |
51
51
  | `verovio-url` | where to load Verovio from (below) |
52
+ | `verovio-integrity` | the SRI digest (`sha384-…`) the `verovio-url` copy must have; on a mismatch the package's own copy loads (below) |
53
+ | `preload` | `"none"` (default), `"intent"` or `"idle"`: when to start loading Verovio (below) |
52
54
 
53
55
  The `text` property is the chart's text (`null` goes back to `src` or the
54
56
  script child). The element fires a `viewchange` event, with
@@ -89,7 +91,83 @@ bundling the 7 MB inside the worker; it only changes where that module
89
91
  comes from. The URL is resolved against the page and must be http(s);
90
92
  anything else is refused and the score is not drawn. The first
91
93
  `verovio-url` that loads wins for the whole page: every element shares one
92
- worker, so a later or different URL is not loaded.
94
+ worker, so a later or different URL is not loaded. The worker downloads a
95
+ `verovio-url` with `fetch` (with or without `verovio-integrity`) and
96
+ imports it from a `blob:` URL, so a worker served with its own
97
+ Content-Security-Policy needs the module's origin (a CDN's, say) in
98
+ `connect-src` and `blob:` in `script-src`.
99
+
100
+ ### While the score loads
101
+
102
+ The first score waits for Verovio to download and compile. Until it is
103
+ drawn, the score pane shows a status region (`role="status"`) with a
104
+ progress bar, in three phases:
105
+
106
+ 1. **Loading the score engine…**, with how far the download has come
107
+ when that can be measured: a percentage, and "3.1 of 7.4 MB" only when
108
+ the total is the size actually transferred.
109
+ 2. **Preparing…** while the worker compiles Verovio's WebAssembly.
110
+ 3. **Engraving…** while the chart is engraved.
111
+
112
+ The live region speaks each phase once; the percentage is the progress
113
+ bar's value. With `prefers-reduced-motion`, the bar does not animate.
114
+
115
+ The download can be measured when the worker fetches Verovio itself,
116
+ which it does for a `verovio-url`: it reads the response as it arrives,
117
+ then imports the module from a `blob:` URL. A compressed response (gzip,
118
+ brotli) has a `Content-Length` that is the compressed size, while the
119
+ bytes read are decoded, so they are measured against Verovio's known
120
+ decoded size (`VEROVIO_MODULE_BYTES`) instead; an uncompressed one is
121
+ measured against its `Content-Length` (a cross-origin server that does
122
+ not expose `Content-Encoding` is taken as compressed when its length is
123
+ short of that size); anything else shows the bar without a percentage.
124
+ The package's own copy, without `verovio-url`, is loaded by your
125
+ bundler, so its download is shown without a percentage; so is a worker
126
+ bundled with Verovio inside it, whose download is the worker's own
127
+ script.
128
+
129
+ ### A copy from a CDN
130
+
131
+ `verovio-url` can point at a public copy of the exact Verovio this
132
+ package uses, checked with `verovio-integrity`. For Verovio 6.4.1 on
133
+ jsDelivr (served with CORS `*` and cached as immutable):
134
+
135
+ ```html
136
+ <barmark-score
137
+ verovio-url="https://cdn.jsdelivr.net/npm/verovio@6.4.1/dist/verovio-module.mjs"
138
+ verovio-integrity="sha384-iGNyhtxpKLNw90cjbI9ES538TJtbNZjLxsFVUuI8PwE2TTNQ+i2j9CjQnRMhZXHk"
139
+ src="/charts/peaceful-dreams.chart.md"
140
+ ></barmark-score>
141
+ ```
142
+
143
+ The package exports both as `VEROVIO_CDN_URL` and `VEROVIO_CDN_INTEGRITY`
144
+ (with `VEROVIO_VERSION`). With `verovio-integrity` set, the worker
145
+ downloads the URL, checks its digest (`sha256-`, `sha384-` or `sha512-`)
146
+ with `crypto.subtle` before importing it, and on a mismatch or any
147
+ failure to load it warns in the console, naming the reason, and loads the
148
+ package's own copy instead, once. Without `verovio-integrity` there is no
149
+ fallback: a `verovio-url` that fails is a score that can't be drawn. A
150
+ malformed digest is refused like a bad URL.
151
+
152
+ A CDN does not save your readers a download they made on another site:
153
+ browsers partition their caches by site, so each site's readers fetch
154
+ Verovio once for that site whichever URL it comes from. What a CDN gives
155
+ is delivery from an edge near the reader and the 2.4 MB kept off your own
156
+ server.
157
+
158
+ ### Preloading
159
+
160
+ `preload` starts loading Verovio before the first press, so the score
161
+ comes sooner. It only loads the engine (nothing is engraved), shares the
162
+ one load every element on the page uses, and asking twice does nothing.
163
+
164
+ - `"none"` (the default): Verovio loads on the first switch to the score.
165
+ - `"intent"`: on the first pointer over, focus on or touch of the Score
166
+ switch.
167
+ - `"idle"`: once the page is idle after the element connects
168
+ (`requestIdleCallback`, or half a second later where there is none).
169
+ When the reader has asked to save data, or is on a 2G connection
170
+ (`navigator.connection`), it waits for intent instead.
93
171
 
94
172
  ### When the score can't be drawn
95
173
 
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Downloading a Verovio module with progress, and checking its digest.
3
+ * Verovio-free: the worker uses it before any Verovio is loaded.
4
+ */
5
+ /**
6
+ * How far a download has come: `fraction` from 0 to 1, or null when it
7
+ * cannot be known; `bytes` only when its total is the real transfer size.
8
+ */
9
+ export type Download = {
10
+ phase: "download";
11
+ fraction: number | null;
12
+ bytes: {
13
+ done: number;
14
+ total: number;
15
+ } | null;
16
+ };
17
+ /**
18
+ * Measures a download whose body arrives decoded. With Content-Encoding,
19
+ * Content-Length is the compressed size, so decoded bytes are measured
20
+ * against it only when the response is not encoded; otherwise against
21
+ * `expected`, the module's decoded size, when known; otherwise not at all.
22
+ * A `crossOrigin` response hides Content-Encoding unless the server
23
+ * exposes it, so there a length short of `expected` is taken as
24
+ * compressed. A body that outgrows the length it is measured against is
25
+ * measured by the next rule.
26
+ */
27
+ export declare function downloadMeter(headers: Headers, expected?: number, crossOrigin?: boolean): (decoded: number) => Download;
28
+ /** "42%", with "(3.1 of 7.4 MB)" when the total is the real transfer size; "" when unknown. */
29
+ export declare function progressText(d: Download): string;
30
+ /** Whether `integrity` is one SRI digest this package checks: sha256, sha384 or sha512. */
31
+ export declare const isIntegrity: (integrity: string) => boolean;
32
+ /** Whether `bytes` have the SRI digest `integrity` (`sha384-…`); anything else fails. */
33
+ export declare function checkIntegrity(bytes: BufferSource, integrity: string): Promise<boolean>;
34
+ export type FetchModuleOptions = {
35
+ fetch: (url: string) => Promise<Response>;
36
+ onProgress: (d: Download) => void;
37
+ /** The SRI digest the module must have; checked before it is returned. */
38
+ integrity?: string;
39
+ /** The module's decoded size, when known. */
40
+ expected?: number;
41
+ };
42
+ /** Downloads the module at `url` with progress, as a JavaScript blob ready to import from an object URL. */
43
+ export declare function fetchModule(url: string, options: FetchModuleOptions): Promise<Blob>;
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Downloading a Verovio module with progress, and checking its digest.
3
+ * Verovio-free: the worker uses it before any Verovio is loaded.
4
+ */
5
+ const unknown = () => ({ phase: "download", fraction: null, bytes: null });
6
+ const lengthOf = (headers) => {
7
+ const n = Number(headers.get("content-length") ?? "");
8
+ return Number.isSafeInteger(n) && n > 0 ? n : null;
9
+ };
10
+ const encoded = (headers) => {
11
+ const e = headers.get("content-encoding")?.trim().toLowerCase();
12
+ return e !== undefined && e !== "" && e !== "identity";
13
+ };
14
+ /**
15
+ * Measures a download whose body arrives decoded. With Content-Encoding,
16
+ * Content-Length is the compressed size, so decoded bytes are measured
17
+ * against it only when the response is not encoded; otherwise against
18
+ * `expected`, the module's decoded size, when known; otherwise not at all.
19
+ * A `crossOrigin` response hides Content-Encoding unless the server
20
+ * exposes it, so there a length short of `expected` is taken as
21
+ * compressed. A body that outgrows the length it is measured against is
22
+ * measured by the next rule.
23
+ */
24
+ export function downloadMeter(headers, expected, crossOrigin = false) {
25
+ const given = lengthOf(headers);
26
+ const hidden = crossOrigin && expected !== undefined && given !== null && given < expected;
27
+ const length = encoded(headers) || hidden ? null : given;
28
+ const byExpected = (done) => expected !== undefined && done <= expected
29
+ ? { phase: "download", fraction: done / expected, bytes: null }
30
+ : unknown();
31
+ return (done) => length !== null && done <= length
32
+ ? { phase: "download", fraction: done / length, bytes: { done, total: length } }
33
+ : byExpected(done);
34
+ }
35
+ const mb = (n) => (n / 1_000_000).toFixed(1);
36
+ /** "42%", with "(3.1 of 7.4 MB)" when the total is the real transfer size; "" when unknown. */
37
+ export function progressText(d) {
38
+ if (d.fraction === null)
39
+ return "";
40
+ const percent = `${Math.floor(d.fraction * 100)}%`;
41
+ return d.bytes ? `${percent} (${mb(d.bytes.done)} of ${mb(d.bytes.total)} MB)` : percent;
42
+ }
43
+ const SRI = /^(sha256|sha384|sha512)-([A-Za-z0-9+/]+={0,2})$/;
44
+ /** Whether `integrity` is one SRI digest this package checks: sha256, sha384 or sha512. */
45
+ export const isIntegrity = (integrity) => SRI.test(integrity.trim());
46
+ const base64 = (buffer) => {
47
+ let s = "";
48
+ for (const b of new Uint8Array(buffer))
49
+ s += String.fromCharCode(b);
50
+ return btoa(s);
51
+ };
52
+ /** Whether `bytes` have the SRI digest `integrity` (`sha384-…`); anything else fails. */
53
+ export async function checkIntegrity(bytes, integrity) {
54
+ const m = SRI.exec(integrity.trim());
55
+ if (!m)
56
+ return false;
57
+ const alg = `SHA-${m[1].slice(3)}`;
58
+ return base64(await crypto.subtle.digest(alg, bytes)) === m[2];
59
+ }
60
+ /** How often an unmeasurable download reports: every this many bytes. */
61
+ const UNKNOWN_STEP = 512 * 1024;
62
+ /** A download's measure, but unmeasured from the first time it would go down (the body outgrew its length). */
63
+ function rising() {
64
+ let high = -1;
65
+ let lost = false;
66
+ return (d) => {
67
+ const percent = d.fraction === null ? -1 : Math.floor(d.fraction * 100);
68
+ lost ||= percent >= 0 && percent < high;
69
+ high = Math.max(high, percent);
70
+ return lost ? { ...d, fraction: null, bytes: null } : d;
71
+ };
72
+ }
73
+ /**
74
+ * Reports a download only when its whole percentage rises (it never goes
75
+ * down: see `rising`), or, unmeasured, every UNKNOWN_STEP bytes.
76
+ */
77
+ function throttled(report) {
78
+ const monotone = rising();
79
+ let last = null;
80
+ return (d, done) => {
81
+ const shown = monotone(d);
82
+ const mark = shown.fraction === null
83
+ ? -1 - Math.floor(done / UNKNOWN_STEP)
84
+ : Math.floor(shown.fraction * 100);
85
+ if (mark === last)
86
+ return;
87
+ last = mark;
88
+ report(shown);
89
+ };
90
+ }
91
+ /** Downloads the module at `url` with progress, as a JavaScript blob ready to import from an object URL. */
92
+ export async function fetchModule(url, options) {
93
+ const response = await options.fetch(url);
94
+ if (!response.ok)
95
+ throw new Error(`${response.status} ${response.statusText}`.trim());
96
+ const meter = downloadMeter(response.headers, options.expected, response.type === "cors");
97
+ const report = throttled(options.onProgress);
98
+ const chunks = [];
99
+ let done = 0;
100
+ report(meter(0), 0);
101
+ const reader = response.body?.getReader();
102
+ for (let r = await reader?.read(); r && !r.done; r = await reader?.read()) {
103
+ chunks.push(r.value);
104
+ done += r.value.byteLength;
105
+ report(meter(done), done);
106
+ }
107
+ // One copy of the module: the chunks are joined and dropped before it is digested and wrapped.
108
+ const bytes = new Uint8Array(done);
109
+ let at = 0;
110
+ for (const chunk of chunks.splice(0)) {
111
+ bytes.set(chunk, at);
112
+ at += chunk.byteLength;
113
+ }
114
+ if (options.integrity !== undefined && !(await checkIntegrity(bytes, options.integrity)))
115
+ throw new Error(`${url} does not match its integrity digest`);
116
+ const blob = new Blob([bytes], { type: "text/javascript" });
117
+ return blob;
118
+ }
package/dist/element.d.ts CHANGED
@@ -3,7 +3,8 @@
3
3
  * Grid / Score switch. Its chart comes from the `text` property, a `src` URL or
4
4
  * a child `<script type="text/barmark">`, as `<barmark-chart>`'s does. A shadow
5
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
6
+ * worker) loads on the first switch to the score, or earlier as `preload`
7
+ * asks, showing its progress while it loads. Importing
7
8
  * this module registers the element (once) and the font (once per document).
8
9
  */
9
10
  import type { Engine } from "./engine.js";
package/dist/element.js CHANGED
@@ -3,12 +3,15 @@
3
3
  * Grid / Score switch. Its chart comes from the `text` property, a `src` URL or
4
4
  * a child `<script type="text/barmark">`, as `<barmark-chart>`'s does. A shadow
5
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
6
+ * worker) loads on the first switch to the score, or earlier as `preload`
7
+ * asks, showing its progress while it loads. Importing
7
8
  * this module registers the element (once) and the font (once per document).
8
9
  */
9
10
  import { FONT_FAMILY, fontFaceCss, renderChartUnwrapped, } from "@barmark/render";
10
11
  import { chartSource, inlineChartText, optionsFromAttributes, } from "@barmark/render/element";
11
12
  import { parseChart } from "barmark";
13
+ import { isIntegrity } from "./download.js";
14
+ import { showStatus, UNMEASURED } from "./loading.js";
12
15
  import { isLeipzigFace, scorePane } from "./markup.js";
13
16
  import { decodeCarried, gridError, scoreShell } from "./shell.js";
14
17
  import { viewOf } from "./switch.js";
@@ -18,18 +21,22 @@ export function setEngineForTests(factory) {
18
21
  testEngine = factory;
19
22
  }
20
23
  let loading = null;
24
+ /** The page's engine once imported. */
25
+ let loaded = null;
21
26
  /** The page's engine, imported on first use; a failed import is tried again next time. */
22
27
  function loadEngine() {
23
28
  const factory = testEngine;
24
29
  if (factory)
25
30
  return Promise.resolve().then(factory);
26
- loading ??= import("./engine.js").then((m) => m.engine(), (e) => {
31
+ loading ??= import("./engine.js").then((m) => {
32
+ loaded = m.engine();
33
+ return loaded;
34
+ }, (e) => {
27
35
  loading = null;
28
36
  throw e;
29
37
  });
30
38
  return loading;
31
39
  }
32
- const LOADING = "Loading score…";
33
40
  /** The score's accessible name when the chart has no title. */
34
41
  const UNTITLED = "Score";
35
42
  const NOTE = "The score couldn't be drawn";
@@ -77,13 +84,23 @@ function takeEarlyText(el) {
77
84
  /** The grid's attributes, as `<barmark-chart>` observes them, then the score's own. */
78
85
  const OBSERVED = [
79
86
  ...["src", "theme", "bar-numbers", "rehearsal-letters", "numerals", "wrap", "show-part"],
80
- ...["view", "verovio-url"],
87
+ ...["view", "verovio-url", "verovio-integrity", "preload"],
81
88
  ];
89
+ /** With no `requestIdleCallback`, how long after connecting `preload="idle"` starts the load. */
90
+ const IDLE_FALLBACK_MS = 500;
91
+ /** Whether the reader asked to save data, or is on a 2G line: `preload="idle"` waits for intent there. */
92
+ function sparing() {
93
+ const c = globalThis.navigator?.connection;
94
+ return c?.saveData === true || c?.effectiveType === "2g" || c?.effectiveType === "slow-2g";
95
+ }
96
+ /** The pointer, focus or touch on the Score radio that says a reader may want the score. */
97
+ const INTENT = ["pointerenter", "focus", "touchstart"];
82
98
  const messageOf = (e) => (e instanceof Error ? e.message : String(e));
83
99
  /** The radio a click or key landed on. */
84
100
  const radioOf = (target) => target?.closest?.("[data-view]") ?? null;
85
101
  const same = (a, b) => a !== null && a.text === b.text && Math.abs(a.width - b.width) <= SLACK;
86
102
  const URL_REASON = "verovio-url must be an http(s) URL";
103
+ const INTEGRITY_REASON = "verovio-integrity must be one sha256-, sha384- or sha512- digest";
87
104
  /** `verovio-url` resolved against the page: undefined when absent, null unless http(s). */
88
105
  function verovioHref(value, base) {
89
106
  if (value === null)
@@ -122,6 +139,12 @@ function defineElement() {
122
139
  /** The engraving and theme the pane holds, so an unchanged one is not written again. */
123
140
  #revealed = null;
124
141
  #asked = null;
142
+ /** What the engine last said about the request being waited on. */
143
+ #status = UNMEASURED;
144
+ /** Whether this element has asked the engine to preload. */
145
+ #preloaded = false;
146
+ /** The pending idle preload's cancel, if one is armed. */
147
+ #idle = null;
125
148
  connectedCallback() {
126
149
  const early = takeEarlyText(this);
127
150
  if (early)
@@ -133,8 +156,11 @@ function defineElement() {
133
156
  this.#resize.observe(this);
134
157
  }
135
158
  this.#schedule();
159
+ this.#armIdle();
136
160
  }
137
161
  disconnectedCallback() {
162
+ this.#idle?.();
163
+ this.#idle = null;
138
164
  this.#observer.disconnect();
139
165
  this.#resize?.disconnect();
140
166
  this.#resize = null;
@@ -144,8 +170,10 @@ function defineElement() {
144
170
  if (!this.isConnected || old === value)
145
171
  return;
146
172
  // A new URL may be the fix: the Score radio works again, as after a new chart.
147
- if (name === "verovio-url")
173
+ if (name === "verovio-url" || name === "verovio-integrity")
148
174
  this.#clearFailure();
175
+ else if (name === "preload")
176
+ this.#preloadChanged();
149
177
  else if (name === "view")
150
178
  this.#applyView();
151
179
  else if (name === "src")
@@ -260,6 +288,73 @@ function defineElement() {
260
288
  this.#wired = switcher;
261
289
  switcher.addEventListener("click", (e) => this.#pick(radioOf(e.target)));
262
290
  switcher.addEventListener("keydown", (e) => this.#key(e));
291
+ const score = switcher.querySelector('[data-view="score"]');
292
+ for (const type of INTENT)
293
+ score?.addEventListener(type, () => this.#intent(), { passive: true });
294
+ }
295
+ /** `preload`: "none" unless "intent" or "idle"; "idle" is "intent" on a sparing connection. */
296
+ #preloadMode() {
297
+ const v = this.getAttribute("preload");
298
+ if (v === "idle")
299
+ return sparing() ? "intent" : "idle";
300
+ return v === "intent" ? "intent" : "none";
301
+ }
302
+ /** A reader reaching for Score: any preload but "none" starts now. */
303
+ #intent() {
304
+ if (this.#preloadMode() !== "none")
305
+ this.#preload();
306
+ }
307
+ /** A new `preload`: an idle load armed for "idle" is cancelled unless it is still "idle". */
308
+ #preloadChanged() {
309
+ if (this.#preloadMode() !== "idle") {
310
+ this.#idle?.();
311
+ this.#idle = null;
312
+ }
313
+ this.#armIdle();
314
+ }
315
+ /** `preload="idle"`: start the load when the page is idle (or shortly, without requestIdleCallback). */
316
+ #armIdle() {
317
+ if (this.#idle || this.#preloaded || this.#preloadMode() !== "idle")
318
+ return;
319
+ const run = () => {
320
+ this.#idle = null;
321
+ this.#preload();
322
+ };
323
+ const g = globalThis;
324
+ if (g.requestIdleCallback) {
325
+ const id = g.requestIdleCallback(run);
326
+ this.#idle = () => g.cancelIdleCallback?.(id);
327
+ }
328
+ else {
329
+ const t = setTimeout(run, IDLE_FALLBACK_MS);
330
+ this.#idle = () => clearTimeout(t);
331
+ }
332
+ }
333
+ /** Loads the engine with no job, once per element; the engine shares the one load. */
334
+ #preload() {
335
+ if (this.#preloaded)
336
+ return;
337
+ const source = this.#source();
338
+ if (source === null)
339
+ return;
340
+ this.#preloaded = true;
341
+ loadEngine().then((e) => e.preload(source.url, source.integrity), () => { });
342
+ }
343
+ /** Where Verovio comes from, or null (and why) when `verovio-url` or `verovio-integrity` is refused. */
344
+ #verovio() {
345
+ const url = verovioHref(this.getAttribute("verovio-url"), this.ownerDocument.baseURI);
346
+ if (url === null)
347
+ return { refused: URL_REASON };
348
+ const integrity = url === undefined ? null : this.getAttribute("verovio-integrity");
349
+ if (integrity === null)
350
+ return { url, integrity: undefined };
351
+ return isIntegrity(integrity)
352
+ ? { url, integrity: integrity.trim() }
353
+ : { refused: INTEGRITY_REASON };
354
+ }
355
+ #source() {
356
+ const v = this.#verovio();
357
+ return "refused" in v ? null : v;
263
358
  }
264
359
  #pick(radio) {
265
360
  if (!radio || radio.getAttribute("aria-disabled") === "true")
@@ -330,19 +425,32 @@ function defineElement() {
330
425
  return this.#reveal(this.#engraved);
331
426
  if (same(this.#asked, want))
332
427
  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);
428
+ const verovio = this.#verovio();
429
+ if ("refused" in verovio)
430
+ return this.#fail(verovio.refused);
431
+ void this.#engrave(want, verovio);
337
432
  }
338
- /** Engraves `want`; only the newest request this element made is shown. */
339
- async #engrave(want, url) {
340
- this.#busy();
433
+ /** Engraves `want`; only the newest request this element made is shown, with its status while it waits. */
434
+ async #engrave(want, verovio) {
341
435
  this.#asked = want;
342
436
  const ask = ++this.#engraves;
437
+ this.#status = UNMEASURED;
438
+ const onStatus = (s) => {
439
+ if (ask !== this.#engraves)
440
+ return;
441
+ this.#status = s;
442
+ const { pane } = this.#parts();
443
+ if (pane && this.#revealed === null)
444
+ showStatus(pane, s);
445
+ };
446
+ const call = verovio.integrity === undefined ? { onStatus } : { onStatus, integrity: verovio.integrity };
447
+ const run = (e) => e.engrave(this, want.text, want.width, verovio.url, call);
448
+ // A loaded engine is asked at once, so its status (not a provisional one) is the first drawn.
449
+ const request = loaded ? run(loaded) : loadEngine().then(run);
450
+ this.#busy();
343
451
  let reply;
344
452
  try {
345
- reply = await (await loadEngine()).engrave(this, want.text, want.width, url);
453
+ reply = await request;
346
454
  }
347
455
  catch (e) {
348
456
  reply = { id: 0, ok: false, reason: messageOf(e) };
@@ -357,13 +465,13 @@ function defineElement() {
357
465
  if (this.view === "score")
358
466
  this.#reveal(this.#engraved);
359
467
  }
360
- /** A score on its way: a shown one stays (busy) until the new one lands, else "Loading score…". */
468
+ /** A score on its way: a shown one stays (busy) until the new one lands, else its loading status. */
361
469
  #busy() {
362
470
  const { grid, pane } = this.#parts();
363
471
  if (!pane)
364
472
  return;
365
473
  if (this.#revealed === null)
366
- pane.textContent = LOADING;
474
+ showStatus(pane, this.#status);
367
475
  pane.setAttribute("aria-busy", "true");
368
476
  pane.toggleAttribute("hidden", false);
369
477
  grid?.toggleAttribute("hidden", true);
package/dist/engine.d.ts CHANGED
@@ -1,9 +1,22 @@
1
- /** What a page asks the worker for: one chart, laid out for a width. */
2
- export type Request = {
1
+ import type { Download } from "./download.js";
2
+ /**
3
+ * Where a worker loads Verovio from: no `verovioUrl`, the package's own;
4
+ * with `verovioIntegrity`, a copy that must have that digest (or the
5
+ * package's own is loaded in its place).
6
+ */
7
+ export type VerovioSource = {
8
+ verovioUrl?: string;
9
+ verovioIntegrity?: string;
10
+ };
11
+ /**
12
+ * What a page asks the worker for: one chart, laid out for a width; or,
13
+ * with `preload`, only to load Verovio (`text` and `width` unused).
14
+ */
15
+ export type Request = VerovioSource & {
3
16
  id: number;
4
17
  text: string;
5
18
  width: number;
6
- verovioUrl?: string;
19
+ preload?: true;
7
20
  };
8
21
  /** What the worker answers. No `xml` or `diagnostics` cross the boundary. */
9
22
  export type Reply = {
@@ -25,12 +38,29 @@ export type EngraveReply = Reply;
25
38
  */
26
39
  export type Ready = {
27
40
  id: number;
28
- loaded: {
29
- verovioUrl?: string;
30
- };
41
+ loaded: VerovioSource;
42
+ };
43
+ /** How a worker's Verovio load is going: downloading (as far as it can be measured), then preparing. */
44
+ export type LoadStatus = Download | {
45
+ phase: "prepare";
46
+ };
47
+ /** What the worker says while it loads Verovio for job `id`. */
48
+ export type Progress = {
49
+ id: number;
50
+ status: LoadStatus;
51
+ };
52
+ /** Every message a worker sends: a job's `Progress` while it loads, its `Ready`, then its `Reply`. */
53
+ export type WorkerMessage = Reply | Ready | Progress;
54
+ /** What a caller hears while it waits: the engine's load, then its engraving. */
55
+ export type EngineStatus = LoadStatus | {
56
+ phase: "engrave";
57
+ };
58
+ export type EngraveCall = {
59
+ /** The SRI digest (`sha384-…`) the `verovioUrl` copy must have; on a mismatch the package's own loads. */
60
+ integrity?: string;
61
+ /** Hears the engine's status now, and as it changes, until the request settles. */
62
+ onStatus?: (status: EngineStatus) => void;
31
63
  };
32
- /** Every message a worker sends: a job's `Ready`, then its `Reply`. */
33
- export type WorkerMessage = Reply | Ready;
34
64
  /**
35
65
  * The part of a `Worker` the engine uses, so a test can pass a fake. It is
36
66
  * driven by the `onmessage` and `onerror` properties (a real `Worker`
@@ -49,7 +79,13 @@ export type Engine = {
49
79
  * with "The score engine failed" if the worker crashes on it, or its
50
80
  * Verovio load or its engraving runs past its deadline.
51
81
  */
52
- engrave(key: object, text: string, width: number, verovioUrl?: string): Promise<EngraveReply | null>;
82
+ engrave(key: object, text: string, width: number, verovioUrl?: string, call?: EngraveCall): Promise<EngraveReply | null>;
83
+ /**
84
+ * Starts loading Verovio (from `verovioUrl`, checked against `integrity`
85
+ * when given) with no job, so a first score is quicker. Does nothing if
86
+ * a worker has Verovio loaded or is busy: there is one load to share.
87
+ */
88
+ preload(verovioUrl?: string, integrity?: string): void;
53
89
  };
54
90
  /** How long one job may engrave, from its worker's Verovio being ready, before the worker is cut off and the request rejects. */
55
91
  export declare const JOB_DEADLINE_MS = 20000;
package/dist/engine.js CHANGED
@@ -11,7 +11,15 @@ export const LOAD_DEADLINE_MS = 60_000;
11
11
  */
12
12
  export const SUPERSEDED_GRACE_MS = 3_000;
13
13
  const FAILED = "The score engine failed";
14
- const isReady = (m) => !("ok" in m);
14
+ const isReady = (m) => "loaded" in m;
15
+ const isProgress = (m) => "status" in m;
16
+ const UNMEASURED = { phase: "download", fraction: null, bytes: null };
17
+ const ENGRAVING = { phase: "engrave" };
18
+ /** `source` without its absent fields (so a request carries no `verovioUrl: undefined`). */
19
+ const present = ({ verovioUrl, verovioIntegrity, }) => ({
20
+ ...(verovioUrl === undefined ? {} : { verovioUrl }),
21
+ ...(verovioUrl === undefined || verovioIntegrity === undefined ? {} : { verovioIntegrity }),
22
+ });
15
23
  const clear = (job) => {
16
24
  for (const t of job.timers)
17
25
  clearTimeout(t);
@@ -31,10 +39,16 @@ export function createEngine(makeWorker, options = {}) {
31
39
  let worker = null;
32
40
  let running = null;
33
41
  let loaded;
42
+ /** Whether the current worker has its Verovio loaded. */
43
+ let warm = false;
44
+ /** The engine's status, as a new caller first hears it. */
45
+ let status = UNMEASURED;
34
46
  let nextId = 0;
35
47
  const waiting = [];
36
48
  const pending = new Map();
37
49
  const newest = new WeakMap();
50
+ /** Preload jobs: no one waits on them, and they end at `Ready`. */
51
+ const preloads = new Set();
38
52
  const settle = (id) => {
39
53
  const p = pending.get(id);
40
54
  pending.delete(id);
@@ -48,15 +62,32 @@ export function createEngine(makeWorker, options = {}) {
48
62
  running = null;
49
63
  const w = worker;
50
64
  worker = null;
65
+ warm = false;
66
+ preloads.delete(id);
51
67
  w?.terminate();
52
68
  if (reason !== null)
53
69
  settle(id)?.reject(new Error(reason));
70
+ // A fresh worker loads Verovio again: the callers still waiting hear it from the start.
71
+ tell(UNMEASURED);
54
72
  next();
55
73
  };
56
74
  const overdue = (id, what) => () => cut(id, `${FAILED}: ${what} took too long`);
57
- /** Verovio is ready: the job's engraving deadline and its grace start now. */
75
+ /** Tells every waiting caller the engine's new status. */
76
+ const tell = (now) => {
77
+ status = now;
78
+ for (const p of pending.values())
79
+ p.onStatus?.(now);
80
+ };
81
+ /** Verovio is ready: the job's engraving deadline and its grace start now; a preload is done. */
58
82
  const onReady = (job, ready) => {
59
83
  loaded ??= ready.loaded;
84
+ warm = true;
85
+ // A preload's Ready engraves nothing: the job behind it hears "engrave" at its own Ready.
86
+ if (preloads.has(job.id)) {
87
+ finish(job);
88
+ return next();
89
+ }
90
+ tell(ENGRAVING);
60
91
  clear(job);
61
92
  job.timers = [
62
93
  setTimeout(overdue(job.id, "engraving"), deadline),
@@ -67,9 +98,14 @@ export function createEngine(makeWorker, options = {}) {
67
98
  }, grace),
68
99
  ];
69
100
  };
70
- const onReply = (job, reply) => {
101
+ /** The worker is done with `job`. */
102
+ const finish = (job) => {
71
103
  clear(job);
72
104
  running = null;
105
+ preloads.delete(job.id);
106
+ };
107
+ const onReply = (job, reply) => {
108
+ finish(job);
73
109
  settle(reply.id)?.resolve(reply);
74
110
  next();
75
111
  };
@@ -81,7 +117,9 @@ export function createEngine(makeWorker, options = {}) {
81
117
  const job = running;
82
118
  if (worker !== w || job?.id !== data.id)
83
119
  return;
84
- if (isReady(data))
120
+ if (isProgress(data))
121
+ tell(data.status);
122
+ else if (isReady(data))
85
123
  onReady(job, data);
86
124
  else
87
125
  onReply(job, data);
@@ -98,12 +136,11 @@ export function createEngine(makeWorker, options = {}) {
98
136
  const request = running ? undefined : waiting.shift();
99
137
  if (!request)
100
138
  return;
101
- const { verovioUrl, ...rest } = request;
102
- const url = loaded ? loaded.verovioUrl : verovioUrl;
139
+ const { verovioUrl, verovioIntegrity, ...rest } = request;
103
140
  const id = rest.id;
104
141
  running = { id, superseded: false, graceOver: false, timers: [] };
105
142
  running.timers = [setTimeout(overdue(id, "loading Verovio"), loadDeadline)];
106
- start().postMessage(url === undefined ? rest : { ...rest, verovioUrl: url });
143
+ start().postMessage({ ...rest, ...present(loaded ?? { verovioUrl, verovioIntegrity }) });
107
144
  };
108
145
  /** No one waits for `id` any more: drop it if it waits its turn, cut it off past its grace if it runs. */
109
146
  const supersede = (id) => {
@@ -118,18 +155,38 @@ export function createEngine(makeWorker, options = {}) {
118
155
  cut(id, null);
119
156
  };
120
157
  return {
121
- engrave(key, text, width, verovioUrl) {
158
+ engrave(key, text, width, verovioUrl, call = {}) {
122
159
  const id = ++nextId;
123
160
  const before = newest.get(key);
124
161
  newest.set(key, id);
125
162
  return new Promise((resolve, reject) => {
126
- pending.set(id, { resolve, reject });
163
+ pending.set(id, { resolve, reject, onStatus: call.onStatus });
164
+ call.onStatus?.(warm ? ENGRAVING : status);
127
165
  if (before !== undefined)
128
166
  supersede(before);
129
- waiting.push(verovioUrl === undefined ? { id, text, width } : { id, text, width, verovioUrl });
167
+ waiting.push({
168
+ id,
169
+ text,
170
+ width,
171
+ ...present({ verovioUrl, verovioIntegrity: call.integrity }),
172
+ });
130
173
  next();
131
174
  });
132
175
  },
176
+ preload(verovioUrl, integrity) {
177
+ if (warm || running || waiting.length > 0)
178
+ return;
179
+ const id = ++nextId;
180
+ preloads.add(id);
181
+ waiting.push({
182
+ id,
183
+ text: "",
184
+ width: 0,
185
+ preload: true,
186
+ ...present({ verovioUrl, verovioIntegrity: integrity }),
187
+ });
188
+ next();
189
+ },
133
190
  };
134
191
  }
135
192
  let shared;
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
- export { createEngine, type Engine, type EngineOptions, type EngraveReply, engine, JOB_DEADLINE_MS, LOAD_DEADLINE_MS, type Ready, type Reply, type Request, SUPERSEDED_GRACE_MS, type WorkerLike, type WorkerMessage, } from "./engine.js";
1
+ export { createEngine, type Engine, type EngineOptions, type EngineStatus, type EngraveCall, type EngraveReply, engine, JOB_DEADLINE_MS, LOAD_DEADLINE_MS, type LoadStatus, type Progress, type Ready, type Reply, type Request, SUPERSEDED_GRACE_MS, type VerovioSource, type WorkerLike, type WorkerMessage, } from "./engine.js";
2
2
  export { type Engraved, type EngraveOptions, engraveChart, engraveXml, LAYOUT, MAX_SCORE_COST, MAX_XML_LENGTH, scoreCost, } from "./engrave.js";
3
3
  export { cleanSvg, type ScoreTheme, scorePane, scoreStyles } from "./markup.js";
4
+ export { VEROVIO_CDN_INTEGRITY, VEROVIO_CDN_URL, VEROVIO_MODULE_BYTES, VEROVIO_VERSION, } from "./verovio.js";
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  export { createEngine, engine, JOB_DEADLINE_MS, LOAD_DEADLINE_MS, SUPERSEDED_GRACE_MS, } from "./engine.js";
2
2
  export { engraveChart, engraveXml, LAYOUT, MAX_SCORE_COST, MAX_XML_LENGTH, scoreCost, } from "./engrave.js";
3
3
  export { cleanSvg, scorePane, scoreStyles } from "./markup.js";
4
+ export { VEROVIO_CDN_INTEGRITY, VEROVIO_CDN_URL, VEROVIO_MODULE_BYTES, VEROVIO_VERSION, } from "./verovio.js";
@@ -0,0 +1,17 @@
1
+ import type { EngineStatus } from "./engine.js";
2
+ /** Before anything is heard: the engine downloading, unmeasured. */
3
+ export declare const UNMEASURED: EngineStatus;
4
+ /**
5
+ * Shows `status` in `pane`, building the region the first time and then
6
+ * updating it in place: the live region's text changes only with the
7
+ * phase, so a screen reader hears each phase once, and the percentage is
8
+ * the bar's value (and the amount beside it, hidden from assistive
9
+ * technology, which reads the bar).
10
+ */
11
+ export declare function showStatus(pane: Element, status: EngineStatus): void;
12
+ /**
13
+ * The region's look, in the switch's ink and rule. An indeterminate bar
14
+ * (no `aria-valuenow`) slides; with reduced motion it stands still, a
15
+ * faint full bar, and a measured one jumps rather than glides.
16
+ */
17
+ export declare const loadingStyles = ".bms-loading{display:flex;flex-wrap:wrap;align-items:center;gap:.375rem .75rem;padding:.75rem 0;color:var(--bms-ink);font-family:var(--barmark-label-font,system-ui,-apple-system,\"Segoe UI\",sans-serif);font-size:.875em}\n.bms-status{margin:0;flex:1 0 100%}\n.bms-bar{position:relative;flex:0 1 16rem;height:.375rem;border:1px solid var(--bms-rule);border-radius:.375rem;overflow:hidden}\n.bms-bar>span{position:absolute;top:0;bottom:0;left:0;width:var(--bms-done,0%);background:var(--bms-ink);transition:width .2s linear}\n.bms-bar:not([aria-valuenow])>span{width:30%;animation:bms-slide 1.2s ease-in-out infinite alternate}\n@keyframes bms-slide{from{left:0}to{left:70%}}\n.bms-amount{font-variant-numeric:tabular-nums}\n@media (prefers-reduced-motion:reduce){.bms-bar>span{transition:none}.bms-bar:not([aria-valuenow])>span{animation:none;width:100%;opacity:.35}}";
@@ -0,0 +1,78 @@
1
+ // What `<barmark-score>` shows while its score is on its way: the phase in a status region,
2
+ // a progress bar and, while the download can be measured, how far it has come.
3
+ // Verovio-free, like ./shell.js.
4
+ import { progressText } from "./download.js";
5
+ /** Each phase's words: shown (and spoken, once per phase) and the bar's name. */
6
+ const PHASES = {
7
+ download: { text: "Loading the score engine…", label: "Loading the score engine" },
8
+ prepare: { text: "Preparing…", label: "Preparing" },
9
+ engrave: { text: "Engraving…", label: "Engraving" },
10
+ };
11
+ /** Before anything is heard: the engine downloading, unmeasured. */
12
+ export const UNMEASURED = { phase: "download", fraction: null, bytes: null };
13
+ function build(doc) {
14
+ const make = (tag, cls, attrs = {}) => {
15
+ const e = doc.createElement(tag);
16
+ e.className = cls;
17
+ for (const [k, v] of Object.entries(attrs))
18
+ e.setAttribute(k, v);
19
+ return e;
20
+ };
21
+ const box = make("div", "bms-loading");
22
+ const bar = make("div", "bms-bar", {
23
+ role: "progressbar",
24
+ "aria-valuemin": "0",
25
+ "aria-valuemax": "100",
26
+ });
27
+ bar.append(doc.createElement("span"));
28
+ box.append(make("p", "bms-status", { role: "status" }), bar, make("span", "bms-amount", { "aria-hidden": "true" }));
29
+ return box;
30
+ }
31
+ /**
32
+ * Shows `status` in `pane`, building the region the first time and then
33
+ * updating it in place: the live region's text changes only with the
34
+ * phase, so a screen reader hears each phase once, and the percentage is
35
+ * the bar's value (and the amount beside it, hidden from assistive
36
+ * technology, which reads the bar).
37
+ */
38
+ export function showStatus(pane, status) {
39
+ let box = pane.querySelector(":scope > .bms-loading");
40
+ if (!box) {
41
+ box = build(pane.ownerDocument);
42
+ pane.replaceChildren(box);
43
+ }
44
+ const { text, label } = PHASES[status.phase];
45
+ const live = box.querySelector(".bms-status");
46
+ if (live && live.textContent !== text)
47
+ live.textContent = text;
48
+ const bar = box.querySelector(".bms-bar");
49
+ bar?.setAttribute("aria-label", label);
50
+ const fraction = status.phase === "download" ? status.fraction : null;
51
+ const amount = status.phase === "download" ? progressText(status) : "";
52
+ if (fraction === null) {
53
+ for (const a of ["aria-valuenow", "aria-valuetext"])
54
+ bar?.removeAttribute(a);
55
+ }
56
+ else {
57
+ const percent = Math.floor(fraction * 100);
58
+ bar?.setAttribute("aria-valuenow", String(percent));
59
+ bar?.setAttribute("aria-valuetext", `${percent}%`);
60
+ bar?.style?.setProperty("--bms-done", `${percent}%`);
61
+ }
62
+ const shown = box.querySelector(".bms-amount");
63
+ if (shown)
64
+ shown.textContent = amount;
65
+ }
66
+ /**
67
+ * The region's look, in the switch's ink and rule. An indeterminate bar
68
+ * (no `aria-valuenow`) slides; with reduced motion it stands still, a
69
+ * faint full bar, and a measured one jumps rather than glides.
70
+ */
71
+ export const loadingStyles = `.bms-loading{display:flex;flex-wrap:wrap;align-items:center;gap:.375rem .75rem;padding:.75rem 0;color:var(--bms-ink);font-family:var(--barmark-label-font,system-ui,-apple-system,"Segoe UI",sans-serif);font-size:.875em}
72
+ .bms-status{margin:0;flex:1 0 100%}
73
+ .bms-bar{position:relative;flex:0 1 16rem;height:.375rem;border:1px solid var(--bms-rule);border-radius:.375rem;overflow:hidden}
74
+ .bms-bar>span{position:absolute;top:0;bottom:0;left:0;width:var(--bms-done,0%);background:var(--bms-ink);transition:width .2s linear}
75
+ .bms-bar:not([aria-valuenow])>span{width:30%;animation:bms-slide 1.2s ease-in-out infinite alternate}
76
+ @keyframes bms-slide{from{left:0}to{left:70%}}
77
+ .bms-amount{font-variant-numeric:tabular-nums}
78
+ @media (prefers-reduced-motion:reduce){.bms-bar>span{transition:none}.bms-bar:not([aria-valuenow])>span{animation:none;width:100%;opacity:.35}}`;
package/dist/shell.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // What the server and the element both write inside `<barmark-score>`'s shadow root,
2
2
  // so client-drawn and server-drawn markup are the same. Verovio-free, like ./server.js.
3
3
  import { stylesheet } from "@barmark/render";
4
+ import { loadingStyles } from "./loading.js";
4
5
  import { escapeHtml, scoreStyles } from "./markup.js";
5
6
  import { switchHtml, switchStyles } from "./switch.js";
6
7
  /** Chart text for a `<script>`: the two sequences that would end or hide it are written with a backslash. */
@@ -8,7 +9,7 @@ export const carry = (text) => text.replace(/<\/(script)/gi, "<\\/$1").replaceAl
8
9
  /** The text `renderScoreHtml` carried, as it was given. */
9
10
  export const decodeCarried = (text) => text.replace(/<\\\/(script)/gi, "</$1").replaceAll("<\\!--", "<!--");
10
11
  /** The shadow root's content around a drawn grid: styles, the switch, the grid, the (empty) score pane. */
11
- export const scoreShell = (grid, view) => `<style>${stylesheet}${switchStyles}${scoreStyles}</style>${switchHtml(view)}<div class="bms-grid">${grid}</div><div class="bms-pane" hidden></div>`;
12
+ export const scoreShell = (grid, view) => `<style>${stylesheet}${switchStyles}${scoreStyles}${loadingStyles}</style>${switchHtml(view)}<div class="bms-grid">${grid}</div><div class="bms-pane" hidden></div>`;
12
13
  /** A chart that could not be loaded, drawn where the grid would be, as `<barmark-chart>` draws it. */
13
14
  export function gridError(message, theme) {
14
15
  const m = escapeHtml(message);
@@ -0,0 +1,8 @@
1
+ /** The Verovio this package is pinned to (tests/download.test.ts holds these to the installed copy). */
2
+ export declare const VEROVIO_VERSION = "6.4.1";
3
+ /** `verovio/dist/verovio-module.mjs`'s size, decoded: what a compressed download is measured against. */
4
+ export declare const VEROVIO_MODULE_BYTES = 7400749;
5
+ /** The same module on jsDelivr (CORS `*`, immutable), for `verovio-url`. */
6
+ export declare const VEROVIO_CDN_URL = "https://cdn.jsdelivr.net/npm/verovio@6.4.1/dist/verovio-module.mjs";
7
+ /** Its digest, for `verovio-integrity`. */
8
+ export declare const VEROVIO_CDN_INTEGRITY = "sha384-iGNyhtxpKLNw90cjbI9ES538TJtbNZjLxsFVUuI8PwE2TTNQ+i2j9CjQnRMhZXHk";
@@ -0,0 +1,8 @@
1
+ /** The Verovio this package is pinned to (tests/download.test.ts holds these to the installed copy). */
2
+ export const VEROVIO_VERSION = "6.4.1";
3
+ /** `verovio/dist/verovio-module.mjs`'s size, decoded: what a compressed download is measured against. */
4
+ export const VEROVIO_MODULE_BYTES = 7_400_749;
5
+ /** The same module on jsDelivr (CORS `*`, immutable), for `verovio-url`. */
6
+ export const VEROVIO_CDN_URL = `https://cdn.jsdelivr.net/npm/verovio@${VEROVIO_VERSION}/dist/verovio-module.mjs`;
7
+ /** Its digest, for `verovio-integrity`. */
8
+ export const VEROVIO_CDN_INTEGRITY = "sha384-iGNyhtxpKLNw90cjbI9ES538TJtbNZjLxsFVUuI8PwE2TTNQ+i2j9CjQnRMhZXHk";
package/dist/worker.d.ts CHANGED
@@ -1,26 +1,62 @@
1
1
  import { VerovioToolkit } from "verovio/esm";
2
- import type { Ready, Reply, Request } from "./engine.js";
2
+ import { type Download } from "./download.js";
3
+ import type { LoadStatus, Progress, Ready, Reply, Request, VerovioSource, WorkerMessage } from "./engine.js";
3
4
  type Toolkit = VerovioToolkit;
4
5
  /** Run `load` once and keep its result; a load that fails is forgotten, so the next call tries again. */
5
6
  export declare function loadOnce<A, T>(load: (arg: A) => Promise<T>): (arg: A) => Promise<T>;
7
+ type Report = (status: LoadStatus) => void;
8
+ /** A toolkit, and where its Verovio came from (no `verovioUrl`: the package's own). */
9
+ export type Loaded<T> = {
10
+ toolkit: T;
11
+ from: VerovioSource;
12
+ };
6
13
  /**
7
14
  * A worker's one Verovio toolkit, loaded on first use and reused, and
8
- * where it came from once loaded (no `verovioUrl`: the package's own), so
9
- * the engine can give a replacement worker the same. The first load that
10
- * succeeds wins for the worker's life: later URLs are ignored.
15
+ * where it came from once loaded, so the engine can give a replacement
16
+ * worker the same. The first load that succeeds wins for the worker's
17
+ * life: later sources are ignored. The first load's `report` hears it.
11
18
  */
12
- export declare function toolkitLoader<T>(load: (verovioUrl: string | undefined) => Promise<T>): {
13
- ready: (arg: string | undefined) => Promise<T>;
14
- loaded: () => {
15
- verovioUrl?: string;
16
- } | undefined;
19
+ export declare function toolkitLoader<T>(load: (source: VerovioSource, report: Report) => Promise<Loaded<T>>): {
20
+ ready: (source: VerovioSource, report: Report) => Promise<T>;
21
+ loaded: () => VerovioSource | undefined;
22
+ };
23
+ /** What loading Verovio needs, so a test can pass fakes. `M` is a Verovio module, `T` a toolkit. */
24
+ export type LoaderDeps<M, T> = {
25
+ /** Downloads `url` with progress, checked against `integrity` when given (download.ts). */
26
+ fetchModule(url: string, options: {
27
+ integrity?: string;
28
+ onProgress: (d: Download) => void;
29
+ }): Promise<Blob>;
30
+ /** Imports a downloaded module. */
31
+ importBlob(blob: Blob): Promise<M>;
32
+ /** The package's own Verovio, as the bundler placed it. */
33
+ own(): Promise<M>;
34
+ /** Instantiates the module's WebAssembly: the toolkit. */
35
+ instantiate(m: M): Promise<T>;
36
+ warn(message: string): void;
17
37
  };
18
38
  /**
19
- * The toolkit for `request`, saying it is `Ready` (and where it came
20
- * from) once loaded, before the job is engraved: the engine starts the
21
- * job's deadline then, so a slow download is not counted against it.
39
+ * Loads Verovio from `source`. The package's own copy comes through the
40
+ * bundler, its download unmeasured. A `verovioUrl` is downloaded here,
41
+ * with progress, and imported from a blob; with `verovioIntegrity` its
42
+ * digest is checked first, and a mismatch or any failure falls back to
43
+ * the package's own copy, once, with a warning. Without one, a failure is
44
+ * the failure.
45
+ */
46
+ export declare function verovioLoader<M, T>(deps: LoaderDeps<M, T>): (source: VerovioSource, report: Report) => Promise<Loaded<T>>;
47
+ /**
48
+ * The toolkit for `request`, posting its load's progress, then saying it
49
+ * is `Ready` (and where it came from) once loaded, before the job is
50
+ * engraved: the engine starts the job's deadline then, so a slow download
51
+ * is not counted against it.
52
+ */
53
+ export declare function withReady<T>(loader: ReturnType<typeof toolkitLoader<T>>, request: Request, post: (message: Ready | Progress) => void): () => Promise<T>;
54
+ /**
55
+ * Answers one request: a job is engraved (`engrave`, which never throws)
56
+ * and replied to; a preload only loads, posting `Ready`, or a reply with
57
+ * the reason when the load fails.
22
58
  */
23
- export declare function withReady<T>(loader: ReturnType<typeof toolkitLoader<T>>, request: Request, post: (ready: Ready) => void): () => Promise<T>;
59
+ export declare function answer<T>(request: Request, loader: ReturnType<typeof toolkitLoader<T>>, post: (message: WorkerMessage) => void, engrave: (request: Request, ready: () => Promise<T>) => Promise<Reply>): Promise<void>;
24
60
  /** Answer one request. Never throws: a failure is a reply with its reason. */
25
61
  export declare function handle(request: Request, loaded: () => Promise<Toolkit>): Promise<Reply>;
26
62
  export {};
package/dist/worker.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import * as esm from "verovio/esm";
2
2
  import { VerovioToolkit } from "verovio/esm";
3
+ import { fetchModule } from "./download.js";
3
4
  import { engraveChart } from "./engrave.js";
5
+ import { VEROVIO_MODULE_BYTES } from "./verovio.js";
4
6
  // Verovio's typings omit the log switch; it is exported all the same.
5
7
  const { enableLog, LOG_OFF } = esm;
6
8
  /** Run `load` once and keep its result; a load that fails is forgotten, so the next call tries again. */
@@ -16,43 +18,115 @@ export function loadOnce(load) {
16
18
  }
17
19
  /**
18
20
  * A worker's one Verovio toolkit, loaded on first use and reused, and
19
- * where it came from once loaded (no `verovioUrl`: the package's own), so
20
- * the engine can give a replacement worker the same. The first load that
21
- * succeeds wins for the worker's life: later URLs are ignored.
21
+ * where it came from once loaded, so the engine can give a replacement
22
+ * worker the same. The first load that succeeds wins for the worker's
23
+ * life: later sources are ignored. The first load's `report` hears it.
22
24
  */
23
25
  export function toolkitLoader(load) {
24
26
  let loaded;
25
- const ready = loadOnce(async (verovioUrl) => {
26
- const toolkit = await load(verovioUrl);
27
- loaded = verovioUrl === undefined ? {} : { verovioUrl };
28
- return toolkit;
27
+ const once = loadOnce(async ({ source, report }) => {
28
+ const r = await load(source, report);
29
+ loaded = r.from;
30
+ return r.toolkit;
29
31
  });
30
- return { ready, loaded: () => loaded };
32
+ return {
33
+ ready: (source, report) => once({ source, report }),
34
+ loaded: () => loaded,
35
+ };
31
36
  }
37
+ const UNMEASURED = { phase: "download", fraction: null, bytes: null };
32
38
  /**
33
- * By default the package's own `verovio/wasm`; when a request carries
34
- * `verovioUrl` that module is imported instead.
39
+ * Loads Verovio from `source`. The package's own copy comes through the
40
+ * bundler, its download unmeasured. A `verovioUrl` is downloaded here,
41
+ * with progress, and imported from a blob; with `verovioIntegrity` its
42
+ * digest is checked first, and a mismatch or any failure falls back to
43
+ * the package's own copy, once, with a warning. Without one, a failure is
44
+ * the failure.
35
45
  */
36
- const toolkit = toolkitLoader(async (verovioUrl) => {
37
- const m = verovioUrl
38
- ? await import(/* @vite-ignore */ verovioUrl)
39
- : await import("verovio/wasm");
40
- const module = await m.default();
41
- enableLog(LOG_OFF, module);
42
- return new VerovioToolkit(module);
46
+ export function verovioLoader(deps) {
47
+ const prepared = async (m, report) => {
48
+ report({ phase: "prepare" });
49
+ return deps.instantiate(m);
50
+ };
51
+ const own = async (report) => {
52
+ report(UNMEASURED);
53
+ return { toolkit: await prepared(await deps.own(), report), from: {} };
54
+ };
55
+ const fromUrl = async (verovioUrl, integrity, report) => {
56
+ const options = integrity === undefined ? { onProgress: report } : { integrity, onProgress: report };
57
+ const blob = await deps.fetchModule(verovioUrl, options);
58
+ return prepared(await deps.importBlob(blob), report);
59
+ };
60
+ return async (source, report) => {
61
+ const { verovioUrl, verovioIntegrity } = source;
62
+ if (verovioUrl === undefined)
63
+ return own(report);
64
+ if (verovioIntegrity === undefined)
65
+ return { toolkit: await fromUrl(verovioUrl, undefined, report), from: { verovioUrl } };
66
+ try {
67
+ return { toolkit: await fromUrl(verovioUrl, verovioIntegrity, report), from: source };
68
+ }
69
+ catch (err) {
70
+ deps.warn(`<barmark-score>: Verovio from ${verovioUrl} was not used (${String(err)}); loading the package's own copy instead`);
71
+ return own(report);
72
+ }
73
+ };
74
+ }
75
+ /** A module from a blob, through an object URL revoked once it is imported. */
76
+ async function importBlob(blob) {
77
+ const url = URL.createObjectURL(blob);
78
+ try {
79
+ return await import(/* @vite-ignore */ url);
80
+ }
81
+ finally {
82
+ URL.revokeObjectURL(url);
83
+ }
84
+ }
85
+ const toolkit = toolkitLoader(verovioLoader({
86
+ fetchModule: (url, options) => fetchModule(url, { ...options, fetch: (u) => fetch(u), expected: VEROVIO_MODULE_BYTES }),
87
+ importBlob,
88
+ own: () => import("verovio/wasm"),
89
+ instantiate: async (m) => {
90
+ const module = await m.default();
91
+ enableLog(LOG_OFF, module);
92
+ return new VerovioToolkit(module);
93
+ },
94
+ warn: (message) => console.warn(message),
95
+ }));
96
+ /** `request`'s Verovio source, without its absent fields. */
97
+ const sourceOf = ({ verovioUrl, verovioIntegrity }) => ({
98
+ ...(verovioUrl === undefined ? {} : { verovioUrl }),
99
+ ...(verovioIntegrity === undefined ? {} : { verovioIntegrity }),
43
100
  });
44
101
  /**
45
- * The toolkit for `request`, saying it is `Ready` (and where it came
46
- * from) once loaded, before the job is engraved: the engine starts the
47
- * job's deadline then, so a slow download is not counted against it.
102
+ * The toolkit for `request`, posting its load's progress, then saying it
103
+ * is `Ready` (and where it came from) once loaded, before the job is
104
+ * engraved: the engine starts the job's deadline then, so a slow download
105
+ * is not counted against it.
48
106
  */
49
107
  export function withReady(loader, request, post) {
50
108
  return async () => {
51
- const toolkit = await loader.ready(request.verovioUrl);
109
+ const toolkit = await loader.ready(sourceOf(request), (status) => post({ id: request.id, status }));
52
110
  post({ id: request.id, loaded: loader.loaded() ?? {} });
53
111
  return toolkit;
54
112
  };
55
113
  }
114
+ /**
115
+ * Answers one request: a job is engraved (`engrave`, which never throws)
116
+ * and replied to; a preload only loads, posting `Ready`, or a reply with
117
+ * the reason when the load fails.
118
+ */
119
+ export async function answer(request, loader, post, engrave) {
120
+ const ready = withReady(loader, request, post);
121
+ if (!request.preload)
122
+ return post(await engrave(request, ready));
123
+ try {
124
+ await ready();
125
+ }
126
+ catch (err) {
127
+ post({ id: request.id, ok: false, reason: String(err) });
128
+ }
129
+ }
56
130
  /** Answer one request. Never throws: a failure is a reply with its reason. */
57
131
  export async function handle(request, loaded) {
58
132
  const { id, text, width } = request;
@@ -70,7 +144,5 @@ const scope = globalThis;
70
144
  // Only a worker global answers messages: importing this in a page or a test has no effect.
71
145
  if (typeof scope.WorkerGlobalScope === "function" &&
72
146
  globalThis instanceof scope.WorkerGlobalScope) {
73
- scope.onmessage = async (e) => {
74
- scope.postMessage(await handle(e.data, withReady(toolkit, e.data, (r) => scope.postMessage(r))));
75
- };
147
+ scope.onmessage = (e) => answer(e.data, toolkit, (m) => scope.postMessage(m), handle);
76
148
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@barmark/score",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Show a barmark chord chart as a full engraved score: MusicXML from @barmark/musicxml, engraved by Verovio (LGPL-3.0, a dependency loaded unchanged).",
5
5
  "type": "module",
6
6
  "exports": {
@@ -52,7 +52,7 @@
52
52
  "@barmark/musicxml": "^0.8.0",
53
53
  "@barmark/render": "^0.18.0",
54
54
  "barmark": "^0.22.0",
55
- "verovio": "^6.4.1"
55
+ "verovio": "6.4.1"
56
56
  },
57
57
  "scripts": {
58
58
  "build": "rm -rf dist && tsc -p tsconfig.build.json",