guidex 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1002 +0,0 @@
1
- import { A as stanzaWarnings, C as selectStanza, D as stackedStanzaNumbers, E as stackStanzas, P as GuidoScript, d as transposeBy, o as STYLE_SETS, r as layoutScore, s as inlineStylesFor } from "./chantLayout-B0xiaMo9.js";
2
- //#region src/guidoRender.ts
3
- /**
4
- * Renders a GuidoScript into a tidy score: a notes line in the chant font,
5
- * and a text line where each syllable is centered below its notes.
6
- *
7
- * The DOM emitter of the shared layout pass (`layoutScore` in
8
- * chantLayout.ts, which owns every line-breaking and placement decision):
9
- * `render` turns the laid-out lines into (notes `.guido` div, text `<p>`)
10
- * pairs — px-measured inline-block spacer spans fake the horizontal gaps.
11
- * The Word export (wordExport.ts) consumes the same layout with a
12
- * character-based spacer mechanism instead. Given several underlays of
13
- * one melody (stacked stanzas, issue #84 — see `stackStanzas`), every
14
- * notes line is followed by one text `<p>` per underlay.
15
- */
16
- var GuidoRender = class GuidoRender {
17
- script;
18
- constructor(source) {
19
- const parse = (s) => typeof s === "string" ? new GuidoScript(s) : s;
20
- this.script = typeof source === "string" || source instanceof GuidoScript ? parse(source) : source.map(parse);
21
- }
22
- /**
23
- * Renders the score into `container` as (notes line, text line) pairs.
24
- * When `maxWidthPx` is finite, a new pair starts before any syllable
25
- * whose notes would push the current notes line past it; the clef is
26
- * repeated at the start of every line. Throws when the style set is
27
- * unknown or one of its fonts cannot be loaded.
28
- */
29
- async render(container, options = {}) {
30
- const { debug = false } = options;
31
- const { lines, styleSet, styleName, textPx, notesPx, bold, starTarget, starWidth } = await layoutScore(this.script, options);
32
- container.style.fontSize = `${textPx}px`;
33
- container.style.fontFamily = styleSet.textFontStack;
34
- container.dataset.style = styleName;
35
- container.replaceChildren(...lines.flatMap((l) => [GuidoRender.notesLine(l, notesPx, starTarget, starWidth, debug), ...l.texts.map((text) => GuidoRender.textLine(text, textPx, bold, debug))]));
36
- }
37
- /** Builds a line's notes div: the chant font text plus, on broken
38
- * lines, the break marker `*` as an inline span (so it shares the
39
- * text's baseline) shifted right so its right edge lands on the
40
- * padding-extended max-width position. position: relative keeps the
41
- * shift out of the flow measurements. */
42
- static notesLine(line, notesPx, starTarget, starWidth, debug) {
43
- const notesEl = document.createElement("div");
44
- notesEl.className = "guido";
45
- notesEl.style.fontSize = `${notesPx}px`;
46
- notesEl.textContent = line.clefPrefix + line.notesParts.join("");
47
- if (line.breakMarkerLeftPx !== void 0) {
48
- const star = document.createElement("span");
49
- star.className = "guido-break";
50
- star.textContent = "*";
51
- star.style.position = "relative";
52
- star.style.left = `${line.breakMarkerLeftPx}px`;
53
- if (debug) star.title = `line break at ${starTarget.toFixed(1)}px (staff filled to ${(starTarget - line.breakMarkerLeftPx - starWidth).toFixed(1)}px)`;
54
- notesEl.appendChild(star);
55
- }
56
- return notesEl;
57
- }
58
- /** Builds a line's text paragraph from its segments: spacer spans fake
59
- * every horizontal gap (lead-in, word gaps, dash connector pads), each
60
- * syllable is one span of nested runs, and word spaces are their own
61
- * spans. */
62
- static textLine(line, textPx, bold, debug) {
63
- const textEl = document.createElement("p");
64
- if (bold) textEl.style.fontWeight = "700";
65
- for (const seg of line.segments) switch (seg.kind) {
66
- case "gap": {
67
- const spacerEl = GuidoRender.spacer(seg.width);
68
- if (debug) spacerEl.title = `${seg.role === "lead-in" ? "lead-in" : "word gap"} ${seg.width.toFixed(1)}px → text ${seg.textStartPx.toFixed(1)}`;
69
- textEl.appendChild(spacerEl);
70
- break;
71
- }
72
- case "connector": {
73
- const leadPad = GuidoRender.spacer(seg.pad);
74
- const dash = document.createElement("span");
75
- dash.className = "dash";
76
- dash.textContent = "-";
77
- const trailPad = GuidoRender.spacer(seg.pad);
78
- if (debug) {
79
- leadPad.title = `lead pad ${seg.pad.toFixed(1)}px (gap ${seg.gapWidth.toFixed(1)} − dash ${seg.dashWidth.toFixed(1)}, halved)`;
80
- dash.title = `dash ${seg.dashWidth.toFixed(1)}px`;
81
- trailPad.title = `trail pad ${seg.pad.toFixed(1)}px`;
82
- }
83
- textEl.append(leadPad, dash, trailPad);
84
- break;
85
- }
86
- case "syl": {
87
- const span = GuidoRender.sylSpan(seg.parts, textPx);
88
- if (debug) {
89
- if (seg.noNotes) span.title = `no notes, text w ${seg.textWidth.toFixed(1)}, ${seg.trailing ? "end of score" : "before the next syllable with notes"}`;
90
- else {
91
- const theoDiff = (seg.textWidth - seg.contentWidth) / 2;
92
- const cursDiff = seg.textStart - seg.contentStart;
93
- span.title = [
94
- `text w ${seg.textWidth.toFixed(1)}`,
95
- `notes w ${seg.contentWidth.toFixed(1)}`,
96
- seg.extraDashes ? `+${seg.extraDashes} pad dash(es)` : null,
97
- `text start ${seg.textStart.toFixed(1)}`,
98
- `notes start ${seg.contentStart.toFixed(1)}`,
99
- `theoDiff: ${theoDiff.toFixed(1)}`,
100
- `cursDiff: ${cursDiff.toFixed(1)}`
101
- ].filter(Boolean).join(", ");
102
- }
103
- }
104
- textEl.appendChild(span);
105
- break;
106
- }
107
- case "word-space": {
108
- const ws = document.createElement("span");
109
- ws.className = "word-space";
110
- ws.textContent = " ";
111
- if (debug) ws.title = `word space ${seg.width.toFixed(1)}px`;
112
- textEl.appendChild(ws);
113
- break;
114
- }
115
- case "line-end-dash": {
116
- const leadPad = GuidoRender.spacer(seg.pad);
117
- const dash = document.createElement("span");
118
- dash.className = "dash";
119
- dash.textContent = "-";
120
- const trailPad = GuidoRender.spacer(seg.pad);
121
- if (debug) {
122
- leadPad.title = `lead pad ${seg.pad.toFixed(1)}px → line-end dash (text end ${seg.textEndPx.toFixed(1)}, notes end ${seg.trailEndPx.toFixed(1)})`;
123
- dash.title = `dash ${seg.dashWidth.toFixed(1)}px (line end)`;
124
- trailPad.title = `trail pad ${seg.pad.toFixed(1)}px`;
125
- }
126
- textEl.append(leadPad, dash, trailPad);
127
- break;
128
- }
129
- }
130
- return textEl;
131
- }
132
- /** Builds a syllable span from its resolved runs: one nested span per
133
- * run, carrying the run's inline styles and its notation-fixed kind
134
- * class (`liturgy`, `rubric`, `star`, `marker`, `plus`); runs marked
135
- * `initial` by the `*…*` marker carry the initial class. */
136
- static sylSpan(parts, textPx) {
137
- const sylSpan = document.createElement("span");
138
- sylSpan.className = "syl";
139
- parts.forEach((part) => {
140
- const partSpan = document.createElement("span");
141
- partSpan.textContent = part.text;
142
- for (const [prop, value] of Object.entries(inlineStylesFor(part.style, textPx))) partSpan.style.setProperty(prop, value);
143
- const classes = [...part.kind ? [part.kind] : [], ...part.style.initial ? ["initial"] : []].join(" ");
144
- if (classes) partSpan.className = classes;
145
- sylSpan.appendChild(partSpan);
146
- });
147
- return sylSpan;
148
- }
149
- static spacer(width) {
150
- const spacer = document.createElement("span");
151
- spacer.className = "spacer";
152
- spacer.style.display = "inline-block";
153
- spacer.style.width = `${width}px`;
154
- return spacer;
155
- }
156
- };
157
- //#endregion
158
- //#region src/embed/core.ts
159
- var version = {
160
- name: "guidex",
161
- version: "0.3.2",
162
- description: "Guidex — render plainchant scores from a compact GuidoScript notation, as a web app and an embeddable runtime",
163
- type: "module",
164
- workspaces: ["examples/*"],
165
- main: "./dist/lib/embed/manual.js",
166
- types: "./dist/lib/embed/manual.d.ts",
167
- exports: {
168
- ".": {
169
- "types": "./dist/lib/embed/manual.d.ts",
170
- "default": "./dist/lib/embed/manual.js"
171
- },
172
- "./embed": {
173
- "types": "./dist/lib/embed/index.d.ts",
174
- "default": "./dist/lib/embed/index.js"
175
- },
176
- "./guidex.css": {
177
- "types": "./dist/lib/guidex.css.d.ts",
178
- "default": "./dist/lib/guidex.css"
179
- },
180
- "./fonts/*": "./dist/lib/fonts/*",
181
- "./react": {
182
- "types": "./dist/lib/react/index.d.ts",
183
- "default": "./dist/lib/react/index.js"
184
- },
185
- "./word": {
186
- "types": "./dist/lib/word/index.d.ts",
187
- "default": "./dist/lib/word/index.js"
188
- }
189
- },
190
- files: ["dist-embed", "dist/lib"],
191
- peerDependencies: { "react": ">=18" },
192
- peerDependenciesMeta: { "react": { "optional": true } },
193
- publishConfig: { "access": "public" },
194
- scripts: {
195
- "dev": "vite --host",
196
- "build": "tsc && vite build",
197
- "build:embed": "vite build --config vite.embed.config.ts",
198
- "build:lib": "vite build --config vite.lib.config.ts",
199
- "preview": "vite preview",
200
- "test": "vitest run",
201
- "lint": "eslint ."
202
- },
203
- keywords: [
204
- "plainchant",
205
- "gregorian",
206
- "guido",
207
- "score",
208
- "notation",
209
- "liturgy"
210
- ],
211
- repository: {
212
- "type": "git",
213
- "url": "git+https://github.com/BrownieMaar/guidex.git"
214
- },
215
- bugs: { "url": "https://github.com/BrownieMaar/guidex/issues" },
216
- homepage: "https://github.com/BrownieMaar/guidex#readme",
217
- devDependencies: {
218
- "@eslint/js": "^10.0.1",
219
- "@testing-library/dom": "^10.4.2",
220
- "@testing-library/react": "^16.3.3",
221
- "@testing-library/user-event": "^14.6.7",
222
- "@types/react": "^19.3.0",
223
- "@types/react-dom": "^19.3.0",
224
- "@vitejs/plugin-react": "^6.1.1",
225
- "eslint": "^10.10.0",
226
- "jsdom": "^29.1.1",
227
- "react": "^19.3.0",
228
- "react-dom": "^19.3.0",
229
- "typescript": "~6.0.2",
230
- "typescript-eslint": "^8.70.0",
231
- "vite": "^8.2.2",
232
- "vite-plugin-dts": "^5.1.1",
233
- "vitest": "^4.1.11"
234
- }
235
- }.version;
236
- var DEFAULT_SELECTOR = ".guidex-script, .guido-script";
237
- var DEFAULTS = {
238
- maxWidth: "auto",
239
- style: "BNS",
240
- bold: false,
241
- textPx: 18,
242
- transpose: 0,
243
- stanza: 1,
244
- stack: void 0,
245
- emptySlots: "normal",
246
- stanzas: void 0,
247
- debug: false
248
- };
249
- var globalOptions = {};
250
- /** The raw script of each target, cached across re-renders: rendering
251
- * replaces the element's content, so the original text would be lost. */
252
- var sources = /* @__PURE__ */ new WeakMap();
253
- /** Per-element render race counter: a slow render (font loading) must
254
- * never overwrite a newer one's output. */
255
- var runs = /* @__PURE__ */ new WeakMap();
256
- /** The line-breaking budget each element last rendered at; resize
257
- * re-renders are skipped while the width is unchanged (height-only
258
- * ResizeObserver entries from our own renders must not loop). */
259
- var lastWidths = /* @__PURE__ */ new WeakMap();
260
- /** data-* boolean attribute: bare presence or 'true' → true, 'false' →
261
- * false, anything else → unset. */
262
- function flag(value) {
263
- if (value === void 0) return void 0;
264
- if (value === "" || value === "true") return true;
265
- if (value === "false") return false;
266
- }
267
- function number(value) {
268
- if (value === void 0) return void 0;
269
- const n = Number(value);
270
- return Number.isFinite(n) ? n : void 0;
271
- }
272
- function parseMaxWidth(value, fallback) {
273
- if (/^auto$/i.test(value.trim())) return "auto";
274
- const n = Number(value);
275
- if (Number.isFinite(n) && n > 0) return n;
276
- console.warn(`[guidex] ignoring invalid data-max-width "${value}"`);
277
- return fallback;
278
- }
279
- /** Per-element option overrides set by `renderScore` (programmatic
280
- * callers): element data attributes win over these, these win over
281
- * `init` site-wide defaults. */
282
- var overrides = /* @__PURE__ */ new WeakMap();
283
- function emptySlotsValue(value) {
284
- if (value === void 0) return void 0;
285
- if (value === "normal" || value === "small" || value === "partial") return value;
286
- console.warn(`[guidex] ignoring invalid data-empty-slots "${value}"`);
287
- }
288
- /** `data-stack`: `all`, or a comma-separated list of stanza numbers. */
289
- function stackValue(value) {
290
- if (value === void 0) return void 0;
291
- if (/^\s*all\s*$/i.test(value)) return "all";
292
- const list = value.split(",").map((n) => Number(n.trim()));
293
- if (value.trim() !== "" && list.every((n) => Number.isInteger(n) && n > 0)) return list;
294
- console.warn(`[guidex] ignoring invalid data-stack "${value}"`);
295
- }
296
- /** Element data attributes (or unset) over `renderScore` overrides over
297
- * init options over defaults. */
298
- function readOptions(el) {
299
- const ds = el.dataset;
300
- const local = overrides.get(el) ?? {};
301
- return {
302
- maxWidth: ds.maxWidth !== void 0 ? parseMaxWidth(ds.maxWidth, local.maxWidth ?? globalOptions.maxWidth ?? DEFAULTS.maxWidth) : local.maxWidth ?? globalOptions.maxWidth ?? DEFAULTS.maxWidth,
303
- style: ds.style ?? local.style ?? globalOptions.style ?? DEFAULTS.style,
304
- bold: flag(ds.bold) ?? local.bold ?? globalOptions.bold ?? DEFAULTS.bold,
305
- textPx: number(ds.textPx) ?? local.textPx ?? globalOptions.textPx ?? DEFAULTS.textPx,
306
- transpose: number(ds.transpose) ?? local.transpose ?? globalOptions.transpose ?? DEFAULTS.transpose,
307
- stanza: number(ds.stanza) ?? local.stanza ?? globalOptions.stanza ?? DEFAULTS.stanza,
308
- stack: stackValue(ds.stack) ?? local.stack ?? globalOptions.stack ?? DEFAULTS.stack,
309
- emptySlots: emptySlotsValue(ds.emptySlots) ?? local.emptySlots ?? globalOptions.emptySlots ?? DEFAULTS.emptySlots,
310
- stanzas: local.stanzas ?? DEFAULTS.stanzas,
311
- debug: flag(ds.debug) ?? local.debug ?? globalOptions.debug ?? DEFAULTS.debug
312
- };
313
- }
314
- /** The element's content-box width (the score wrapper spans it), the
315
- * line-box width the rendered score actually has to fit. Falls back to
316
- * the parent for inline targets; zero means no layout (hidden). */
317
- function contentWidthPx(el) {
318
- return el.querySelector(":scope > .guidex-render")?.clientWidth || el.clientWidth || el.parentElement?.clientWidth || 0;
319
- }
320
- /** The line-breaking budget in pixels for this render. Fixed values pass
321
- * through; 'auto' fits the element's content box, shrunk by the style
322
- * set's break-star padding: the renderer hangs the `guido-break` star
323
- * `padding` px past the budget, and when the budget is the line-box
324
- * width itself that star would overflow the line and wrap. A zero width
325
- * (hidden element) renders unbroken; once it becomes visible the resize
326
- * listener re-renders it at the real width. */
327
- function resolveWidthPx(el, maxWidth, style) {
328
- if (typeof maxWidth === "number") return maxWidth;
329
- const width = contentWidthPx(el);
330
- if (width <= 0) return Infinity;
331
- const budget = width - (STYLE_SETS[style]?.padding ?? 0);
332
- return budget > 0 ? budget : width;
333
- }
334
- /** The element's script source: a fresh non-empty text node wins (so
335
- * hosts can update the source by setting textContent and calling
336
- * renderAll), otherwise the cached one from the previous render. */
337
- function extractSource(el) {
338
- for (const node of el.childNodes) if (node.nodeType === Node.TEXT_NODE && node.nodeValue?.trim()) return node.nodeValue.trim();
339
- return sources.get(el) ?? "";
340
- }
341
- /** The score wrapper inside the target; the renderer swaps the score
342
- * into it, never touching the target element's own classes or dataset. */
343
- function scoreWrapper(el) {
344
- const existing = el.querySelector(":scope > .guidex-render");
345
- if (existing) return existing;
346
- const wrapper = document.createElement("div");
347
- wrapper.className = "guidex-render";
348
- el.replaceChildren(wrapper);
349
- return wrapper;
350
- }
351
- function renderError(wrapper, message) {
352
- const note = document.createElement("p");
353
- note.className = "guidex-error";
354
- note.textContent = message;
355
- wrapper.replaceChildren(note);
356
- }
357
- /** The transforms a score renders with after the stanza swap: the style
358
- * set's defaults (BNS marks the first initial), then the user-requested
359
- * transpose. An unknown style name yields no defaults here — the render
360
- * itself reports it. */
361
- function scriptTransforms(options) {
362
- const transforms = [...STYLE_SETS[options.style]?.scriptTransforms ?? []];
363
- if (options.transpose !== 0) transforms.push(transposeBy(options.transpose));
364
- return transforms;
365
- }
366
- /** The scripts a score renders: the stacked stanzas when a stack is set
367
- * (one text line each), otherwise the one stanza — the stanza swap runs
368
- * first, so the other transforms see the stanza's text. Returns the
369
- * rendered stanzas' count mismatches with them. */
370
- function renderedScripts(source, options) {
371
- const transforms = scriptTransforms(options);
372
- const { stanzas, emptySlots } = options;
373
- if (options.stack !== void 0) {
374
- const rendered = stackedStanzaNumbers(source, options.stack, { stanzas });
375
- return {
376
- scripts: stackStanzas(source, rendered, {
377
- stanzas,
378
- emptySlots,
379
- transforms
380
- }),
381
- warnings: rendered.flatMap((stanza) => stanzaWarnings(source, {
382
- stanzas,
383
- stanza
384
- }))
385
- };
386
- }
387
- if (options.stanza !== 1 || emptySlots !== "normal") transforms.unshift(selectStanza(options.stanza, {
388
- stanzas,
389
- emptySlots
390
- }));
391
- return {
392
- scripts: [new GuidoScript(source, { transforms })],
393
- warnings: stanzaWarnings(source, {
394
- stanzas,
395
- stanza: options.stanza
396
- })
397
- };
398
- }
399
- /** Builds the score into a detached scratch wrapper and swaps it into
400
- * the live one only when this run is still the latest — a stale render
401
- * that finished late leaves no footprint. A failure (a script or stanza
402
- * error, an unloadable font) replaces the score with an error note.
403
- * Resolves with the rendered stanza's warnings, also logged. */
404
- async function drawScore(el, run, source, options, widthPx) {
405
- const wrapper = scoreWrapper(el);
406
- const scratch = document.createElement("div");
407
- try {
408
- const { scripts, warnings } = renderedScripts(source, options);
409
- await new GuidoRender(scripts).render(scratch, {
410
- style: options.style,
411
- bold: options.bold,
412
- textPx: options.textPx,
413
- debug: options.debug,
414
- maxWidthPx: widthPx
415
- });
416
- if (runs.get(el) !== run) return { warnings };
417
- for (const warning of warnings) console.warn(`[guidex] ${warning.message}`);
418
- wrapper.replaceChildren(...scratch.childNodes);
419
- wrapper.style.cssText = scratch.style.cssText;
420
- if (scratch.dataset.style) wrapper.dataset.style = scratch.dataset.style;
421
- return { warnings };
422
- } catch (e) {
423
- if (runs.get(el) !== run) return { warnings: [] };
424
- console.error("[guidex]", e);
425
- renderError(wrapper, e instanceof Error ? e.message : String(e));
426
- return { warnings: [] };
427
- }
428
- }
429
- /** Renders one target element from its source and resolved options. */
430
- async function renderElement(el) {
431
- const run = (runs.get(el) ?? 0) + 1;
432
- runs.set(el, run);
433
- const options = readOptions(el);
434
- const source = extractSource(el);
435
- sources.set(el, source);
436
- scoreWrapper(el);
437
- const widthPx = resolveWidthPx(el, options.maxWidth, options.style);
438
- lastWidths.set(el, widthPx);
439
- await drawScore(el, run, source, options, widthPx);
440
- }
441
- /** Sets up one resize listener per target element, on first render.
442
- * Only a changed line-breaking budget (width) triggers a re-render. */
443
- var detachFns = /* @__PURE__ */ new WeakMap();
444
- function widthChanged(el) {
445
- const options = readOptions(el);
446
- const width = resolveWidthPx(el, options.maxWidth, options.style);
447
- return Math.abs(width - (lastWidths.get(el) ?? NaN)) > 1;
448
- }
449
- function attachResizeListener(el) {
450
- if (detachFns.has(el)) return;
451
- let detach;
452
- if (typeof ResizeObserver !== "undefined") {
453
- const observer = new ResizeObserver(() => {
454
- if (widthChanged(el)) renderElement(el);
455
- });
456
- observer.observe(el);
457
- detach = () => observer.disconnect();
458
- } else {
459
- const onResize = () => {
460
- if (widthChanged(el)) renderElement(el);
461
- };
462
- window.addEventListener("resize", onResize);
463
- detach = () => window.removeEventListener("resize", onResize);
464
- }
465
- detachFns.set(el, detach);
466
- }
467
- /** Cleans up a programmatically rendered element: stops resize
468
- * re-rendering and drops the cached source and option overrides. Does
469
- * not remove the rendered score itself. */
470
- function dispose(el) {
471
- detachFns.get(el)?.();
472
- detachFns.delete(el);
473
- sources.delete(el);
474
- overrides.delete(el);
475
- runs.delete(el);
476
- lastWidths.delete(el);
477
- }
478
- /** Renders a GuidoScript source string into one element
479
- * programmatically — no selector scanning, no site-wide state. The
480
- * element's own text content is replaced by the rendered score and
481
- * re-rendered on resize. Call again with a new source to update.
482
- * Options set here override `init` defaults; data attributes on the
483
- * element still win. `stanzas` replaces the script's `(@stanza …)`
484
- * statements. Resolves when the score has finished rendering, with the
485
- * rendered stanza's count mismatches. */
486
- async function renderScore(el, source, options = {}) {
487
- overrides.set(el, options);
488
- const run = (runs.get(el) ?? 0) + 1;
489
- runs.set(el, run);
490
- sources.set(el, source);
491
- const resolved = readOptions(el);
492
- scoreWrapper(el);
493
- const widthPx = resolveWidthPx(el, resolved.maxWidth, resolved.style);
494
- lastWidths.set(el, widthPx);
495
- attachResizeListener(el);
496
- return drawScore(el, run, source, resolved, widthPx);
497
- }
498
- /** Renders every target under `root` (default: the whole document).
499
- * Already-rendered targets re-render from their cached source, so a
500
- * host can change data attributes or the source text and call this to
501
- * refresh. Resolves when every score has finished rendering. */
502
- async function renderAll(root = document) {
503
- const selector = globalOptions.selector ?? DEFAULT_SELECTOR;
504
- const targets = [];
505
- if (root instanceof Element && root.matches(selector)) targets.push(root);
506
- targets.push(...root.querySelectorAll(selector));
507
- return Promise.all(targets.map((el) => {
508
- attachResizeListener(el);
509
- return renderElement(el);
510
- })).then(() => void 0);
511
- }
512
- /** Late-added elements (AJAX, SPA routing) render too: document-wide
513
- * child mutations are scanned for matching targets. Our own score
514
- * elements are skipped, so renders never re-trigger the observer. */
515
- var observerStarted = false;
516
- function startMutationObserver() {
517
- if (observerStarted || typeof MutationObserver === "undefined") return;
518
- observerStarted = true;
519
- const selector = globalOptions.selector ?? DEFAULT_SELECTOR;
520
- new MutationObserver((mutations) => {
521
- const targets = /* @__PURE__ */ new Set();
522
- for (const mutation of mutations) for (const node of mutation.addedNodes) {
523
- if (!(node instanceof Element)) continue;
524
- if (node.closest(".guidex-render")) continue;
525
- if (node.matches(selector)) targets.add(node);
526
- for (const match of node.querySelectorAll(selector)) targets.add(match);
527
- }
528
- for (const el of targets) {
529
- attachResizeListener(el);
530
- renderElement(el);
531
- }
532
- }).observe(document.documentElement, {
533
- childList: true,
534
- subtree: true
535
- });
536
- }
537
- /** Sets site-wide defaults and renders the document. Call again (even
538
- * with different options) to re-render everything with new settings. */
539
- function init(options = {}) {
540
- globalOptions = {
541
- ...globalOptions,
542
- ...options
543
- };
544
- startMutationObserver();
545
- renderAll();
546
- }
547
- //#endregion
548
- //#region src/scoreImage.ts
549
- /** The computed properties that draw a score line and its content:
550
- * everything load-bearing beyond the renderer's own inline styles (the
551
- * notes line's leading and padding, the theme's resolved colors, the
552
- * relative shifts) comes from this list. Box widths are deliberately
553
- * absent — a block line spans its container, not its content, and the
554
- * sized elements (the spacer spans) already carry inline widths. */
555
- var COPY_PROPS = [
556
- "font-family",
557
- "font-size",
558
- "font-style",
559
- "font-weight",
560
- "line-height",
561
- "letter-spacing",
562
- "text-transform",
563
- "color",
564
- "position",
565
- "top",
566
- "left",
567
- "margin-top",
568
- "margin-bottom",
569
- "padding-top",
570
- "padding-bottom"
571
- ];
572
- /** The wrapper (the render container's stand-in) gets typography only:
573
- * no box properties, so the cloned lines stack from the crop's own
574
- * top-left corner. */
575
- var WRAPPER_PROPS = [
576
- "font-family",
577
- "font-size",
578
- "font-style",
579
- "font-weight",
580
- "line-height",
581
- "letter-spacing",
582
- "color"
583
- ];
584
- /** Debug/export furniture skipped when cloning: the editor's max-width
585
- * guide and anything the host marks with `data-score-image-ignore`. The
586
- * debug syllable guides need no entry — they are ::before/::after CSS,
587
- * which never clones. */
588
- function isIgnorable(el) {
589
- return el.classList.contains("max-width-guide") || el.hasAttribute("data-score-image-ignore");
590
- }
591
- /** The element whose direct children are the rendered line pairs: the
592
- * parent of the first chant-font line under `el`. Accepts the render
593
- * container itself or any ancestor of it (the editor's outer score div,
594
- * an embed target). */
595
- function scoreRoot(el) {
596
- const root = el.querySelector(".guido")?.parentElement;
597
- if (!root) throw new Error("No rendered score found to export — render a score into the element first.");
598
- return root;
599
- }
600
- /** One line's content extent, relative to the line box's own top-left
601
- * corner: the union of its contents' rects. The line box itself is
602
- * excluded horizontally (it spans the container, not the text); the
603
- * Range covers the text nodes and each descendant element rect keeps
604
- * the position:relative shifts (raised runs, the break star). */
605
- function lineExtent(line) {
606
- const box = line.getBoundingClientRect();
607
- const parts = [];
608
- const range = document.createRange();
609
- range.selectNodeContents(line);
610
- if (typeof range.getBoundingClientRect === "function") parts.push(range.getBoundingClientRect());
611
- line.querySelectorAll("*").forEach((el) => parts.push(el.getBoundingClientRect()));
612
- if (parts.length === 0) parts.push(box);
613
- return {
614
- left: Math.min(...parts.map((r) => r.left)) - box.left,
615
- top: Math.min(...parts.map((r) => r.top)) - box.top,
616
- right: Math.max(...parts.map((r) => r.right)) - box.left,
617
- bottom: Math.max(...parts.map((r) => r.bottom)) - box.top
618
- };
619
- }
620
- /** How many visual rows a line's content occupies: the Range's client
621
- * rects cluster into rows by vertical overlap (inline boxes of
622
- * different sizes sit side by side on one row with different tops). A
623
- * line that wraps inside its host container must re-wrap at the same
624
- * width in the clone, so it is pinned to its live box width. */
625
- function countRows(line) {
626
- const range = document.createRange();
627
- range.selectNodeContents(line);
628
- if (typeof range.getClientRects !== "function") return 1;
629
- const rects = Array.from(range.getClientRects()).filter((r) => r.width > 0 || r.height > 0);
630
- if (rects.length === 0) return 1;
631
- rects.sort((a, b) => a.top - b.top);
632
- let rows = 0;
633
- let rowBottom = -Infinity;
634
- for (const r of rects) if (r.top >= rowBottom) {
635
- rows++;
636
- rowBottom = r.bottom;
637
- } else if (r.bottom > rowBottom) rowBottom = r.bottom;
638
- return rows;
639
- }
640
- /** Splits a computed font-family stack into family names, honoring
641
- * quotes around names that contain commas. */
642
- function parseFamilies(stack) {
643
- const families = [];
644
- let current = "";
645
- let quote = null;
646
- for (const ch of stack) if (quote) {
647
- if (ch === quote) quote = null;
648
- else current += ch;
649
- } else if (ch === "\"" || ch === "'") quote = ch;
650
- else if (ch === ",") {
651
- families.push(current.trim());
652
- current = "";
653
- } else current += ch;
654
- families.push(current.trim());
655
- return families.filter(Boolean);
656
- }
657
- function normalizeWeight(weight) {
658
- if (weight === "normal") return "400";
659
- if (weight === "bold") return "700";
660
- return weight;
661
- }
662
- /** Escapes a value for use inside a double-quoted XML attribute. */
663
- function escapeXmlAttribute(value) {
664
- return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
665
- }
666
- /** Builds one face from a `src` value plus its descriptor strings,
667
- * resolving the URL against `baseHref`. Undefined when the src has no
668
- * fetchable url() (local()-only faces need no embedding). */
669
- function faceFromSrc(family, styleRaw, weightRaw, src, baseHref) {
670
- const urlMatch = /url\(\s*(['"]?)([^'")]+)\1\s*\)/.exec(src);
671
- if (!urlMatch) return void 0;
672
- let url;
673
- try {
674
- url = new URL(urlMatch[2], baseHref ?? location.href).toString();
675
- } catch {
676
- return;
677
- }
678
- return {
679
- family,
680
- style: styleRaw || "normal",
681
- weight: normalizeWeight(weightRaw || "400"),
682
- url,
683
- format: /format\(\s*['"]?([^'")]+?)['"]?\s*\)/.exec(src)?.[1]
684
- };
685
- }
686
- /** Parses @font-face blocks out of a stylesheet's raw text — the
687
- * fallback for cross-origin sheets whose `cssRules` are unreadable but
688
- * whose file a CORS fetch can still reach (the CDN-served embed build). */
689
- function parseFontFacesFromCss(cssText, baseUrl) {
690
- const faces = [];
691
- for (const match of cssText.matchAll(/@font-face\s*{([^}]*)}/g)) {
692
- const block = match[1];
693
- const pick = (prop) => {
694
- const m = new RegExp(`(?:^|[;\\s])${prop}\\s*:\\s*([^;]+)`, "i").exec(block);
695
- return m ? m[1].trim() : "";
696
- };
697
- const familyRaw = pick("font-family");
698
- const src = pick("src");
699
- if (!familyRaw || !src) continue;
700
- const family = parseFamilies(familyRaw)[0];
701
- if (!family) continue;
702
- const face = faceFromSrc(family, pick("font-style"), pick("font-weight"), src, baseUrl);
703
- if (face) faces.push(face);
704
- }
705
- return faces;
706
- }
707
- /** Collects the @font-face rules for `families` from every stylesheet.
708
- * Cross-origin sheets throw on `cssRules`; their text is fetched
709
- * instead and parsed by hand, so a CDN-served embed build's fonts still
710
- * travel with the export. Faces dedupe per family/style/weight — one
711
- * font file can legitimately serve several declarations. */
712
- async function collectFontFaces(families) {
713
- const faces = [];
714
- const seenKeys = /* @__PURE__ */ new Set();
715
- const addFace = (face) => {
716
- const key = `${face.family}|${face.style}|${face.weight}`;
717
- if (seenKeys.has(key)) return;
718
- seenKeys.add(key);
719
- faces.push(face);
720
- };
721
- const crossOriginSheets = [];
722
- for (const sheet of document.styleSheets) {
723
- let rules;
724
- try {
725
- rules = sheet.cssRules;
726
- } catch {
727
- if (sheet.href) crossOriginSheets.push(sheet.href);
728
- continue;
729
- }
730
- for (const rule of Array.from(rules)) {
731
- const style = rule.style;
732
- if (!style) continue;
733
- const src = style.getPropertyValue("src");
734
- const familyRaw = style.getPropertyValue("font-family");
735
- if (!src || !familyRaw) continue;
736
- const family = parseFamilies(familyRaw)[0];
737
- if (!family || !families.has(family)) continue;
738
- const face = faceFromSrc(family, style.getPropertyValue("font-style"), style.getPropertyValue("font-weight"), src, sheet.href ?? void 0);
739
- if (face) addFace(face);
740
- }
741
- }
742
- for (const href of crossOriginSheets) try {
743
- const response = await fetch(href);
744
- if (!response.ok) throw new Error(String(response.status));
745
- const text = await response.text();
746
- for (const face of parseFontFacesFromCss(text, href)) if (families.has(face.family)) addFace(face);
747
- } catch {
748
- console.warn(`[guidex] scoreImage: a cross-origin stylesheet (${href}) could not be read — fonts declared only there are missing from the export`);
749
- }
750
- return faces;
751
- }
752
- async function fetchFontDataUrl(url) {
753
- const response = await fetch(url);
754
- if (!response.ok) return void 0;
755
- const blob = await response.blob();
756
- return new Promise((resolve) => {
757
- const reader = new FileReader();
758
- reader.onload = () => resolve(typeof reader.result === "string" ? reader.result : void 0);
759
- reader.onerror = () => resolve(void 0);
760
- reader.readAsDataURL(blob);
761
- });
762
- }
763
- /** Fetches and inlines faces as base64 @font-face blocks. Faces share
764
- * fetched files through a URL cache; a family's normal faces always
765
- * embed, its italic faces when the tree uses italics — or when the
766
- * family declares nothing else, since the browser would use them
767
- * anyway. A face whose file cannot be fetched is skipped with a warning
768
- * — the picture falls back to the next family in the stack, as the page
769
- * itself would. */
770
- async function embedFontFaces(faces, italics) {
771
- const blocks = [];
772
- const failed = /* @__PURE__ */ new Set();
773
- const dataUrls = /* @__PURE__ */ new Map();
774
- const fetchDataUrl = (url) => {
775
- let pending = dataUrls.get(url);
776
- if (!pending) {
777
- pending = fetchFontDataUrl(url).catch(() => void 0);
778
- dataUrls.set(url, pending);
779
- }
780
- return pending;
781
- };
782
- const byFamily = /* @__PURE__ */ new Map();
783
- for (const face of faces) {
784
- const group = byFamily.get(face.family) ?? [];
785
- group.push(face);
786
- byFamily.set(face.family, group);
787
- }
788
- for (const [family, group] of byFamily) {
789
- const normal = group.filter((f) => f.style === "normal");
790
- const keep = normal.length > 0 ? [...normal, ...italics ? group.filter((f) => f.style !== "normal") : []] : group;
791
- for (const face of keep) {
792
- const dataUrl = await fetchDataUrl(face.url);
793
- if (!dataUrl) {
794
- failed.add(family);
795
- continue;
796
- }
797
- const format = face.format ? ` format('${face.format}')` : "";
798
- blocks.push(`@font-face{font-family:'${face.family}';font-style:${face.style};font-weight:${face.weight};src:url(${dataUrl})${format}}`);
799
- }
800
- }
801
- for (const family of failed) console.warn(`[guidex] scoreImage: could not embed the ${family} webfont — the export falls back to the next family in its stack`);
802
- return blocks.join("");
803
- }
804
- /** Normalizes any CSS color string to the CSSOM's canonical form, so a
805
- * stylesheet's `--red: #d40000` matches a computed `rgb(212, 0, 0)`. A
806
- * fresh probe element per call: getComputedStyle declarations are
807
- * cached per element, so a reused probe would answer every later
808
- * comparison with its first value. */
809
- function colorProbe(value) {
810
- const probe = document.createElement("span");
811
- probe.style.color = value;
812
- return getComputedStyle(probe).color;
813
- }
814
- /** The style set's accent, resolved from the container's `--red` custom
815
- * property to its canonical form ('' when none is in scope). */
816
- function resolvedAccent(container) {
817
- const raw = getComputedStyle(container).getPropertyValue("--red").trim();
818
- return raw ? colorProbe(raw) : "";
819
- }
820
- /** Whether an element's ink is the accent: either its computed color
821
- * equals the resolved accent, or its inline color is the `var(--red)`
822
- * reference the style sets put on accent runs (the form a CSSOM without
823
- * custom-property resolution leaves in place). */
824
- function isAccentInk(el, computedColor, accent) {
825
- if (accent && computedColor && colorProbe(computedColor) === accent) return true;
826
- return el.style?.getPropertyValue("color").replace(/\s+/g, "") === "var(--red)";
827
- }
828
- /** Copies the computed properties from each original onto its clone and
829
- * reports which webfont families / styles the tree uses, so only those
830
- * faces are embedded. Runs after the clone, so literal computed values
831
- * overwrite the clone's inherited `var()` references — that is what
832
- * bakes the current theme into the picture. The `foreground`/`accent`
833
- * overrides remap that ink: accent-classified elements take the accent
834
- * color, everything else the foreground. */
835
- function copyComputedStyles(originals, clones, overrides) {
836
- const families = /* @__PURE__ */ new Set();
837
- let italics = false;
838
- for (let i = 0; i < originals.length; i++) {
839
- const original = originals[i];
840
- const clone = clones[i];
841
- const computed = getComputedStyle(original);
842
- for (const prop of i === 0 ? WRAPPER_PROPS : COPY_PROPS) {
843
- if (prop === "color") {
844
- const computedColor = computed.getPropertyValue("color");
845
- if (!computedColor) continue;
846
- const override = isAccentInk(original, computedColor, overrides.accentProbe) ? overrides.accent : overrides.foreground;
847
- clone.style.setProperty("color", override || computedColor);
848
- continue;
849
- }
850
- const value = computed.getPropertyValue(prop);
851
- if (value) clone.style.setProperty(prop, value);
852
- }
853
- const family = computed.getPropertyValue("font-family");
854
- if (family) for (const f of parseFamilies(family)) families.add(f);
855
- if (computed.getPropertyValue("font-style") === "italic") italics = true;
856
- }
857
- return {
858
- families,
859
- italics
860
- };
861
- }
862
- async function fontsReady() {
863
- const fonts = document.fonts;
864
- if (fonts?.ready) await fonts.ready;
865
- }
866
- /** The whole capture: crop measurement, styled clone, embedded fonts,
867
- * and the assembled SVG string with its outer pixel size. */
868
- async function serializeScore(el, options) {
869
- const padding = Math.max(0, options.padding ?? 0);
870
- const root = scoreRoot(el);
871
- if (!root.isConnected) throw new Error("scoreImage: the score left the document before the export — re-render it and try again");
872
- await fontsReady();
873
- const lines = Array.from(root.children).filter((child) => child.classList.contains("guido") || child.tagName === "P");
874
- if (lines.length === 0) throw new Error("No rendered score found to export — render a score into the element first.");
875
- const lineRects = lines.map((line) => line.getBoundingClientRect());
876
- const base = lineRects[0];
877
- const stacked = lines.map((line, i) => {
878
- const extent = lineExtent(line);
879
- const rect = lineRects[i];
880
- const offsetLeft = rect.left - base.left;
881
- const wraps = countRows(line) > 1;
882
- return {
883
- left: extent.left + offsetLeft,
884
- top: extent.top + (rect.top - base.top),
885
- right: (wraps ? Math.max(rect.width, extent.right) : extent.right) + offsetLeft,
886
- bottom: extent.bottom + (rect.top - base.top),
887
- pinWidth: wraps ? rect.width : void 0
888
- };
889
- });
890
- const cropLeft = Math.min(0, ...stacked.map((e) => e.left));
891
- const cropTop = Math.min(0, ...stacked.map((e) => e.top));
892
- const contentRight = Math.max(...stacked.map((e) => e.right));
893
- const contentBottom = Math.max(...stacked.map((e) => e.bottom));
894
- const width = Math.max(1, Math.ceil(contentRight - cropLeft)) + padding * 2;
895
- const height = Math.max(1, Math.ceil(contentBottom - cropTop)) + padding * 2;
896
- const clone = root.cloneNode(true);
897
- clone.querySelectorAll(".max-width-guide, [data-score-image-ignore]").forEach((el) => el.remove());
898
- const originals = [root];
899
- const clones = [clone];
900
- const walk = (el, into) => {
901
- for (const child of el.children) {
902
- if (isIgnorable(child)) continue;
903
- into.push(child);
904
- walk(child, into);
905
- }
906
- };
907
- walk(root, originals);
908
- walk(clone, clones);
909
- if (clones.length !== originals.length) throw new Error("scoreImage: the cloned tree diverged from the live one");
910
- for (const el of [clone, ...clone.querySelectorAll("*")]) el.removeAttribute("title");
911
- const { families, italics } = copyComputedStyles(originals, clones, {
912
- foreground: options.foreground,
913
- accent: options.accent,
914
- accentProbe: resolvedAccent(root)
915
- });
916
- clone.style.setProperty("white-space", "nowrap");
917
- const cloneLines = Array.from(clone.children).filter((child) => child.classList.contains("guido") || child.tagName === "P");
918
- stacked.forEach((entry, i) => {
919
- const cloneLine = cloneLines[i];
920
- if (entry.pinWidth !== void 0 && cloneLine) cloneLine.style.setProperty("width", `${entry.pinWidth}px`);
921
- });
922
- clone.style.setProperty("padding-top", `${padding - cropTop}px`);
923
- clone.style.setProperty("padding-left", `${padding - cropLeft}px`);
924
- clone.style.setProperty("padding-right", `${padding}px`);
925
- clone.style.setProperty("padding-bottom", `${padding}px`);
926
- const faceCss = await embedFontFaces(await collectFontFaces(families), italics);
927
- const wrapper = new XMLSerializer().serializeToString(clone);
928
- const bgRect = options.background ? `<rect width="100%" height="100%" fill="${escapeXmlAttribute(options.background)}"/>` : "";
929
- return {
930
- svg: `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">` + bgRect + (faceCss ? `<style>${faceCss}</style>` : "") + `<foreignObject x="0" y="0" width="${width}" height="${height}">` + wrapper + "</foreignObject></svg>",
931
- width,
932
- height
933
- };
934
- }
935
- /** Serializes the rendered score under `el` into a self-contained SVG
936
- * string (fonts embedded, colors resolved) sized to the score's content.
937
- * Throws when no score was rendered into the element. */
938
- async function scoreSvg(el, options = {}) {
939
- return (await serializeScore(el, options)).svg;
940
- }
941
- /** Rasterizes the rendered score under `el` to a PNG blob: the
942
- * self-contained SVG loads as an image (the browser's own renderer
943
- * paints it, so the picture matches the DOM exactly) and draws onto a
944
- * canvas at `scale`×. Throws when no score was rendered into the
945
- * element or the environment has no 2D canvas. */
946
- async function scorePngBlob(el, options = {}) {
947
- const { svg, width, height } = await serializeScore(el, options);
948
- const scale = Math.max(1, options.scale ?? 2);
949
- const image = new Image();
950
- image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
951
- await new Promise((resolve, reject) => {
952
- image.onload = () => resolve();
953
- image.onerror = () => reject(/* @__PURE__ */ new Error("scoreImage: the exported SVG failed to rasterize"));
954
- });
955
- try {
956
- await image.decode();
957
- } catch {}
958
- const canvas = document.createElement("canvas");
959
- canvas.width = Math.ceil(width * scale);
960
- canvas.height = Math.ceil(height * scale);
961
- const ctx = canvas.getContext("2d");
962
- if (!ctx) throw new Error("scoreImage: this environment provides no 2D canvas");
963
- ctx.scale(scale, scale);
964
- if (options.background) {
965
- ctx.fillStyle = options.background;
966
- ctx.fillRect(0, 0, width, height);
967
- }
968
- const draw = () => ctx.drawImage(image, 0, 0, width, height);
969
- draw();
970
- if (/^((?!chrome|android|crios|fxios).)*safari/i.test(navigator.userAgent)) {
971
- await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
972
- draw();
973
- }
974
- const blob = await new Promise((resolve) => canvas.toBlob(resolve, "image/png"));
975
- if (!blob) throw new Error("scoreImage: PNG encoding failed");
976
- return blob;
977
- }
978
- function downloadBlob(blob, filename) {
979
- const url = URL.createObjectURL(blob);
980
- const anchor = document.createElement("a");
981
- anchor.href = url;
982
- anchor.download = filename;
983
- anchor.click();
984
- setTimeout(() => URL.revokeObjectURL(url), 1e4);
985
- }
986
- /** Exports the rendered score under `el` as a PNG download. Resolves
987
- * with the filename used. */
988
- async function downloadScorePng(el, options = {}) {
989
- const filename = options.filename ?? "score.png";
990
- downloadBlob(await scorePngBlob(el, options), filename);
991
- return filename;
992
- }
993
- /** Exports the rendered score under `el` as a self-contained SVG
994
- * download (fonts embedded — the print-friendlier artifact). Resolves
995
- * with the filename used. */
996
- async function downloadScoreSvg(el, options = {}) {
997
- const filename = options.filename ?? "score.svg";
998
- downloadBlob(new Blob([await scoreSvg(el, options)], { type: "image/svg+xml;charset=utf-8" }), filename);
999
- return filename;
1000
- }
1001
- //#endregion
1002
- export { dispose as a, renderScore as c, scoreSvg as i, version as l, downloadScoreSvg as n, init as o, scorePngBlob as r, renderAll as s, downloadScorePng as t };