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
|
@@ -0,0 +1,1985 @@
|
|
|
1
|
+
import { A as CLEF_GLYPHS, D as resolveSpans, E as unescape, F as isModifierGlyph, G as variantOf, H as toSmallHead, M as baseOf, P as isClefGlyph, _ as GuidoScript, b as isC4ClefGroup, f as resolveMarks, g as unknownMarks, h as styleSetOf, j as STAFF, k as splitNoteMarkers, l as inlineStylesFor, m as resolveTextRuns, r as layoutScore, u as kindOf, w as statementSource, x as isStatementGroup, y as escape } from "./chantLayout-g_xuQ9nD.js";
|
|
2
|
+
//#region src/stanzas.ts
|
|
3
|
+
/**
|
|
4
|
+
* Stanzas on one melody (issue #69): a hymn stores its melody once, as
|
|
5
|
+
* stanza 1's GuidoScript, and every further stanza as syllabified text
|
|
6
|
+
* whose syllables map one-to-one onto the melody's note groups — the
|
|
7
|
+
* slots.
|
|
8
|
+
*
|
|
9
|
+
* A slot is one note group: held groups and `~` empty slots included
|
|
10
|
+
* (issue #83), syllables without notes and marker-only groups not. The
|
|
11
|
+
* further stanzas ride the script as `(@stanza …)` statements at its end
|
|
12
|
+
* (`GuidoScript.stanzas`), or come from a `stanzas` option that replaces
|
|
13
|
+
* them. Stanza numbers and slot numbers are 1-based: stanza 1 is the
|
|
14
|
+
* script itself, and they are what the warnings report.
|
|
15
|
+
*
|
|
16
|
+
* Stanza text follows Aretino's lyric-line rules (see `parseStanza`).
|
|
17
|
+
* Rendering stanza k is a script rewrite (`selectStanza`, `withStanza`):
|
|
18
|
+
* its syllables are swapped onto the slots, the notes never change, so
|
|
19
|
+
* every emitter (DOM, image, Word) works on the result unchanged.
|
|
20
|
+
*/
|
|
21
|
+
/** The syllable text that marks a slot a stanza is missing a syllable
|
|
22
|
+
* for: a rubric ellipsis, red in BNS, so the mismatch shows in the
|
|
23
|
+
* render (and in the Word export). */
|
|
24
|
+
var STANZA_PLACEHOLDER = "_…_";
|
|
25
|
+
/** The unescaped characters that end a syllable within a word: the
|
|
26
|
+
* hyphen, the mandatory hyphen and the soft hyphen. */
|
|
27
|
+
var SYLLABLE_BREAKS = "-=";
|
|
28
|
+
/** The characters an escape takes out of the syllable formatting. */
|
|
29
|
+
var MARKUP_CHARS = "_*†∗{}";
|
|
30
|
+
/**
|
|
31
|
+
* Parses stanza text into its slot items, by Aretino's lyric-line rules:
|
|
32
|
+
*
|
|
33
|
+
* - whitespace separates words, `-` separates the syllables of a word
|
|
34
|
+
* (a soft hyphen U+00AD counts as `-`, and so does the mandatory
|
|
35
|
+
* hyphen `=` — the renderer has no hyphen it may not drop yet);
|
|
36
|
+
* - a lone `-` (or an empty syllable, `Al--le`) holds the slot for the
|
|
37
|
+
* syllable before it; that syllable's word end is its own (`Al- - le`
|
|
38
|
+
* is mid-word, `bunt - gen` ends the word);
|
|
39
|
+
* - a lone `~` is an empty slot; `~` inside a syllable is a
|
|
40
|
+
* non-breaking space;
|
|
41
|
+
* - a backslash makes the next character literal (`\-`, `\~`, `\=`,
|
|
42
|
+
* `\(`, `\\`), markup characters included (`\_`, `\*`).
|
|
43
|
+
*
|
|
44
|
+
* There are no `_` extenders: `_…_`, `__…__` and `*…*` stay the
|
|
45
|
+
* syllable formatting of the script notation.
|
|
46
|
+
*/
|
|
47
|
+
function parseStanza(text) {
|
|
48
|
+
const words = [];
|
|
49
|
+
let word = null;
|
|
50
|
+
const chars = Array.from(text);
|
|
51
|
+
for (let i = 0; i < chars.length; i++) {
|
|
52
|
+
let ch = chars[i];
|
|
53
|
+
const escaped = ch === "\\" && i + 1 < chars.length;
|
|
54
|
+
if (escaped) ch = chars[++i];
|
|
55
|
+
if (!escaped && /\s/.test(ch)) {
|
|
56
|
+
word = null;
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
if (word === null) {
|
|
60
|
+
word = [];
|
|
61
|
+
words.push(word);
|
|
62
|
+
}
|
|
63
|
+
word.push({
|
|
64
|
+
ch,
|
|
65
|
+
escaped
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
const out = [];
|
|
69
|
+
for (const w of words) {
|
|
70
|
+
if (w.length === 1 && !w[0].escaped && w[0].ch === "~") {
|
|
71
|
+
out.push({ kind: "empty" });
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
const pieces = [""];
|
|
75
|
+
const written = [""];
|
|
76
|
+
for (const { ch, escaped } of w) {
|
|
77
|
+
if (!escaped && SYLLABLE_BREAKS.includes(ch)) {
|
|
78
|
+
pieces.push("");
|
|
79
|
+
written.push("");
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
const shown = !escaped && ch === "~" ? "\xA0" : ch;
|
|
83
|
+
pieces[pieces.length - 1] += shown;
|
|
84
|
+
written[written.length - 1] += escaped && MARKUP_CHARS.includes(ch) ? `\\${ch}` : escape(shown);
|
|
85
|
+
}
|
|
86
|
+
const last = pieces.length - 1;
|
|
87
|
+
for (const [p, piece] of pieces.entries()) {
|
|
88
|
+
if (piece === "") {
|
|
89
|
+
if (p < last) out.push({ kind: "hold" });
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
const source = written[p];
|
|
93
|
+
out.push({
|
|
94
|
+
kind: "syllable",
|
|
95
|
+
text: piece,
|
|
96
|
+
wordEnd: p === last,
|
|
97
|
+
...source !== escape(piece) ? { source } : {}
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return standaloneSpans(out);
|
|
102
|
+
}
|
|
103
|
+
/** Closes a `{…}` span at each stanza syllable and reopens it at the next,
|
|
104
|
+
* so a syllable stands on its own wherever a slice cuts the stanza. */
|
|
105
|
+
function standaloneSpans(items) {
|
|
106
|
+
const syllables = items.filter((item) => item.kind === "syllable");
|
|
107
|
+
const written = syllables.map((syl) => syl.source ?? escape(syl.text));
|
|
108
|
+
if (!written.some((text) => /[{}]/.test(text))) return items;
|
|
109
|
+
const { pieces } = resolveSpans(written);
|
|
110
|
+
for (const [i, syl] of syllables.entries()) syl.source = pieces[i].source;
|
|
111
|
+
return items;
|
|
112
|
+
}
|
|
113
|
+
/** Whether a token opens a slot: a sung syllable with notes that are not
|
|
114
|
+
* all markers. Labels and signs are never slots. */
|
|
115
|
+
function isSlot(tok) {
|
|
116
|
+
return tok.kind === "syllable" && tok.role !== "label" && tok.role !== "sign" && tok.notes !== "" && splitNoteMarkers(tok.notes).core !== "";
|
|
117
|
+
}
|
|
118
|
+
function parsed(script) {
|
|
119
|
+
return typeof script === "string" ? new GuidoScript(script) : script;
|
|
120
|
+
}
|
|
121
|
+
/** The number of slots (note groups that take a stanza syllable). */
|
|
122
|
+
function slotCount(script) {
|
|
123
|
+
return parsed(script).tokens.filter(isSlot).length;
|
|
124
|
+
}
|
|
125
|
+
/** The stanza texts of stanzas 2, 3, …: the `stanzas` option when
|
|
126
|
+
* given, the script's `(@stanza …)` statements otherwise. */
|
|
127
|
+
function stanzaTexts(script, options = {}) {
|
|
128
|
+
return options.stanzas ?? parsed(script).stanzas;
|
|
129
|
+
}
|
|
130
|
+
/** How many stanzas the script has, stanza 1 (the script) included. */
|
|
131
|
+
function stanzaCount(script, options = {}) {
|
|
132
|
+
return stanzaTexts(script, options).length + 1;
|
|
133
|
+
}
|
|
134
|
+
function sings(fill) {
|
|
135
|
+
return fill.kind === "syllable" || fill.kind === "hold";
|
|
136
|
+
}
|
|
137
|
+
/** Stanza 1's fills: the slot tokens themselves. */
|
|
138
|
+
function scriptFills(slots) {
|
|
139
|
+
return slots.map((tok) => tok.empty ? { kind: "empty" } : tok.held ? { kind: "hold" } : {
|
|
140
|
+
kind: "syllable",
|
|
141
|
+
text: tok.text,
|
|
142
|
+
source: tok.source,
|
|
143
|
+
wordEnd: tok.wordEnd
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
/** A stanza's syllables laid on `count` slots, with its mismatches. */
|
|
147
|
+
function alignStanza(text, count, stanza) {
|
|
148
|
+
const syllables = parseStanza(text);
|
|
149
|
+
const fills = [];
|
|
150
|
+
const warnings = [];
|
|
151
|
+
for (let i = 0; i < count; i++) {
|
|
152
|
+
const syl = syllables[i];
|
|
153
|
+
fills.push(syl ?? { kind: "missing" });
|
|
154
|
+
if (syl === void 0) warnings.push({
|
|
155
|
+
stanza,
|
|
156
|
+
slot: i + 1,
|
|
157
|
+
kind: "missing",
|
|
158
|
+
message: `Stanza ${stanza} has no syllable for slot ${i + 1} of ${count}`
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
for (const [i, syl] of syllables.slice(count).entries()) {
|
|
162
|
+
const shown = syl.kind === "syllable" ? syl.text : syl.kind === "hold" ? "-" : "~";
|
|
163
|
+
warnings.push({
|
|
164
|
+
stanza,
|
|
165
|
+
slot: count + i + 1,
|
|
166
|
+
kind: "extra",
|
|
167
|
+
text: shown,
|
|
168
|
+
message: `Stanza ${stanza} has an extra syllable "${shown}" past the last slot (${count})`
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
return {
|
|
172
|
+
fills,
|
|
173
|
+
warnings
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
/** Throws when `stanza` is not one of the script's stanzas. */
|
|
177
|
+
function checkStanzaNumber(stanza, count) {
|
|
178
|
+
if (!Number.isInteger(stanza) || stanza < 1 || stanza > count) throw new RangeError(`Stanza ${stanza} does not exist: the script has ${count} stanza${count === 1 ? "" : "s"}`);
|
|
179
|
+
}
|
|
180
|
+
/** The count mismatches of one stanza (`options.stanza`), or of every
|
|
181
|
+
* stanza when none is named. Stanza 1 is the script and never warns;
|
|
182
|
+
* an intentional `~` is a syllable like any other. */
|
|
183
|
+
function stanzaWarnings(script, options = {}) {
|
|
184
|
+
const texts = stanzaTexts(script, options);
|
|
185
|
+
const count = slotCount(script);
|
|
186
|
+
if (options.stanza !== void 0) {
|
|
187
|
+
checkStanzaNumber(options.stanza, texts.length + 1);
|
|
188
|
+
if (options.stanza === 1) return [];
|
|
189
|
+
return alignStanza(texts[options.stanza - 2], count, options.stanza).warnings;
|
|
190
|
+
}
|
|
191
|
+
return texts.flatMap((text, i) => alignStanza(text, count, i + 2).warnings);
|
|
192
|
+
}
|
|
193
|
+
/** Pads stanza text with `~` empty slots up to the script's slot count
|
|
194
|
+
* (unchanged when it already has enough syllables). */
|
|
195
|
+
function padStanza(script, text) {
|
|
196
|
+
const missing = slotCount(script) - parseStanza(text).length;
|
|
197
|
+
return missing > 0 ? `${text.trimEnd()}${" ~".repeat(missing)}` : text;
|
|
198
|
+
}
|
|
199
|
+
/** A note group with its plain heads, virgas and longas swapped for small
|
|
200
|
+
* heads (connectors, markers and signs stay). */
|
|
201
|
+
function smallHeads(notes) {
|
|
202
|
+
return Array.from(notes, (ch) => {
|
|
203
|
+
const small = toSmallHead(ch);
|
|
204
|
+
if (small !== void 0) return small;
|
|
205
|
+
const variant = baseOf(ch);
|
|
206
|
+
if (variant && (variant.role === "virga" || variant.role === "longa")) return toSmallHead(variant.base) ?? ch;
|
|
207
|
+
return ch;
|
|
208
|
+
}).join("");
|
|
209
|
+
}
|
|
210
|
+
/** A stanza syllable written in the script notation. */
|
|
211
|
+
function syllableSource({ text, source }) {
|
|
212
|
+
return source ?? (text === "~" ? "\\~" : escape(text));
|
|
213
|
+
}
|
|
214
|
+
/** Rewrites a script's source to sing stanza `stanza`. */
|
|
215
|
+
function stanzaSource(source, stanza, options) {
|
|
216
|
+
const script = new GuidoScript(source);
|
|
217
|
+
const texts = stanzaTexts(script, options);
|
|
218
|
+
checkStanzaNumber(stanza, texts.length + 1);
|
|
219
|
+
const rendered = options.rendered ?? [stanza];
|
|
220
|
+
for (const k of rendered) checkStanzaNumber(k, texts.length + 1);
|
|
221
|
+
const mode = options.emptySlots ?? "normal";
|
|
222
|
+
if (stanza === 1 && mode === "normal") return source;
|
|
223
|
+
const tokens = script.tokens;
|
|
224
|
+
const slotTokens = tokens.filter((t) => isSlot(t));
|
|
225
|
+
const allFills = [scriptFills(slotTokens), ...texts.map((text, i) => alignStanza(text, slotTokens.length, i + 2).fills)];
|
|
226
|
+
const fills = allFills[stanza - 1];
|
|
227
|
+
const cue = (slot) => mode === "partial" ? allFills.some((f) => sings(f[slot])) && !allFills.every((f) => sings(f[slot])) : mode === "small" && rendered.every((k) => !sings(allFills[k - 1][slot])) && allFills.some((f, j) => !rendered.includes(j + 1) && sings(f[slot]));
|
|
228
|
+
let out = script.clef !== void 0 ? `(${script.clef})` : "";
|
|
229
|
+
let first = true;
|
|
230
|
+
let pendingSpace = false;
|
|
231
|
+
let canHold = false;
|
|
232
|
+
const emit = (piece, space) => {
|
|
233
|
+
out += (space && !first ? " " : "") + piece;
|
|
234
|
+
first = false;
|
|
235
|
+
};
|
|
236
|
+
let slot = 0;
|
|
237
|
+
for (const tok of tokens) {
|
|
238
|
+
if (tok.kind !== "syllable") {
|
|
239
|
+
emit(statementSource(tok), pendingSpace);
|
|
240
|
+
pendingSpace = false;
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
if (!isSlot(tok)) {
|
|
244
|
+
if (tok.held) {
|
|
245
|
+
emit(`(${escape(tok.notes)})`, pendingSpace);
|
|
246
|
+
pendingSpace = false;
|
|
247
|
+
} else {
|
|
248
|
+
emit(`${tok.source}(${escape(tok.notes)})`, pendingSpace || tok.spaceBefore);
|
|
249
|
+
pendingSpace = tok.wordEnd;
|
|
250
|
+
canHold = tok.notes !== "";
|
|
251
|
+
}
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
const fill = fills[slot];
|
|
255
|
+
const notes = escape(cue(slot) ? smallHeads(tok.notes) : tok.notes);
|
|
256
|
+
slot++;
|
|
257
|
+
switch (fill.kind) {
|
|
258
|
+
case "syllable":
|
|
259
|
+
emit(`${syllableSource(fill)}(${notes})`, pendingSpace);
|
|
260
|
+
pendingSpace = fill.wordEnd;
|
|
261
|
+
break;
|
|
262
|
+
case "hold":
|
|
263
|
+
emit(`${canHold ? "" : "~"}(${notes})`, false);
|
|
264
|
+
break;
|
|
265
|
+
case "empty":
|
|
266
|
+
emit(`~(${notes})`, false);
|
|
267
|
+
break;
|
|
268
|
+
case "missing":
|
|
269
|
+
emit(`${STANZA_PLACEHOLDER}(${notes})`, true);
|
|
270
|
+
pendingSpace = true;
|
|
271
|
+
}
|
|
272
|
+
canHold = true;
|
|
273
|
+
}
|
|
274
|
+
return out;
|
|
275
|
+
}
|
|
276
|
+
/** The `selectStanza` transform factory: rewrites the script to sing
|
|
277
|
+
* stanza `stanza` (1-based; 1 is the script itself). Its syllables go on
|
|
278
|
+
* the slots in order — missing ones become `STANZA_PLACEHOLDER`
|
|
279
|
+
* syllables, extra ones are dropped (`stanzaWarnings` reports both) — and
|
|
280
|
+
* the `(@stanza …)` statements are dropped. Everything that is not a
|
|
281
|
+
* slot (statements, syllables without notes, marker-only groups) stays as
|
|
282
|
+
* written. With `emptySlots: 'small'`, a slot the stanza leaves empty
|
|
283
|
+
* while another stanza sings it gets small heads (`rendered` lists the
|
|
284
|
+
* stanzas stacked with it: then a slot gets small heads when none of
|
|
285
|
+
* them sings it while another stanza does). With `emptySlots:
|
|
286
|
+
* 'partial'`, every slot some stanza sings and another does not gets
|
|
287
|
+
* small heads, whatever is rendered. Stanza 1 with normal
|
|
288
|
+
* empty slots returns the source unchanged. Throws a RangeError for a
|
|
289
|
+
* stanza the script does not have. Register it first, so the other
|
|
290
|
+
* transforms (the initial, the transpositions) see the stanza's text. */
|
|
291
|
+
function selectStanza(stanza, options = {}) {
|
|
292
|
+
return {
|
|
293
|
+
name: "selectStanza",
|
|
294
|
+
apply: (source) => stanzaSource(source, stanza, options)
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
/** The script singing stanza `stanza` (see `selectStanza`); `transforms`
|
|
298
|
+
* run after the stanza swap. A GuidoScript argument is taken by its
|
|
299
|
+
* (already transformed) source. */
|
|
300
|
+
function withStanza(script, stanza, options = {}) {
|
|
301
|
+
const source = typeof script === "string" ? script : script.source;
|
|
302
|
+
return new GuidoScript(source, { transforms: [selectStanza(stanza, options), ...options.transforms ?? []] });
|
|
303
|
+
}
|
|
304
|
+
/** The stanza numbers a stack names: every stanza for `'all'`, the
|
|
305
|
+
* listed ones otherwise. Throws a RangeError for an empty list or a
|
|
306
|
+
* stanza the script does not have. */
|
|
307
|
+
function stackedStanzaNumbers(script, stack, options = {}) {
|
|
308
|
+
const count = stanzaCount(script, options);
|
|
309
|
+
if (stack === "all") return Array.from({ length: count }, (_, k) => k + 1);
|
|
310
|
+
if (stack.length === 0) throw new RangeError("No stanza to stack: the list is empty");
|
|
311
|
+
for (const k of stack) checkStanzaNumber(k, count);
|
|
312
|
+
return [...stack];
|
|
313
|
+
}
|
|
314
|
+
/** The scripts of stacked stanzas (issue #84): one per stanza of the
|
|
315
|
+
* stack, in its order, each singing its stanza on the shared notes (see
|
|
316
|
+
* `withStanza`; `transforms` run after the swap). Hand them to the layout
|
|
317
|
+
* together (`layoutScore`, `GuidoRender`, the Word export) for one text
|
|
318
|
+
* line per stanza under one staff. With `emptySlots: 'small'`, a slot
|
|
319
|
+
* gets small heads when no stacked stanza sings it while a stanza left
|
|
320
|
+
* out of the stack does, so every script carries the same notes. */
|
|
321
|
+
function stackStanzas(script, stack, options = {}) {
|
|
322
|
+
const rendered = stackedStanzaNumbers(script, stack, options);
|
|
323
|
+
return rendered.map((k) => withStanza(script, k, {
|
|
324
|
+
...options,
|
|
325
|
+
rendered
|
|
326
|
+
}));
|
|
327
|
+
}
|
|
328
|
+
//#endregion
|
|
329
|
+
//#region src/exactTranspose.ts
|
|
330
|
+
/**
|
|
331
|
+
* Exact transposition (issue #70): moves the sounding pitches of a
|
|
332
|
+
* script and re-notates them under a target clef and key, so the result
|
|
333
|
+
* reads like a chant notated at the new pitch. The staff-degree shift
|
|
334
|
+
* (`transposeBy`) stays separate and ignores pitch meaning.
|
|
335
|
+
*
|
|
336
|
+
* A note's sounding pitch is its staff position + the clef in effect +
|
|
337
|
+
* the key in effect + any sign written in its group. A sign affects its
|
|
338
|
+
* whole group: every note of that pitch letter, in every octave. The
|
|
339
|
+
* transposition is two steps:
|
|
340
|
+
*
|
|
341
|
+
* 1. Move every pitch by a spelled interval (letter steps + semitones,
|
|
342
|
+
* so a major third up turns b♭ into d, not e♭♭).
|
|
343
|
+
* 2. Re-notate under the target clef and key: each note's staff position
|
|
344
|
+
* and glyph, plus the signs the target key doesn't cover. Added signs
|
|
345
|
+
* go before the note group, after its leading markers (the #49 rule).
|
|
346
|
+
*
|
|
347
|
+
* Keys are written with the classical key-signature layout
|
|
348
|
+
* (`KEY_SIGNATURES`). Results past the glyph range and missing glyph
|
|
349
|
+
* variants are errors, never silent clamps.
|
|
350
|
+
*/
|
|
351
|
+
/** A transposed note past the end of the glyph range. Thrown as its own
|
|
352
|
+
* class so the octave search for a `final` can tell it apart. */
|
|
353
|
+
var TranspositionRangeError = class extends Error {
|
|
354
|
+
constructor(message) {
|
|
355
|
+
super(message);
|
|
356
|
+
this.name = "TranspositionRangeError";
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
/** The key-signature glyphs per clef glyph (issue #70): flats in the
|
|
360
|
+
* order b e a d g c f, sharps in the order f c g d a e b, each at the
|
|
361
|
+
* highest octave of the shape that stays on the staff. A key of n signs
|
|
362
|
+
* is the first n glyphs of its row. */
|
|
363
|
+
var KEY_SIGNATURES = {
|
|
364
|
+
M: {
|
|
365
|
+
flats: "XBYVÍCS",
|
|
366
|
+
sharps: "ôþùßÑòÒ"
|
|
367
|
+
},
|
|
368
|
+
"<": {
|
|
369
|
+
flats: "XBYVÍCS",
|
|
370
|
+
sharps: "ôþùßÑòÒ"
|
|
371
|
+
},
|
|
372
|
+
">": {
|
|
373
|
+
flats: "V$CNXBY",
|
|
374
|
+
sharps: "ÑòÒôþùß"
|
|
375
|
+
},
|
|
376
|
+
"#": {
|
|
377
|
+
flats: "NXBYVÍC",
|
|
378
|
+
sharps: "þÐßÑÎÒÏ"
|
|
379
|
+
},
|
|
380
|
+
"&": {
|
|
381
|
+
flats: "YVÍCSXA",
|
|
382
|
+
sharps: "òÒôþÐßÑ"
|
|
383
|
+
},
|
|
384
|
+
"@": {
|
|
385
|
+
flats: "CNXBYVÍ",
|
|
386
|
+
sharps: "ÐßÑòÒôþ"
|
|
387
|
+
},
|
|
388
|
+
"{": {
|
|
389
|
+
flats: "BYVÍCSX",
|
|
390
|
+
sharps: "ÒÏþÐÌÑÎ"
|
|
391
|
+
},
|
|
392
|
+
"}": {
|
|
393
|
+
flats: "ÍCSXAYa",
|
|
394
|
+
sharps: "ßÑòÒÏþÐ"
|
|
395
|
+
}
|
|
396
|
+
};
|
|
397
|
+
var FLAT_ORDER = "beadgcf";
|
|
398
|
+
var SHARP_ORDER = "fcgdaeb";
|
|
399
|
+
/** Pitch letters from c, so a diatonic step's letter is `step mod 7`. */
|
|
400
|
+
var LETTERS = "cdefgab";
|
|
401
|
+
var LETTER_SEMITONES = [
|
|
402
|
+
0,
|
|
403
|
+
2,
|
|
404
|
+
4,
|
|
405
|
+
5,
|
|
406
|
+
7,
|
|
407
|
+
9,
|
|
408
|
+
11
|
|
409
|
+
];
|
|
410
|
+
var mod7 = (n) => (n % 7 + 7) % 7;
|
|
411
|
+
function semitoneOf({ step, alter }) {
|
|
412
|
+
return Math.floor(step / 7) * 12 + LETTER_SEMITONES[mod7(step)] + alter;
|
|
413
|
+
}
|
|
414
|
+
function letterName(step) {
|
|
415
|
+
return LETTERS[mod7(step)];
|
|
416
|
+
}
|
|
417
|
+
/** A pitch moved by a spelled interval: the letter moves by the steps,
|
|
418
|
+
* the alteration absorbs whatever the semitones leave over. */
|
|
419
|
+
function movePitch(pitch, interval) {
|
|
420
|
+
const step = pitch.step + interval.steps;
|
|
421
|
+
const alter = semitoneOf(pitch) + interval.semitones - semitoneOf({
|
|
422
|
+
step,
|
|
423
|
+
alter: 0
|
|
424
|
+
});
|
|
425
|
+
if (Math.abs(alter) > 1) throw new Error(`Moving ${letterName(pitch.step)}${alterName(pitch.alter)} lands on a double accidental (${letterName(step)}, ${alter > 0 ? "+" : ""}${alter})`);
|
|
426
|
+
return {
|
|
427
|
+
step,
|
|
428
|
+
alter
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
function alterName(alter) {
|
|
432
|
+
return alter < 0 ? "♭" : alter > 0 ? "♯" : "";
|
|
433
|
+
}
|
|
434
|
+
function roleOfAlter(alter) {
|
|
435
|
+
return alter < 0 ? "modifyDown" : alter > 0 ? "modifyUp" : "modifyNatural";
|
|
436
|
+
}
|
|
437
|
+
function alterOfRole(role) {
|
|
438
|
+
return role === "modifyDown" ? -1 : role === "modifyUp" ? 1 : 0;
|
|
439
|
+
}
|
|
440
|
+
/** The staff position of a clef's own line and the step of its pitch. */
|
|
441
|
+
function clefAnchor(clef) {
|
|
442
|
+
const entry = CLEF_GLYPHS[clef];
|
|
443
|
+
const step = {
|
|
444
|
+
c: 28,
|
|
445
|
+
f: 24,
|
|
446
|
+
g: 32
|
|
447
|
+
}[entry.clef];
|
|
448
|
+
return {
|
|
449
|
+
position: STAFF.indexOf("2") + 2 * (entry.line - 1),
|
|
450
|
+
step
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
function stepAt(position, clef) {
|
|
454
|
+
const anchor = clefAnchor(clef);
|
|
455
|
+
return anchor.step + position - anchor.position;
|
|
456
|
+
}
|
|
457
|
+
function positionOf(step, clef) {
|
|
458
|
+
const anchor = clefAnchor(clef);
|
|
459
|
+
return anchor.position + step - anchor.step;
|
|
460
|
+
}
|
|
461
|
+
/** The staff position and variant role of a pitched glyph (`'base'` for
|
|
462
|
+
* a base glyph), or undefined for a glyph without pitch. */
|
|
463
|
+
function glyphOf(ch) {
|
|
464
|
+
if (STAFF.includes(ch)) return {
|
|
465
|
+
position: STAFF.indexOf(ch),
|
|
466
|
+
role: "base"
|
|
467
|
+
};
|
|
468
|
+
const entry = baseOf(ch);
|
|
469
|
+
return entry ? {
|
|
470
|
+
position: STAFF.indexOf(entry.base),
|
|
471
|
+
role: entry.role
|
|
472
|
+
} : void 0;
|
|
473
|
+
}
|
|
474
|
+
/** Whether `ch` is in a pitch row. Read at call time: this module and
|
|
475
|
+
* the transforms module import each other. */
|
|
476
|
+
function isPitchChar(ch) {
|
|
477
|
+
return PITCH_ROWS.some((row) => row.includes(ch));
|
|
478
|
+
}
|
|
479
|
+
/** The glyph of `role` at a staff position. Throws past the glyph range
|
|
480
|
+
* and when the variant does not exist. */
|
|
481
|
+
function glyphAt(position, role, what) {
|
|
482
|
+
const base = STAFF[position];
|
|
483
|
+
if (base === void 0) throw new TranspositionRangeError(`${what} runs past the glyph range`);
|
|
484
|
+
const glyph = role === "base" ? base : variantOf(base, role);
|
|
485
|
+
if (glyph === void 0) throw new Error(`${what}: the glyph "${base}" has no ${role} variant`);
|
|
486
|
+
return glyph;
|
|
487
|
+
}
|
|
488
|
+
/** A key read from modifier glyphs under `clef`. Naturals carry no
|
|
489
|
+
* alteration, so they drop out. */
|
|
490
|
+
function readKey(glyphs, clef) {
|
|
491
|
+
const key = /* @__PURE__ */ new Map();
|
|
492
|
+
for (const ch of glyphs) {
|
|
493
|
+
if (!isModifierGlyph(ch)) continue;
|
|
494
|
+
const { base, role } = baseOf(ch);
|
|
495
|
+
const letter = mod7(stepAt(STAFF.indexOf(base), clef));
|
|
496
|
+
const alter = alterOfRole(role);
|
|
497
|
+
if (alter === 0) key.delete(letter);
|
|
498
|
+
else key.set(letter, alter);
|
|
499
|
+
}
|
|
500
|
+
return key;
|
|
501
|
+
}
|
|
502
|
+
/** A signed key count: −n is the first n flats, n the first n sharps. */
|
|
503
|
+
function countedKey(count) {
|
|
504
|
+
if (!Number.isInteger(count) || Math.abs(count) > 7) throw new Error(`A key has −7 to 7 signs, not ${count}`);
|
|
505
|
+
const order = count < 0 ? FLAT_ORDER : SHARP_ORDER;
|
|
506
|
+
const key = /* @__PURE__ */ new Map();
|
|
507
|
+
for (const name of order.slice(0, Math.abs(count))) key.set(LETTERS.indexOf(name), Math.sign(count));
|
|
508
|
+
return key;
|
|
509
|
+
}
|
|
510
|
+
/** A key moved by an interval. The key is a scale, not a set of
|
|
511
|
+
* pitches: every letter moves (d minor's natural e becomes g minor's
|
|
512
|
+
* e♭ a fourth up), and the moved key is whatever the scale alters. */
|
|
513
|
+
function moveKey(key, interval) {
|
|
514
|
+
const moved = /* @__PURE__ */ new Map();
|
|
515
|
+
for (let letter = 0; letter < 7; letter++) {
|
|
516
|
+
const pitch = movePitch({
|
|
517
|
+
step: letter,
|
|
518
|
+
alter: key.get(letter) ?? 0
|
|
519
|
+
}, interval);
|
|
520
|
+
if (pitch.alter !== 0) moved.set(mod7(pitch.step), pitch.alter);
|
|
521
|
+
}
|
|
522
|
+
return moved;
|
|
523
|
+
}
|
|
524
|
+
function sameKey(a, b) {
|
|
525
|
+
return a.size === b.size && [...a].every(([letter, alter]) => b.get(letter) === alter);
|
|
526
|
+
}
|
|
527
|
+
/** Whether two keys written as modifier glyphs under `clef` alter the
|
|
528
|
+
* same pitch letters the same way (glyph order and octave aside). */
|
|
529
|
+
function sameKeyGlyphs(a, b, clef) {
|
|
530
|
+
return sameKey(readKey(a, clef), readKey(b, clef));
|
|
531
|
+
}
|
|
532
|
+
/** A key written with the key-signature layout of `clef`: flats first,
|
|
533
|
+
* then sharps, each in the table's order. */
|
|
534
|
+
function writeKey(key, clef) {
|
|
535
|
+
const row = KEY_SIGNATURES[clef];
|
|
536
|
+
const glyphs = (order, alter, signs) => [...order].map((name, i) => key.get(LETTERS.indexOf(name)) === alter ? signs[i] : "").join("");
|
|
537
|
+
return glyphs(FLAT_ORDER, -1, row.flats) + glyphs(SHARP_ORDER, 1, row.sharps);
|
|
538
|
+
}
|
|
539
|
+
/** Parses an interval name: an optional sign, a quality (`P`, `M`, `m`,
|
|
540
|
+
* `A`, `d`) and a number (`P1`, `-P5`, `M3`, `A4`, `P8`, `M9`). */
|
|
541
|
+
function parseInterval(name) {
|
|
542
|
+
const match = name.trim().match(/^([+-]?)([PMmAd])(\d+)$/);
|
|
543
|
+
const number = match ? Number(match[3]) : 0;
|
|
544
|
+
if (!match || number < 1) throw new Error(`Unknown interval "${name}"`);
|
|
545
|
+
const [, sign, quality] = match;
|
|
546
|
+
const steps = number - 1;
|
|
547
|
+
const perfect = [
|
|
548
|
+
0,
|
|
549
|
+
3,
|
|
550
|
+
4
|
|
551
|
+
].includes(steps % 7);
|
|
552
|
+
if (!(perfect ? "PAd" : "MmAd").includes(quality)) throw new Error(`Unknown interval "${name}"`);
|
|
553
|
+
const base = Math.floor(steps / 7) * 12 + LETTER_SEMITONES[steps % 7];
|
|
554
|
+
const adjust = {
|
|
555
|
+
P: 0,
|
|
556
|
+
M: 0,
|
|
557
|
+
A: 1,
|
|
558
|
+
m: -1,
|
|
559
|
+
d: perfect ? -1 : -2
|
|
560
|
+
}[quality];
|
|
561
|
+
const direction = sign === "-" ? -1 : 1;
|
|
562
|
+
return {
|
|
563
|
+
steps: direction * steps,
|
|
564
|
+
semitones: direction * (base + adjust)
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
var GROUP = /((?:[^()\\]|\\.)*)\(((?:[^)\\]|\\.)*)\)/g;
|
|
568
|
+
function escapeNotes(notes) {
|
|
569
|
+
return notes.replace(/\\/g, "\\\\").replace(/[()]/g, (ch) => `\\${ch}`);
|
|
570
|
+
}
|
|
571
|
+
/** Re-notates one note group. `src*` are the clef and key in effect in
|
|
572
|
+
* the source, `tgt*` the ones in the result. Records the group's last
|
|
573
|
+
* note pitch (the candidate final) through `onNote`. */
|
|
574
|
+
function renotateGroup(notes, interval, srcClef, srcKey, tgtClef, tgtKey, onNote) {
|
|
575
|
+
const { leading, core, trailing } = splitNoteMarkers(notes);
|
|
576
|
+
const chars = [...core];
|
|
577
|
+
const groupSigns = /* @__PURE__ */ new Map();
|
|
578
|
+
for (const ch of chars) {
|
|
579
|
+
if (!isModifierGlyph(ch)) continue;
|
|
580
|
+
const glyph = glyphOf(ch);
|
|
581
|
+
const letter = mod7(stepAt(glyph.position, srcClef));
|
|
582
|
+
const alter = alterOfRole(glyph.role);
|
|
583
|
+
if (groupSigns.has(letter) && groupSigns.get(letter) !== alter) throw new Error(`The note group "${notes}" carries two different signs for ${LETTERS[letter]}`);
|
|
584
|
+
groupSigns.set(letter, alter);
|
|
585
|
+
}
|
|
586
|
+
const coveredLetters = /* @__PURE__ */ new Set();
|
|
587
|
+
const out = [];
|
|
588
|
+
const added = [];
|
|
589
|
+
const pending = [];
|
|
590
|
+
for (const ch of chars) {
|
|
591
|
+
const glyph = glyphOf(ch);
|
|
592
|
+
if (!glyph) {
|
|
593
|
+
if (isPitchChar(ch)) throw new Error(`The glyph "${ch}" has no glyph-family entry, so it cannot be transposed exactly`);
|
|
594
|
+
out.push(ch);
|
|
595
|
+
continue;
|
|
596
|
+
}
|
|
597
|
+
const step = stepAt(glyph.position, srcClef);
|
|
598
|
+
const letter = mod7(step);
|
|
599
|
+
const keyAlter = srcKey.get(letter) ?? 0;
|
|
600
|
+
if (isModifierGlyph(ch)) {
|
|
601
|
+
const alter = alterOfRole(glyph.role);
|
|
602
|
+
const moved = movePitch({
|
|
603
|
+
step,
|
|
604
|
+
alter
|
|
605
|
+
}, interval);
|
|
606
|
+
const tgtAlter = tgtKey.get(mod7(moved.step)) ?? 0;
|
|
607
|
+
if (moved.alter !== tgtAlter || alter === keyAlter) {
|
|
608
|
+
const position = positionOf(moved.step, tgtClef);
|
|
609
|
+
out.push(glyphAt(position, roleOfAlter(moved.alter), `The sign "${ch}"`));
|
|
610
|
+
coveredLetters.add(mod7(moved.step));
|
|
611
|
+
}
|
|
612
|
+
continue;
|
|
613
|
+
}
|
|
614
|
+
const pitch = {
|
|
615
|
+
step,
|
|
616
|
+
alter: groupSigns.get(letter) ?? keyAlter
|
|
617
|
+
};
|
|
618
|
+
const moved = movePitch(pitch, interval);
|
|
619
|
+
out.push(glyphAt(positionOf(moved.step, tgtClef), glyph.role, `The note "${ch}"`));
|
|
620
|
+
if (glyph.role === "smallPoint") continue;
|
|
621
|
+
onNote(pitch);
|
|
622
|
+
pending.push(moved);
|
|
623
|
+
}
|
|
624
|
+
for (const moved of pending) {
|
|
625
|
+
const letter = mod7(moved.step);
|
|
626
|
+
if (coveredLetters.has(letter) || moved.alter === (tgtKey.get(letter) ?? 0)) continue;
|
|
627
|
+
const sign = glyphAt(positionOf(moved.step, tgtClef), roleOfAlter(moved.alter), `The sign for ${letterName(moved.step)}${alterName(moved.alter)}`);
|
|
628
|
+
if (!added.includes(sign)) added.push(sign);
|
|
629
|
+
}
|
|
630
|
+
return leading + added.join("") + out.join("") + trailing;
|
|
631
|
+
}
|
|
632
|
+
/** One re-notation pass over the source. Returns the result and the
|
|
633
|
+
* source's final (the pitch of its last note). */
|
|
634
|
+
function renotate(source, plan) {
|
|
635
|
+
new GuidoScript(source).tokens;
|
|
636
|
+
const head = source.match(/^\s*\(([^)]*)\)/);
|
|
637
|
+
const opening = head && (!isStatementGroup(head[1]) || isC4ClefGroup(head[1])) ? head : null;
|
|
638
|
+
const openingClef = opening && isClefGlyph(opening[1].trimStart()[0] ?? "") ? opening[1].trimStart()[0] : void 0;
|
|
639
|
+
if (opening && openingClef === void 0 && opening[1].trim() !== "") throw new Error(`The opening group "(${opening[1]})" does not start with a clef glyph`);
|
|
640
|
+
if (plan.clef !== void 0 && !isClefGlyph(plan.clef)) throw new Error(`"${plan.clef}" is not a clef glyph`);
|
|
641
|
+
let srcClef = openingClef ?? "M";
|
|
642
|
+
let srcKey = readKey(opening && openingClef ? opening[1].trimStart().slice(1) : "", srcClef);
|
|
643
|
+
let tgtClef = plan.clef ?? srcClef;
|
|
644
|
+
let tgtKey = plan.key === void 0 ? moveKey(srcKey, plan.interval) : typeof plan.key === "number" ? countedKey(plan.key) : readKey(plan.key, tgtClef);
|
|
645
|
+
const openingKey = writeKey(tgtKey, tgtClef);
|
|
646
|
+
const openingGroup = opening || plan.clef !== void 0 || openingKey !== "" ? `(${tgtClef}${openingKey})` : "";
|
|
647
|
+
let final;
|
|
648
|
+
const offset = opening ? opening[0].length : 0;
|
|
649
|
+
return {
|
|
650
|
+
result: openingGroup + source.slice(offset).replace(GROUP, (_, text, rawNotes) => {
|
|
651
|
+
if (isStatementGroup(rawNotes)) {
|
|
652
|
+
const [, keyword, args = ""] = rawNotes.trim().match(/^@(\S*)(?: (.*))?$/) ?? [];
|
|
653
|
+
if (keyword === "clef") {
|
|
654
|
+
srcClef = args[0];
|
|
655
|
+
srcKey = readKey(args.slice(1), srcClef);
|
|
656
|
+
const moved = moveKey(srcKey, plan.interval);
|
|
657
|
+
if (plan.clef === void 0) {
|
|
658
|
+
tgtClef = srcClef;
|
|
659
|
+
tgtKey = moved;
|
|
660
|
+
return `${text}(@clef ${tgtClef}${writeKey(tgtKey, tgtClef)})`;
|
|
661
|
+
}
|
|
662
|
+
if (sameKey(moved, tgtKey)) return text;
|
|
663
|
+
tgtKey = moved;
|
|
664
|
+
const key = writeKey(tgtKey, tgtClef);
|
|
665
|
+
return `${text}(@key${key === "" ? "" : ` ${key}`})`;
|
|
666
|
+
}
|
|
667
|
+
if (keyword === "key") {
|
|
668
|
+
srcKey = readKey(args, srcClef);
|
|
669
|
+
tgtKey = moveKey(srcKey, plan.interval);
|
|
670
|
+
const key = writeKey(tgtKey, tgtClef);
|
|
671
|
+
return `${text}(@key${key === "" ? "" : ` ${key}`})`;
|
|
672
|
+
}
|
|
673
|
+
return `${text}(${rawNotes})`;
|
|
674
|
+
}
|
|
675
|
+
return `${text}(${escapeNotes(renotateGroup(unescape(rawNotes), plan.interval, srcClef, srcKey, tgtClef, tgtKey, (pitch) => {
|
|
676
|
+
final = pitch;
|
|
677
|
+
}))})`;
|
|
678
|
+
}),
|
|
679
|
+
final
|
|
680
|
+
};
|
|
681
|
+
}
|
|
682
|
+
/** The finals' pitch letter and alteration (`g`, `bb`, `b♭`, `f#`). */
|
|
683
|
+
function parseFinal(final) {
|
|
684
|
+
const match = final.trim().match(/^([a-gA-G])(b|♭|#|♯)?$/);
|
|
685
|
+
if (!match) throw new Error(`Unknown final "${final}"`);
|
|
686
|
+
const alter = match[2] === void 0 ? 0 : "b♭".includes(match[2]) ? -1 : 1;
|
|
687
|
+
return {
|
|
688
|
+
letter: LETTERS.indexOf(match[1].toLowerCase()),
|
|
689
|
+
alter
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
/**
|
|
693
|
+
* Transposes a script exactly: moves its sounding pitches and
|
|
694
|
+
* re-notates them under the target clef and key (see
|
|
695
|
+
* `TranspositionTarget`). Without a key, the key moves with the
|
|
696
|
+
* interval; without a clef, the clefs stay as written (mid-script
|
|
697
|
+
* `(@clef …)` included); `(@key …)` statements always move with the
|
|
698
|
+
* interval. A target clef re-notates the whole script in that clef and
|
|
699
|
+
* removes mid-script `(@clef …)` statements (one that changed the key
|
|
700
|
+
* leaves a `(@key …)` behind). With a `final`, the octave whose result
|
|
701
|
+
* fits the glyph range wins — the smaller move when several fit.
|
|
702
|
+
* Throws past the glyph range and on a missing glyph variant.
|
|
703
|
+
*/
|
|
704
|
+
function transposeScript(source, target) {
|
|
705
|
+
if (target.interval !== void 0 && target.final !== void 0) throw new Error("A transposition target takes an interval or a final, not both");
|
|
706
|
+
const plan = (interval) => ({
|
|
707
|
+
interval,
|
|
708
|
+
clef: target.clef,
|
|
709
|
+
key: target.key
|
|
710
|
+
});
|
|
711
|
+
if (target.final === void 0) return renotate(source, plan(typeof target.interval === "string" ? parseInterval(target.interval) : target.interval ?? {
|
|
712
|
+
steps: 0,
|
|
713
|
+
semitones: 0
|
|
714
|
+
})).result;
|
|
715
|
+
const sourceFinal = renotate(source, { interval: {
|
|
716
|
+
steps: 0,
|
|
717
|
+
semitones: 0
|
|
718
|
+
} }).final;
|
|
719
|
+
if (sourceFinal === void 0) throw new Error("The script has no notes, so it has no final");
|
|
720
|
+
const wanted = parseFinal(target.final);
|
|
721
|
+
const up = mod7(wanted.letter - sourceFinal.step);
|
|
722
|
+
const candidates = [
|
|
723
|
+
-14,
|
|
724
|
+
-7,
|
|
725
|
+
0,
|
|
726
|
+
7,
|
|
727
|
+
14
|
|
728
|
+
].map((octave) => {
|
|
729
|
+
const semitones = semitoneOf({
|
|
730
|
+
step: sourceFinal.step + up + octave,
|
|
731
|
+
alter: wanted.alter
|
|
732
|
+
}) - semitoneOf(sourceFinal);
|
|
733
|
+
return {
|
|
734
|
+
steps: up + octave,
|
|
735
|
+
semitones
|
|
736
|
+
};
|
|
737
|
+
}).sort((a, b) => Math.abs(a.semitones) - Math.abs(b.semitones) || b.semitones - a.semitones);
|
|
738
|
+
let rangeError;
|
|
739
|
+
for (const interval of candidates) try {
|
|
740
|
+
return renotate(source, plan(interval)).result;
|
|
741
|
+
} catch (error) {
|
|
742
|
+
if (!(error instanceof TranspositionRangeError)) throw error;
|
|
743
|
+
rangeError ??= error;
|
|
744
|
+
}
|
|
745
|
+
throw rangeError;
|
|
746
|
+
}
|
|
747
|
+
/** The exact transposition as a script transform (see `transposeScript`). */
|
|
748
|
+
function transposeExact(target) {
|
|
749
|
+
return {
|
|
750
|
+
name: "transposeExact",
|
|
751
|
+
apply: (source) => transposeScript(source, target)
|
|
752
|
+
};
|
|
753
|
+
}
|
|
754
|
+
//#endregion
|
|
755
|
+
//#region src/guidoScriptTransforms.ts
|
|
756
|
+
/**
|
|
757
|
+
* Source-level transformations for GuidoScript: named rewrites applied
|
|
758
|
+
* to a script's raw source before parsing (see the `transforms` option
|
|
759
|
+
* on the GuidoScript constructor). Each one receives the source and
|
|
760
|
+
* returns the rewritten source — or the source unchanged when the
|
|
761
|
+
* feature does not apply. They compose in registration order, and the
|
|
762
|
+
* parsed script never sees which ones ran. New script-level features
|
|
763
|
+
* are added here, and only here, as factories returning a ScriptTransform
|
|
764
|
+
* (see `transposeBy`).
|
|
765
|
+
*/
|
|
766
|
+
/** The pitch rows of the chant font: every character carrying pitch
|
|
767
|
+
* information, grouped into rows of neighbouring pitches from low to
|
|
768
|
+
* high. A transpose shift moves a character this many positions along
|
|
769
|
+
* its row; characters outside every row carry no pitch and stay put.
|
|
770
|
+
* Rows are searched in order, so a character found in several rows
|
|
771
|
+
* transposes within the first one. */
|
|
772
|
+
var PITCH_ROWS = [
|
|
773
|
+
"ðñ0123456789öüó",
|
|
774
|
+
"^]qwertzuiopõú",
|
|
775
|
+
"ÝÞQWERTZUIOPÕÚ",
|
|
776
|
+
"×sdfghjkléáû",
|
|
777
|
+
"ØÙDFGHJKLÉÁÛ",
|
|
778
|
+
"÷øaASÍYXCVBN$m",
|
|
779
|
+
"ÈÊËÌÎÏÐÑÒþßòôùý",
|
|
780
|
+
"“”•–—˜™š›œº»",
|
|
781
|
+
"®−§ÿ\"+!%/=()ÖÜÓ",
|
|
782
|
+
"Ÿ¡¢£[¥¦©ª«¬",
|
|
783
|
+
"~¯‚ƒ„…†‡ˆ‰Š‹Œ‘’",
|
|
784
|
+
"àâãäåæçèêëìîï",
|
|
785
|
+
"½°±²³´μ·¾¸¹"
|
|
786
|
+
];
|
|
787
|
+
/** Maps one character to its pitch-shifted neighbour, or undefined when
|
|
788
|
+
* it is not a pitch character (and so stays unchanged). */
|
|
789
|
+
function shiftPitch(ch, shift, overflow) {
|
|
790
|
+
for (const row of PITCH_ROWS) {
|
|
791
|
+
const index = row.indexOf(ch);
|
|
792
|
+
if (index === -1) continue;
|
|
793
|
+
const target = index + shift;
|
|
794
|
+
if (target < 0 || target >= row.length) {
|
|
795
|
+
if (overflow === "null") return "\0";
|
|
796
|
+
if (overflow === "error") throw new Error(`Transposing "${ch}" by ${shift} runs past the glyph range`);
|
|
797
|
+
return row[Math.max(0, Math.min(row.length - 1, target))];
|
|
798
|
+
}
|
|
799
|
+
return row[target];
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
/** Transposes the pitch characters of one note group's content as
|
|
803
|
+
* written in the source (escapes included) — the staff-degree shift
|
|
804
|
+
* `transposeBy` applies to every group. Escape pairs stand for their
|
|
805
|
+
* underlying character (an escaped paren is a pitch glyph of the
|
|
806
|
+
* `®−§ÿ…` row), and a shifted result that is a control character of the
|
|
807
|
+
* group syntax is written escaped. A statement group's content (`@…`) is returned
|
|
808
|
+
* unchanged: its keyword letters are pitch glyphs, but no notes. */
|
|
809
|
+
function transposeNotes(notes, shift, options = {}) {
|
|
810
|
+
if (shift === 0 || isStatementGroup(notes)) return notes;
|
|
811
|
+
const overflow = options.overflow ?? "clamp";
|
|
812
|
+
let out = "";
|
|
813
|
+
for (let i = 0; i < notes.length; i++) {
|
|
814
|
+
const ch = notes[i];
|
|
815
|
+
const escaped = ch === "\\" && notes[i + 1] !== void 0;
|
|
816
|
+
const shifted = shiftPitch(escaped ? notes[i + 1] : ch, shift, overflow);
|
|
817
|
+
if (shifted === void 0) {
|
|
818
|
+
out += escaped ? ch + notes[i + 1] : ch;
|
|
819
|
+
if (escaped) i++;
|
|
820
|
+
continue;
|
|
821
|
+
}
|
|
822
|
+
out += "\\()".includes(shifted) ? `\\${shifted}` : shifted;
|
|
823
|
+
if (escaped) i++;
|
|
824
|
+
}
|
|
825
|
+
return out;
|
|
826
|
+
}
|
|
827
|
+
/** The `transposeBy` transform factory: shifts every pitch character of
|
|
828
|
+
* every notes group `shift` positions along its pitch row. The clef
|
|
829
|
+
* group and the syllable text are left alone — clef handling is a
|
|
830
|
+
* separate, future tool. */
|
|
831
|
+
function transposeBy(shift, options = {}) {
|
|
832
|
+
const overflow = options.overflow ?? "clamp";
|
|
833
|
+
const apply = (source) => {
|
|
834
|
+
if (shift === 0) return source;
|
|
835
|
+
const clefMatch = source.match(/^\s*\(([^)]*)\)/);
|
|
836
|
+
const offset = clefMatch ? clefMatch[0].length : 0;
|
|
837
|
+
return source.slice(0, offset) + source.slice(offset).replace(/((?:[^()\\]|\\.)*)\(((?:[^)\\]|\\.)*)\)/g, (_, text, notes) => `${text}(${transposeNotes(notes, shift, { overflow })})`);
|
|
838
|
+
};
|
|
839
|
+
return {
|
|
840
|
+
name: "transpose",
|
|
841
|
+
apply
|
|
842
|
+
};
|
|
843
|
+
}
|
|
844
|
+
//#endregion
|
|
845
|
+
//#region src/chantMarkup.ts
|
|
846
|
+
/**
|
|
847
|
+
* The marked-up text of a chant script, for other applications: the parsed
|
|
848
|
+
* runs of the score, with what they mean and what they are for, and no
|
|
849
|
+
* style set in them. `chantRuns` gives the structured form; `chantHtml`
|
|
850
|
+
* serializes it as HTML spans a consumer styles with its own CSS
|
|
851
|
+
* (`chantTextStyle` gives a mark's look in a style set).
|
|
852
|
+
*/
|
|
853
|
+
var ALL_ROLES = [
|
|
854
|
+
"sung",
|
|
855
|
+
"label",
|
|
856
|
+
"sign",
|
|
857
|
+
"aid"
|
|
858
|
+
];
|
|
859
|
+
var chantRunOf = (run, role) => {
|
|
860
|
+
const kind = kindOf(run.marks);
|
|
861
|
+
return {
|
|
862
|
+
text: run.text,
|
|
863
|
+
...kind ? { kind } : {},
|
|
864
|
+
...run.marks.includes("initial") ? { initial: true } : {},
|
|
865
|
+
marks: run.marks,
|
|
866
|
+
role
|
|
867
|
+
};
|
|
868
|
+
};
|
|
869
|
+
var sameMarks = (a, b) => a.length === b.length && a.every((mark, i) => mark === b[i]);
|
|
870
|
+
function chantRuns(script, options = {}) {
|
|
871
|
+
const roles = options.roles ?? ALL_ROLES;
|
|
872
|
+
const words = new GuidoScript(script).words.map((word) => ({ syllables: word.syllables.filter((syl) => roles.includes(syl.role) && syl.runs.length > 0).map((syl) => ({ runs: syl.runs.map((run) => chantRunOf(run, syl.role)) })) })).filter((word) => word.syllables.length > 0);
|
|
873
|
+
if (options.merge !== "word") return words;
|
|
874
|
+
return words.flatMap((word) => {
|
|
875
|
+
const merged = [];
|
|
876
|
+
for (const run of word.syllables.flatMap((syl) => syl.runs)) {
|
|
877
|
+
const last = merged[merged.length - 1];
|
|
878
|
+
if (last && last.role === run.role && sameMarks(last.marks, run.marks)) last.text += run.text;
|
|
879
|
+
else merged.push({
|
|
880
|
+
...run,
|
|
881
|
+
wordEnd: false
|
|
882
|
+
});
|
|
883
|
+
}
|
|
884
|
+
merged[merged.length - 1].wordEnd = true;
|
|
885
|
+
return merged;
|
|
886
|
+
});
|
|
887
|
+
}
|
|
888
|
+
/** The marked-up text as an HTML string: one span per marked run, classed
|
|
889
|
+
* with its kind, `initial` and any marks of its own, bare text otherwise.
|
|
890
|
+
* Syllables of a word concatenate and words join with single spaces —
|
|
891
|
+
* hyphenation is the consumer's job, and `chantRuns` has the syllable
|
|
892
|
+
* boundaries. Text is HTML-escaped. */
|
|
893
|
+
function chantHtml(script, options = {}) {
|
|
894
|
+
const run = (r) => runHtml(r, options.classPrefix ?? "");
|
|
895
|
+
return chantRuns(script, { roles: options.roles }).map((word) => word.syllables.map((syl) => syl.runs.map(run).join("")).join("")).join(" ");
|
|
896
|
+
}
|
|
897
|
+
/** The marks the notation names through `kind` and `initial`. */
|
|
898
|
+
var NOTATION_MARKS = /* @__PURE__ */ new Set([
|
|
899
|
+
"liturgy",
|
|
900
|
+
"rubric",
|
|
901
|
+
"star",
|
|
902
|
+
"marker",
|
|
903
|
+
"plus",
|
|
904
|
+
"initial"
|
|
905
|
+
]);
|
|
906
|
+
var runHtml = (run, prefix) => {
|
|
907
|
+
const classes = [
|
|
908
|
+
...run.kind ? [run.kind] : [],
|
|
909
|
+
...run.initial ? ["initial"] : [],
|
|
910
|
+
...run.marks.filter((mark) => !NOTATION_MARKS.has(mark)).map((mark) => mark.replace(/[^\w-]/g, "-"))
|
|
911
|
+
].map((name) => prefix + name).join(" ");
|
|
912
|
+
return classes ? `<span class="${classes}">${escapeHtml(run.text)}</span>` : escapeHtml(run.text);
|
|
913
|
+
};
|
|
914
|
+
var escapeHtml = (text) => text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
915
|
+
/** The resolved look of comma-separated marks (`red,sc`), for a host styling
|
|
916
|
+
* prose to match a score. */
|
|
917
|
+
function chantTextStyle(marks, options = {}) {
|
|
918
|
+
const styleName = options.style ?? "BNS";
|
|
919
|
+
const styleSet = styleSetOf(styleName);
|
|
920
|
+
if (!styleSet) throw new Error(`Unknown style set: "${styleName}"`);
|
|
921
|
+
return resolveMarks(marks, styleSet, options.marks);
|
|
922
|
+
}
|
|
923
|
+
/** Everything `liturgy.ttf` maps. */
|
|
924
|
+
var LITURGY_GLYPHS = /* @__PURE__ */ new Set([
|
|
925
|
+
"+",
|
|
926
|
+
".",
|
|
927
|
+
"/",
|
|
928
|
+
"R",
|
|
929
|
+
"V"
|
|
930
|
+
]);
|
|
931
|
+
/** What is wrong with the script's text markup: malformed `{…}` spans,
|
|
932
|
+
* unknown marks, and characters the Liturgy font does not have, each once
|
|
933
|
+
* per syllable. */
|
|
934
|
+
function markupWarnings(script, options = {}) {
|
|
935
|
+
const parsed = typeof script === "string" ? new GuidoScript(script) : script;
|
|
936
|
+
const styleSet = styleSetOf(options.style ?? "BNS");
|
|
937
|
+
if (!styleSet) return parsed.spanProblems;
|
|
938
|
+
const warnings = [...parsed.spanProblems];
|
|
939
|
+
const unknown = /* @__PURE__ */ new Set();
|
|
940
|
+
for (const tok of parsed.tokens) {
|
|
941
|
+
if (tok.kind !== "syllable") continue;
|
|
942
|
+
for (const mark of unknownMarks([...new Set(tok.runs.flatMap((run) => run.marks))], styleSet, options.marks)) {
|
|
943
|
+
if (unknown.has(mark)) continue;
|
|
944
|
+
unknown.add(mark);
|
|
945
|
+
warnings.push({
|
|
946
|
+
kind: "mark",
|
|
947
|
+
mark,
|
|
948
|
+
text: tok.source,
|
|
949
|
+
message: `Unknown mark "${mark}" (in "${tok.source}")`
|
|
950
|
+
});
|
|
951
|
+
}
|
|
952
|
+
const drawn = resolveTextRuns(tok.runs, styleSet, false, options.marks).filter((part) => part.style.fontFamily?.includes("Liturgy") && part.kind !== "marker").flatMap((part) => [...part.text]);
|
|
953
|
+
for (const char of new Set(drawn)) {
|
|
954
|
+
if (LITURGY_GLYPHS.has(char) || /\s/.test(char)) continue;
|
|
955
|
+
warnings.push({
|
|
956
|
+
kind: "glyph",
|
|
957
|
+
char,
|
|
958
|
+
text: tok.source,
|
|
959
|
+
message: `The Liturgy font has no "${char}" (in "${tok.source}"); it has only + . / R V`
|
|
960
|
+
});
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
return warnings;
|
|
964
|
+
}
|
|
965
|
+
//#endregion
|
|
966
|
+
//#region src/guidoRender.ts
|
|
967
|
+
/**
|
|
968
|
+
* Renders a GuidoScript into a tidy score: a notes line in the chant font,
|
|
969
|
+
* and a text line where each syllable is centered below its notes.
|
|
970
|
+
*
|
|
971
|
+
* The DOM emitter of the shared layout pass (`layoutScore` in
|
|
972
|
+
* chantLayout.ts, which owns every line-breaking and placement decision):
|
|
973
|
+
* `render` turns the laid-out lines into (notes `.guido` div, text `<p>`)
|
|
974
|
+
* pairs — px-measured inline-block spacer spans fake the horizontal gaps.
|
|
975
|
+
* The Word export (wordExport.ts) consumes the same layout with a
|
|
976
|
+
* character-based spacer mechanism instead. Given several underlays of
|
|
977
|
+
* one melody (stacked stanzas, issue #84 — see `stackStanzas`), every
|
|
978
|
+
* notes line is followed by one text `<p>` per underlay.
|
|
979
|
+
*/
|
|
980
|
+
var GuidoRender = class GuidoRender {
|
|
981
|
+
script;
|
|
982
|
+
constructor(source) {
|
|
983
|
+
const parse = (s) => typeof s === "string" ? new GuidoScript(s) : s;
|
|
984
|
+
this.script = typeof source === "string" || source instanceof GuidoScript ? parse(source) : source.map(parse);
|
|
985
|
+
}
|
|
986
|
+
/**
|
|
987
|
+
* Renders the score into `container` as (notes line, text line) pairs.
|
|
988
|
+
* When `maxWidthPx` is finite, a new pair starts before any syllable
|
|
989
|
+
* whose notes would push the current notes line past it; the clef is
|
|
990
|
+
* repeated at the start of every line. Throws when the style set is
|
|
991
|
+
* unknown or one of its fonts cannot be loaded.
|
|
992
|
+
*/
|
|
993
|
+
async render(container, options = {}) {
|
|
994
|
+
const { debug = false } = options;
|
|
995
|
+
const { lines, styleSet, styleName, textPx, notesPx, bold, starWidth } = await layoutScore(this.script, options);
|
|
996
|
+
container.style.fontSize = `${textPx}px`;
|
|
997
|
+
container.style.fontFamily = styleSet.textFontStack;
|
|
998
|
+
container.dataset.style = styleName;
|
|
999
|
+
container.replaceChildren(...lines.flatMap((l) => [GuidoRender.notesLine(l, notesPx, starWidth, debug), ...l.texts.map((text) => GuidoRender.textLine(text, textPx, bold, debug))]));
|
|
1000
|
+
}
|
|
1001
|
+
/** Builds a line's notes div: the chant font text plus, on broken
|
|
1002
|
+
* lines, the break marker `*` as an inline span (so it shares the
|
|
1003
|
+
* text's baseline) shifted right so its right edge lands on the
|
|
1004
|
+
* padding-extended max-width position. position: relative keeps the
|
|
1005
|
+
* shift out of the flow measurements. */
|
|
1006
|
+
static notesLine(line, notesPx, starWidth, debug) {
|
|
1007
|
+
const notesEl = document.createElement("div");
|
|
1008
|
+
notesEl.className = "guido";
|
|
1009
|
+
notesEl.style.fontSize = `${notesPx}px`;
|
|
1010
|
+
notesEl.textContent = line.clefPrefix + line.notesParts.join("");
|
|
1011
|
+
if (line.breakMarkerLeftPx !== void 0) {
|
|
1012
|
+
const star = document.createElement("span");
|
|
1013
|
+
star.className = "guido-break";
|
|
1014
|
+
star.textContent = "*";
|
|
1015
|
+
star.style.position = "relative";
|
|
1016
|
+
star.style.left = `${line.breakMarkerLeftPx}px`;
|
|
1017
|
+
if (debug) star.title = `line break at ${(line.staffEnd + line.breakMarkerLeftPx + starWidth).toFixed(1)}px (staff filled to ${line.staffEnd.toFixed(1)}px)`;
|
|
1018
|
+
notesEl.appendChild(star);
|
|
1019
|
+
}
|
|
1020
|
+
return notesEl;
|
|
1021
|
+
}
|
|
1022
|
+
/** Builds a line's text paragraph from its segments: spacer spans fake
|
|
1023
|
+
* every horizontal gap (lead-in, word gaps, dash connector pads), each
|
|
1024
|
+
* syllable is one span of nested runs, and word spaces are their own
|
|
1025
|
+
* spans. */
|
|
1026
|
+
static textLine(line, textPx, bold, debug) {
|
|
1027
|
+
const textEl = document.createElement("p");
|
|
1028
|
+
if (bold) textEl.style.fontWeight = "700";
|
|
1029
|
+
for (const seg of line.segments) switch (seg.kind) {
|
|
1030
|
+
case "gap": {
|
|
1031
|
+
const spacerEl = GuidoRender.spacer(seg.width);
|
|
1032
|
+
if (debug) spacerEl.title = `${seg.role === "lead-in" ? "lead-in" : "word gap"} ${seg.width.toFixed(1)}px → text ${seg.textStartPx.toFixed(1)}`;
|
|
1033
|
+
textEl.appendChild(spacerEl);
|
|
1034
|
+
break;
|
|
1035
|
+
}
|
|
1036
|
+
case "connector": {
|
|
1037
|
+
const leadPad = GuidoRender.spacer(seg.pad);
|
|
1038
|
+
const dash = GuidoRender.dashSpan(seg.parts, textPx);
|
|
1039
|
+
const trailPad = GuidoRender.spacer(seg.pad);
|
|
1040
|
+
if (debug) {
|
|
1041
|
+
leadPad.title = `lead pad ${seg.pad.toFixed(1)}px (gap ${seg.gapWidth.toFixed(1)} − dash ${seg.dashWidth.toFixed(1)}, halved)`;
|
|
1042
|
+
dash.title = `dash ${seg.dashWidth.toFixed(1)}px`;
|
|
1043
|
+
trailPad.title = `trail pad ${seg.pad.toFixed(1)}px`;
|
|
1044
|
+
}
|
|
1045
|
+
textEl.append(leadPad, dash, trailPad);
|
|
1046
|
+
break;
|
|
1047
|
+
}
|
|
1048
|
+
case "syl": {
|
|
1049
|
+
const span = GuidoRender.sylSpan(seg.parts, textPx);
|
|
1050
|
+
if (debug) {
|
|
1051
|
+
if (seg.noNotes) span.title = `no notes, text w ${seg.textWidth.toFixed(1)}, ${seg.trailing ? "end of score" : "before the next syllable with notes"}`;
|
|
1052
|
+
else {
|
|
1053
|
+
const theoDiff = (seg.textWidth - seg.contentWidth) / 2;
|
|
1054
|
+
const cursDiff = seg.textStart - seg.contentStart;
|
|
1055
|
+
span.title = [
|
|
1056
|
+
`text w ${seg.textWidth.toFixed(1)}`,
|
|
1057
|
+
`notes w ${seg.contentWidth.toFixed(1)}`,
|
|
1058
|
+
seg.extraDashes ? `+${seg.extraDashes} pad dash(es)` : null,
|
|
1059
|
+
`text start ${seg.textStart.toFixed(1)}`,
|
|
1060
|
+
`notes start ${seg.contentStart.toFixed(1)}`,
|
|
1061
|
+
`theoDiff: ${theoDiff.toFixed(1)}`,
|
|
1062
|
+
`cursDiff: ${cursDiff.toFixed(1)}`
|
|
1063
|
+
].filter(Boolean).join(", ");
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
textEl.appendChild(span);
|
|
1067
|
+
break;
|
|
1068
|
+
}
|
|
1069
|
+
case "word-space": {
|
|
1070
|
+
const ws = document.createElement("span");
|
|
1071
|
+
ws.className = "word-space";
|
|
1072
|
+
ws.textContent = " ";
|
|
1073
|
+
if (debug) ws.title = `word space ${seg.width.toFixed(1)}px`;
|
|
1074
|
+
textEl.appendChild(ws);
|
|
1075
|
+
break;
|
|
1076
|
+
}
|
|
1077
|
+
case "line-end-dash": {
|
|
1078
|
+
const leadPad = GuidoRender.spacer(seg.pad);
|
|
1079
|
+
const dash = GuidoRender.dashSpan(seg.parts, textPx);
|
|
1080
|
+
const trailPad = GuidoRender.spacer(seg.pad);
|
|
1081
|
+
if (debug) {
|
|
1082
|
+
leadPad.title = `lead pad ${seg.pad.toFixed(1)}px → line-end dash (text end ${seg.textEndPx.toFixed(1)}, notes end ${seg.trailEndPx.toFixed(1)})`;
|
|
1083
|
+
dash.title = `dash ${seg.dashWidth.toFixed(1)}px (line end)`;
|
|
1084
|
+
trailPad.title = `trail pad ${seg.pad.toFixed(1)}px`;
|
|
1085
|
+
}
|
|
1086
|
+
textEl.append(leadPad, dash, trailPad);
|
|
1087
|
+
break;
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
return textEl;
|
|
1091
|
+
}
|
|
1092
|
+
/** Builds a syllable span from its resolved runs: one nested span per
|
|
1093
|
+
* run, carrying the run's inline styles and its notation-fixed kind
|
|
1094
|
+
* class (`liturgy`, `rubric`, `star`, `marker`, `plus`); runs marked
|
|
1095
|
+
* `initial` by the `*…*` marker carry the initial class. */
|
|
1096
|
+
static dashSpan(parts, textPx) {
|
|
1097
|
+
const dash = document.createElement("span");
|
|
1098
|
+
dash.className = "dash";
|
|
1099
|
+
dash.textContent = "-";
|
|
1100
|
+
const style = parts?.[0]?.style;
|
|
1101
|
+
if (style) for (const [prop, value] of Object.entries(inlineStylesFor(style, textPx))) dash.style.setProperty(prop, value);
|
|
1102
|
+
return dash;
|
|
1103
|
+
}
|
|
1104
|
+
static sylSpan(parts, textPx) {
|
|
1105
|
+
const sylSpan = document.createElement("span");
|
|
1106
|
+
sylSpan.className = "syl";
|
|
1107
|
+
parts.forEach((part) => {
|
|
1108
|
+
const partSpan = document.createElement("span");
|
|
1109
|
+
partSpan.textContent = part.text;
|
|
1110
|
+
for (const [prop, value] of Object.entries(inlineStylesFor(part.style, textPx))) partSpan.style.setProperty(prop, value);
|
|
1111
|
+
const classes = [...part.kind ? [part.kind] : [], ...part.style.initial ? ["initial"] : []].join(" ");
|
|
1112
|
+
if (classes) partSpan.className = classes;
|
|
1113
|
+
sylSpan.appendChild(partSpan);
|
|
1114
|
+
});
|
|
1115
|
+
return sylSpan;
|
|
1116
|
+
}
|
|
1117
|
+
static spacer(width) {
|
|
1118
|
+
const spacer = document.createElement("span");
|
|
1119
|
+
spacer.className = "spacer";
|
|
1120
|
+
spacer.style.display = "inline-block";
|
|
1121
|
+
spacer.style.width = `${width}px`;
|
|
1122
|
+
return spacer;
|
|
1123
|
+
}
|
|
1124
|
+
};
|
|
1125
|
+
//#endregion
|
|
1126
|
+
//#region src/embed/core.ts
|
|
1127
|
+
var version = {
|
|
1128
|
+
name: "guidex",
|
|
1129
|
+
version: "0.4.0",
|
|
1130
|
+
description: "Guidex — render plainchant scores from a compact GuidoScript notation, as a web app and an embeddable runtime",
|
|
1131
|
+
type: "module",
|
|
1132
|
+
workspaces: ["examples/*"],
|
|
1133
|
+
main: "./dist/lib/embed/manual.js",
|
|
1134
|
+
types: "./dist/lib/embed/manual.d.ts",
|
|
1135
|
+
exports: {
|
|
1136
|
+
".": {
|
|
1137
|
+
"types": "./dist/lib/embed/manual.d.ts",
|
|
1138
|
+
"default": "./dist/lib/embed/manual.js"
|
|
1139
|
+
},
|
|
1140
|
+
"./embed": {
|
|
1141
|
+
"types": "./dist/lib/embed/index.d.ts",
|
|
1142
|
+
"default": "./dist/lib/embed/index.js"
|
|
1143
|
+
},
|
|
1144
|
+
"./guidex.css": {
|
|
1145
|
+
"types": "./dist/lib/guidex.css.d.ts",
|
|
1146
|
+
"default": "./dist/lib/guidex.css"
|
|
1147
|
+
},
|
|
1148
|
+
"./fonts/*": "./dist/lib/fonts/*",
|
|
1149
|
+
"./react": {
|
|
1150
|
+
"types": "./dist/lib/react/index.d.ts",
|
|
1151
|
+
"default": "./dist/lib/react/index.js"
|
|
1152
|
+
},
|
|
1153
|
+
"./word": {
|
|
1154
|
+
"types": "./dist/lib/word/index.d.ts",
|
|
1155
|
+
"default": "./dist/lib/word/index.js"
|
|
1156
|
+
}
|
|
1157
|
+
},
|
|
1158
|
+
files: ["dist-embed", "dist/lib"],
|
|
1159
|
+
peerDependencies: { "react": ">=18" },
|
|
1160
|
+
peerDependenciesMeta: { "react": { "optional": true } },
|
|
1161
|
+
publishConfig: { "access": "public" },
|
|
1162
|
+
scripts: {
|
|
1163
|
+
"dev": "vite --host",
|
|
1164
|
+
"build": "tsc && vite build",
|
|
1165
|
+
"build:embed": "vite build --config vite.embed.config.ts",
|
|
1166
|
+
"build:lib": "vite build --config vite.lib.config.ts",
|
|
1167
|
+
"preview": "vite preview",
|
|
1168
|
+
"test": "vitest run",
|
|
1169
|
+
"lint": "eslint ."
|
|
1170
|
+
},
|
|
1171
|
+
keywords: [
|
|
1172
|
+
"plainchant",
|
|
1173
|
+
"gregorian",
|
|
1174
|
+
"guido",
|
|
1175
|
+
"score",
|
|
1176
|
+
"notation",
|
|
1177
|
+
"liturgy"
|
|
1178
|
+
],
|
|
1179
|
+
repository: {
|
|
1180
|
+
"type": "git",
|
|
1181
|
+
"url": "git+https://github.com/BrownieMaar/guidex.git"
|
|
1182
|
+
},
|
|
1183
|
+
bugs: { "url": "https://github.com/BrownieMaar/guidex/issues" },
|
|
1184
|
+
homepage: "https://github.com/BrownieMaar/guidex#readme",
|
|
1185
|
+
devDependencies: {
|
|
1186
|
+
"@eslint/js": "^10.0.1",
|
|
1187
|
+
"@testing-library/dom": "^10.4.2",
|
|
1188
|
+
"@testing-library/react": "^16.3.3",
|
|
1189
|
+
"@testing-library/user-event": "^14.6.7",
|
|
1190
|
+
"@types/react": "^19.3.0",
|
|
1191
|
+
"@types/react-dom": "^19.3.0",
|
|
1192
|
+
"@vitejs/plugin-react": "^6.1.1",
|
|
1193
|
+
"eslint": "^10.10.0",
|
|
1194
|
+
"jsdom": "^29.1.1",
|
|
1195
|
+
"react": "^19.3.0",
|
|
1196
|
+
"react-dom": "^19.3.0",
|
|
1197
|
+
"typescript": "~6.0.2",
|
|
1198
|
+
"typescript-eslint": "^8.70.0",
|
|
1199
|
+
"vite": "^8.2.2",
|
|
1200
|
+
"vite-plugin-dts": "^5.1.1",
|
|
1201
|
+
"vitest": "^4.1.11"
|
|
1202
|
+
}
|
|
1203
|
+
}.version;
|
|
1204
|
+
var DEFAULT_SELECTOR = ".guidex-script, .guido-script";
|
|
1205
|
+
var DEFAULTS = {
|
|
1206
|
+
maxWidth: "auto",
|
|
1207
|
+
style: "BNS",
|
|
1208
|
+
marks: void 0,
|
|
1209
|
+
bold: false,
|
|
1210
|
+
textPx: 18,
|
|
1211
|
+
junctionDashes: 3,
|
|
1212
|
+
staffFill: "all-but-last",
|
|
1213
|
+
staffFillSnapPx: 0,
|
|
1214
|
+
transpose: 0,
|
|
1215
|
+
stanza: 1,
|
|
1216
|
+
stack: void 0,
|
|
1217
|
+
emptySlots: "normal",
|
|
1218
|
+
stanzas: void 0,
|
|
1219
|
+
debug: false
|
|
1220
|
+
};
|
|
1221
|
+
var globalOptions = {};
|
|
1222
|
+
/** The raw script of each target, cached across re-renders: rendering
|
|
1223
|
+
* replaces the element's content, so the original text would be lost. */
|
|
1224
|
+
var sources = /* @__PURE__ */ new WeakMap();
|
|
1225
|
+
/** Per-element render race counter: a slow render (font loading) must
|
|
1226
|
+
* never overwrite a newer one's output. */
|
|
1227
|
+
var runs = /* @__PURE__ */ new WeakMap();
|
|
1228
|
+
/** The line-breaking budget each element last rendered at; resize
|
|
1229
|
+
* re-renders are skipped while the width is unchanged (height-only
|
|
1230
|
+
* ResizeObserver entries from our own renders must not loop). */
|
|
1231
|
+
var lastWidths = /* @__PURE__ */ new WeakMap();
|
|
1232
|
+
/** data-* boolean attribute: bare presence or 'true' → true, 'false' →
|
|
1233
|
+
* false, anything else → unset. */
|
|
1234
|
+
function flag(value) {
|
|
1235
|
+
if (value === void 0) return void 0;
|
|
1236
|
+
if (value === "" || value === "true") return true;
|
|
1237
|
+
if (value === "false") return false;
|
|
1238
|
+
}
|
|
1239
|
+
function number(value) {
|
|
1240
|
+
if (value === void 0) return void 0;
|
|
1241
|
+
const n = Number(value);
|
|
1242
|
+
return Number.isFinite(n) ? n : void 0;
|
|
1243
|
+
}
|
|
1244
|
+
function parseMaxWidth(value, fallback) {
|
|
1245
|
+
if (/^auto$/i.test(value.trim())) return "auto";
|
|
1246
|
+
const n = Number(value);
|
|
1247
|
+
if (n > 0) return n;
|
|
1248
|
+
console.warn(`[guidex] ignoring invalid data-max-width "${value}"`);
|
|
1249
|
+
return fallback;
|
|
1250
|
+
}
|
|
1251
|
+
/** Per-element option overrides set by `renderScore` (programmatic
|
|
1252
|
+
* callers): element data attributes win over these, these win over
|
|
1253
|
+
* `init` site-wide defaults. */
|
|
1254
|
+
var overrides = /* @__PURE__ */ new WeakMap();
|
|
1255
|
+
function emptySlotsValue(value) {
|
|
1256
|
+
if (value === void 0) return void 0;
|
|
1257
|
+
if (value === "normal" || value === "small" || value === "partial") return value;
|
|
1258
|
+
console.warn(`[guidex] ignoring invalid data-empty-slots "${value}"`);
|
|
1259
|
+
}
|
|
1260
|
+
function staffFillValue(value) {
|
|
1261
|
+
if (value === void 0) return void 0;
|
|
1262
|
+
if (value === "all-but-last" || value === "none" || value === "all" || value === "longest") return value;
|
|
1263
|
+
console.warn(`[guidex] ignoring invalid data-staff-fill "${value}"`);
|
|
1264
|
+
}
|
|
1265
|
+
/** `data-stack`: `all`, or a comma-separated list of stanza numbers. */
|
|
1266
|
+
function stackValue(value) {
|
|
1267
|
+
if (value === void 0) return void 0;
|
|
1268
|
+
if (/^\s*all\s*$/i.test(value)) return "all";
|
|
1269
|
+
const list = value.split(",").map((n) => Number(n.trim()));
|
|
1270
|
+
if (value.trim() !== "" && list.every((n) => Number.isInteger(n) && n > 0)) return list;
|
|
1271
|
+
console.warn(`[guidex] ignoring invalid data-stack "${value}"`);
|
|
1272
|
+
}
|
|
1273
|
+
/** Element data attributes (or unset) over `renderScore` overrides over
|
|
1274
|
+
* init options over defaults. */
|
|
1275
|
+
function readOptions(el) {
|
|
1276
|
+
const ds = el.dataset;
|
|
1277
|
+
const local = overrides.get(el) ?? {};
|
|
1278
|
+
const maxWidth = ds.maxWidth !== void 0 ? parseMaxWidth(ds.maxWidth, local.maxWidth ?? globalOptions.maxWidth ?? DEFAULTS.maxWidth) : local.maxWidth ?? globalOptions.maxWidth ?? DEFAULTS.maxWidth;
|
|
1279
|
+
return {
|
|
1280
|
+
marks: local.marks ?? globalOptions.marks,
|
|
1281
|
+
maxWidth,
|
|
1282
|
+
style: ds.style ?? local.style ?? globalOptions.style ?? DEFAULTS.style,
|
|
1283
|
+
bold: flag(ds.bold) ?? local.bold ?? globalOptions.bold ?? DEFAULTS.bold,
|
|
1284
|
+
textPx: number(ds.textPx) ?? local.textPx ?? globalOptions.textPx ?? DEFAULTS.textPx,
|
|
1285
|
+
junctionDashes: number(ds.junctionDashes) ?? local.junctionDashes ?? globalOptions.junctionDashes ?? DEFAULTS.junctionDashes,
|
|
1286
|
+
staffFill: staffFillValue(ds.staffFill) ?? local.staffFill ?? globalOptions.staffFill ?? DEFAULTS.staffFill,
|
|
1287
|
+
staffFillSnapPx: number(ds.staffFillSnap) ?? local.staffFillSnapPx ?? globalOptions.staffFillSnapPx ?? DEFAULTS.staffFillSnapPx,
|
|
1288
|
+
transpose: number(ds.transpose) ?? local.transpose ?? globalOptions.transpose ?? DEFAULTS.transpose,
|
|
1289
|
+
stanza: number(ds.stanza) ?? local.stanza ?? globalOptions.stanza ?? DEFAULTS.stanza,
|
|
1290
|
+
stack: stackValue(ds.stack) ?? local.stack ?? globalOptions.stack ?? DEFAULTS.stack,
|
|
1291
|
+
emptySlots: emptySlotsValue(ds.emptySlots) ?? local.emptySlots ?? globalOptions.emptySlots ?? DEFAULTS.emptySlots,
|
|
1292
|
+
stanzas: local.stanzas ?? DEFAULTS.stanzas,
|
|
1293
|
+
debug: flag(ds.debug) ?? local.debug ?? globalOptions.debug ?? DEFAULTS.debug
|
|
1294
|
+
};
|
|
1295
|
+
}
|
|
1296
|
+
/** The element's content-box width (the score wrapper spans it), the
|
|
1297
|
+
* line-box width the rendered score actually has to fit. Falls back to
|
|
1298
|
+
* the parent for inline targets; zero means no layout (hidden). */
|
|
1299
|
+
function contentWidthPx(el) {
|
|
1300
|
+
const wrapper = el.querySelector(":scope > .guidex-render");
|
|
1301
|
+
wrapper?.removeAttribute("data-fixed-width");
|
|
1302
|
+
return wrapper?.clientWidth || el.clientWidth || el.parentElement?.clientWidth || 0;
|
|
1303
|
+
}
|
|
1304
|
+
/** The line-breaking budget in pixels for this render. Fixed values pass
|
|
1305
|
+
* through; 'auto' fits the element's content box, shrunk by the style
|
|
1306
|
+
* set's break-star padding: the renderer hangs the `guido-break` star
|
|
1307
|
+
* `padding` px past the budget, and when the budget is the line-box
|
|
1308
|
+
* width itself that star would overflow the line and wrap. A zero width
|
|
1309
|
+
* (hidden element) renders unbroken; once it becomes visible the resize
|
|
1310
|
+
* listener re-renders it at the real width. */
|
|
1311
|
+
function resolveWidthPx(el, maxWidth, style) {
|
|
1312
|
+
if (typeof maxWidth === "number") return maxWidth;
|
|
1313
|
+
const width = contentWidthPx(el);
|
|
1314
|
+
if (width <= 0) return Infinity;
|
|
1315
|
+
const budget = width - (styleSetOf(style)?.padding ?? 0);
|
|
1316
|
+
return budget > 0 ? budget : width;
|
|
1317
|
+
}
|
|
1318
|
+
/** The element's script source: a fresh non-empty text node wins (so
|
|
1319
|
+
* hosts can update the source by setting textContent and calling
|
|
1320
|
+
* renderAll), otherwise the cached one from the previous render. */
|
|
1321
|
+
function extractSource(el) {
|
|
1322
|
+
for (const node of el.childNodes) if (node.nodeType === Node.TEXT_NODE && node.nodeValue?.trim()) return node.nodeValue.trim();
|
|
1323
|
+
return sources.get(el) ?? "";
|
|
1324
|
+
}
|
|
1325
|
+
/** The score wrapper inside the target; the renderer swaps the score
|
|
1326
|
+
* into it, never touching the target element's own classes or dataset. */
|
|
1327
|
+
function scoreWrapper(el) {
|
|
1328
|
+
const existing = el.querySelector(":scope > .guidex-render");
|
|
1329
|
+
if (existing) return existing;
|
|
1330
|
+
const wrapper = document.createElement("div");
|
|
1331
|
+
wrapper.className = "guidex-render";
|
|
1332
|
+
el.replaceChildren(wrapper);
|
|
1333
|
+
return wrapper;
|
|
1334
|
+
}
|
|
1335
|
+
function renderError(wrapper, message) {
|
|
1336
|
+
const note = document.createElement("p");
|
|
1337
|
+
note.className = "guidex-error";
|
|
1338
|
+
note.textContent = message;
|
|
1339
|
+
wrapper.removeAttribute("data-fixed-width");
|
|
1340
|
+
wrapper.replaceChildren(note);
|
|
1341
|
+
}
|
|
1342
|
+
/** The transforms a score renders with after the stanza swap. */
|
|
1343
|
+
function scriptTransforms(options) {
|
|
1344
|
+
return options.transpose !== 0 ? [transposeBy(options.transpose)] : [];
|
|
1345
|
+
}
|
|
1346
|
+
/** The scripts a score renders: the stacked stanzas when a stack is set
|
|
1347
|
+
* (one text line each), otherwise the one stanza — the stanza swap runs
|
|
1348
|
+
* first, so the other transforms see the stanza's text. Returns the
|
|
1349
|
+
* rendered stanzas' count mismatches with them. */
|
|
1350
|
+
function renderedScripts(source, options) {
|
|
1351
|
+
const withGlyphs = (scripts, warnings) => ({
|
|
1352
|
+
scripts,
|
|
1353
|
+
warnings: [...warnings, ...scripts.flatMap((script) => markupWarnings(script, options))]
|
|
1354
|
+
});
|
|
1355
|
+
const transforms = scriptTransforms(options);
|
|
1356
|
+
const { stanzas, emptySlots } = options;
|
|
1357
|
+
if (options.stack !== void 0) {
|
|
1358
|
+
const rendered = stackedStanzaNumbers(source, options.stack, { stanzas });
|
|
1359
|
+
return withGlyphs(stackStanzas(source, rendered, {
|
|
1360
|
+
stanzas,
|
|
1361
|
+
emptySlots,
|
|
1362
|
+
transforms
|
|
1363
|
+
}), rendered.flatMap((stanza) => stanzaWarnings(source, {
|
|
1364
|
+
stanzas,
|
|
1365
|
+
stanza
|
|
1366
|
+
})));
|
|
1367
|
+
}
|
|
1368
|
+
if (options.stanza !== 1 || emptySlots !== "normal") transforms.unshift(selectStanza(options.stanza, {
|
|
1369
|
+
stanzas,
|
|
1370
|
+
emptySlots
|
|
1371
|
+
}));
|
|
1372
|
+
return withGlyphs([new GuidoScript(source, { transforms })], stanzaWarnings(source, {
|
|
1373
|
+
stanzas,
|
|
1374
|
+
stanza: options.stanza
|
|
1375
|
+
}));
|
|
1376
|
+
}
|
|
1377
|
+
/** Builds the score into a detached scratch wrapper and swaps it into
|
|
1378
|
+
* the live one only when this run is still the latest — a stale render
|
|
1379
|
+
* that finished late leaves no footprint. A failure (a script or stanza
|
|
1380
|
+
* error, an unloadable font) replaces the score with an error note.
|
|
1381
|
+
* Resolves with the rendered stanza's warnings, also logged. */
|
|
1382
|
+
async function drawScore(el, run, source, options, widthPx) {
|
|
1383
|
+
const wrapper = scoreWrapper(el);
|
|
1384
|
+
const scratch = document.createElement("div");
|
|
1385
|
+
try {
|
|
1386
|
+
const { scripts, warnings } = renderedScripts(source, options);
|
|
1387
|
+
await new GuidoRender(scripts).render(scratch, {
|
|
1388
|
+
style: options.style,
|
|
1389
|
+
marks: options.marks,
|
|
1390
|
+
bold: options.bold,
|
|
1391
|
+
textPx: options.textPx,
|
|
1392
|
+
junctionDashes: options.junctionDashes,
|
|
1393
|
+
staffFill: options.staffFill,
|
|
1394
|
+
staffFillSnapPx: options.staffFillSnapPx,
|
|
1395
|
+
debug: options.debug,
|
|
1396
|
+
maxWidthPx: widthPx
|
|
1397
|
+
});
|
|
1398
|
+
if (runs.get(el) !== run) return { warnings };
|
|
1399
|
+
for (const warning of warnings) console.warn(`[guidex] ${warning.message}`);
|
|
1400
|
+
wrapper.replaceChildren(...scratch.childNodes);
|
|
1401
|
+
wrapper.style.cssText = scratch.style.cssText;
|
|
1402
|
+
if (scratch.dataset.style) wrapper.dataset.style = scratch.dataset.style;
|
|
1403
|
+
wrapper.toggleAttribute("data-fixed-width", typeof options.maxWidth === "number");
|
|
1404
|
+
return { warnings };
|
|
1405
|
+
} catch (e) {
|
|
1406
|
+
if (runs.get(el) !== run) return { warnings: [] };
|
|
1407
|
+
console.error("[guidex]", e);
|
|
1408
|
+
renderError(wrapper, e instanceof Error ? e.message : String(e));
|
|
1409
|
+
return { warnings: [] };
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
/** Renders one target element from its source and resolved options. */
|
|
1413
|
+
async function renderElement(el) {
|
|
1414
|
+
const run = (runs.get(el) ?? 0) + 1;
|
|
1415
|
+
runs.set(el, run);
|
|
1416
|
+
const options = readOptions(el);
|
|
1417
|
+
const source = extractSource(el);
|
|
1418
|
+
sources.set(el, source);
|
|
1419
|
+
scoreWrapper(el);
|
|
1420
|
+
const widthPx = resolveWidthPx(el, options.maxWidth, options.style);
|
|
1421
|
+
lastWidths.set(el, widthPx);
|
|
1422
|
+
await drawScore(el, run, source, options, widthPx);
|
|
1423
|
+
}
|
|
1424
|
+
/** Sets up one resize listener per target element, on first render.
|
|
1425
|
+
* Only a changed line-breaking budget (width) triggers a re-render. */
|
|
1426
|
+
var detachFns = /* @__PURE__ */ new WeakMap();
|
|
1427
|
+
function widthChanged(el) {
|
|
1428
|
+
const options = readOptions(el);
|
|
1429
|
+
const width = resolveWidthPx(el, options.maxWidth, options.style);
|
|
1430
|
+
return Math.abs(width - (lastWidths.get(el) ?? NaN)) > 1;
|
|
1431
|
+
}
|
|
1432
|
+
function attachResizeListener(el) {
|
|
1433
|
+
if (detachFns.has(el)) return;
|
|
1434
|
+
let detach;
|
|
1435
|
+
if (typeof ResizeObserver !== "undefined") {
|
|
1436
|
+
const observer = new ResizeObserver(() => {
|
|
1437
|
+
if (widthChanged(el)) renderElement(el);
|
|
1438
|
+
});
|
|
1439
|
+
observer.observe(el);
|
|
1440
|
+
detach = () => observer.disconnect();
|
|
1441
|
+
} else {
|
|
1442
|
+
const onResize = () => {
|
|
1443
|
+
if (widthChanged(el)) renderElement(el);
|
|
1444
|
+
};
|
|
1445
|
+
window.addEventListener("resize", onResize);
|
|
1446
|
+
detach = () => window.removeEventListener("resize", onResize);
|
|
1447
|
+
}
|
|
1448
|
+
detachFns.set(el, detach);
|
|
1449
|
+
}
|
|
1450
|
+
/** Cleans up a programmatically rendered element: stops resize
|
|
1451
|
+
* re-rendering and drops the cached source and option overrides. Does
|
|
1452
|
+
* not remove the rendered score itself. */
|
|
1453
|
+
function dispose(el) {
|
|
1454
|
+
detachFns.get(el)?.();
|
|
1455
|
+
detachFns.delete(el);
|
|
1456
|
+
sources.delete(el);
|
|
1457
|
+
overrides.delete(el);
|
|
1458
|
+
runs.delete(el);
|
|
1459
|
+
lastWidths.delete(el);
|
|
1460
|
+
}
|
|
1461
|
+
/** Renders a GuidoScript source string into one element
|
|
1462
|
+
* programmatically — no selector scanning, no site-wide state. The
|
|
1463
|
+
* element's own text content is replaced by the rendered score and
|
|
1464
|
+
* re-rendered on resize. Call again with a new source to update.
|
|
1465
|
+
* Options set here override `init` defaults; data attributes on the
|
|
1466
|
+
* element still win. `stanzas` replaces the script's `(@stanza …)`
|
|
1467
|
+
* statements. Resolves when the score has finished rendering, with the
|
|
1468
|
+
* rendered stanza's count mismatches. */
|
|
1469
|
+
async function renderScore(el, source, options = {}) {
|
|
1470
|
+
overrides.set(el, options);
|
|
1471
|
+
const run = (runs.get(el) ?? 0) + 1;
|
|
1472
|
+
runs.set(el, run);
|
|
1473
|
+
sources.set(el, source);
|
|
1474
|
+
const resolved = readOptions(el);
|
|
1475
|
+
scoreWrapper(el);
|
|
1476
|
+
const widthPx = resolveWidthPx(el, resolved.maxWidth, resolved.style);
|
|
1477
|
+
lastWidths.set(el, widthPx);
|
|
1478
|
+
attachResizeListener(el);
|
|
1479
|
+
return drawScore(el, run, source, resolved, widthPx);
|
|
1480
|
+
}
|
|
1481
|
+
/** Renders every target under `root` (default: the whole document).
|
|
1482
|
+
* Already-rendered targets re-render from their cached source, so a
|
|
1483
|
+
* host can change data attributes or the source text and call this to
|
|
1484
|
+
* refresh. Resolves when every score has finished rendering. */
|
|
1485
|
+
async function renderAll(root = document) {
|
|
1486
|
+
const selector = globalOptions.selector ?? DEFAULT_SELECTOR;
|
|
1487
|
+
const targets = [];
|
|
1488
|
+
if (root instanceof Element && root.matches(selector)) targets.push(root);
|
|
1489
|
+
targets.push(...root.querySelectorAll(selector));
|
|
1490
|
+
return Promise.all(targets.map((el) => {
|
|
1491
|
+
attachResizeListener(el);
|
|
1492
|
+
return renderElement(el);
|
|
1493
|
+
})).then(() => void 0);
|
|
1494
|
+
}
|
|
1495
|
+
/** Late-added elements (AJAX, SPA routing) render too: document-wide
|
|
1496
|
+
* child mutations are scanned for matching targets. Our own score
|
|
1497
|
+
* elements are skipped, so renders never re-trigger the observer. */
|
|
1498
|
+
var observerStarted = false;
|
|
1499
|
+
function startMutationObserver() {
|
|
1500
|
+
if (observerStarted || typeof MutationObserver === "undefined") return;
|
|
1501
|
+
observerStarted = true;
|
|
1502
|
+
const selector = globalOptions.selector ?? DEFAULT_SELECTOR;
|
|
1503
|
+
new MutationObserver((mutations) => {
|
|
1504
|
+
const targets = /* @__PURE__ */ new Set();
|
|
1505
|
+
for (const mutation of mutations) for (const node of mutation.addedNodes) {
|
|
1506
|
+
if (!(node instanceof Element)) continue;
|
|
1507
|
+
if (node.closest(".guidex-render")) continue;
|
|
1508
|
+
if (node.matches(selector)) targets.add(node);
|
|
1509
|
+
for (const match of node.querySelectorAll(selector)) targets.add(match);
|
|
1510
|
+
}
|
|
1511
|
+
for (const el of targets) {
|
|
1512
|
+
attachResizeListener(el);
|
|
1513
|
+
renderElement(el);
|
|
1514
|
+
}
|
|
1515
|
+
}).observe(document.documentElement, {
|
|
1516
|
+
childList: true,
|
|
1517
|
+
subtree: true
|
|
1518
|
+
});
|
|
1519
|
+
}
|
|
1520
|
+
/** Sets site-wide defaults and renders the document. Call again (even
|
|
1521
|
+
* with different options) to re-render everything with new settings. */
|
|
1522
|
+
function init(options = {}) {
|
|
1523
|
+
globalOptions = {
|
|
1524
|
+
...globalOptions,
|
|
1525
|
+
...options
|
|
1526
|
+
};
|
|
1527
|
+
startMutationObserver();
|
|
1528
|
+
renderAll();
|
|
1529
|
+
}
|
|
1530
|
+
//#endregion
|
|
1531
|
+
//#region src/scoreImage.ts
|
|
1532
|
+
/** The computed properties that draw a score line and its content:
|
|
1533
|
+
* everything load-bearing beyond the renderer's own inline styles (the
|
|
1534
|
+
* notes line's leading and padding, the theme's resolved colors, the
|
|
1535
|
+
* relative shifts) comes from this list. Box widths are deliberately
|
|
1536
|
+
* absent — a block line spans its container, not its content, and the
|
|
1537
|
+
* sized elements (the spacer spans) already carry inline widths. */
|
|
1538
|
+
var COPY_PROPS = [
|
|
1539
|
+
"font-family",
|
|
1540
|
+
"font-size",
|
|
1541
|
+
"font-style",
|
|
1542
|
+
"font-weight",
|
|
1543
|
+
"line-height",
|
|
1544
|
+
"letter-spacing",
|
|
1545
|
+
"text-transform",
|
|
1546
|
+
"color",
|
|
1547
|
+
"position",
|
|
1548
|
+
"top",
|
|
1549
|
+
"left",
|
|
1550
|
+
"margin-top",
|
|
1551
|
+
"margin-bottom",
|
|
1552
|
+
"padding-top",
|
|
1553
|
+
"padding-bottom"
|
|
1554
|
+
];
|
|
1555
|
+
/** The wrapper (the render container's stand-in) gets typography only:
|
|
1556
|
+
* no box properties, so the cloned lines stack from the crop's own
|
|
1557
|
+
* top-left corner. */
|
|
1558
|
+
var WRAPPER_PROPS = [
|
|
1559
|
+
"font-family",
|
|
1560
|
+
"font-size",
|
|
1561
|
+
"font-style",
|
|
1562
|
+
"font-weight",
|
|
1563
|
+
"line-height",
|
|
1564
|
+
"letter-spacing",
|
|
1565
|
+
"color"
|
|
1566
|
+
];
|
|
1567
|
+
/** Debug/export furniture skipped when cloning: the editor's max-width
|
|
1568
|
+
* guide and anything the host marks with `data-score-image-ignore`. The
|
|
1569
|
+
* debug syllable guides need no entry — they are ::before/::after CSS,
|
|
1570
|
+
* which never clones. */
|
|
1571
|
+
function isIgnorable(el) {
|
|
1572
|
+
return el.classList.contains("max-width-guide") || el.hasAttribute("data-score-image-ignore");
|
|
1573
|
+
}
|
|
1574
|
+
/** The element whose direct children are the rendered line pairs: the
|
|
1575
|
+
* parent of the first chant-font line under `el`. Accepts the render
|
|
1576
|
+
* container itself or any ancestor of it (the editor's outer score div,
|
|
1577
|
+
* an embed target). */
|
|
1578
|
+
function scoreRoot(el) {
|
|
1579
|
+
const root = el.querySelector(".guido")?.parentElement;
|
|
1580
|
+
if (!root) throw new Error("No rendered score found to export — render a score into the element first.");
|
|
1581
|
+
return root;
|
|
1582
|
+
}
|
|
1583
|
+
/** One line's content extent, relative to the line box's own top-left
|
|
1584
|
+
* corner: the union of its contents' rects. The line box itself is
|
|
1585
|
+
* excluded horizontally (it spans the container, not the text); the
|
|
1586
|
+
* Range covers the text nodes and each descendant element rect keeps
|
|
1587
|
+
* the position:relative shifts (raised runs, the break star). */
|
|
1588
|
+
function lineExtent(line) {
|
|
1589
|
+
const box = line.getBoundingClientRect();
|
|
1590
|
+
const parts = [];
|
|
1591
|
+
const range = document.createRange();
|
|
1592
|
+
range.selectNodeContents(line);
|
|
1593
|
+
if (typeof range.getBoundingClientRect === "function") parts.push(range.getBoundingClientRect());
|
|
1594
|
+
line.querySelectorAll("*").forEach((el) => parts.push(el.getBoundingClientRect()));
|
|
1595
|
+
if (parts.length === 0) parts.push(box);
|
|
1596
|
+
return {
|
|
1597
|
+
left: Math.min(...parts.map((r) => r.left)) - box.left,
|
|
1598
|
+
top: Math.min(...parts.map((r) => r.top)) - box.top,
|
|
1599
|
+
right: Math.max(...parts.map((r) => r.right)) - box.left,
|
|
1600
|
+
bottom: Math.max(...parts.map((r) => r.bottom)) - box.top
|
|
1601
|
+
};
|
|
1602
|
+
}
|
|
1603
|
+
/** How many visual rows a line's content occupies: the Range's client
|
|
1604
|
+
* rects cluster into rows by vertical overlap (inline boxes of
|
|
1605
|
+
* different sizes sit side by side on one row with different tops). A
|
|
1606
|
+
* line that wraps inside its host container must re-wrap at the same
|
|
1607
|
+
* width in the clone, so it is pinned to its live box width. */
|
|
1608
|
+
function countRows(line) {
|
|
1609
|
+
const range = document.createRange();
|
|
1610
|
+
range.selectNodeContents(line);
|
|
1611
|
+
if (typeof range.getClientRects !== "function") return 1;
|
|
1612
|
+
const rects = Array.from(range.getClientRects()).filter((r) => r.width > 0 || r.height > 0);
|
|
1613
|
+
if (rects.length === 0) return 1;
|
|
1614
|
+
rects.sort((a, b) => a.top - b.top);
|
|
1615
|
+
let rows = 0;
|
|
1616
|
+
let rowBottom = -Infinity;
|
|
1617
|
+
for (const r of rects) if (r.top >= rowBottom) {
|
|
1618
|
+
rows++;
|
|
1619
|
+
rowBottom = r.bottom;
|
|
1620
|
+
} else if (r.bottom > rowBottom) rowBottom = r.bottom;
|
|
1621
|
+
return rows;
|
|
1622
|
+
}
|
|
1623
|
+
/** Splits a computed font-family stack into family names, honoring
|
|
1624
|
+
* quotes around names that contain commas. */
|
|
1625
|
+
function parseFamilies(stack) {
|
|
1626
|
+
const families = [];
|
|
1627
|
+
let current = "";
|
|
1628
|
+
let quote = null;
|
|
1629
|
+
for (const ch of stack) if (quote) {
|
|
1630
|
+
if (ch === quote) quote = null;
|
|
1631
|
+
else current += ch;
|
|
1632
|
+
} else if (ch === "\"" || ch === "'") quote = ch;
|
|
1633
|
+
else if (ch === ",") {
|
|
1634
|
+
families.push(current.trim());
|
|
1635
|
+
current = "";
|
|
1636
|
+
} else current += ch;
|
|
1637
|
+
families.push(current.trim());
|
|
1638
|
+
return families.filter(Boolean);
|
|
1639
|
+
}
|
|
1640
|
+
function normalizeWeight(weight) {
|
|
1641
|
+
if (weight === "normal") return "400";
|
|
1642
|
+
if (weight === "bold") return "700";
|
|
1643
|
+
return weight;
|
|
1644
|
+
}
|
|
1645
|
+
/** Escapes a value for use inside a double-quoted XML attribute. */
|
|
1646
|
+
function escapeXmlAttribute(value) {
|
|
1647
|
+
return value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
|
|
1648
|
+
}
|
|
1649
|
+
/** Builds one face from a `src` value plus its descriptor strings,
|
|
1650
|
+
* resolving the URL against `baseHref`. Undefined when the src has no
|
|
1651
|
+
* fetchable url() (local()-only faces need no embedding). */
|
|
1652
|
+
function faceFromSrc(family, styleRaw, weightRaw, src, baseHref) {
|
|
1653
|
+
const urlMatch = /url\(\s*(['"]?)([^'")]+)\1\s*\)/.exec(src);
|
|
1654
|
+
if (!urlMatch) return void 0;
|
|
1655
|
+
let url;
|
|
1656
|
+
try {
|
|
1657
|
+
url = new URL(urlMatch[2], baseHref ?? location.href).toString();
|
|
1658
|
+
} catch {
|
|
1659
|
+
return;
|
|
1660
|
+
}
|
|
1661
|
+
return {
|
|
1662
|
+
family,
|
|
1663
|
+
style: styleRaw || "normal",
|
|
1664
|
+
weight: normalizeWeight(weightRaw || "400"),
|
|
1665
|
+
url,
|
|
1666
|
+
format: /format\(\s*['"]?([^'")]+?)['"]?\s*\)/.exec(src)?.[1]
|
|
1667
|
+
};
|
|
1668
|
+
}
|
|
1669
|
+
/** Parses @font-face blocks out of a stylesheet's raw text — the
|
|
1670
|
+
* fallback for cross-origin sheets whose `cssRules` are unreadable but
|
|
1671
|
+
* whose file a CORS fetch can still reach (the CDN-served embed build). */
|
|
1672
|
+
function parseFontFacesFromCss(cssText, baseUrl) {
|
|
1673
|
+
const faces = [];
|
|
1674
|
+
for (const match of cssText.matchAll(/@font-face\s*{([^}]*)}/g)) {
|
|
1675
|
+
const block = match[1];
|
|
1676
|
+
const pick = (prop) => {
|
|
1677
|
+
const m = new RegExp(`(?:^|[;\\s])${prop}\\s*:\\s*([^;]+)`, "i").exec(block);
|
|
1678
|
+
return m ? m[1].trim() : "";
|
|
1679
|
+
};
|
|
1680
|
+
const familyRaw = pick("font-family");
|
|
1681
|
+
const src = pick("src");
|
|
1682
|
+
if (!familyRaw || !src) continue;
|
|
1683
|
+
const family = parseFamilies(familyRaw)[0];
|
|
1684
|
+
if (!family) continue;
|
|
1685
|
+
const face = faceFromSrc(family, pick("font-style"), pick("font-weight"), src, baseUrl);
|
|
1686
|
+
if (face) faces.push(face);
|
|
1687
|
+
}
|
|
1688
|
+
return faces;
|
|
1689
|
+
}
|
|
1690
|
+
/** Collects the @font-face rules for `families` from every stylesheet.
|
|
1691
|
+
* Cross-origin sheets throw on `cssRules`; their text is fetched
|
|
1692
|
+
* instead and parsed by hand, so a CDN-served embed build's fonts still
|
|
1693
|
+
* travel with the export. Faces dedupe per family/style/weight — one
|
|
1694
|
+
* font file can legitimately serve several declarations. */
|
|
1695
|
+
async function collectFontFaces(families) {
|
|
1696
|
+
const faces = [];
|
|
1697
|
+
const seenKeys = /* @__PURE__ */ new Set();
|
|
1698
|
+
const addFace = (face) => {
|
|
1699
|
+
const key = `${face.family}|${face.style}|${face.weight}`;
|
|
1700
|
+
if (seenKeys.has(key)) return;
|
|
1701
|
+
seenKeys.add(key);
|
|
1702
|
+
faces.push(face);
|
|
1703
|
+
};
|
|
1704
|
+
const crossOriginSheets = [];
|
|
1705
|
+
for (const sheet of document.styleSheets) {
|
|
1706
|
+
let rules;
|
|
1707
|
+
try {
|
|
1708
|
+
rules = sheet.cssRules;
|
|
1709
|
+
} catch {
|
|
1710
|
+
if (sheet.href) crossOriginSheets.push(sheet.href);
|
|
1711
|
+
continue;
|
|
1712
|
+
}
|
|
1713
|
+
for (const rule of Array.from(rules)) {
|
|
1714
|
+
const style = rule.style;
|
|
1715
|
+
if (!style) continue;
|
|
1716
|
+
const src = style.getPropertyValue("src");
|
|
1717
|
+
const familyRaw = style.getPropertyValue("font-family");
|
|
1718
|
+
if (!src || !familyRaw) continue;
|
|
1719
|
+
const family = parseFamilies(familyRaw)[0];
|
|
1720
|
+
if (!family || !families.has(family)) continue;
|
|
1721
|
+
const face = faceFromSrc(family, style.getPropertyValue("font-style"), style.getPropertyValue("font-weight"), src, sheet.href ?? void 0);
|
|
1722
|
+
if (face) addFace(face);
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
for (const href of crossOriginSheets) try {
|
|
1726
|
+
const response = await fetch(href);
|
|
1727
|
+
if (!response.ok) throw new Error(String(response.status));
|
|
1728
|
+
const text = await response.text();
|
|
1729
|
+
for (const face of parseFontFacesFromCss(text, href)) if (families.has(face.family)) addFace(face);
|
|
1730
|
+
} catch {
|
|
1731
|
+
console.warn(`[guidex] scoreImage: a cross-origin stylesheet (${href}) could not be read — fonts declared only there are missing from the export`);
|
|
1732
|
+
}
|
|
1733
|
+
return faces;
|
|
1734
|
+
}
|
|
1735
|
+
async function fetchFontDataUrl(url) {
|
|
1736
|
+
const response = await fetch(url);
|
|
1737
|
+
if (!response.ok) return void 0;
|
|
1738
|
+
const blob = await response.blob();
|
|
1739
|
+
return new Promise((resolve) => {
|
|
1740
|
+
const reader = new FileReader();
|
|
1741
|
+
reader.onload = () => resolve(typeof reader.result === "string" ? reader.result : void 0);
|
|
1742
|
+
reader.onerror = () => resolve(void 0);
|
|
1743
|
+
reader.readAsDataURL(blob);
|
|
1744
|
+
});
|
|
1745
|
+
}
|
|
1746
|
+
/** Fetches and inlines faces as base64 @font-face blocks. Faces share
|
|
1747
|
+
* fetched files through a URL cache; a family's normal faces always
|
|
1748
|
+
* embed, its italic faces when the tree uses italics — or when the
|
|
1749
|
+
* family declares nothing else, since the browser would use them
|
|
1750
|
+
* anyway. A face whose file cannot be fetched is skipped with a warning
|
|
1751
|
+
* — the picture falls back to the next family in the stack, as the page
|
|
1752
|
+
* itself would. */
|
|
1753
|
+
async function embedFontFaces(faces, italics) {
|
|
1754
|
+
const blocks = [];
|
|
1755
|
+
const failed = /* @__PURE__ */ new Set();
|
|
1756
|
+
const dataUrls = /* @__PURE__ */ new Map();
|
|
1757
|
+
const fetchDataUrl = (url) => {
|
|
1758
|
+
let pending = dataUrls.get(url);
|
|
1759
|
+
if (!pending) {
|
|
1760
|
+
pending = fetchFontDataUrl(url).catch(() => void 0);
|
|
1761
|
+
dataUrls.set(url, pending);
|
|
1762
|
+
}
|
|
1763
|
+
return pending;
|
|
1764
|
+
};
|
|
1765
|
+
const byFamily = /* @__PURE__ */ new Map();
|
|
1766
|
+
for (const face of faces) {
|
|
1767
|
+
const group = byFamily.get(face.family) ?? [];
|
|
1768
|
+
group.push(face);
|
|
1769
|
+
byFamily.set(face.family, group);
|
|
1770
|
+
}
|
|
1771
|
+
for (const [family, group] of byFamily) {
|
|
1772
|
+
const normal = group.filter((f) => f.style === "normal");
|
|
1773
|
+
const keep = normal.length > 0 ? [...normal, ...italics ? group.filter((f) => f.style !== "normal") : []] : group;
|
|
1774
|
+
for (const face of keep) {
|
|
1775
|
+
const dataUrl = await fetchDataUrl(face.url);
|
|
1776
|
+
if (!dataUrl) {
|
|
1777
|
+
failed.add(family);
|
|
1778
|
+
continue;
|
|
1779
|
+
}
|
|
1780
|
+
const format = face.format ? ` format('${face.format}')` : "";
|
|
1781
|
+
blocks.push(`@font-face{font-family:'${face.family}';font-style:${face.style};font-weight:${face.weight};src:url(${dataUrl})${format}}`);
|
|
1782
|
+
}
|
|
1783
|
+
}
|
|
1784
|
+
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`);
|
|
1785
|
+
return blocks.join("");
|
|
1786
|
+
}
|
|
1787
|
+
/** Normalizes any CSS color string to the CSSOM's canonical form, so a
|
|
1788
|
+
* stylesheet's `--red: #d40000` matches a computed `rgb(212, 0, 0)`. A
|
|
1789
|
+
* fresh probe element per call: getComputedStyle declarations are
|
|
1790
|
+
* cached per element, so a reused probe would answer every later
|
|
1791
|
+
* comparison with its first value. */
|
|
1792
|
+
function colorProbe(value) {
|
|
1793
|
+
const probe = document.createElement("span");
|
|
1794
|
+
probe.style.color = value;
|
|
1795
|
+
return getComputedStyle(probe).color;
|
|
1796
|
+
}
|
|
1797
|
+
/** The style set's accent, resolved from the container's `--red` custom
|
|
1798
|
+
* property to its canonical form ('' when none is in scope). */
|
|
1799
|
+
function resolvedAccent(container) {
|
|
1800
|
+
const raw = getComputedStyle(container).getPropertyValue("--red").trim();
|
|
1801
|
+
return raw ? colorProbe(raw) : "";
|
|
1802
|
+
}
|
|
1803
|
+
/** Whether an element's ink is the accent: either its computed color
|
|
1804
|
+
* equals the resolved accent, or its inline color is the `var(--red)`
|
|
1805
|
+
* reference the style sets put on accent runs (the form a CSSOM without
|
|
1806
|
+
* custom-property resolution leaves in place). */
|
|
1807
|
+
function isAccentInk(el, computedColor, accent) {
|
|
1808
|
+
if (accent && computedColor && colorProbe(computedColor) === accent) return true;
|
|
1809
|
+
return el.style?.getPropertyValue("color").replace(/\s+/g, "") === "var(--red)";
|
|
1810
|
+
}
|
|
1811
|
+
/** Copies the computed properties from each original onto its clone and
|
|
1812
|
+
* reports which webfont families / styles the tree uses, so only those
|
|
1813
|
+
* faces are embedded. Runs after the clone, so literal computed values
|
|
1814
|
+
* overwrite the clone's inherited `var()` references — that is what
|
|
1815
|
+
* bakes the current theme into the picture. The `foreground`/`accent`
|
|
1816
|
+
* overrides remap that ink: accent-classified elements take the accent
|
|
1817
|
+
* color, everything else the foreground. */
|
|
1818
|
+
function copyComputedStyles(originals, clones, overrides) {
|
|
1819
|
+
const families = /* @__PURE__ */ new Set();
|
|
1820
|
+
let italics = false;
|
|
1821
|
+
for (let i = 0; i < originals.length; i++) {
|
|
1822
|
+
const original = originals[i];
|
|
1823
|
+
const clone = clones[i];
|
|
1824
|
+
const computed = getComputedStyle(original);
|
|
1825
|
+
for (const prop of i === 0 ? WRAPPER_PROPS : COPY_PROPS) {
|
|
1826
|
+
if (prop === "color") {
|
|
1827
|
+
const computedColor = computed.getPropertyValue("color");
|
|
1828
|
+
if (!computedColor) continue;
|
|
1829
|
+
const override = isAccentInk(original, computedColor, overrides.accentProbe) ? overrides.accent : overrides.foreground;
|
|
1830
|
+
clone.style.setProperty("color", override || computedColor);
|
|
1831
|
+
continue;
|
|
1832
|
+
}
|
|
1833
|
+
const value = computed.getPropertyValue(prop);
|
|
1834
|
+
if (value) clone.style.setProperty(prop, value);
|
|
1835
|
+
}
|
|
1836
|
+
const family = computed.getPropertyValue("font-family");
|
|
1837
|
+
if (family) for (const f of parseFamilies(family)) families.add(f);
|
|
1838
|
+
if (computed.getPropertyValue("font-style") === "italic") italics = true;
|
|
1839
|
+
}
|
|
1840
|
+
return {
|
|
1841
|
+
families,
|
|
1842
|
+
italics
|
|
1843
|
+
};
|
|
1844
|
+
}
|
|
1845
|
+
async function fontsReady() {
|
|
1846
|
+
const fonts = document.fonts;
|
|
1847
|
+
if (fonts?.ready) await fonts.ready;
|
|
1848
|
+
}
|
|
1849
|
+
/** The whole capture: crop measurement, styled clone, embedded fonts,
|
|
1850
|
+
* and the assembled SVG string with its outer pixel size. */
|
|
1851
|
+
async function serializeScore(el, options) {
|
|
1852
|
+
const padding = Math.max(0, options.padding ?? 0);
|
|
1853
|
+
const root = scoreRoot(el);
|
|
1854
|
+
if (!root.isConnected) throw new Error("scoreImage: the score left the document before the export — re-render it and try again");
|
|
1855
|
+
await fontsReady();
|
|
1856
|
+
const lines = Array.from(root.children).filter((child) => child.classList.contains("guido") || child.tagName === "P");
|
|
1857
|
+
if (lines.length === 0) throw new Error("No rendered score found to export — render a score into the element first.");
|
|
1858
|
+
const lineRects = lines.map((line) => line.getBoundingClientRect());
|
|
1859
|
+
const base = lineRects[0];
|
|
1860
|
+
const stacked = lines.map((line, i) => {
|
|
1861
|
+
const extent = lineExtent(line);
|
|
1862
|
+
const rect = lineRects[i];
|
|
1863
|
+
const offsetLeft = rect.left - base.left;
|
|
1864
|
+
const wraps = countRows(line) > 1;
|
|
1865
|
+
return {
|
|
1866
|
+
left: extent.left + offsetLeft,
|
|
1867
|
+
top: extent.top + (rect.top - base.top),
|
|
1868
|
+
right: (wraps ? Math.max(rect.width, extent.right) : extent.right) + offsetLeft,
|
|
1869
|
+
bottom: extent.bottom + (rect.top - base.top),
|
|
1870
|
+
pinWidth: wraps ? rect.width : void 0
|
|
1871
|
+
};
|
|
1872
|
+
});
|
|
1873
|
+
const cropLeft = Math.min(0, ...stacked.map((e) => e.left));
|
|
1874
|
+
const cropTop = Math.min(0, ...stacked.map((e) => e.top));
|
|
1875
|
+
const contentRight = Math.max(...stacked.map((e) => e.right));
|
|
1876
|
+
const contentBottom = Math.max(...stacked.map((e) => e.bottom));
|
|
1877
|
+
const width = Math.max(1, Math.ceil(contentRight - cropLeft)) + padding * 2;
|
|
1878
|
+
const height = Math.max(1, Math.ceil(contentBottom - cropTop)) + padding * 2;
|
|
1879
|
+
const clone = root.cloneNode(true);
|
|
1880
|
+
clone.querySelectorAll(".max-width-guide, [data-score-image-ignore]").forEach((el) => el.remove());
|
|
1881
|
+
const originals = [root];
|
|
1882
|
+
const clones = [clone];
|
|
1883
|
+
const walk = (el, into) => {
|
|
1884
|
+
for (const child of el.children) {
|
|
1885
|
+
if (isIgnorable(child)) continue;
|
|
1886
|
+
into.push(child);
|
|
1887
|
+
walk(child, into);
|
|
1888
|
+
}
|
|
1889
|
+
};
|
|
1890
|
+
walk(root, originals);
|
|
1891
|
+
walk(clone, clones);
|
|
1892
|
+
if (clones.length !== originals.length) throw new Error("scoreImage: the cloned tree diverged from the live one");
|
|
1893
|
+
for (const el of [clone, ...clone.querySelectorAll("*")]) el.removeAttribute("title");
|
|
1894
|
+
const { families, italics } = copyComputedStyles(originals, clones, {
|
|
1895
|
+
foreground: options.foreground,
|
|
1896
|
+
accent: options.accent,
|
|
1897
|
+
accentProbe: resolvedAccent(root)
|
|
1898
|
+
});
|
|
1899
|
+
clone.style.setProperty("white-space", "nowrap");
|
|
1900
|
+
const cloneLines = Array.from(clone.children).filter((child) => child.classList.contains("guido") || child.tagName === "P");
|
|
1901
|
+
stacked.forEach((entry, i) => {
|
|
1902
|
+
const cloneLine = cloneLines[i];
|
|
1903
|
+
if (entry.pinWidth !== void 0 && cloneLine) cloneLine.style.setProperty("width", `${entry.pinWidth}px`);
|
|
1904
|
+
});
|
|
1905
|
+
clone.style.setProperty("padding-top", `${padding - cropTop}px`);
|
|
1906
|
+
clone.style.setProperty("padding-left", `${padding - cropLeft}px`);
|
|
1907
|
+
clone.style.setProperty("padding-right", `${padding}px`);
|
|
1908
|
+
clone.style.setProperty("padding-bottom", `${padding}px`);
|
|
1909
|
+
const faceCss = await embedFontFaces(await collectFontFaces(families), italics);
|
|
1910
|
+
const wrapper = new XMLSerializer().serializeToString(clone);
|
|
1911
|
+
const bgRect = options.background ? `<rect width="100%" height="100%" fill="${escapeXmlAttribute(options.background)}"/>` : "";
|
|
1912
|
+
return {
|
|
1913
|
+
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>",
|
|
1914
|
+
width,
|
|
1915
|
+
height
|
|
1916
|
+
};
|
|
1917
|
+
}
|
|
1918
|
+
/** Serializes the rendered score under `el` into a self-contained SVG
|
|
1919
|
+
* string (fonts embedded, colors resolved) sized to the score's content.
|
|
1920
|
+
* Throws when no score was rendered into the element. */
|
|
1921
|
+
async function scoreSvg(el, options = {}) {
|
|
1922
|
+
return (await serializeScore(el, options)).svg;
|
|
1923
|
+
}
|
|
1924
|
+
/** Rasterizes the rendered score under `el` to a PNG blob: the
|
|
1925
|
+
* self-contained SVG loads as an image (the browser's own renderer
|
|
1926
|
+
* paints it, so the picture matches the DOM exactly) and draws onto a
|
|
1927
|
+
* canvas at `scale`×. Throws when no score was rendered into the
|
|
1928
|
+
* element or the environment has no 2D canvas. */
|
|
1929
|
+
async function scorePngBlob(el, options = {}) {
|
|
1930
|
+
const { svg, width, height } = await serializeScore(el, options);
|
|
1931
|
+
const scale = Math.max(1, options.scale ?? 2);
|
|
1932
|
+
const image = new Image();
|
|
1933
|
+
image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
|
|
1934
|
+
await new Promise((resolve, reject) => {
|
|
1935
|
+
image.onload = () => resolve();
|
|
1936
|
+
image.onerror = () => reject(/* @__PURE__ */ new Error("scoreImage: the exported SVG failed to rasterize"));
|
|
1937
|
+
});
|
|
1938
|
+
try {
|
|
1939
|
+
await image.decode();
|
|
1940
|
+
} catch {}
|
|
1941
|
+
const canvas = document.createElement("canvas");
|
|
1942
|
+
canvas.width = Math.ceil(width * scale);
|
|
1943
|
+
canvas.height = Math.ceil(height * scale);
|
|
1944
|
+
const ctx = canvas.getContext("2d");
|
|
1945
|
+
if (!ctx) throw new Error("scoreImage: this environment provides no 2D canvas");
|
|
1946
|
+
ctx.scale(scale, scale);
|
|
1947
|
+
if (options.background) {
|
|
1948
|
+
ctx.fillStyle = options.background;
|
|
1949
|
+
ctx.fillRect(0, 0, width, height);
|
|
1950
|
+
}
|
|
1951
|
+
const draw = () => ctx.drawImage(image, 0, 0, width, height);
|
|
1952
|
+
draw();
|
|
1953
|
+
if (/^((?!chrome|android|crios|fxios).)*safari/i.test(navigator.userAgent)) {
|
|
1954
|
+
await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
|
1955
|
+
draw();
|
|
1956
|
+
}
|
|
1957
|
+
const blob = await new Promise((resolve) => canvas.toBlob(resolve, "image/png"));
|
|
1958
|
+
if (!blob) throw new Error("scoreImage: PNG encoding failed");
|
|
1959
|
+
return blob;
|
|
1960
|
+
}
|
|
1961
|
+
function downloadBlob(blob, filename) {
|
|
1962
|
+
const url = URL.createObjectURL(blob);
|
|
1963
|
+
const anchor = document.createElement("a");
|
|
1964
|
+
anchor.href = url;
|
|
1965
|
+
anchor.download = filename;
|
|
1966
|
+
anchor.click();
|
|
1967
|
+
setTimeout(() => URL.revokeObjectURL(url), 1e4);
|
|
1968
|
+
}
|
|
1969
|
+
/** Exports the rendered score under `el` as a PNG download. Resolves
|
|
1970
|
+
* with the filename used. */
|
|
1971
|
+
async function downloadScorePng(el, options = {}) {
|
|
1972
|
+
const filename = options.filename ?? "score.png";
|
|
1973
|
+
downloadBlob(await scorePngBlob(el, options), filename);
|
|
1974
|
+
return filename;
|
|
1975
|
+
}
|
|
1976
|
+
/** Exports the rendered score under `el` as a self-contained SVG
|
|
1977
|
+
* download (fonts embedded — the print-friendlier artifact). Resolves
|
|
1978
|
+
* with the filename used. */
|
|
1979
|
+
async function downloadScoreSvg(el, options = {}) {
|
|
1980
|
+
const filename = options.filename ?? "score.svg";
|
|
1981
|
+
downloadBlob(new Blob([await scoreSvg(el, options)], { type: "image/svg+xml;charset=utf-8" }), filename);
|
|
1982
|
+
return filename;
|
|
1983
|
+
}
|
|
1984
|
+
//#endregion
|
|
1985
|
+
export { stackStanzas as A, STANZA_PLACEHOLDER as C, selectStanza as D, parseStanza as E, withStanza as F, stanzaCount as M, stanzaTexts as N, slotCount as O, stanzaWarnings as P, transposeScript as S, padStanza as T, KEY_SIGNATURES as _, dispose as a, sameKeyGlyphs as b, renderScore as c, chantRuns as d, chantTextStyle as f, transposeNotes as g, transposeBy as h, scoreSvg as i, stackedStanzaNumbers as j, smallHeads as k, version as l, PITCH_ROWS as m, downloadScoreSvg as n, init as o, markupWarnings as p, scorePngBlob as r, renderAll as s, downloadScorePng as t, chantHtml as u, TranspositionRangeError as v, isSlot as w, transposeExact as x, parseInterval as y };
|