@barmark/score 0.0.0 → 0.1.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.
@@ -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,35 @@
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
+ /** MusicXML laid out for a width, every page as SVG in a `bms-score-page` div. Throws on unreadable XML. */
30
+ export declare function engraveXml(vrv: VerovioToolkit, xml: string, options: EngraveOptions): {
31
+ svg: string;
32
+ pages: number;
33
+ };
34
+ /** A chart as a full score, or why it cannot be one. */
35
+ export declare function engraveChart(vrv: VerovioToolkit, text: string, options: EngraveOptions): Engraved;
@@ -0,0 +1,53 @@
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
+ /** MusicXML laid out for a width, every page as SVG in a `bms-score-page` div. Throws on unreadable XML. */
16
+ export function engraveXml(vrv, xml, options) {
17
+ const scale = options.scale ?? DEFAULT_SCALE;
18
+ vrv.setOptions({
19
+ ...LAYOUT,
20
+ scale,
21
+ // Verovio's page width is in its own units at scale 100.
22
+ pageWidth: Math.round((Math.max(MIN_WIDTH, options.width) * 100) / scale),
23
+ });
24
+ if (!vrv.loadData(xml))
25
+ throw new Error("Verovio could not read the score");
26
+ const pages = vrv.getPageCount();
27
+ if (pages < 1)
28
+ throw new Error("The score has no pages");
29
+ const svgs = [];
30
+ for (let p = 1; p <= pages; p++)
31
+ svgs.push(`<div class="bms-score-page">${vrv.renderToSVG(p)}</div>`);
32
+ return { svg: svgs.join(""), pages };
33
+ }
34
+ function refusal(diagnostics) {
35
+ const first = diagnostics.find((d) => d.severity === "error") ?? diagnostics[0];
36
+ if (!first)
37
+ return "The chart has no bars";
38
+ // A diagnostic about the whole chart has line 0: there is no line to name.
39
+ return first.line > 0 ? `Line ${first.line}: ${first.message}` : first.message;
40
+ }
41
+ /** A chart as a full score, or why it cannot be one. */
42
+ export function engraveChart(vrv, text, options) {
43
+ const exported = exportMusicXml(text);
44
+ if (!exported.ok)
45
+ return { ok: false, reason: refusal(exported.diagnostics), diagnostics: exported.diagnostics };
46
+ try {
47
+ const engraved = engraveXml(vrv, exported.xml, options);
48
+ return { ok: true, xml: exported.xml, pages: engraved.pages, svg: cleanSvg(engraved.svg) };
49
+ }
50
+ catch (e) {
51
+ return { ok: false, reason: e instanceof Error ? e.message : String(e), diagnostics: [] };
52
+ }
53
+ }
@@ -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
@@ -0,0 +1,3 @@
1
+ export { createEngine, engine, } from "./engine.js";
2
+ export { engraveChart, engraveXml, LAYOUT } from "./engrave.js";
3
+ export { cleanSvg, scorePane, scoreStyles } from "./markup.js";
@@ -0,0 +1,23 @@
1
+ export type ScoreTheme = "auto" | "light" | "dark";
2
+ /**
3
+ * Verovio's SVG reduced to what Verovio emits: only the listed elements and
4
+ * attributes survive, an unlisted element goes with its content, links keep
5
+ * only `#` targets. Hand-scanned, no DOM. Throws if the markup cannot be read
6
+ * cleanly (unbalanced quotes, comments, a stray `<`, unclosed elements): the
7
+ * caller treats that as "could not draw".
8
+ */
9
+ export declare function cleanSvg(svg: string): string;
10
+ /**
11
+ * The score's own layout. Colour comes from `@barmark/render`'s stylesheet
12
+ * (the `.bm-chart` wrapper that `scorePane` writes), which must be in the same
13
+ * shadow root; Verovio draws in `currentColor`, but its inner page svg carries `color="black"`, which `color:inherit` overrides.
14
+ */
15
+ export declare const scoreStyles = ".bms-score{padding:1rem;color:inherit;background:transparent}\n.bms-score-page{width:100%}\n.bms-score-page svg{display:block;width:100%;height:auto}\n.bms-score-page svg{fill:currentColor}\n.bms-score-page svg svg{color:inherit}";
16
+ /** Text made safe for HTML content and quoted attribute values (`&` first, so nothing is escaped twice). */
17
+ export declare const escapeHtml: (text: string) => string;
18
+ /**
19
+ * The cleaned pages in a themed pane: render's `.bm-chart` supplies the
20
+ * palette. The score is one image to assistive technology, named `label`
21
+ * (the chart's title, say), or "Score".
22
+ */
23
+ export declare function scorePane(svg: string, theme: ScoreTheme, label?: string): string;
package/dist/markup.js ADDED
@@ -0,0 +1,240 @@
1
+ const GEOMETRY = ["x", "y", "width", "height", "transform", "class", "id"];
2
+ /** The elements Verovio emits, each with the attributes it may carry; everything else goes. */
3
+ const ALLOWED = {
4
+ div: ["class"],
5
+ svg: [
6
+ ...GEOMETRY,
7
+ "viewBox",
8
+ "version",
9
+ "xmlns",
10
+ "xmlns:xlink",
11
+ "overflow",
12
+ "color",
13
+ "font-family",
14
+ ],
15
+ g: ["id", "class", "transform"],
16
+ defs: [],
17
+ desc: [],
18
+ title: ["class"],
19
+ symbol: ["id", "viewBox"],
20
+ clipPath: ["id"],
21
+ path: ["transform", "d", "stroke-width", "stroke-linecap", "stroke-linejoin", "class"],
22
+ text: ["x", "y", "text-anchor", "font-size", "class"],
23
+ tspan: [
24
+ "id",
25
+ "class",
26
+ "font-size",
27
+ "font-weight",
28
+ "font-style",
29
+ "x",
30
+ "y",
31
+ "text-anchor",
32
+ "font-family",
33
+ "fill",
34
+ "xml:space",
35
+ ],
36
+ use: ["xlink:href", "href", "transform", "x", "y"],
37
+ ellipse: ["cx", "cy", "rx", "ry", "transform"],
38
+ rect: ["x", "y", "height", "width", "transform"],
39
+ polygon: ["points"],
40
+ polyline: ["points", "stroke-width"],
41
+ line: ["x1", "y1", "x2", "y2", "stroke-width"],
42
+ style: ["type"],
43
+ };
44
+ /** The stylesheets Verovio writes (one with a random id, one embedding its font); any other `<style>` is dropped. */
45
+ const STYLE_ID = /^#([A-Za-z0-9]+) g\.ending,/;
46
+ const STYLE_TEMPLATE = "#@ g.ending, #@ g.fing, #@ g.reh, #@ g.tempo {font-weight:bold;}#@ g.dir, #@ g.dynam, #@ g.mNum {font-style:italic;}#@ g.label {font-weight:normal;}#@ ellipse, #@ path, #@ polygon, #@ polyline, #@ rect {stroke:currentColor}#@ g.cursor {fill:dodgerblue; color:dodgerblue;}#@ g.cursor.chord {fill:limegreen; color:limegreen;}#@ g.placeholder {visibility:hidden}";
47
+ /** The one embedded font Verovio adds for some scores: Leipzig as a base64 woff2, nothing else. */
48
+ const FONT_FACE = /^@font-face \{\s*font-family: 'Leipzig';\s*src: url\(data:application\/font-woff2;charset=utf-8;base64,[A-Za-z0-9+/=]+\) format\('woff2'\);\s*font-weight: normal;\s*font-style: normal;\s*\}$/;
49
+ function isVerovioStyle(css) {
50
+ if (FONT_FACE.test(css))
51
+ return true;
52
+ const id = STYLE_ID.exec(css)?.[1];
53
+ return id !== undefined && css === STYLE_TEMPLATE.replaceAll("@", id);
54
+ }
55
+ const NAME = /^[A-Za-z][A-Za-z0-9:_.-]*/;
56
+ const WHITESPACE = /\s/;
57
+ class Unclean extends Error {
58
+ }
59
+ function fail(why) {
60
+ throw new Unclean(`The score markup is not clean SVG: ${why}`);
61
+ }
62
+ /** Elements whose content the HTML parser reads as raw text, even when written `<x/>`. */
63
+ const RAW_TEXT = new Set([
64
+ "style",
65
+ "script",
66
+ "title",
67
+ "textarea",
68
+ "xmp",
69
+ "iframe",
70
+ "noembed",
71
+ "noframes",
72
+ "noscript",
73
+ "plaintext",
74
+ ]);
75
+ function refuseSelfClosingRawText(tag) {
76
+ if (tag.selfClosing && RAW_TEXT.has(tag.name.toLowerCase()))
77
+ fail("a self-closing raw-text element");
78
+ }
79
+ function keepAttribute(name, value) {
80
+ // Verovio writes no entities in attributes; a character reference could decode to `url(` or `javascript:`.
81
+ if (value.includes("&"))
82
+ return false;
83
+ if ((name === "href" || name === "xlink:href") && !value.startsWith("#"))
84
+ return false;
85
+ if (/url\(/i.test(value.replace(/url\(\s*#/gi, "")))
86
+ return false;
87
+ return true;
88
+ }
89
+ const skipSpace = (src, from) => {
90
+ let p = from;
91
+ while (WHITESPACE.test(src[p] ?? "x"))
92
+ p++;
93
+ return p;
94
+ };
95
+ /** A quoted attribute value from `q`, free of `<`. */
96
+ function readValue(src, q) {
97
+ const quote = src[q];
98
+ if (quote !== '"' && quote !== "'")
99
+ fail("an unquoted attribute value");
100
+ const close = src.indexOf(quote, q + 1);
101
+ if (close < 0)
102
+ fail("an unbalanced quote");
103
+ const value = src.slice(q + 1, close);
104
+ if (value.includes("<"))
105
+ fail("a < in an attribute value");
106
+ return { value, end: close + 1 };
107
+ }
108
+ /** One `name="value"` from `p`. */
109
+ function readAttribute(src, p) {
110
+ const name = /^[^\s/>=<"']+/.exec(src.slice(p))?.[0] ?? fail("a bad attribute name");
111
+ const eq = skipSpace(src, p + name.length);
112
+ if (src[eq] !== "=")
113
+ fail("an attribute with no value");
114
+ return { name, ...readValue(src, skipSpace(src, eq + 1)) };
115
+ }
116
+ /** Where a start tag's attributes stop (`>` or `/>`), reading each into `attrs`. */
117
+ function readAttributes(src, from, attrs) {
118
+ let p = from;
119
+ while (src[p] !== undefined && src[p] !== ">" && !(src[p] === "/" && src[p + 1] === ">")) {
120
+ if (src[p] === "/" || WHITESPACE.test(src[p] ?? "")) {
121
+ p++;
122
+ continue;
123
+ }
124
+ const attr = readAttribute(src, p);
125
+ attrs.push([attr.name, attr.value]);
126
+ p = attr.end;
127
+ }
128
+ if (src[p] === undefined)
129
+ fail("a tag that never ends");
130
+ return p;
131
+ }
132
+ /** One start tag from `i` (at `<`); `/` and whitespace both separate attributes. Throws on anything unclean. */
133
+ function readStartTag(src, i) {
134
+ const name = NAME.exec(src.slice(i + 1))?.[0] ?? fail("a tag with no name");
135
+ const attrs = [];
136
+ const p = readAttributes(src, i + 1 + name.length, attrs);
137
+ const selfClosing = src[p] === "/";
138
+ const spaced = selfClosing && WHITESPACE.test(src[p - 1] ?? "");
139
+ return { name, attrs, selfClosing, spaced, end: p + (selfClosing ? 2 : 1) };
140
+ }
141
+ function writeTag(tag) {
142
+ const allowed = ALLOWED[tag.name] ?? [];
143
+ const attrs = tag.attrs
144
+ .filter(([n, v]) => allowed.includes(n) && keepAttribute(n, v))
145
+ .map(([n, v]) => ` ${n}="${v.replaceAll('"', "&quot;")}"`)
146
+ .join("");
147
+ return `<${tag.name}${attrs}${tag.selfClosing ? (tag.spaced ? " />" : "/>") : ">"}`;
148
+ }
149
+ /** A closing tag from `i`; returns where it ends, writing it if its element was written. */
150
+ function readEndTag(src, i, open, out) {
151
+ const name = NAME.exec(src.slice(i + 2))?.[0] ?? fail("a closing tag with no name");
152
+ const p = skipSpace(src, i + 2 + name.length);
153
+ if (src[p] !== ">")
154
+ fail("a closing tag that never ends");
155
+ const top = open.pop();
156
+ if (top?.name !== name)
157
+ fail("a closing tag that matches nothing");
158
+ if (top.emit)
159
+ out.push(`</${name}>`);
160
+ return p + 1;
161
+ }
162
+ /** A `<style>`'s text after `tag`: kept only if it is one of Verovio's. Returns where its end tag starts. */
163
+ function readStyle(src, tag, emit, open, out) {
164
+ const close = src.indexOf("</style", tag.end);
165
+ const css = src.slice(tag.end, close < 0 ? undefined : close);
166
+ if (close < 0 || css.includes("<"))
167
+ fail("a style that never ends");
168
+ const write = emit && isVerovioStyle(css);
169
+ if (write)
170
+ out.push(writeTag(tag), css);
171
+ open.push({ name: "style", emit: write });
172
+ return close;
173
+ }
174
+ /**
175
+ * Verovio's SVG reduced to what Verovio emits: only the listed elements and
176
+ * attributes survive, an unlisted element goes with its content, links keep
177
+ * only `#` targets. Hand-scanned, no DOM. Throws if the markup cannot be read
178
+ * cleanly (unbalanced quotes, comments, a stray `<`, unclosed elements): the
179
+ * caller treats that as "could not draw".
180
+ */
181
+ export function cleanSvg(svg) {
182
+ const out = [];
183
+ // Open elements, each with whether it is written (false inside an unlisted element).
184
+ const open = [];
185
+ let i = 0;
186
+ while (i < svg.length) {
187
+ const lt = svg.indexOf("<", i);
188
+ if (open.every((o) => o.emit))
189
+ out.push(svg.slice(i, lt < 0 ? undefined : lt));
190
+ if (lt < 0)
191
+ break;
192
+ i = readTag(svg, lt, open, out);
193
+ }
194
+ if (open.length)
195
+ fail("an element that never closes");
196
+ return out.join("");
197
+ }
198
+ /** The tag at `i` (a `<`), written or dropped; returns where it ends. */
199
+ function readTag(svg, i, open, out) {
200
+ if (svg[i + 1] === "/")
201
+ return readEndTag(svg, i, open, out);
202
+ if (!/[A-Za-z]/.test(svg[i + 1] ?? ""))
203
+ fail("a < that starts no tag");
204
+ const emit = open.every((o) => o.emit);
205
+ const tag = readStartTag(svg, i);
206
+ refuseSelfClosingRawText(tag);
207
+ if (tag.name === "style" && !tag.selfClosing)
208
+ return readStyle(svg, tag, emit, open, out);
209
+ const write = emit && tag.name in ALLOWED;
210
+ if (write)
211
+ out.push(writeTag(tag));
212
+ if (!tag.selfClosing)
213
+ open.push({ name: tag.name, emit: write });
214
+ return tag.end;
215
+ }
216
+ /**
217
+ * The score's own layout. Colour comes from `@barmark/render`'s stylesheet
218
+ * (the `.bm-chart` wrapper that `scorePane` writes), which must be in the same
219
+ * shadow root; Verovio draws in `currentColor`, but its inner page svg carries `color="black"`, which `color:inherit` overrides.
220
+ */
221
+ export const scoreStyles = `.bms-score{padding:1rem;color:inherit;background:transparent}
222
+ .bms-score-page{width:100%}
223
+ .bms-score-page svg{display:block;width:100%;height:auto}
224
+ .bms-score-page svg{fill:currentColor}
225
+ .bms-score-page svg svg{color:inherit}`;
226
+ /** Text made safe for HTML content and quoted attribute values (`&` first, so nothing is escaped twice). */
227
+ export const escapeHtml = (text) => text
228
+ .replaceAll("&", "&amp;")
229
+ .replaceAll("<", "&lt;")
230
+ .replaceAll(">", "&gt;")
231
+ .replaceAll('"', "&quot;")
232
+ .replaceAll("'", "&#39;");
233
+ /**
234
+ * The cleaned pages in a themed pane: render's `.bm-chart` supplies the
235
+ * palette. The score is one image to assistive technology, named `label`
236
+ * (the chart's title, say), or "Score".
237
+ */
238
+ export function scorePane(svg, theme, label = "Score") {
239
+ return `<div class="bm-chart" data-theme="${theme}"><div class="bms-score" role="img" aria-label="${escapeHtml(label)}">${cleanSvg(svg)}</div></div>`;
240
+ }
@@ -0,0 +1,14 @@
1
+ import { type RenderOptions } from "@barmark/render";
2
+ import { type ScoreView, switchHtml } from "./switch.js";
3
+ export type ScoreOptions = RenderOptions & {
4
+ view?: ScoreView;
5
+ };
6
+ export { decodeCarried } from "./shell.js";
7
+ export { switchHtml };
8
+ /**
9
+ * `<barmark-score>` drawn on the server: the grid, the Grid / Score switch and
10
+ * the chart text, so the grid shows before any script runs. The switch checks
11
+ * Grid, since the grid is what shows; `view: "score"` is kept as the element's
12
+ * attribute, and the element switches to the score once it loads.
13
+ */
14
+ export declare function renderScoreHtml(text: string, options?: ScoreOptions): string;
package/dist/server.js ADDED
@@ -0,0 +1,26 @@
1
+ // The server entry. It imports only @barmark/render, ./shell.js, ./switch.js and ./markup.js:
2
+ // never ./index.js, whose engine reaches the Verovio worker.
3
+ import { fontFaceCss, renderChart, renderChartUnwrapped, } from "@barmark/render";
4
+ import { carry, scoreShell } from "./shell.js";
5
+ import { switchHtml, viewOf } from "./switch.js";
6
+ export { decodeCarried } from "./shell.js";
7
+ export { switchHtml };
8
+ /** The attributes `renderChart` writes for these options, so the two elements agree. */
9
+ function gridAttributes(options) {
10
+ const html = renderChart("", options);
11
+ return /^<barmark-chart([^>]*)>/.exec(html)?.[1] ?? "";
12
+ }
13
+ /**
14
+ * `<barmark-score>` drawn on the server: the grid, the Grid / Score switch and
15
+ * the chart text, so the grid shows before any script runs. The switch checks
16
+ * Grid, since the grid is what shows; `view: "score"` is kept as the element's
17
+ * attribute, and the element switches to the score once it loads.
18
+ */
19
+ export function renderScoreHtml(text, options = {}) {
20
+ const { view: asked, fontUrl, ...gridOptions } = options;
21
+ const view = viewOf(asked);
22
+ const font = fontUrl ? `<style>${fontFaceCss(fontUrl)}</style>` : "";
23
+ const grid = renderChartUnwrapped(text, gridOptions);
24
+ const attrs = `${gridAttributes(gridOptions)}${view === "score" ? ' view="score"' : ""}`;
25
+ return `${font}<barmark-score${attrs}><template shadowrootmode="open">${scoreShell(grid, "grid")}</template><script type="text/barmark">${carry(text)}</script></barmark-score>`;
26
+ }
@@ -0,0 +1,9 @@
1
+ import { type ScoreView } from "./switch.js";
2
+ /** Chart text for a `<script>`: the two sequences that would end or hide it are written with a backslash. */
3
+ export declare const carry: (text: string) => string;
4
+ /** The text `renderScoreHtml` carried, as it was given. */
5
+ export declare const decodeCarried: (text: string) => string;
6
+ /** The shadow root's content around a drawn grid: styles, the switch, the grid, the (empty) score pane. */
7
+ export declare const scoreShell: (grid: string, view: ScoreView) => string;
8
+ /** A chart that could not be loaded, drawn where the grid would be, as `<barmark-chart>` draws it. */
9
+ export declare function gridError(message: string, theme: string): string;
package/dist/shell.js ADDED
@@ -0,0 +1,16 @@
1
+ // What the server and the element both write inside `<barmark-score>`'s shadow root,
2
+ // so client-drawn and server-drawn markup are the same. Verovio-free, like ./server.js.
3
+ import { stylesheet } from "@barmark/render";
4
+ import { escapeHtml, scoreStyles } from "./markup.js";
5
+ import { switchHtml, switchStyles } from "./switch.js";
6
+ /** Chart text for a `<script>`: the two sequences that would end or hide it are written with a backslash. */
7
+ export const carry = (text) => text.replace(/<\/(script)/gi, "<\\/$1").replaceAll("<!--", "<\\!--");
8
+ /** The text `renderScoreHtml` carried, as it was given. */
9
+ export const decodeCarried = (text) => text.replace(/<\\\/(script)/gi, "</$1").replaceAll("<\\!--", "<!--");
10
+ /** 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
+ /** A chart that could not be loaded, drawn where the grid would be, as `<barmark-chart>` draws it. */
13
+ export function gridError(message, theme) {
14
+ const m = escapeHtml(message);
15
+ return `<div class="bm-chart" data-theme="${escapeHtml(theme)}"><div class="bm-error" title="${m}"><code></code><span class="bm-sr">Error: ${m}</span></div></div>`;
16
+ }
@@ -0,0 +1,7 @@
1
+ export type ScoreView = "grid" | "score";
2
+ /** Anything but `"score"` is the grid. */
3
+ export declare const viewOf: (value: unknown) => ScoreView;
4
+ /** The Grid / Score switch: a radio group of two buttons, the current view checked. */
5
+ export declare function switchHtml(view: ScoreView): string;
6
+ /** The switch's own look, in render's palette variables. */
7
+ export declare const switchStyles = ".bms-switch{display:inline-flex;margin:0 0 .5rem;border:1px solid var(--bm-rule,currentColor);border-radius:.4rem;overflow:hidden}\n.bms-switch button{font:inherit;color:var(--bm-ink,inherit);background:transparent;border:0;padding:.25rem .75rem;cursor:pointer}\n.bms-switch button[aria-checked=\"true\"]{font-weight:bold;text-decoration:underline}\n.bms-switch button:focus-visible{outline:2px solid currentColor;outline-offset:-2px}\n.bms-switch button[aria-disabled=\"true\"]{opacity:.5;cursor:not-allowed}\n.bms-note{margin:0 0 .5rem;font-size:.875em;color:var(--bm-ink,inherit)}";
package/dist/switch.js ADDED
@@ -0,0 +1,14 @@
1
+ /** Anything but `"score"` is the grid. */
2
+ export const viewOf = (value) => (value === "score" ? "score" : "grid");
3
+ /** The Grid / Score switch: a radio group of two buttons, the current view checked. */
4
+ export function switchHtml(view) {
5
+ const radio = (value, label) => `<button type="button" role="radio" data-view="${value}" aria-checked="${view === value}"${view === value ? "" : ' tabindex="-1"'}>${label}</button>`;
6
+ return `<div class="bms-switch" role="radiogroup" aria-label="View">${radio("grid", "Grid")}${radio("score", "Score")}</div>`;
7
+ }
8
+ /** The switch's own look, in render's palette variables. */
9
+ export const switchStyles = `.bms-switch{display:inline-flex;margin:0 0 .5rem;border:1px solid var(--bm-rule,currentColor);border-radius:.4rem;overflow:hidden}
10
+ .bms-switch button{font:inherit;color:var(--bm-ink,inherit);background:transparent;border:0;padding:.25rem .75rem;cursor:pointer}
11
+ .bms-switch button[aria-checked="true"]{font-weight:bold;text-decoration:underline}
12
+ .bms-switch button:focus-visible{outline:2px solid currentColor;outline-offset:-2px}
13
+ .bms-switch button[aria-disabled="true"]{opacity:.5;cursor:not-allowed}
14
+ .bms-note{margin:0 0 .5rem;font-size:.875em;color:var(--bm-ink,inherit)}`;
@@ -0,0 +1,8 @@
1
+ import { VerovioToolkit } from "verovio/esm";
2
+ import type { Reply, Request } from "./engine.js";
3
+ type Toolkit = VerovioToolkit;
4
+ /** Run `load` once and keep its result; a load that fails is forgotten, so the next call tries again. */
5
+ export declare function loadOnce<A, T>(load: (arg: A) => Promise<T>): (arg: A) => Promise<T>;
6
+ /** Answer one request. Never throws: a failure is a reply with its reason. */
7
+ export declare function handle(request: Request, loaded: () => Promise<Toolkit>): Promise<Reply>;
8
+ export {};
package/dist/worker.js ADDED
@@ -0,0 +1,52 @@
1
+ import * as esm from "verovio/esm";
2
+ import { VerovioToolkit } from "verovio/esm";
3
+ import { engraveChart } from "./engrave.js";
4
+ // Verovio's typings omit the log switch; it is exported all the same.
5
+ const { enableLog, LOG_OFF } = esm;
6
+ /** Run `load` once and keep its result; a load that fails is forgotten, so the next call tries again. */
7
+ export function loadOnce(load) {
8
+ let kept;
9
+ return (arg) => {
10
+ kept ??= load(arg).catch((err) => {
11
+ kept = undefined;
12
+ throw err;
13
+ });
14
+ return kept;
15
+ };
16
+ }
17
+ /**
18
+ * The page's one Verovio toolkit, loaded on first use and reused. By
19
+ * default the package's own `verovio/wasm`; when a request carries
20
+ * `verovioUrl` that module is imported instead. The first request whose
21
+ * load succeeds wins for the worker's life: later URLs are ignored.
22
+ */
23
+ const ready = loadOnce(async (verovioUrl) => {
24
+ const m = verovioUrl
25
+ ? await import(/* @vite-ignore */ verovioUrl)
26
+ : await import("verovio/wasm");
27
+ const module = await m.default();
28
+ enableLog(LOG_OFF, module);
29
+ return new VerovioToolkit(module);
30
+ });
31
+ /** Answer one request. Never throws: a failure is a reply with its reason. */
32
+ export async function handle(request, loaded) {
33
+ const { id, text, width } = request;
34
+ try {
35
+ const r = engraveChart(await loaded(), text, { width });
36
+ return r.ok
37
+ ? { id, ok: true, svg: r.svg, pages: r.pages }
38
+ : { id, ok: false, reason: r.reason };
39
+ }
40
+ catch (err) {
41
+ return { id, ok: false, reason: String(err) };
42
+ }
43
+ }
44
+ const scope = globalThis;
45
+ // Only a worker global answers messages: importing this in a page or a test has no effect.
46
+ if (typeof scope.WorkerGlobalScope === "function" &&
47
+ globalThis instanceof scope.WorkerGlobalScope) {
48
+ scope.onmessage = async (e) => {
49
+ const { verovioUrl } = e.data;
50
+ scope.postMessage(await handle(e.data, () => ready(verovioUrl)));
51
+ };
52
+ }