guidex 0.3.3 → 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.
- package/README.md +105 -34
- package/dist/lib/app/editorState.d.ts +22 -23
- package/dist/lib/app/shareLink.d.ts +2 -3
- package/dist/lib/{chantLayout-CVVuJUJl.js → chantLayout-g_xuQ9nD.js} +683 -1112
- package/dist/lib/chantLayout.d.ts +30 -2
- package/dist/lib/chantMarkup.d.ts +63 -20
- package/dist/lib/editorStorage.d.ts +9 -4
- package/dist/lib/embed/core.d.ts +16 -3
- package/dist/lib/embed/index.js +1 -1
- package/dist/lib/embed/manual.d.ts +6 -3
- package/dist/lib/embed/manual.js +16 -49
- package/dist/lib/guidoRender.d.ts +11 -3
- package/dist/lib/guidoScript.d.ts +60 -23
- package/dist/lib/guidoScriptTransforms.d.ts +0 -18
- package/dist/lib/guidoStyles.d.ts +85 -74
- package/dist/lib/react/GuidexScore.d.ts +12 -5
- package/dist/lib/react/index.d.ts +2 -0
- package/dist/lib/react/index.js +10 -2
- package/dist/lib/scoreImage-Dz3c55Zi.js +1985 -0
- package/dist/lib/stanzas.d.ts +6 -3
- package/dist/lib/textMarkup.d.ts +67 -0
- package/dist/lib/word/index.js +1 -1
- package/dist/lib/{wordChecker-DG09l_ol.js → wordChecker-B_9vyTt6.js} +38 -13
- package/dist/lib/wordExport.d.ts +17 -4
- package/dist-embed/guidex-embed.min.js +1 -1
- package/package.json +1 -1
- package/dist/lib/scoreImage-lvOrTbG-.js +0 -1009
|
@@ -1,1009 +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-CVVuJUJl.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.3",
|
|
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
|
-
junctionDashes: 3,
|
|
243
|
-
transpose: 0,
|
|
244
|
-
stanza: 1,
|
|
245
|
-
stack: void 0,
|
|
246
|
-
emptySlots: "normal",
|
|
247
|
-
stanzas: void 0,
|
|
248
|
-
debug: false
|
|
249
|
-
};
|
|
250
|
-
var globalOptions = {};
|
|
251
|
-
/** The raw script of each target, cached across re-renders: rendering
|
|
252
|
-
* replaces the element's content, so the original text would be lost. */
|
|
253
|
-
var sources = /* @__PURE__ */ new WeakMap();
|
|
254
|
-
/** Per-element render race counter: a slow render (font loading) must
|
|
255
|
-
* never overwrite a newer one's output. */
|
|
256
|
-
var runs = /* @__PURE__ */ new WeakMap();
|
|
257
|
-
/** The line-breaking budget each element last rendered at; resize
|
|
258
|
-
* re-renders are skipped while the width is unchanged (height-only
|
|
259
|
-
* ResizeObserver entries from our own renders must not loop). */
|
|
260
|
-
var lastWidths = /* @__PURE__ */ new WeakMap();
|
|
261
|
-
/** data-* boolean attribute: bare presence or 'true' → true, 'false' →
|
|
262
|
-
* false, anything else → unset. */
|
|
263
|
-
function flag(value) {
|
|
264
|
-
if (value === void 0) return void 0;
|
|
265
|
-
if (value === "" || value === "true") return true;
|
|
266
|
-
if (value === "false") return false;
|
|
267
|
-
}
|
|
268
|
-
function number(value) {
|
|
269
|
-
if (value === void 0) return void 0;
|
|
270
|
-
const n = Number(value);
|
|
271
|
-
return Number.isFinite(n) ? n : void 0;
|
|
272
|
-
}
|
|
273
|
-
function parseMaxWidth(value, fallback) {
|
|
274
|
-
if (/^auto$/i.test(value.trim())) return "auto";
|
|
275
|
-
const n = Number(value);
|
|
276
|
-
if (n > 0) return n;
|
|
277
|
-
console.warn(`[guidex] ignoring invalid data-max-width "${value}"`);
|
|
278
|
-
return fallback;
|
|
279
|
-
}
|
|
280
|
-
/** Per-element option overrides set by `renderScore` (programmatic
|
|
281
|
-
* callers): element data attributes win over these, these win over
|
|
282
|
-
* `init` site-wide defaults. */
|
|
283
|
-
var overrides = /* @__PURE__ */ new WeakMap();
|
|
284
|
-
function emptySlotsValue(value) {
|
|
285
|
-
if (value === void 0) return void 0;
|
|
286
|
-
if (value === "normal" || value === "small" || value === "partial") return value;
|
|
287
|
-
console.warn(`[guidex] ignoring invalid data-empty-slots "${value}"`);
|
|
288
|
-
}
|
|
289
|
-
/** `data-stack`: `all`, or a comma-separated list of stanza numbers. */
|
|
290
|
-
function stackValue(value) {
|
|
291
|
-
if (value === void 0) return void 0;
|
|
292
|
-
if (/^\s*all\s*$/i.test(value)) return "all";
|
|
293
|
-
const list = value.split(",").map((n) => Number(n.trim()));
|
|
294
|
-
if (value.trim() !== "" && list.every((n) => Number.isInteger(n) && n > 0)) return list;
|
|
295
|
-
console.warn(`[guidex] ignoring invalid data-stack "${value}"`);
|
|
296
|
-
}
|
|
297
|
-
/** Element data attributes (or unset) over `renderScore` overrides over
|
|
298
|
-
* init options over defaults. */
|
|
299
|
-
function readOptions(el) {
|
|
300
|
-
const ds = el.dataset;
|
|
301
|
-
const local = overrides.get(el) ?? {};
|
|
302
|
-
return {
|
|
303
|
-
maxWidth: ds.maxWidth !== void 0 ? parseMaxWidth(ds.maxWidth, local.maxWidth ?? globalOptions.maxWidth ?? DEFAULTS.maxWidth) : local.maxWidth ?? globalOptions.maxWidth ?? DEFAULTS.maxWidth,
|
|
304
|
-
style: ds.style ?? local.style ?? globalOptions.style ?? DEFAULTS.style,
|
|
305
|
-
bold: flag(ds.bold) ?? local.bold ?? globalOptions.bold ?? DEFAULTS.bold,
|
|
306
|
-
textPx: number(ds.textPx) ?? local.textPx ?? globalOptions.textPx ?? DEFAULTS.textPx,
|
|
307
|
-
junctionDashes: number(ds.junctionDashes) ?? local.junctionDashes ?? globalOptions.junctionDashes ?? DEFAULTS.junctionDashes,
|
|
308
|
-
transpose: number(ds.transpose) ?? local.transpose ?? globalOptions.transpose ?? DEFAULTS.transpose,
|
|
309
|
-
stanza: number(ds.stanza) ?? local.stanza ?? globalOptions.stanza ?? DEFAULTS.stanza,
|
|
310
|
-
stack: stackValue(ds.stack) ?? local.stack ?? globalOptions.stack ?? DEFAULTS.stack,
|
|
311
|
-
emptySlots: emptySlotsValue(ds.emptySlots) ?? local.emptySlots ?? globalOptions.emptySlots ?? DEFAULTS.emptySlots,
|
|
312
|
-
stanzas: local.stanzas ?? DEFAULTS.stanzas,
|
|
313
|
-
debug: flag(ds.debug) ?? local.debug ?? globalOptions.debug ?? DEFAULTS.debug
|
|
314
|
-
};
|
|
315
|
-
}
|
|
316
|
-
/** The element's content-box width (the score wrapper spans it), the
|
|
317
|
-
* line-box width the rendered score actually has to fit. Falls back to
|
|
318
|
-
* the parent for inline targets; zero means no layout (hidden). */
|
|
319
|
-
function contentWidthPx(el) {
|
|
320
|
-
const wrapper = el.querySelector(":scope > .guidex-render");
|
|
321
|
-
wrapper?.removeAttribute("data-fixed-width");
|
|
322
|
-
return wrapper?.clientWidth || el.clientWidth || el.parentElement?.clientWidth || 0;
|
|
323
|
-
}
|
|
324
|
-
/** The line-breaking budget in pixels for this render. Fixed values pass
|
|
325
|
-
* through; 'auto' fits the element's content box, shrunk by the style
|
|
326
|
-
* set's break-star padding: the renderer hangs the `guido-break` star
|
|
327
|
-
* `padding` px past the budget, and when the budget is the line-box
|
|
328
|
-
* width itself that star would overflow the line and wrap. A zero width
|
|
329
|
-
* (hidden element) renders unbroken; once it becomes visible the resize
|
|
330
|
-
* listener re-renders it at the real width. */
|
|
331
|
-
function resolveWidthPx(el, maxWidth, style) {
|
|
332
|
-
if (typeof maxWidth === "number") return maxWidth;
|
|
333
|
-
const width = contentWidthPx(el);
|
|
334
|
-
if (width <= 0) return Infinity;
|
|
335
|
-
const budget = width - (STYLE_SETS[style]?.padding ?? 0);
|
|
336
|
-
return budget > 0 ? budget : width;
|
|
337
|
-
}
|
|
338
|
-
/** The element's script source: a fresh non-empty text node wins (so
|
|
339
|
-
* hosts can update the source by setting textContent and calling
|
|
340
|
-
* renderAll), otherwise the cached one from the previous render. */
|
|
341
|
-
function extractSource(el) {
|
|
342
|
-
for (const node of el.childNodes) if (node.nodeType === Node.TEXT_NODE && node.nodeValue?.trim()) return node.nodeValue.trim();
|
|
343
|
-
return sources.get(el) ?? "";
|
|
344
|
-
}
|
|
345
|
-
/** The score wrapper inside the target; the renderer swaps the score
|
|
346
|
-
* into it, never touching the target element's own classes or dataset. */
|
|
347
|
-
function scoreWrapper(el) {
|
|
348
|
-
const existing = el.querySelector(":scope > .guidex-render");
|
|
349
|
-
if (existing) return existing;
|
|
350
|
-
const wrapper = document.createElement("div");
|
|
351
|
-
wrapper.className = "guidex-render";
|
|
352
|
-
el.replaceChildren(wrapper);
|
|
353
|
-
return wrapper;
|
|
354
|
-
}
|
|
355
|
-
function renderError(wrapper, message) {
|
|
356
|
-
const note = document.createElement("p");
|
|
357
|
-
note.className = "guidex-error";
|
|
358
|
-
note.textContent = message;
|
|
359
|
-
wrapper.removeAttribute("data-fixed-width");
|
|
360
|
-
wrapper.replaceChildren(note);
|
|
361
|
-
}
|
|
362
|
-
/** The transforms a score renders with after the stanza swap: the style
|
|
363
|
-
* set's defaults (BNS marks the first initial), then the user-requested
|
|
364
|
-
* transpose. An unknown style name yields no defaults here — the render
|
|
365
|
-
* itself reports it. */
|
|
366
|
-
function scriptTransforms(options) {
|
|
367
|
-
const transforms = [...STYLE_SETS[options.style]?.scriptTransforms ?? []];
|
|
368
|
-
if (options.transpose !== 0) transforms.push(transposeBy(options.transpose));
|
|
369
|
-
return transforms;
|
|
370
|
-
}
|
|
371
|
-
/** The scripts a score renders: the stacked stanzas when a stack is set
|
|
372
|
-
* (one text line each), otherwise the one stanza — the stanza swap runs
|
|
373
|
-
* first, so the other transforms see the stanza's text. Returns the
|
|
374
|
-
* rendered stanzas' count mismatches with them. */
|
|
375
|
-
function renderedScripts(source, options) {
|
|
376
|
-
const transforms = scriptTransforms(options);
|
|
377
|
-
const { stanzas, emptySlots } = options;
|
|
378
|
-
if (options.stack !== void 0) {
|
|
379
|
-
const rendered = stackedStanzaNumbers(source, options.stack, { stanzas });
|
|
380
|
-
return {
|
|
381
|
-
scripts: stackStanzas(source, rendered, {
|
|
382
|
-
stanzas,
|
|
383
|
-
emptySlots,
|
|
384
|
-
transforms
|
|
385
|
-
}),
|
|
386
|
-
warnings: rendered.flatMap((stanza) => stanzaWarnings(source, {
|
|
387
|
-
stanzas,
|
|
388
|
-
stanza
|
|
389
|
-
}))
|
|
390
|
-
};
|
|
391
|
-
}
|
|
392
|
-
if (options.stanza !== 1 || emptySlots !== "normal") transforms.unshift(selectStanza(options.stanza, {
|
|
393
|
-
stanzas,
|
|
394
|
-
emptySlots
|
|
395
|
-
}));
|
|
396
|
-
return {
|
|
397
|
-
scripts: [new GuidoScript(source, { transforms })],
|
|
398
|
-
warnings: stanzaWarnings(source, {
|
|
399
|
-
stanzas,
|
|
400
|
-
stanza: options.stanza
|
|
401
|
-
})
|
|
402
|
-
};
|
|
403
|
-
}
|
|
404
|
-
/** Builds the score into a detached scratch wrapper and swaps it into
|
|
405
|
-
* the live one only when this run is still the latest — a stale render
|
|
406
|
-
* that finished late leaves no footprint. A failure (a script or stanza
|
|
407
|
-
* error, an unloadable font) replaces the score with an error note.
|
|
408
|
-
* Resolves with the rendered stanza's warnings, also logged. */
|
|
409
|
-
async function drawScore(el, run, source, options, widthPx) {
|
|
410
|
-
const wrapper = scoreWrapper(el);
|
|
411
|
-
const scratch = document.createElement("div");
|
|
412
|
-
try {
|
|
413
|
-
const { scripts, warnings } = renderedScripts(source, options);
|
|
414
|
-
await new GuidoRender(scripts).render(scratch, {
|
|
415
|
-
style: options.style,
|
|
416
|
-
bold: options.bold,
|
|
417
|
-
textPx: options.textPx,
|
|
418
|
-
junctionDashes: options.junctionDashes,
|
|
419
|
-
debug: options.debug,
|
|
420
|
-
maxWidthPx: widthPx
|
|
421
|
-
});
|
|
422
|
-
if (runs.get(el) !== run) return { warnings };
|
|
423
|
-
for (const warning of warnings) console.warn(`[guidex] ${warning.message}`);
|
|
424
|
-
wrapper.replaceChildren(...scratch.childNodes);
|
|
425
|
-
wrapper.style.cssText = scratch.style.cssText;
|
|
426
|
-
if (scratch.dataset.style) wrapper.dataset.style = scratch.dataset.style;
|
|
427
|
-
wrapper.toggleAttribute("data-fixed-width", typeof options.maxWidth === "number");
|
|
428
|
-
return { warnings };
|
|
429
|
-
} catch (e) {
|
|
430
|
-
if (runs.get(el) !== run) return { warnings: [] };
|
|
431
|
-
console.error("[guidex]", e);
|
|
432
|
-
renderError(wrapper, e instanceof Error ? e.message : String(e));
|
|
433
|
-
return { warnings: [] };
|
|
434
|
-
}
|
|
435
|
-
}
|
|
436
|
-
/** Renders one target element from its source and resolved options. */
|
|
437
|
-
async function renderElement(el) {
|
|
438
|
-
const run = (runs.get(el) ?? 0) + 1;
|
|
439
|
-
runs.set(el, run);
|
|
440
|
-
const options = readOptions(el);
|
|
441
|
-
const source = extractSource(el);
|
|
442
|
-
sources.set(el, source);
|
|
443
|
-
scoreWrapper(el);
|
|
444
|
-
const widthPx = resolveWidthPx(el, options.maxWidth, options.style);
|
|
445
|
-
lastWidths.set(el, widthPx);
|
|
446
|
-
await drawScore(el, run, source, options, widthPx);
|
|
447
|
-
}
|
|
448
|
-
/** Sets up one resize listener per target element, on first render.
|
|
449
|
-
* Only a changed line-breaking budget (width) triggers a re-render. */
|
|
450
|
-
var detachFns = /* @__PURE__ */ new WeakMap();
|
|
451
|
-
function widthChanged(el) {
|
|
452
|
-
const options = readOptions(el);
|
|
453
|
-
const width = resolveWidthPx(el, options.maxWidth, options.style);
|
|
454
|
-
return Math.abs(width - (lastWidths.get(el) ?? NaN)) > 1;
|
|
455
|
-
}
|
|
456
|
-
function attachResizeListener(el) {
|
|
457
|
-
if (detachFns.has(el)) return;
|
|
458
|
-
let detach;
|
|
459
|
-
if (typeof ResizeObserver !== "undefined") {
|
|
460
|
-
const observer = new ResizeObserver(() => {
|
|
461
|
-
if (widthChanged(el)) renderElement(el);
|
|
462
|
-
});
|
|
463
|
-
observer.observe(el);
|
|
464
|
-
detach = () => observer.disconnect();
|
|
465
|
-
} else {
|
|
466
|
-
const onResize = () => {
|
|
467
|
-
if (widthChanged(el)) renderElement(el);
|
|
468
|
-
};
|
|
469
|
-
window.addEventListener("resize", onResize);
|
|
470
|
-
detach = () => window.removeEventListener("resize", onResize);
|
|
471
|
-
}
|
|
472
|
-
detachFns.set(el, detach);
|
|
473
|
-
}
|
|
474
|
-
/** Cleans up a programmatically rendered element: stops resize
|
|
475
|
-
* re-rendering and drops the cached source and option overrides. Does
|
|
476
|
-
* not remove the rendered score itself. */
|
|
477
|
-
function dispose(el) {
|
|
478
|
-
detachFns.get(el)?.();
|
|
479
|
-
detachFns.delete(el);
|
|
480
|
-
sources.delete(el);
|
|
481
|
-
overrides.delete(el);
|
|
482
|
-
runs.delete(el);
|
|
483
|
-
lastWidths.delete(el);
|
|
484
|
-
}
|
|
485
|
-
/** Renders a GuidoScript source string into one element
|
|
486
|
-
* programmatically — no selector scanning, no site-wide state. The
|
|
487
|
-
* element's own text content is replaced by the rendered score and
|
|
488
|
-
* re-rendered on resize. Call again with a new source to update.
|
|
489
|
-
* Options set here override `init` defaults; data attributes on the
|
|
490
|
-
* element still win. `stanzas` replaces the script's `(@stanza …)`
|
|
491
|
-
* statements. Resolves when the score has finished rendering, with the
|
|
492
|
-
* rendered stanza's count mismatches. */
|
|
493
|
-
async function renderScore(el, source, options = {}) {
|
|
494
|
-
overrides.set(el, options);
|
|
495
|
-
const run = (runs.get(el) ?? 0) + 1;
|
|
496
|
-
runs.set(el, run);
|
|
497
|
-
sources.set(el, source);
|
|
498
|
-
const resolved = readOptions(el);
|
|
499
|
-
scoreWrapper(el);
|
|
500
|
-
const widthPx = resolveWidthPx(el, resolved.maxWidth, resolved.style);
|
|
501
|
-
lastWidths.set(el, widthPx);
|
|
502
|
-
attachResizeListener(el);
|
|
503
|
-
return drawScore(el, run, source, resolved, widthPx);
|
|
504
|
-
}
|
|
505
|
-
/** Renders every target under `root` (default: the whole document).
|
|
506
|
-
* Already-rendered targets re-render from their cached source, so a
|
|
507
|
-
* host can change data attributes or the source text and call this to
|
|
508
|
-
* refresh. Resolves when every score has finished rendering. */
|
|
509
|
-
async function renderAll(root = document) {
|
|
510
|
-
const selector = globalOptions.selector ?? DEFAULT_SELECTOR;
|
|
511
|
-
const targets = [];
|
|
512
|
-
if (root instanceof Element && root.matches(selector)) targets.push(root);
|
|
513
|
-
targets.push(...root.querySelectorAll(selector));
|
|
514
|
-
return Promise.all(targets.map((el) => {
|
|
515
|
-
attachResizeListener(el);
|
|
516
|
-
return renderElement(el);
|
|
517
|
-
})).then(() => void 0);
|
|
518
|
-
}
|
|
519
|
-
/** Late-added elements (AJAX, SPA routing) render too: document-wide
|
|
520
|
-
* child mutations are scanned for matching targets. Our own score
|
|
521
|
-
* elements are skipped, so renders never re-trigger the observer. */
|
|
522
|
-
var observerStarted = false;
|
|
523
|
-
function startMutationObserver() {
|
|
524
|
-
if (observerStarted || typeof MutationObserver === "undefined") return;
|
|
525
|
-
observerStarted = true;
|
|
526
|
-
const selector = globalOptions.selector ?? DEFAULT_SELECTOR;
|
|
527
|
-
new MutationObserver((mutations) => {
|
|
528
|
-
const targets = /* @__PURE__ */ new Set();
|
|
529
|
-
for (const mutation of mutations) for (const node of mutation.addedNodes) {
|
|
530
|
-
if (!(node instanceof Element)) continue;
|
|
531
|
-
if (node.closest(".guidex-render")) continue;
|
|
532
|
-
if (node.matches(selector)) targets.add(node);
|
|
533
|
-
for (const match of node.querySelectorAll(selector)) targets.add(match);
|
|
534
|
-
}
|
|
535
|
-
for (const el of targets) {
|
|
536
|
-
attachResizeListener(el);
|
|
537
|
-
renderElement(el);
|
|
538
|
-
}
|
|
539
|
-
}).observe(document.documentElement, {
|
|
540
|
-
childList: true,
|
|
541
|
-
subtree: true
|
|
542
|
-
});
|
|
543
|
-
}
|
|
544
|
-
/** Sets site-wide defaults and renders the document. Call again (even
|
|
545
|
-
* with different options) to re-render everything with new settings. */
|
|
546
|
-
function init(options = {}) {
|
|
547
|
-
globalOptions = {
|
|
548
|
-
...globalOptions,
|
|
549
|
-
...options
|
|
550
|
-
};
|
|
551
|
-
startMutationObserver();
|
|
552
|
-
renderAll();
|
|
553
|
-
}
|
|
554
|
-
//#endregion
|
|
555
|
-
//#region src/scoreImage.ts
|
|
556
|
-
/** The computed properties that draw a score line and its content:
|
|
557
|
-
* everything load-bearing beyond the renderer's own inline styles (the
|
|
558
|
-
* notes line's leading and padding, the theme's resolved colors, the
|
|
559
|
-
* relative shifts) comes from this list. Box widths are deliberately
|
|
560
|
-
* absent — a block line spans its container, not its content, and the
|
|
561
|
-
* sized elements (the spacer spans) already carry inline widths. */
|
|
562
|
-
var COPY_PROPS = [
|
|
563
|
-
"font-family",
|
|
564
|
-
"font-size",
|
|
565
|
-
"font-style",
|
|
566
|
-
"font-weight",
|
|
567
|
-
"line-height",
|
|
568
|
-
"letter-spacing",
|
|
569
|
-
"text-transform",
|
|
570
|
-
"color",
|
|
571
|
-
"position",
|
|
572
|
-
"top",
|
|
573
|
-
"left",
|
|
574
|
-
"margin-top",
|
|
575
|
-
"margin-bottom",
|
|
576
|
-
"padding-top",
|
|
577
|
-
"padding-bottom"
|
|
578
|
-
];
|
|
579
|
-
/** The wrapper (the render container's stand-in) gets typography only:
|
|
580
|
-
* no box properties, so the cloned lines stack from the crop's own
|
|
581
|
-
* top-left corner. */
|
|
582
|
-
var WRAPPER_PROPS = [
|
|
583
|
-
"font-family",
|
|
584
|
-
"font-size",
|
|
585
|
-
"font-style",
|
|
586
|
-
"font-weight",
|
|
587
|
-
"line-height",
|
|
588
|
-
"letter-spacing",
|
|
589
|
-
"color"
|
|
590
|
-
];
|
|
591
|
-
/** Debug/export furniture skipped when cloning: the editor's max-width
|
|
592
|
-
* guide and anything the host marks with `data-score-image-ignore`. The
|
|
593
|
-
* debug syllable guides need no entry — they are ::before/::after CSS,
|
|
594
|
-
* which never clones. */
|
|
595
|
-
function isIgnorable(el) {
|
|
596
|
-
return el.classList.contains("max-width-guide") || el.hasAttribute("data-score-image-ignore");
|
|
597
|
-
}
|
|
598
|
-
/** The element whose direct children are the rendered line pairs: the
|
|
599
|
-
* parent of the first chant-font line under `el`. Accepts the render
|
|
600
|
-
* container itself or any ancestor of it (the editor's outer score div,
|
|
601
|
-
* an embed target). */
|
|
602
|
-
function scoreRoot(el) {
|
|
603
|
-
const root = el.querySelector(".guido")?.parentElement;
|
|
604
|
-
if (!root) throw new Error("No rendered score found to export — render a score into the element first.");
|
|
605
|
-
return root;
|
|
606
|
-
}
|
|
607
|
-
/** One line's content extent, relative to the line box's own top-left
|
|
608
|
-
* corner: the union of its contents' rects. The line box itself is
|
|
609
|
-
* excluded horizontally (it spans the container, not the text); the
|
|
610
|
-
* Range covers the text nodes and each descendant element rect keeps
|
|
611
|
-
* the position:relative shifts (raised runs, the break star). */
|
|
612
|
-
function lineExtent(line) {
|
|
613
|
-
const box = line.getBoundingClientRect();
|
|
614
|
-
const parts = [];
|
|
615
|
-
const range = document.createRange();
|
|
616
|
-
range.selectNodeContents(line);
|
|
617
|
-
if (typeof range.getBoundingClientRect === "function") parts.push(range.getBoundingClientRect());
|
|
618
|
-
line.querySelectorAll("*").forEach((el) => parts.push(el.getBoundingClientRect()));
|
|
619
|
-
if (parts.length === 0) parts.push(box);
|
|
620
|
-
return {
|
|
621
|
-
left: Math.min(...parts.map((r) => r.left)) - box.left,
|
|
622
|
-
top: Math.min(...parts.map((r) => r.top)) - box.top,
|
|
623
|
-
right: Math.max(...parts.map((r) => r.right)) - box.left,
|
|
624
|
-
bottom: Math.max(...parts.map((r) => r.bottom)) - box.top
|
|
625
|
-
};
|
|
626
|
-
}
|
|
627
|
-
/** How many visual rows a line's content occupies: the Range's client
|
|
628
|
-
* rects cluster into rows by vertical overlap (inline boxes of
|
|
629
|
-
* different sizes sit side by side on one row with different tops). A
|
|
630
|
-
* line that wraps inside its host container must re-wrap at the same
|
|
631
|
-
* width in the clone, so it is pinned to its live box width. */
|
|
632
|
-
function countRows(line) {
|
|
633
|
-
const range = document.createRange();
|
|
634
|
-
range.selectNodeContents(line);
|
|
635
|
-
if (typeof range.getClientRects !== "function") return 1;
|
|
636
|
-
const rects = Array.from(range.getClientRects()).filter((r) => r.width > 0 || r.height > 0);
|
|
637
|
-
if (rects.length === 0) return 1;
|
|
638
|
-
rects.sort((a, b) => a.top - b.top);
|
|
639
|
-
let rows = 0;
|
|
640
|
-
let rowBottom = -Infinity;
|
|
641
|
-
for (const r of rects) if (r.top >= rowBottom) {
|
|
642
|
-
rows++;
|
|
643
|
-
rowBottom = r.bottom;
|
|
644
|
-
} else if (r.bottom > rowBottom) rowBottom = r.bottom;
|
|
645
|
-
return rows;
|
|
646
|
-
}
|
|
647
|
-
/** Splits a computed font-family stack into family names, honoring
|
|
648
|
-
* quotes around names that contain commas. */
|
|
649
|
-
function parseFamilies(stack) {
|
|
650
|
-
const families = [];
|
|
651
|
-
let current = "";
|
|
652
|
-
let quote = null;
|
|
653
|
-
for (const ch of stack) if (quote) {
|
|
654
|
-
if (ch === quote) quote = null;
|
|
655
|
-
else current += ch;
|
|
656
|
-
} else if (ch === "\"" || ch === "'") quote = ch;
|
|
657
|
-
else if (ch === ",") {
|
|
658
|
-
families.push(current.trim());
|
|
659
|
-
current = "";
|
|
660
|
-
} else current += ch;
|
|
661
|
-
families.push(current.trim());
|
|
662
|
-
return families.filter(Boolean);
|
|
663
|
-
}
|
|
664
|
-
function normalizeWeight(weight) {
|
|
665
|
-
if (weight === "normal") return "400";
|
|
666
|
-
if (weight === "bold") return "700";
|
|
667
|
-
return weight;
|
|
668
|
-
}
|
|
669
|
-
/** Escapes a value for use inside a double-quoted XML attribute. */
|
|
670
|
-
function escapeXmlAttribute(value) {
|
|
671
|
-
return value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
|
|
672
|
-
}
|
|
673
|
-
/** Builds one face from a `src` value plus its descriptor strings,
|
|
674
|
-
* resolving the URL against `baseHref`. Undefined when the src has no
|
|
675
|
-
* fetchable url() (local()-only faces need no embedding). */
|
|
676
|
-
function faceFromSrc(family, styleRaw, weightRaw, src, baseHref) {
|
|
677
|
-
const urlMatch = /url\(\s*(['"]?)([^'")]+)\1\s*\)/.exec(src);
|
|
678
|
-
if (!urlMatch) return void 0;
|
|
679
|
-
let url;
|
|
680
|
-
try {
|
|
681
|
-
url = new URL(urlMatch[2], baseHref ?? location.href).toString();
|
|
682
|
-
} catch {
|
|
683
|
-
return;
|
|
684
|
-
}
|
|
685
|
-
return {
|
|
686
|
-
family,
|
|
687
|
-
style: styleRaw || "normal",
|
|
688
|
-
weight: normalizeWeight(weightRaw || "400"),
|
|
689
|
-
url,
|
|
690
|
-
format: /format\(\s*['"]?([^'")]+?)['"]?\s*\)/.exec(src)?.[1]
|
|
691
|
-
};
|
|
692
|
-
}
|
|
693
|
-
/** Parses @font-face blocks out of a stylesheet's raw text — the
|
|
694
|
-
* fallback for cross-origin sheets whose `cssRules` are unreadable but
|
|
695
|
-
* whose file a CORS fetch can still reach (the CDN-served embed build). */
|
|
696
|
-
function parseFontFacesFromCss(cssText, baseUrl) {
|
|
697
|
-
const faces = [];
|
|
698
|
-
for (const match of cssText.matchAll(/@font-face\s*{([^}]*)}/g)) {
|
|
699
|
-
const block = match[1];
|
|
700
|
-
const pick = (prop) => {
|
|
701
|
-
const m = new RegExp(`(?:^|[;\\s])${prop}\\s*:\\s*([^;]+)`, "i").exec(block);
|
|
702
|
-
return m ? m[1].trim() : "";
|
|
703
|
-
};
|
|
704
|
-
const familyRaw = pick("font-family");
|
|
705
|
-
const src = pick("src");
|
|
706
|
-
if (!familyRaw || !src) continue;
|
|
707
|
-
const family = parseFamilies(familyRaw)[0];
|
|
708
|
-
if (!family) continue;
|
|
709
|
-
const face = faceFromSrc(family, pick("font-style"), pick("font-weight"), src, baseUrl);
|
|
710
|
-
if (face) faces.push(face);
|
|
711
|
-
}
|
|
712
|
-
return faces;
|
|
713
|
-
}
|
|
714
|
-
/** Collects the @font-face rules for `families` from every stylesheet.
|
|
715
|
-
* Cross-origin sheets throw on `cssRules`; their text is fetched
|
|
716
|
-
* instead and parsed by hand, so a CDN-served embed build's fonts still
|
|
717
|
-
* travel with the export. Faces dedupe per family/style/weight — one
|
|
718
|
-
* font file can legitimately serve several declarations. */
|
|
719
|
-
async function collectFontFaces(families) {
|
|
720
|
-
const faces = [];
|
|
721
|
-
const seenKeys = /* @__PURE__ */ new Set();
|
|
722
|
-
const addFace = (face) => {
|
|
723
|
-
const key = `${face.family}|${face.style}|${face.weight}`;
|
|
724
|
-
if (seenKeys.has(key)) return;
|
|
725
|
-
seenKeys.add(key);
|
|
726
|
-
faces.push(face);
|
|
727
|
-
};
|
|
728
|
-
const crossOriginSheets = [];
|
|
729
|
-
for (const sheet of document.styleSheets) {
|
|
730
|
-
let rules;
|
|
731
|
-
try {
|
|
732
|
-
rules = sheet.cssRules;
|
|
733
|
-
} catch {
|
|
734
|
-
if (sheet.href) crossOriginSheets.push(sheet.href);
|
|
735
|
-
continue;
|
|
736
|
-
}
|
|
737
|
-
for (const rule of Array.from(rules)) {
|
|
738
|
-
const style = rule.style;
|
|
739
|
-
if (!style) continue;
|
|
740
|
-
const src = style.getPropertyValue("src");
|
|
741
|
-
const familyRaw = style.getPropertyValue("font-family");
|
|
742
|
-
if (!src || !familyRaw) continue;
|
|
743
|
-
const family = parseFamilies(familyRaw)[0];
|
|
744
|
-
if (!family || !families.has(family)) continue;
|
|
745
|
-
const face = faceFromSrc(family, style.getPropertyValue("font-style"), style.getPropertyValue("font-weight"), src, sheet.href ?? void 0);
|
|
746
|
-
if (face) addFace(face);
|
|
747
|
-
}
|
|
748
|
-
}
|
|
749
|
-
for (const href of crossOriginSheets) try {
|
|
750
|
-
const response = await fetch(href);
|
|
751
|
-
if (!response.ok) throw new Error(String(response.status));
|
|
752
|
-
const text = await response.text();
|
|
753
|
-
for (const face of parseFontFacesFromCss(text, href)) if (families.has(face.family)) addFace(face);
|
|
754
|
-
} catch {
|
|
755
|
-
console.warn(`[guidex] scoreImage: a cross-origin stylesheet (${href}) could not be read — fonts declared only there are missing from the export`);
|
|
756
|
-
}
|
|
757
|
-
return faces;
|
|
758
|
-
}
|
|
759
|
-
async function fetchFontDataUrl(url) {
|
|
760
|
-
const response = await fetch(url);
|
|
761
|
-
if (!response.ok) return void 0;
|
|
762
|
-
const blob = await response.blob();
|
|
763
|
-
return new Promise((resolve) => {
|
|
764
|
-
const reader = new FileReader();
|
|
765
|
-
reader.onload = () => resolve(typeof reader.result === "string" ? reader.result : void 0);
|
|
766
|
-
reader.onerror = () => resolve(void 0);
|
|
767
|
-
reader.readAsDataURL(blob);
|
|
768
|
-
});
|
|
769
|
-
}
|
|
770
|
-
/** Fetches and inlines faces as base64 @font-face blocks. Faces share
|
|
771
|
-
* fetched files through a URL cache; a family's normal faces always
|
|
772
|
-
* embed, its italic faces when the tree uses italics — or when the
|
|
773
|
-
* family declares nothing else, since the browser would use them
|
|
774
|
-
* anyway. A face whose file cannot be fetched is skipped with a warning
|
|
775
|
-
* — the picture falls back to the next family in the stack, as the page
|
|
776
|
-
* itself would. */
|
|
777
|
-
async function embedFontFaces(faces, italics) {
|
|
778
|
-
const blocks = [];
|
|
779
|
-
const failed = /* @__PURE__ */ new Set();
|
|
780
|
-
const dataUrls = /* @__PURE__ */ new Map();
|
|
781
|
-
const fetchDataUrl = (url) => {
|
|
782
|
-
let pending = dataUrls.get(url);
|
|
783
|
-
if (!pending) {
|
|
784
|
-
pending = fetchFontDataUrl(url).catch(() => void 0);
|
|
785
|
-
dataUrls.set(url, pending);
|
|
786
|
-
}
|
|
787
|
-
return pending;
|
|
788
|
-
};
|
|
789
|
-
const byFamily = /* @__PURE__ */ new Map();
|
|
790
|
-
for (const face of faces) {
|
|
791
|
-
const group = byFamily.get(face.family) ?? [];
|
|
792
|
-
group.push(face);
|
|
793
|
-
byFamily.set(face.family, group);
|
|
794
|
-
}
|
|
795
|
-
for (const [family, group] of byFamily) {
|
|
796
|
-
const normal = group.filter((f) => f.style === "normal");
|
|
797
|
-
const keep = normal.length > 0 ? [...normal, ...italics ? group.filter((f) => f.style !== "normal") : []] : group;
|
|
798
|
-
for (const face of keep) {
|
|
799
|
-
const dataUrl = await fetchDataUrl(face.url);
|
|
800
|
-
if (!dataUrl) {
|
|
801
|
-
failed.add(family);
|
|
802
|
-
continue;
|
|
803
|
-
}
|
|
804
|
-
const format = face.format ? ` format('${face.format}')` : "";
|
|
805
|
-
blocks.push(`@font-face{font-family:'${face.family}';font-style:${face.style};font-weight:${face.weight};src:url(${dataUrl})${format}}`);
|
|
806
|
-
}
|
|
807
|
-
}
|
|
808
|
-
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`);
|
|
809
|
-
return blocks.join("");
|
|
810
|
-
}
|
|
811
|
-
/** Normalizes any CSS color string to the CSSOM's canonical form, so a
|
|
812
|
-
* stylesheet's `--red: #d40000` matches a computed `rgb(212, 0, 0)`. A
|
|
813
|
-
* fresh probe element per call: getComputedStyle declarations are
|
|
814
|
-
* cached per element, so a reused probe would answer every later
|
|
815
|
-
* comparison with its first value. */
|
|
816
|
-
function colorProbe(value) {
|
|
817
|
-
const probe = document.createElement("span");
|
|
818
|
-
probe.style.color = value;
|
|
819
|
-
return getComputedStyle(probe).color;
|
|
820
|
-
}
|
|
821
|
-
/** The style set's accent, resolved from the container's `--red` custom
|
|
822
|
-
* property to its canonical form ('' when none is in scope). */
|
|
823
|
-
function resolvedAccent(container) {
|
|
824
|
-
const raw = getComputedStyle(container).getPropertyValue("--red").trim();
|
|
825
|
-
return raw ? colorProbe(raw) : "";
|
|
826
|
-
}
|
|
827
|
-
/** Whether an element's ink is the accent: either its computed color
|
|
828
|
-
* equals the resolved accent, or its inline color is the `var(--red)`
|
|
829
|
-
* reference the style sets put on accent runs (the form a CSSOM without
|
|
830
|
-
* custom-property resolution leaves in place). */
|
|
831
|
-
function isAccentInk(el, computedColor, accent) {
|
|
832
|
-
if (accent && computedColor && colorProbe(computedColor) === accent) return true;
|
|
833
|
-
return el.style?.getPropertyValue("color").replace(/\s+/g, "") === "var(--red)";
|
|
834
|
-
}
|
|
835
|
-
/** Copies the computed properties from each original onto its clone and
|
|
836
|
-
* reports which webfont families / styles the tree uses, so only those
|
|
837
|
-
* faces are embedded. Runs after the clone, so literal computed values
|
|
838
|
-
* overwrite the clone's inherited `var()` references — that is what
|
|
839
|
-
* bakes the current theme into the picture. The `foreground`/`accent`
|
|
840
|
-
* overrides remap that ink: accent-classified elements take the accent
|
|
841
|
-
* color, everything else the foreground. */
|
|
842
|
-
function copyComputedStyles(originals, clones, overrides) {
|
|
843
|
-
const families = /* @__PURE__ */ new Set();
|
|
844
|
-
let italics = false;
|
|
845
|
-
for (let i = 0; i < originals.length; i++) {
|
|
846
|
-
const original = originals[i];
|
|
847
|
-
const clone = clones[i];
|
|
848
|
-
const computed = getComputedStyle(original);
|
|
849
|
-
for (const prop of i === 0 ? WRAPPER_PROPS : COPY_PROPS) {
|
|
850
|
-
if (prop === "color") {
|
|
851
|
-
const computedColor = computed.getPropertyValue("color");
|
|
852
|
-
if (!computedColor) continue;
|
|
853
|
-
const override = isAccentInk(original, computedColor, overrides.accentProbe) ? overrides.accent : overrides.foreground;
|
|
854
|
-
clone.style.setProperty("color", override || computedColor);
|
|
855
|
-
continue;
|
|
856
|
-
}
|
|
857
|
-
const value = computed.getPropertyValue(prop);
|
|
858
|
-
if (value) clone.style.setProperty(prop, value);
|
|
859
|
-
}
|
|
860
|
-
const family = computed.getPropertyValue("font-family");
|
|
861
|
-
if (family) for (const f of parseFamilies(family)) families.add(f);
|
|
862
|
-
if (computed.getPropertyValue("font-style") === "italic") italics = true;
|
|
863
|
-
}
|
|
864
|
-
return {
|
|
865
|
-
families,
|
|
866
|
-
italics
|
|
867
|
-
};
|
|
868
|
-
}
|
|
869
|
-
async function fontsReady() {
|
|
870
|
-
const fonts = document.fonts;
|
|
871
|
-
if (fonts?.ready) await fonts.ready;
|
|
872
|
-
}
|
|
873
|
-
/** The whole capture: crop measurement, styled clone, embedded fonts,
|
|
874
|
-
* and the assembled SVG string with its outer pixel size. */
|
|
875
|
-
async function serializeScore(el, options) {
|
|
876
|
-
const padding = Math.max(0, options.padding ?? 0);
|
|
877
|
-
const root = scoreRoot(el);
|
|
878
|
-
if (!root.isConnected) throw new Error("scoreImage: the score left the document before the export — re-render it and try again");
|
|
879
|
-
await fontsReady();
|
|
880
|
-
const lines = Array.from(root.children).filter((child) => child.classList.contains("guido") || child.tagName === "P");
|
|
881
|
-
if (lines.length === 0) throw new Error("No rendered score found to export — render a score into the element first.");
|
|
882
|
-
const lineRects = lines.map((line) => line.getBoundingClientRect());
|
|
883
|
-
const base = lineRects[0];
|
|
884
|
-
const stacked = lines.map((line, i) => {
|
|
885
|
-
const extent = lineExtent(line);
|
|
886
|
-
const rect = lineRects[i];
|
|
887
|
-
const offsetLeft = rect.left - base.left;
|
|
888
|
-
const wraps = countRows(line) > 1;
|
|
889
|
-
return {
|
|
890
|
-
left: extent.left + offsetLeft,
|
|
891
|
-
top: extent.top + (rect.top - base.top),
|
|
892
|
-
right: (wraps ? Math.max(rect.width, extent.right) : extent.right) + offsetLeft,
|
|
893
|
-
bottom: extent.bottom + (rect.top - base.top),
|
|
894
|
-
pinWidth: wraps ? rect.width : void 0
|
|
895
|
-
};
|
|
896
|
-
});
|
|
897
|
-
const cropLeft = Math.min(0, ...stacked.map((e) => e.left));
|
|
898
|
-
const cropTop = Math.min(0, ...stacked.map((e) => e.top));
|
|
899
|
-
const contentRight = Math.max(...stacked.map((e) => e.right));
|
|
900
|
-
const contentBottom = Math.max(...stacked.map((e) => e.bottom));
|
|
901
|
-
const width = Math.max(1, Math.ceil(contentRight - cropLeft)) + padding * 2;
|
|
902
|
-
const height = Math.max(1, Math.ceil(contentBottom - cropTop)) + padding * 2;
|
|
903
|
-
const clone = root.cloneNode(true);
|
|
904
|
-
clone.querySelectorAll(".max-width-guide, [data-score-image-ignore]").forEach((el) => el.remove());
|
|
905
|
-
const originals = [root];
|
|
906
|
-
const clones = [clone];
|
|
907
|
-
const walk = (el, into) => {
|
|
908
|
-
for (const child of el.children) {
|
|
909
|
-
if (isIgnorable(child)) continue;
|
|
910
|
-
into.push(child);
|
|
911
|
-
walk(child, into);
|
|
912
|
-
}
|
|
913
|
-
};
|
|
914
|
-
walk(root, originals);
|
|
915
|
-
walk(clone, clones);
|
|
916
|
-
if (clones.length !== originals.length) throw new Error("scoreImage: the cloned tree diverged from the live one");
|
|
917
|
-
for (const el of [clone, ...clone.querySelectorAll("*")]) el.removeAttribute("title");
|
|
918
|
-
const { families, italics } = copyComputedStyles(originals, clones, {
|
|
919
|
-
foreground: options.foreground,
|
|
920
|
-
accent: options.accent,
|
|
921
|
-
accentProbe: resolvedAccent(root)
|
|
922
|
-
});
|
|
923
|
-
clone.style.setProperty("white-space", "nowrap");
|
|
924
|
-
const cloneLines = Array.from(clone.children).filter((child) => child.classList.contains("guido") || child.tagName === "P");
|
|
925
|
-
stacked.forEach((entry, i) => {
|
|
926
|
-
const cloneLine = cloneLines[i];
|
|
927
|
-
if (entry.pinWidth !== void 0 && cloneLine) cloneLine.style.setProperty("width", `${entry.pinWidth}px`);
|
|
928
|
-
});
|
|
929
|
-
clone.style.setProperty("padding-top", `${padding - cropTop}px`);
|
|
930
|
-
clone.style.setProperty("padding-left", `${padding - cropLeft}px`);
|
|
931
|
-
clone.style.setProperty("padding-right", `${padding}px`);
|
|
932
|
-
clone.style.setProperty("padding-bottom", `${padding}px`);
|
|
933
|
-
const faceCss = await embedFontFaces(await collectFontFaces(families), italics);
|
|
934
|
-
const wrapper = new XMLSerializer().serializeToString(clone);
|
|
935
|
-
const bgRect = options.background ? `<rect width="100%" height="100%" fill="${escapeXmlAttribute(options.background)}"/>` : "";
|
|
936
|
-
return {
|
|
937
|
-
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>",
|
|
938
|
-
width,
|
|
939
|
-
height
|
|
940
|
-
};
|
|
941
|
-
}
|
|
942
|
-
/** Serializes the rendered score under `el` into a self-contained SVG
|
|
943
|
-
* string (fonts embedded, colors resolved) sized to the score's content.
|
|
944
|
-
* Throws when no score was rendered into the element. */
|
|
945
|
-
async function scoreSvg(el, options = {}) {
|
|
946
|
-
return (await serializeScore(el, options)).svg;
|
|
947
|
-
}
|
|
948
|
-
/** Rasterizes the rendered score under `el` to a PNG blob: the
|
|
949
|
-
* self-contained SVG loads as an image (the browser's own renderer
|
|
950
|
-
* paints it, so the picture matches the DOM exactly) and draws onto a
|
|
951
|
-
* canvas at `scale`×. Throws when no score was rendered into the
|
|
952
|
-
* element or the environment has no 2D canvas. */
|
|
953
|
-
async function scorePngBlob(el, options = {}) {
|
|
954
|
-
const { svg, width, height } = await serializeScore(el, options);
|
|
955
|
-
const scale = Math.max(1, options.scale ?? 2);
|
|
956
|
-
const image = new Image();
|
|
957
|
-
image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
|
|
958
|
-
await new Promise((resolve, reject) => {
|
|
959
|
-
image.onload = () => resolve();
|
|
960
|
-
image.onerror = () => reject(/* @__PURE__ */ new Error("scoreImage: the exported SVG failed to rasterize"));
|
|
961
|
-
});
|
|
962
|
-
try {
|
|
963
|
-
await image.decode();
|
|
964
|
-
} catch {}
|
|
965
|
-
const canvas = document.createElement("canvas");
|
|
966
|
-
canvas.width = Math.ceil(width * scale);
|
|
967
|
-
canvas.height = Math.ceil(height * scale);
|
|
968
|
-
const ctx = canvas.getContext("2d");
|
|
969
|
-
if (!ctx) throw new Error("scoreImage: this environment provides no 2D canvas");
|
|
970
|
-
ctx.scale(scale, scale);
|
|
971
|
-
if (options.background) {
|
|
972
|
-
ctx.fillStyle = options.background;
|
|
973
|
-
ctx.fillRect(0, 0, width, height);
|
|
974
|
-
}
|
|
975
|
-
const draw = () => ctx.drawImage(image, 0, 0, width, height);
|
|
976
|
-
draw();
|
|
977
|
-
if (/^((?!chrome|android|crios|fxios).)*safari/i.test(navigator.userAgent)) {
|
|
978
|
-
await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
|
979
|
-
draw();
|
|
980
|
-
}
|
|
981
|
-
const blob = await new Promise((resolve) => canvas.toBlob(resolve, "image/png"));
|
|
982
|
-
if (!blob) throw new Error("scoreImage: PNG encoding failed");
|
|
983
|
-
return blob;
|
|
984
|
-
}
|
|
985
|
-
function downloadBlob(blob, filename) {
|
|
986
|
-
const url = URL.createObjectURL(blob);
|
|
987
|
-
const anchor = document.createElement("a");
|
|
988
|
-
anchor.href = url;
|
|
989
|
-
anchor.download = filename;
|
|
990
|
-
anchor.click();
|
|
991
|
-
setTimeout(() => URL.revokeObjectURL(url), 1e4);
|
|
992
|
-
}
|
|
993
|
-
/** Exports the rendered score under `el` as a PNG download. Resolves
|
|
994
|
-
* with the filename used. */
|
|
995
|
-
async function downloadScorePng(el, options = {}) {
|
|
996
|
-
const filename = options.filename ?? "score.png";
|
|
997
|
-
downloadBlob(await scorePngBlob(el, options), filename);
|
|
998
|
-
return filename;
|
|
999
|
-
}
|
|
1000
|
-
/** Exports the rendered score under `el` as a self-contained SVG
|
|
1001
|
-
* download (fonts embedded — the print-friendlier artifact). Resolves
|
|
1002
|
-
* with the filename used. */
|
|
1003
|
-
async function downloadScoreSvg(el, options = {}) {
|
|
1004
|
-
const filename = options.filename ?? "score.svg";
|
|
1005
|
-
downloadBlob(new Blob([await scoreSvg(el, options)], { type: "image/svg+xml;charset=utf-8" }), filename);
|
|
1006
|
-
return filename;
|
|
1007
|
-
}
|
|
1008
|
-
//#endregion
|
|
1009
|
-
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 };
|