guidex 0.2.6 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +219 -0
- package/dist/lib/app/ControlsRow.d.ts +1 -0
- package/dist/lib/app/Editor.d.ts +1 -0
- package/dist/lib/app/EditorContext.d.ts +17 -0
- package/dist/lib/app/EditorTextarea.d.ts +1 -0
- package/dist/lib/app/ExportSettings.d.ts +1 -0
- package/dist/lib/app/FeedbackSpan.d.ts +5 -0
- package/dist/lib/app/RenderSettings.d.ts +1 -0
- package/dist/lib/app/SamplesRow.d.ts +1 -0
- package/dist/lib/app/SettingsMenu.d.ts +1 -0
- package/dist/lib/app/SettingsPanel.d.ts +1 -0
- package/dist/lib/app/SyllablesTable.d.ts +1 -0
- package/dist/lib/app/WordCheckPanel.d.ts +1 -0
- package/dist/lib/app/WordCopyControls.d.ts +1 -0
- package/dist/lib/app/chantLibrary.d.ts +11 -0
- package/dist/lib/app/editorState.d.ts +159 -0
- package/dist/lib/app/samples.d.ts +10 -0
- package/dist/lib/app/wordCopy.d.ts +30 -0
- package/dist/lib/chantLayout-GAfg2iKS.js +1042 -0
- package/dist/lib/chantLayout.d.ts +169 -0
- package/dist/lib/chantMarkup.d.ts +36 -0
- package/dist/lib/editorStorage.d.ts +179 -0
- package/dist/lib/embed/index.d.ts +1 -0
- package/dist/lib/embed/index.js +2 -2
- package/dist/lib/embed/manual.d.ts +15 -4
- package/dist/lib/embed/manual.js +43 -2
- package/dist/lib/guidoRender.d.ts +22 -29
- package/dist/lib/guidoScript.d.ts +28 -3
- package/dist/lib/guidoScriptTransforms.d.ts +5 -4
- package/dist/lib/guidoStyles.d.ts +23 -5
- package/dist/lib/main.d.ts +0 -1
- package/dist/lib/react/index.d.ts +1 -0
- package/dist/lib/react/index.js +2 -2
- package/dist/lib/scoreImage-DnFIbtF_.js +951 -0
- package/dist/lib/scoreImage.d.ts +63 -0
- package/dist/lib/word/index.d.ts +17 -0
- package/dist/lib/word/index.js +2 -0
- package/dist/lib/wordChecker-C3nJrk_j.js +1042 -0
- package/dist/lib/wordChecker.d.ts +66 -0
- package/dist/lib/wordClipboard.d.ts +25 -0
- package/dist/lib/wordExport.d.ts +244 -0
- package/dist-embed/guidex-embed.min.js +1 -1
- package/package.json +8 -1
- package/dist/lib/core-hF6L1EtS.js +0 -1268
- package/dist/lib/settingsMenu.d.ts +0 -1
|
@@ -1,1268 +0,0 @@
|
|
|
1
|
-
//#region src/guidoScript.ts
|
|
2
|
-
var GuidoScript = class {
|
|
3
|
-
source;
|
|
4
|
-
constructor(source, options = {}) {
|
|
5
|
-
this.source = (options.transforms ?? []).reduce((script, transform) => transform.apply(script), source);
|
|
6
|
-
}
|
|
7
|
-
/** The starting clef and note modifiers, or undefined when absent. */
|
|
8
|
-
get clef() {
|
|
9
|
-
return this.normalized.match(/^\s*\(([^)]*)\)/)?.[1];
|
|
10
|
-
}
|
|
11
|
-
/** The script broken into syllables, each with its sung text and notes. */
|
|
12
|
-
get syllables() {
|
|
13
|
-
const matches = [...this.normalized.replace(/^\s*\([^)]*\)/, "").matchAll(/((?:[^()\\]|\\.)*)\(((?:[^)\\]|\\.)*)\)/g)];
|
|
14
|
-
return matches.map(([, text, notes], i) => ({
|
|
15
|
-
text: unescape(text.trim()),
|
|
16
|
-
notes: unescape(notes),
|
|
17
|
-
wordEnd: i === matches.length - 1 || /^\s/.test(matches[i + 1][1])
|
|
18
|
-
}));
|
|
19
|
-
}
|
|
20
|
-
/**
|
|
21
|
-
* The source with the typing conveniences folded in, so the parser
|
|
22
|
-
* itself only ever sees complete scripts:
|
|
23
|
-
*
|
|
24
|
-
* - an unclosed parenthesis is closed at the end, so the notes typed
|
|
25
|
-
* so far already preview on the score;
|
|
26
|
-
* - a trailing syllable with no note group gets an empty one, so it
|
|
27
|
-
* renders like a `*()` syllable (text without notes width).
|
|
28
|
-
*/
|
|
29
|
-
get normalized() {
|
|
30
|
-
let script = this.source;
|
|
31
|
-
if ((script.match(/(^|[^\\])\(/g) ?? []).length > (script.match(/(^|[^\\])\)/g) ?? []).length) script += ")";
|
|
32
|
-
if (!/(^|[^\\])\)$/.test(script)) script += "()";
|
|
33
|
-
return script;
|
|
34
|
-
}
|
|
35
|
-
/** The syllables grouped into the words of the text. */
|
|
36
|
-
get words() {
|
|
37
|
-
const words = [];
|
|
38
|
-
let word;
|
|
39
|
-
for (const syl of this.syllables) {
|
|
40
|
-
word ??= {
|
|
41
|
-
text: "",
|
|
42
|
-
syllables: []
|
|
43
|
-
};
|
|
44
|
-
word.syllables.push({
|
|
45
|
-
text: syl.text,
|
|
46
|
-
notes: syl.notes
|
|
47
|
-
});
|
|
48
|
-
word.text = word.syllables.map((s) => s.text).join("");
|
|
49
|
-
if (syl.wordEnd) {
|
|
50
|
-
words.push(word);
|
|
51
|
-
word = void 0;
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
return words;
|
|
55
|
-
}
|
|
56
|
-
/** The script rebuilt from the parsed pieces — a round-trip of the source. */
|
|
57
|
-
toString() {
|
|
58
|
-
const parts = this.syllables.map((s, i) => `${i > 0 && this.syllables[i - 1].wordEnd ? " " : ""}${escape(s.text)}(${escape(s.notes)})`);
|
|
59
|
-
return `${this.clef !== void 0 ? `(${this.clef})` : ""}${parts.join("")}`;
|
|
60
|
-
}
|
|
61
|
-
};
|
|
62
|
-
/** The sung text of the script: the clef stripped, syllables joined
|
|
63
|
-
* into words, and the words joined with single spaces. */
|
|
64
|
-
function chantText(script) {
|
|
65
|
-
return new GuidoScript(script).words.map((word) => word.text).join(" ");
|
|
66
|
-
}
|
|
67
|
-
/** Folds backslash escapes into the characters they stand for. Shared
|
|
68
|
-
* with the transforms module (guidoScriptTransforms.ts). */
|
|
69
|
-
function unescape(text) {
|
|
70
|
-
return text.replace(/\\(.)/g, "$1");
|
|
71
|
-
}
|
|
72
|
-
/** Turns literal parentheses and backslashes into their escape sequences. */
|
|
73
|
-
function escape(text) {
|
|
74
|
-
return text.replace(/\\/g, "\\\\").replace(/[()]/g, (ch) => `\\${ch}`);
|
|
75
|
-
}
|
|
76
|
-
//#endregion
|
|
77
|
-
//#region src/guidoScriptTransforms.ts
|
|
78
|
-
/**
|
|
79
|
-
* Source-level transformations for GuidoScript: named rewrites applied
|
|
80
|
-
* to a script's raw source before parsing (see the `transforms` option
|
|
81
|
-
* on the GuidoScript constructor). Each one receives the source and
|
|
82
|
-
* returns the rewritten source — or the source unchanged when the
|
|
83
|
-
* feature does not apply. They compose in registration order, and the
|
|
84
|
-
* parsed script never sees which ones ran. New script-level features
|
|
85
|
-
* are added here, and only here: as entries of SCRIPT_TRANSFORMS, or —
|
|
86
|
-
* when the feature takes parameters — as factories returning a
|
|
87
|
-
* ScriptTransform (see `transposeBy`).
|
|
88
|
-
*/
|
|
89
|
-
/** The first character unit of a text run: a backslash escape pair or a
|
|
90
|
-
* single character, skipping leading whitespace. Returns null when the
|
|
91
|
-
* run has no characters to mark. */
|
|
92
|
-
function firstCharUnit(text) {
|
|
93
|
-
const chars = [...text];
|
|
94
|
-
for (let i = 0; i < chars.length; i++) {
|
|
95
|
-
const ch = chars[i];
|
|
96
|
-
if (/\s/.test(ch)) continue;
|
|
97
|
-
return {
|
|
98
|
-
unit: ch === "\\" && chars[i + 1] !== void 0 ? ch + chars[i + 1] : ch,
|
|
99
|
-
index: i
|
|
100
|
-
};
|
|
101
|
-
}
|
|
102
|
-
return null;
|
|
103
|
-
}
|
|
104
|
-
/** The `startWithInitial` transform: finds the first syllable group with
|
|
105
|
-
* actual notes (the clef and no-notes groups don't count) and wraps the
|
|
106
|
-
* syllable's first character in the `*…*` initial marker. Already-marked
|
|
107
|
-
* text (leading `*`) and syllables without text are left alone. */
|
|
108
|
-
function startWithInitial(source) {
|
|
109
|
-
const clefMatch = source.match(/^\s*\(([^)]*)\)/);
|
|
110
|
-
const offset = clefMatch ? clefMatch[0].length : 0;
|
|
111
|
-
const rest = source.slice(offset);
|
|
112
|
-
for (const match of rest.matchAll(/((?:[^()\\]|\\.)*)\(((?:[^)\\]|\\.)*)\)/g)) {
|
|
113
|
-
const [, text, notes] = match;
|
|
114
|
-
if (unescape(notes).trim().length === 0) continue;
|
|
115
|
-
const unit = firstCharUnit(text);
|
|
116
|
-
if (!unit || text.trimStart().startsWith("*")) return source;
|
|
117
|
-
const unitStart = offset + match.index + unit.index;
|
|
118
|
-
const unitEnd = unitStart + unit.unit.length;
|
|
119
|
-
return `${source.slice(0, unitStart)}*${source.slice(unitStart, unitEnd)}*${source.slice(unitEnd)}`;
|
|
120
|
-
}
|
|
121
|
-
return source;
|
|
122
|
-
}
|
|
123
|
-
/**
|
|
124
|
-
* The built-in transformations, keyed by name; pass the ones a feature
|
|
125
|
-
* needs to the GuidoScript constructor.
|
|
126
|
-
*/
|
|
127
|
-
var SCRIPT_TRANSFORMS = {
|
|
128
|
-
/** Wraps the first letter of the first syllable that has notes in
|
|
129
|
-
* `*…*`, the initial marker of the style marking system. */
|
|
130
|
-
startWithInitial: {
|
|
131
|
-
name: "startWithInitial",
|
|
132
|
-
apply: startWithInitial
|
|
133
|
-
} };
|
|
134
|
-
/** The pitch rows of the chant font: every character carrying pitch
|
|
135
|
-
* information, grouped into rows of neighbouring pitches from low to
|
|
136
|
-
* high. A transpose shift moves a character this many positions along
|
|
137
|
-
* its row; characters outside every row carry no pitch and stay put.
|
|
138
|
-
* Rows are searched in order, so a character found in several rows
|
|
139
|
-
* transposes within the first one. */
|
|
140
|
-
var PITCH_ROWS = [
|
|
141
|
-
"ðñ0123456789öüó",
|
|
142
|
-
"^]qwertzuiopõú",
|
|
143
|
-
"ÝÞQWERTZUIOPÕÚ",
|
|
144
|
-
"×sdfghjkléáû",
|
|
145
|
-
"ØÙDFGHJKLÉÁÛ",
|
|
146
|
-
"÷øaASÍYXCVBN$m",
|
|
147
|
-
"ÈÊËÌÎÏÐÑÒþ¬ßòôùý",
|
|
148
|
-
"“”•–—˜™š›œº»",
|
|
149
|
-
"®−§ÿ\"+!%/=()ÖÜÓ",
|
|
150
|
-
"Ÿ¡¢£[¥¦©ª«¬",
|
|
151
|
-
"~¯‚ƒ„…†‡ˆ‰Š‹Œ‘’",
|
|
152
|
-
"àâãäåæçèêëìîï",
|
|
153
|
-
"½°±²³´μ·¾¸¹"
|
|
154
|
-
];
|
|
155
|
-
/** Maps one character to its pitch-shifted neighbour, or undefined when
|
|
156
|
-
* it is not a pitch character (and so stays unchanged). */
|
|
157
|
-
function shiftPitch(ch, shift, overflow) {
|
|
158
|
-
for (const row of PITCH_ROWS) {
|
|
159
|
-
const index = row.indexOf(ch);
|
|
160
|
-
if (index === -1) continue;
|
|
161
|
-
const target = index + shift;
|
|
162
|
-
if (target < 0 || target >= row.length) {
|
|
163
|
-
if (overflow === "null") return "\0";
|
|
164
|
-
return row[Math.max(0, Math.min(row.length - 1, target))];
|
|
165
|
-
}
|
|
166
|
-
return row[target];
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
/** Transposes the pitch characters of one notes group's content. Escape
|
|
170
|
-
* pairs stand for their underlying character (an escaped paren is the
|
|
171
|
-
* pitch glyph of row 6), and a shifted result that is a control
|
|
172
|
-
* character of the group syntax is written escaped. */
|
|
173
|
-
function transposeNotes(notes, shift, overflow) {
|
|
174
|
-
let out = "";
|
|
175
|
-
for (let i = 0; i < notes.length; i++) {
|
|
176
|
-
const ch = notes[i];
|
|
177
|
-
const escaped = ch === "\\" && notes[i + 1] !== void 0;
|
|
178
|
-
const shifted = shiftPitch(escaped ? notes[i + 1] : ch, shift, overflow);
|
|
179
|
-
if (shifted === void 0) {
|
|
180
|
-
out += escaped ? ch + notes[i + 1] : ch;
|
|
181
|
-
if (escaped) i++;
|
|
182
|
-
continue;
|
|
183
|
-
}
|
|
184
|
-
out += "\\()".includes(shifted) ? `\\${shifted}` : shifted;
|
|
185
|
-
if (escaped) i++;
|
|
186
|
-
}
|
|
187
|
-
return out;
|
|
188
|
-
}
|
|
189
|
-
/** The `transposeBy` transform factory: shifts every pitch character of
|
|
190
|
-
* every notes group `shift` positions along its pitch row. The clef
|
|
191
|
-
* group and the syllable text are left alone — clef handling is a
|
|
192
|
-
* separate, future tool. */
|
|
193
|
-
function transposeBy(shift, options = {}) {
|
|
194
|
-
const overflow = options.overflow ?? "clamp";
|
|
195
|
-
const apply = (source) => {
|
|
196
|
-
if (shift === 0) return source;
|
|
197
|
-
const clefMatch = source.match(/^\s*\(([^)]*)\)/);
|
|
198
|
-
const offset = clefMatch ? clefMatch[0].length : 0;
|
|
199
|
-
return source.slice(0, offset) + source.slice(offset).replace(/((?:[^()\\]|\\.)*)\(((?:[^)\\]|\\.)*)\)/g, (_, text, notes) => `${text}(${transposeNotes(notes, shift, overflow)})`);
|
|
200
|
-
};
|
|
201
|
-
return {
|
|
202
|
-
name: "transpose",
|
|
203
|
-
apply
|
|
204
|
-
};
|
|
205
|
-
}
|
|
206
|
-
//#endregion
|
|
207
|
-
//#region src/guidoStyles.ts
|
|
208
|
-
/**
|
|
209
|
-
* Style sets for the renderer: named appearance rules (fonts, colors, and
|
|
210
|
-
* the special syllable decorations) kept in one constant registry, so a
|
|
211
|
-
* new style is a data entry here rather than a renderer fork.
|
|
212
|
-
*/
|
|
213
|
-
/** Text characters (* and †) rendered in Times New Roman. */
|
|
214
|
-
var TIMES_MARKER_GLYPHS = {
|
|
215
|
-
chars: /* @__PURE__ */ new Set(["*", "†"]),
|
|
216
|
-
fontFamily: "'Times New Roman', Times, serif"
|
|
217
|
-
};
|
|
218
|
-
/** How a `+` inside a Liturgy-font run is drawn: normal weight (the font
|
|
219
|
-
* is bold-looking by design), sized to 70% and raised 20% of the text
|
|
220
|
-
* size so it sits like a connecting sign between syllable parts. */
|
|
221
|
-
var LITURGY_PLUS_STYLE = {
|
|
222
|
-
weight: "400",
|
|
223
|
-
scale: .7,
|
|
224
|
-
raise: .2
|
|
225
|
-
};
|
|
226
|
-
var STYLE_SETS = {
|
|
227
|
-
/** Book Antiqua text with red accents. */
|
|
228
|
-
BNS: {
|
|
229
|
-
textFontStack: "'Book Antiqua', Georgia, serif",
|
|
230
|
-
notesFontStack: "'Guidohu'",
|
|
231
|
-
markerGlyphs: TIMES_MARKER_GLYPHS,
|
|
232
|
-
verifiedFonts: [
|
|
233
|
-
{
|
|
234
|
-
family: "'Book Antiqua'",
|
|
235
|
-
weight: "400"
|
|
236
|
-
},
|
|
237
|
-
{
|
|
238
|
-
family: "'Book Antiqua'",
|
|
239
|
-
weight: "700"
|
|
240
|
-
},
|
|
241
|
-
{
|
|
242
|
-
family: "'Guidohu'",
|
|
243
|
-
weight: "400"
|
|
244
|
-
},
|
|
245
|
-
{
|
|
246
|
-
family: "'Liturgy'",
|
|
247
|
-
weight: "700"
|
|
248
|
-
}
|
|
249
|
-
],
|
|
250
|
-
decorations: {
|
|
251
|
-
__: {
|
|
252
|
-
fontFamily: "'Liturgy', serif",
|
|
253
|
-
weight: "700",
|
|
254
|
-
color: "var(--red)"
|
|
255
|
-
},
|
|
256
|
-
_: {
|
|
257
|
-
uppercase: true,
|
|
258
|
-
scale: .7,
|
|
259
|
-
color: "var(--red)"
|
|
260
|
-
},
|
|
261
|
-
"*": {
|
|
262
|
-
weight: "700",
|
|
263
|
-
color: "var(--red)",
|
|
264
|
-
initial: true
|
|
265
|
-
}
|
|
266
|
-
},
|
|
267
|
-
specialStarStyle: {
|
|
268
|
-
fontFamily: TIMES_MARKER_GLYPHS.fontFamily,
|
|
269
|
-
weight: "700",
|
|
270
|
-
scale: 1,
|
|
271
|
-
measureScale: .95,
|
|
272
|
-
raise: .1,
|
|
273
|
-
color: "var(--red)"
|
|
274
|
-
},
|
|
275
|
-
padding: 12,
|
|
276
|
-
scriptTransforms: [SCRIPT_TRANSFORMS.startWithInitial]
|
|
277
|
-
},
|
|
278
|
-
/** Times New Roman text, strictly black and white. */
|
|
279
|
-
Vesperale: {
|
|
280
|
-
textFontStack: "'Times New Roman', Times, serif",
|
|
281
|
-
notesFontStack: "'Guidohu'",
|
|
282
|
-
verifiedFonts: [
|
|
283
|
-
{
|
|
284
|
-
family: "'Times New Roman', Times, serif",
|
|
285
|
-
weight: "400"
|
|
286
|
-
},
|
|
287
|
-
{
|
|
288
|
-
family: "'Times New Roman', Times, serif",
|
|
289
|
-
weight: "700"
|
|
290
|
-
},
|
|
291
|
-
{
|
|
292
|
-
family: "'Guidohu'",
|
|
293
|
-
weight: "400"
|
|
294
|
-
},
|
|
295
|
-
{
|
|
296
|
-
family: "'Liturgy'",
|
|
297
|
-
weight: "700"
|
|
298
|
-
}
|
|
299
|
-
],
|
|
300
|
-
decorations: {
|
|
301
|
-
__: {
|
|
302
|
-
fontFamily: "'Liturgy', serif",
|
|
303
|
-
weight: "700"
|
|
304
|
-
},
|
|
305
|
-
_: {
|
|
306
|
-
scale: .8,
|
|
307
|
-
italic: true
|
|
308
|
-
},
|
|
309
|
-
"*": {
|
|
310
|
-
weight: "700",
|
|
311
|
-
initial: true
|
|
312
|
-
}
|
|
313
|
-
},
|
|
314
|
-
specialStarStyle: {
|
|
315
|
-
fontFamily: TIMES_MARKER_GLYPHS.fontFamily,
|
|
316
|
-
weight: "700",
|
|
317
|
-
scale: 1,
|
|
318
|
-
measureScale: .95,
|
|
319
|
-
raise: .2
|
|
320
|
-
},
|
|
321
|
-
padding: 12,
|
|
322
|
-
scriptTransforms: []
|
|
323
|
-
}
|
|
324
|
-
};
|
|
325
|
-
var DEFAULT_STYLE_SET = "BNS";
|
|
326
|
-
/**
|
|
327
|
-
* Resolves a syllable's raw text into the runs it renders as: the whole-
|
|
328
|
-
* syllable `**` star renders as the bold ∗ operator, a `__…__` or `_…_`
|
|
329
|
-
* wrapper (the same characters on both ends, content between) picks up
|
|
330
|
-
* its decoration rule from the style set, and paired `*` markers wrap any
|
|
331
|
-
* part of the syllable — even the whole of it — with the initial rule
|
|
332
|
-
* (`*sam*ple` → "sam" in the initial style, "ple" normal; an unmatched
|
|
333
|
-
* `*` renders literally), the `bold` option forces weight 700 onto every
|
|
334
|
-
* run, and marker-glyph characters split off into runs of their own font.
|
|
335
|
-
* Inside a Liturgy-font run, `+` gets its own weight-400 runs — the font
|
|
336
|
-
* is bold-looking by design, so the weight stays normal. The wrapper
|
|
337
|
-
* characters themselves are dropped.
|
|
338
|
-
*/
|
|
339
|
-
function resolveSyllableParts(text, styleSet, bold) {
|
|
340
|
-
if (text.length === 0) return [];
|
|
341
|
-
if (text === "**") return [{
|
|
342
|
-
text: "∗",
|
|
343
|
-
style: { ...styleSet.specialStarStyle }
|
|
344
|
-
}];
|
|
345
|
-
let content = text;
|
|
346
|
-
let base = {};
|
|
347
|
-
for (const wrapper of ["__", "_"]) {
|
|
348
|
-
const rule = styleSet.decorations[wrapper];
|
|
349
|
-
if (rule && text.length >= wrapper.length * 2 + 1 && text.startsWith(wrapper) && text.endsWith(wrapper)) {
|
|
350
|
-
content = text.slice(wrapper.length, -wrapper.length);
|
|
351
|
-
base = { ...rule };
|
|
352
|
-
break;
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
const initialRule = styleSet.decorations["*"];
|
|
356
|
-
const segmentSpecs = [];
|
|
357
|
-
let rest = content;
|
|
358
|
-
let plain = "";
|
|
359
|
-
for (let m = /\*([^*]+)\*/.exec(rest); m; m = /\*([^*]+)\*/.exec(rest)) {
|
|
360
|
-
plain += rest.slice(0, m.index);
|
|
361
|
-
if (plain) {
|
|
362
|
-
segmentSpecs.push({
|
|
363
|
-
text: plain,
|
|
364
|
-
marked: false
|
|
365
|
-
});
|
|
366
|
-
plain = "";
|
|
367
|
-
}
|
|
368
|
-
segmentSpecs.push({
|
|
369
|
-
text: m[1],
|
|
370
|
-
marked: true
|
|
371
|
-
});
|
|
372
|
-
rest = rest.slice(m.index + m[0].length);
|
|
373
|
-
}
|
|
374
|
-
plain += rest;
|
|
375
|
-
if (plain) segmentSpecs.push({
|
|
376
|
-
text: plain,
|
|
377
|
-
marked: false
|
|
378
|
-
});
|
|
379
|
-
const segments = segmentSpecs.map(({ text: segText, marked }) => ({
|
|
380
|
-
text: segText,
|
|
381
|
-
style: marked ? {
|
|
382
|
-
...base,
|
|
383
|
-
...initialRule,
|
|
384
|
-
initial: true
|
|
385
|
-
} : { ...base }
|
|
386
|
-
}));
|
|
387
|
-
const glyphs = styleSet.markerGlyphs;
|
|
388
|
-
const parts = [];
|
|
389
|
-
for (const segment of segments) {
|
|
390
|
-
if (segment.style.uppercase) segment.text = segment.text.toUpperCase();
|
|
391
|
-
if (bold) segment.style = {
|
|
392
|
-
...segment.style,
|
|
393
|
-
weight: "700"
|
|
394
|
-
};
|
|
395
|
-
const chars = [...segment.text];
|
|
396
|
-
const inLiturgy = segment.style.fontFamily?.includes("Liturgy") ?? false;
|
|
397
|
-
const runKind = (ch) => {
|
|
398
|
-
if (glyphs && glyphs.chars.has(ch)) return "marker";
|
|
399
|
-
if (inLiturgy && ch === "+") return "plus";
|
|
400
|
-
return "text";
|
|
401
|
-
};
|
|
402
|
-
if (chars.every((ch) => runKind(ch) === "text")) {
|
|
403
|
-
parts.push({
|
|
404
|
-
text: segment.text,
|
|
405
|
-
style: { ...segment.style }
|
|
406
|
-
});
|
|
407
|
-
continue;
|
|
408
|
-
}
|
|
409
|
-
let charRun = "";
|
|
410
|
-
let currentKind = null;
|
|
411
|
-
const pushRun = () => {
|
|
412
|
-
if (!charRun) return;
|
|
413
|
-
let runStyle = { ...segment.style };
|
|
414
|
-
if (currentKind === "marker" && glyphs) runStyle = {
|
|
415
|
-
...runStyle,
|
|
416
|
-
fontFamily: glyphs.fontFamily
|
|
417
|
-
};
|
|
418
|
-
else if (currentKind === "plus") runStyle = {
|
|
419
|
-
...runStyle,
|
|
420
|
-
...LITURGY_PLUS_STYLE
|
|
421
|
-
};
|
|
422
|
-
parts.push({
|
|
423
|
-
text: charRun,
|
|
424
|
-
style: runStyle
|
|
425
|
-
});
|
|
426
|
-
charRun = "";
|
|
427
|
-
};
|
|
428
|
-
for (const ch of chars) {
|
|
429
|
-
const kind = runKind(ch);
|
|
430
|
-
if (kind !== currentKind) pushRun();
|
|
431
|
-
currentKind = kind;
|
|
432
|
-
charRun += ch;
|
|
433
|
-
}
|
|
434
|
-
pushRun();
|
|
435
|
-
}
|
|
436
|
-
return parts;
|
|
437
|
-
}
|
|
438
|
-
/** The canvas font shorthand for measuring a run at the text size. */
|
|
439
|
-
function measurementFont(style, textPx, fallbackStack) {
|
|
440
|
-
return [
|
|
441
|
-
style.italic ? "italic" : "normal",
|
|
442
|
-
"normal",
|
|
443
|
-
style.weight ?? "400",
|
|
444
|
-
`${textPx * (style.measureScale ?? style.scale ?? 1)}px`,
|
|
445
|
-
style.fontFamily ?? fallbackStack
|
|
446
|
-
].join(" ");
|
|
447
|
-
}
|
|
448
|
-
/** The inline CSS properties that draw a run, as dash-cased names for
|
|
449
|
-
* CSSStyleDeclaration.setProperty. */
|
|
450
|
-
function inlineStylesFor(style, textPx) {
|
|
451
|
-
const styles = {};
|
|
452
|
-
if (style.fontFamily) styles["font-family"] = style.fontFamily;
|
|
453
|
-
if (style.weight) styles["font-weight"] = style.weight;
|
|
454
|
-
if (style.italic) styles["font-style"] = "italic";
|
|
455
|
-
if (style.scale !== void 0) styles["font-size"] = `${textPx * style.scale}px`;
|
|
456
|
-
if (style.color) styles["color"] = style.color;
|
|
457
|
-
if (style.raise) {
|
|
458
|
-
styles["position"] = "relative";
|
|
459
|
-
styles["top"] = `${-textPx * style.raise}px`;
|
|
460
|
-
}
|
|
461
|
-
return styles;
|
|
462
|
-
}
|
|
463
|
-
/** The font strings render() must load and verify for a style set. */
|
|
464
|
-
function fontStringsToVerify(styleSet, textPx) {
|
|
465
|
-
return styleSet.verifiedFonts.map((f) => `${f.weight} ${textPx}px ${f.family}`);
|
|
466
|
-
}
|
|
467
|
-
var MARKER_CHARS = new Set(",.:?'\"+!%/=()ÖÜÓ;".split(""));
|
|
468
|
-
var SPECIAL_NOTE_CHARS = new Set("Ÿ¡¢£[¥¦©ª«¬".split(""));
|
|
469
|
-
var NOTE_GROUP_SPLITTERS = ["-", "¨"];
|
|
470
|
-
function splitNoteMarkers(notes) {
|
|
471
|
-
let start = 0;
|
|
472
|
-
while (start < notes.length && MARKER_CHARS.has(notes[start])) start++;
|
|
473
|
-
if (start > 0 && start < notes.length && notes[start] === "-") start++;
|
|
474
|
-
let end = notes.length;
|
|
475
|
-
while (end > start && MARKER_CHARS.has(notes[end - 1])) end--;
|
|
476
|
-
if (end < notes.length && end > start && notes[end - 1] === "-") end--;
|
|
477
|
-
return {
|
|
478
|
-
leading: notes.slice(0, start),
|
|
479
|
-
core: notes.slice(start, end),
|
|
480
|
-
trailing: notes.slice(end)
|
|
481
|
-
};
|
|
482
|
-
}
|
|
483
|
-
/**
|
|
484
|
-
* Renders a GuidoScript into a tidy score: a notes line in the chant font,
|
|
485
|
-
* and a text line where each syllable is centered below its notes. The
|
|
486
|
-
* dashes of the chant font are pure whitespace: centering ignores them and
|
|
487
|
-
* happens under the non-whitespace note characters only. When a syllable's
|
|
488
|
-
* text would overlap the previous one, it starts right after it and the
|
|
489
|
-
* notes group is padded with extra dashes until it covers the text.
|
|
490
|
-
*
|
|
491
|
-
* Appearance comes from a named style set (see guidoStyles.ts): the render
|
|
492
|
-
* options reference it by name, together with the bold option and the
|
|
493
|
-
* text/notes sizes.
|
|
494
|
-
*/
|
|
495
|
-
var GuidoRender = class GuidoRender {
|
|
496
|
-
script;
|
|
497
|
-
constructor(source) {
|
|
498
|
-
this.script = typeof source === "string" ? new GuidoScript(source) : source;
|
|
499
|
-
}
|
|
500
|
-
static ctx = null;
|
|
501
|
-
static measure(text, font) {
|
|
502
|
-
if (!GuidoRender.ctx) GuidoRender.ctx = document.createElement("canvas").getContext("2d");
|
|
503
|
-
GuidoRender.ctx.font = font;
|
|
504
|
-
return GuidoRender.ctx.measureText(text).width;
|
|
505
|
-
}
|
|
506
|
-
/** Ink extents of the text relative to the glyph origin (negative left
|
|
507
|
-
* means the ink starts left of the origin). */
|
|
508
|
-
static ink(text, font) {
|
|
509
|
-
if (!GuidoRender.ctx) GuidoRender.ctx = document.createElement("canvas").getContext("2d");
|
|
510
|
-
GuidoRender.ctx.font = font;
|
|
511
|
-
const m = GuidoRender.ctx.measureText(text);
|
|
512
|
-
return {
|
|
513
|
-
left: m.actualBoundingBoxLeft,
|
|
514
|
-
right: m.actualBoundingBoxRight
|
|
515
|
-
};
|
|
516
|
-
}
|
|
517
|
-
/**
|
|
518
|
-
* Renders the score into `container` as (notes line, text line) pairs.
|
|
519
|
-
* When `maxWidthPx` is finite, a new pair starts before any syllable
|
|
520
|
-
* whose notes would push the current notes line past it; the clef is
|
|
521
|
-
* repeated at the start of every line. Throws when the style set is
|
|
522
|
-
* unknown or one of its fonts cannot be loaded.
|
|
523
|
-
*/
|
|
524
|
-
async render(container, options = {}) {
|
|
525
|
-
const { style: styleName = "BNS", bold = false, textPx = 18, notesPx = textPx * 2, debug = false, maxWidthPx = Infinity } = options;
|
|
526
|
-
const styleSet = STYLE_SETS[styleName];
|
|
527
|
-
if (!styleSet) throw new Error(`Unknown style set: "${styleName}"`);
|
|
528
|
-
for (const font of fontStringsToVerify(styleSet, textPx)) {
|
|
529
|
-
try {
|
|
530
|
-
await document.fonts.load(font);
|
|
531
|
-
} catch {}
|
|
532
|
-
if (!document.fonts.check(font)) throw new Error(`Font could not be loaded: ${font} (style "${styleName}")`);
|
|
533
|
-
}
|
|
534
|
-
const notesFont = `400 ${notesPx}px ${styleSet.notesFontStack}`;
|
|
535
|
-
const textStack = styleSet.textFontStack;
|
|
536
|
-
const spaceFont = measurementFont({ weight: bold ? "700" : "400" }, textPx, textStack);
|
|
537
|
-
const resolveParts = (spanText) => resolveSyllableParts(spanText, styleSet, bold);
|
|
538
|
-
const measureParts = (parts) => parts.reduce((w, part) => w + measure(part.text, measurementFont(part.style, textPx, textStack)), 0);
|
|
539
|
-
const measure = (text, font) => GuidoRender.measure(text, font);
|
|
540
|
-
const dashNotesWidth = measure("-", notesFont);
|
|
541
|
-
const dashTextWidth = measure("-", spaceFont);
|
|
542
|
-
container.style.fontSize = `${textPx}px`;
|
|
543
|
-
container.style.fontFamily = textStack;
|
|
544
|
-
container.dataset.style = styleName;
|
|
545
|
-
const clefPrefix = this.script.clef !== void 0 ? `${this.script.clef}-` : "";
|
|
546
|
-
const lines = [];
|
|
547
|
-
let line;
|
|
548
|
-
let notesSoFar;
|
|
549
|
-
let textCursor;
|
|
550
|
-
let lastGroupTrailingMarker;
|
|
551
|
-
let prevRecited = false;
|
|
552
|
-
let pending = [];
|
|
553
|
-
const startLine = () => {
|
|
554
|
-
if (line) {
|
|
555
|
-
line.textCursor = textCursor;
|
|
556
|
-
line.notesEnd = line.notesParts.length ? measure(clefPrefix + line.notesParts.join(""), notesFont) : 0;
|
|
557
|
-
}
|
|
558
|
-
const notesEl = document.createElement("div");
|
|
559
|
-
notesEl.className = "guido";
|
|
560
|
-
notesEl.style.fontSize = `${notesPx}px`;
|
|
561
|
-
const textEl = document.createElement("p");
|
|
562
|
-
if (bold) textEl.style.fontWeight = "700";
|
|
563
|
-
line = {
|
|
564
|
-
notesEl,
|
|
565
|
-
textEl,
|
|
566
|
-
notesParts: [],
|
|
567
|
-
textCursor: 0,
|
|
568
|
-
notesEnd: 0,
|
|
569
|
-
lastWordEnd: null
|
|
570
|
-
};
|
|
571
|
-
lines.push(line);
|
|
572
|
-
notesSoFar = clefPrefix;
|
|
573
|
-
textCursor = 0;
|
|
574
|
-
lastGroupTrailingMarker = false;
|
|
575
|
-
prevRecited = false;
|
|
576
|
-
};
|
|
577
|
-
startLine();
|
|
578
|
-
const syllables = this.script.syllables;
|
|
579
|
-
const items = syllables.map((syl, i) => ({
|
|
580
|
-
syl,
|
|
581
|
-
i,
|
|
582
|
-
text: syl.text,
|
|
583
|
-
notes: syl.notes,
|
|
584
|
-
first: true,
|
|
585
|
-
lastSeg: true
|
|
586
|
-
}));
|
|
587
|
-
const findBreakCut = (notes, room, measureFromLineStart) => {
|
|
588
|
-
for (let c = notes.length - 1; c > 0; c--) {
|
|
589
|
-
if (!NOTE_GROUP_SPLITTERS.includes(notes[c])) continue;
|
|
590
|
-
let end = c + 1;
|
|
591
|
-
while (end < notes.length && MARKER_CHARS.has(notes[end])) end++;
|
|
592
|
-
if (end >= notes.length) continue;
|
|
593
|
-
if (measureFromLineStart(notes.slice(0, end)) <= room) return c;
|
|
594
|
-
}
|
|
595
|
-
return -1;
|
|
596
|
-
};
|
|
597
|
-
const applyBreakCut = (item, cut) => {
|
|
598
|
-
const notes = item.notes;
|
|
599
|
-
let restStart = cut + 1;
|
|
600
|
-
while (restStart < notes.length && MARKER_CHARS.has(notes[restStart])) restStart++;
|
|
601
|
-
item.notes = notes.slice(0, cut) + notes.slice(cut + 1, restStart);
|
|
602
|
-
return notes.slice(restStart);
|
|
603
|
-
};
|
|
604
|
-
const queueContinuation = (item, idx, rest) => {
|
|
605
|
-
item.lastSeg = false;
|
|
606
|
-
items.splice(idx + 1, 0, {
|
|
607
|
-
syl: item.syl,
|
|
608
|
-
i: item.i,
|
|
609
|
-
text: "",
|
|
610
|
-
notes: rest,
|
|
611
|
-
first: false,
|
|
612
|
-
lastSeg: true
|
|
613
|
-
});
|
|
614
|
-
forceBreak = true;
|
|
615
|
-
};
|
|
616
|
-
let forceBreak = false;
|
|
617
|
-
let idx = 0;
|
|
618
|
-
while (idx < items.length) {
|
|
619
|
-
const item = items[idx];
|
|
620
|
-
const syl = item.syl;
|
|
621
|
-
const i = item.i;
|
|
622
|
-
if (forceBreak) {
|
|
623
|
-
startLine();
|
|
624
|
-
forceBreak = false;
|
|
625
|
-
}
|
|
626
|
-
const last = item.lastSeg && i === syllables.length - 1;
|
|
627
|
-
const spanText = item.text;
|
|
628
|
-
const sylParts = resolveParts(spanText);
|
|
629
|
-
const textWidth = measureParts(sylParts);
|
|
630
|
-
const spaceWidth = !last && syl.wordEnd ? measure(" ", spaceFont) : 0;
|
|
631
|
-
const pendingTotal = pending.reduce((s, p) => s + p.textWidth + p.spaceWidth, 0);
|
|
632
|
-
const special = syl.notes.length === 1 && SPECIAL_NOTE_CHARS.has(syl.notes);
|
|
633
|
-
const specialFits = textCursor === 0 || textCursor + pendingTotal + textWidth + (syl.wordEnd ? 0 : dashTextWidth) <= maxWidthPx;
|
|
634
|
-
if (syl.notes.length === 0) {
|
|
635
|
-
pending.push({
|
|
636
|
-
sylParts,
|
|
637
|
-
textWidth,
|
|
638
|
-
spaceWidth,
|
|
639
|
-
wordEnd: syl.wordEnd
|
|
640
|
-
});
|
|
641
|
-
idx++;
|
|
642
|
-
continue;
|
|
643
|
-
}
|
|
644
|
-
if (item.first && item.lastSeg && syl.text.trim() === "" && splitNoteMarkers(syl.notes).core === "") {
|
|
645
|
-
const last = notesSoFar[notesSoFar.length - 1];
|
|
646
|
-
const sep = last && last !== "-" && !MARKER_CHARS.has(last) && !syl.notes.startsWith("-") ? "-" : "";
|
|
647
|
-
line.notesParts.push(sep + syl.notes);
|
|
648
|
-
notesSoFar += sep + syl.notes;
|
|
649
|
-
lastGroupTrailingMarker = true;
|
|
650
|
-
prevRecited = false;
|
|
651
|
-
idx++;
|
|
652
|
-
continue;
|
|
653
|
-
}
|
|
654
|
-
const runStart = syllables[i - 1]?.notes !== syl.notes;
|
|
655
|
-
if (special && !runStart && line.notesParts.length > 0 && !specialFits) startLine();
|
|
656
|
-
if (!item.first) {
|
|
657
|
-
for (;;) {
|
|
658
|
-
if (measure(notesSoFar + item.notes, notesFont) <= maxWidthPx) break;
|
|
659
|
-
const cut = findBreakCut(item.notes, maxWidthPx, (prefix) => measure(notesSoFar + prefix, notesFont));
|
|
660
|
-
if (cut < 0 || cut + 1 >= item.notes.length) break;
|
|
661
|
-
const rest = applyBreakCut(item, cut);
|
|
662
|
-
queueContinuation(item, idx, rest);
|
|
663
|
-
}
|
|
664
|
-
const parts = splitNoteMarkers(item.notes);
|
|
665
|
-
line.notesParts.push(item.notes);
|
|
666
|
-
notesSoFar += item.notes;
|
|
667
|
-
if (item.lastSeg) lastGroupTrailingMarker = parts.trailing.length > 0;
|
|
668
|
-
line.lastWordEnd = true;
|
|
669
|
-
if (!item.lastSeg) forceBreak = true;
|
|
670
|
-
idx++;
|
|
671
|
-
continue;
|
|
672
|
-
}
|
|
673
|
-
let junctionPrefix = line.notesParts.length === 0 ? "" : prevRecited ? "" : lastGroupTrailingMarker ? "--" : "---";
|
|
674
|
-
let parts = splitNoteMarkers(item.notes);
|
|
675
|
-
const place = (padDashes = 0) => {
|
|
676
|
-
const contentWidth = measure(parts.core, notesFont);
|
|
677
|
-
const contentStart = measure(notesSoFar + junctionPrefix + "-".repeat(padDashes) + parts.leading, notesFont);
|
|
678
|
-
const inkRaw = GuidoRender.ink(parts.core, notesFont);
|
|
679
|
-
const inkStartOffset = -inkRaw.left;
|
|
680
|
-
const inkCenterOffset = (inkRaw.right - inkRaw.left) / 2;
|
|
681
|
-
return {
|
|
682
|
-
contentWidth,
|
|
683
|
-
contentStart,
|
|
684
|
-
textStart: contentWidth >= textWidth || special ? contentStart + inkStartOffset : contentStart + inkCenterOffset - textWidth / 2
|
|
685
|
-
};
|
|
686
|
-
};
|
|
687
|
-
let { contentWidth, contentStart, textStart } = place();
|
|
688
|
-
for (;;) {
|
|
689
|
-
const notesOver = measure(notesSoFar + junctionPrefix + item.notes, notesFont) > maxWidthPx;
|
|
690
|
-
const textOver = textStart + textWidth + (syl.wordEnd ? 0 : dashTextWidth) > maxWidthPx;
|
|
691
|
-
if (!notesOver && !textOver) break;
|
|
692
|
-
if (notesOver) {
|
|
693
|
-
const cut = findBreakCut(item.notes, maxWidthPx, (prefix) => measure(notesSoFar + junctionPrefix + prefix, notesFont));
|
|
694
|
-
if (cut >= 0 && cut + 1 < item.notes.length) {
|
|
695
|
-
const rest = applyBreakCut(item, cut);
|
|
696
|
-
queueContinuation(item, idx, rest);
|
|
697
|
-
parts = splitNoteMarkers(item.notes);
|
|
698
|
-
({contentWidth, contentStart, textStart} = place());
|
|
699
|
-
break;
|
|
700
|
-
}
|
|
701
|
-
}
|
|
702
|
-
if (line.notesParts.length === 0 && textCursor === 0) {
|
|
703
|
-
if (notesOver) {
|
|
704
|
-
const cut = findBreakCut(item.notes, maxWidthPx, (prefix) => measure(notesSoFar + prefix, notesFont));
|
|
705
|
-
if (cut >= 0 && cut + 1 < item.notes.length) {
|
|
706
|
-
const rest = applyBreakCut(item, cut);
|
|
707
|
-
item.notes = item.notes.slice(0, cut);
|
|
708
|
-
queueContinuation(item, idx, rest);
|
|
709
|
-
parts = splitNoteMarkers(item.notes);
|
|
710
|
-
({contentWidth, contentStart, textStart} = place());
|
|
711
|
-
}
|
|
712
|
-
}
|
|
713
|
-
break;
|
|
714
|
-
}
|
|
715
|
-
startLine();
|
|
716
|
-
junctionPrefix = "";
|
|
717
|
-
({contentWidth, contentStart, textStart} = place());
|
|
718
|
-
}
|
|
719
|
-
const connectorDash = line.notesParts.length > 0 && !items[idx - 1].syl.wordEnd && pendingTotal === 0;
|
|
720
|
-
const minStart = textCursor + dashTextWidth;
|
|
721
|
-
const minTextStart = textCursor + pendingTotal + (prevRecited && connectorDash ? dashTextWidth : 0);
|
|
722
|
-
let notesStr = junctionPrefix + item.notes;
|
|
723
|
-
let extraDashes = 0;
|
|
724
|
-
let tightPair = false;
|
|
725
|
-
const padAndPlace = (pads) => {
|
|
726
|
-
extraDashes = pads;
|
|
727
|
-
notesStr = junctionPrefix + "-".repeat(pads) + item.notes;
|
|
728
|
-
({contentWidth, contentStart, textStart} = place(pads));
|
|
729
|
-
};
|
|
730
|
-
const hiddenSpecial = special && !runStart && line.notesParts.length > 0;
|
|
731
|
-
if (hiddenSpecial) {
|
|
732
|
-
junctionPrefix = "";
|
|
733
|
-
textStart = textCursor + pendingTotal;
|
|
734
|
-
const deficit = textStart + textWidth + spaceWidth - measure(notesSoFar, notesFont);
|
|
735
|
-
const room = maxWidthPx - measure(notesSoFar + junctionPrefix, notesFont);
|
|
736
|
-
const fill = deficit > 0 ? Math.min(Math.ceil(deficit / dashNotesWidth), Math.max(0, Math.floor(room / dashNotesWidth))) : 0;
|
|
737
|
-
item.notes = "-".repeat(fill);
|
|
738
|
-
parts = splitNoteMarkers(item.notes);
|
|
739
|
-
notesStr = junctionPrefix + item.notes;
|
|
740
|
-
tightPair = connectorDash;
|
|
741
|
-
}
|
|
742
|
-
if (hiddenSpecial) {} else if (!prevRecited && connectorDash && textStart < minStart && (textWidth > contentWidth || textStart < textCursor)) {
|
|
743
|
-
tightPair = true;
|
|
744
|
-
textStart = textCursor;
|
|
745
|
-
const idealContentStart = contentWidth >= textWidth ? textStart : textStart + (textWidth - contentWidth) / 2;
|
|
746
|
-
if (idealContentStart > contentStart) {
|
|
747
|
-
extraDashes = Math.round((idealContentStart - contentStart) / dashNotesWidth);
|
|
748
|
-
notesStr = junctionPrefix + "-".repeat(extraDashes) + item.notes;
|
|
749
|
-
}
|
|
750
|
-
} else if (textStart < minTextStart) {
|
|
751
|
-
const idealContentStart = contentWidth >= textWidth ? minTextStart : minTextStart + (textWidth - contentWidth) / 2;
|
|
752
|
-
if (idealContentStart > contentStart) {
|
|
753
|
-
let pads = Math.max(0, Math.floor((idealContentStart - contentStart) / dashNotesWidth));
|
|
754
|
-
padAndPlace(pads);
|
|
755
|
-
while (textStart < minTextStart) {
|
|
756
|
-
pads++;
|
|
757
|
-
padAndPlace(pads);
|
|
758
|
-
}
|
|
759
|
-
if (line.notesParts.length > 0 && measure(notesSoFar + notesStr, notesFont) > maxWidthPx) {
|
|
760
|
-
startLine();
|
|
761
|
-
junctionPrefix = "";
|
|
762
|
-
notesStr = junctionPrefix + item.notes;
|
|
763
|
-
extraDashes = 0;
|
|
764
|
-
({contentWidth, contentStart, textStart} = place());
|
|
765
|
-
if (textStart < textCursor + pendingTotal) {
|
|
766
|
-
const freshIdeal = contentWidth >= textWidth ? textCursor + pendingTotal : textCursor + pendingTotal + (textWidth - contentWidth) / 2;
|
|
767
|
-
if (freshIdeal > contentStart) {
|
|
768
|
-
let pads = Math.max(0, Math.floor((freshIdeal - contentStart) / dashNotesWidth));
|
|
769
|
-
padAndPlace(pads);
|
|
770
|
-
while (textStart < textCursor + pendingTotal) {
|
|
771
|
-
pads++;
|
|
772
|
-
padAndPlace(pads);
|
|
773
|
-
}
|
|
774
|
-
}
|
|
775
|
-
}
|
|
776
|
-
}
|
|
777
|
-
}
|
|
778
|
-
}
|
|
779
|
-
if (pendingTotal > 0 && textStart < textCursor + pendingTotal) textStart = textCursor + pendingTotal;
|
|
780
|
-
const spacerWidth = Math.max(0, textStart - pendingTotal - textCursor);
|
|
781
|
-
const sylSpan = GuidoRender.sylSpan(sylParts, textPx);
|
|
782
|
-
if (line.notesParts.length === 0) {
|
|
783
|
-
const spacerEl = GuidoRender.spacer(spacerWidth);
|
|
784
|
-
if (debug) spacerEl.title = `lead-in ${spacerWidth.toFixed(1)}px → text ${textStart.toFixed(1)}`;
|
|
785
|
-
line.textEl.appendChild(spacerEl);
|
|
786
|
-
} else if (items[idx - 1].syl.wordEnd) {
|
|
787
|
-
const spacerEl = GuidoRender.spacer(spacerWidth);
|
|
788
|
-
if (debug) spacerEl.title = `word gap ${spacerWidth.toFixed(1)}px → text ${textStart.toFixed(1)}`;
|
|
789
|
-
line.textEl.appendChild(spacerEl);
|
|
790
|
-
} else if (pendingTotal === 0 && tightPair) {
|
|
791
|
-
if (debug) sylSpan.title += " | tight pair";
|
|
792
|
-
} else if (pendingTotal === 0) {
|
|
793
|
-
const pad = Math.max(0, (spacerWidth - dashTextWidth) / 2);
|
|
794
|
-
const leadPad = GuidoRender.spacer(pad);
|
|
795
|
-
const dash = document.createElement("span");
|
|
796
|
-
dash.className = "dash";
|
|
797
|
-
dash.textContent = "-";
|
|
798
|
-
const trailPad = GuidoRender.spacer(pad);
|
|
799
|
-
if (debug) {
|
|
800
|
-
leadPad.title = `lead pad ${pad.toFixed(1)}px (gap ${spacerWidth.toFixed(1)} − dash ${dashTextWidth.toFixed(1)}, halved)`;
|
|
801
|
-
dash.title = `dash ${dashTextWidth.toFixed(1)}px`;
|
|
802
|
-
trailPad.title = `trail pad ${pad.toFixed(1)}px`;
|
|
803
|
-
}
|
|
804
|
-
line.textEl.append(leadPad, dash, trailPad);
|
|
805
|
-
}
|
|
806
|
-
if (debug) {
|
|
807
|
-
const theoDiff = (textWidth - contentWidth) / 2;
|
|
808
|
-
const cursDiff = textStart - contentStart;
|
|
809
|
-
sylSpan.title = [
|
|
810
|
-
`text w ${textWidth.toFixed(1)}`,
|
|
811
|
-
`notes w ${contentWidth.toFixed(1)}`,
|
|
812
|
-
extraDashes ? `+${extraDashes} pad dash(es)` : null,
|
|
813
|
-
`text start ${textStart.toFixed(1)}`,
|
|
814
|
-
`notes start ${contentStart.toFixed(1)}`,
|
|
815
|
-
`theoDiff: ${theoDiff.toFixed(1)}`,
|
|
816
|
-
`cursDiff: ${cursDiff.toFixed(1)}`
|
|
817
|
-
].filter(Boolean).join(", ");
|
|
818
|
-
}
|
|
819
|
-
for (const p of pending) {
|
|
820
|
-
const span = GuidoRender.sylSpan(p.sylParts, textPx);
|
|
821
|
-
if (debug) span.title = `no notes, text w ${p.textWidth.toFixed(1)}, before the next syllable with notes`;
|
|
822
|
-
line.textEl.appendChild(span);
|
|
823
|
-
if (p.spaceWidth > 0) {
|
|
824
|
-
const ws = document.createElement("span");
|
|
825
|
-
ws.className = "word-space";
|
|
826
|
-
ws.textContent = " ";
|
|
827
|
-
if (debug) ws.title = `word space ${p.spaceWidth.toFixed(1)}px`;
|
|
828
|
-
line.textEl.appendChild(ws);
|
|
829
|
-
}
|
|
830
|
-
}
|
|
831
|
-
pending = [];
|
|
832
|
-
line.textEl.appendChild(sylSpan);
|
|
833
|
-
if (spaceWidth > 0) {
|
|
834
|
-
const spaceSpan = document.createElement("span");
|
|
835
|
-
spaceSpan.className = "word-space";
|
|
836
|
-
spaceSpan.textContent = " ";
|
|
837
|
-
if (debug) spaceSpan.title = `word space ${spaceWidth.toFixed(1)}px`;
|
|
838
|
-
line.textEl.appendChild(spaceSpan);
|
|
839
|
-
}
|
|
840
|
-
textCursor = textStart + textWidth + spaceWidth;
|
|
841
|
-
notesSoFar += notesStr;
|
|
842
|
-
line.notesParts.push(notesStr);
|
|
843
|
-
line.lastWordEnd = syl.wordEnd;
|
|
844
|
-
if (item.lastSeg) {
|
|
845
|
-
lastGroupTrailingMarker = parts.trailing.length > 0;
|
|
846
|
-
prevRecited = special;
|
|
847
|
-
}
|
|
848
|
-
if (!item.lastSeg) forceBreak = true;
|
|
849
|
-
idx++;
|
|
850
|
-
}
|
|
851
|
-
if (pending.length > 0) {
|
|
852
|
-
for (const p of pending) {
|
|
853
|
-
const span = GuidoRender.sylSpan(p.sylParts, textPx);
|
|
854
|
-
if (debug) span.title = `no notes, text w ${p.textWidth.toFixed(1)}, end of score`;
|
|
855
|
-
line.textEl.appendChild(span);
|
|
856
|
-
if (p.spaceWidth > 0) {
|
|
857
|
-
const ws = document.createElement("span");
|
|
858
|
-
ws.className = "word-space";
|
|
859
|
-
ws.textContent = " ";
|
|
860
|
-
if (debug) ws.title = `word space ${p.spaceWidth.toFixed(1)}px`;
|
|
861
|
-
line.textEl.appendChild(ws);
|
|
862
|
-
}
|
|
863
|
-
textCursor += p.textWidth + p.spaceWidth;
|
|
864
|
-
}
|
|
865
|
-
line.lastWordEnd = pending[pending.length - 1].wordEnd;
|
|
866
|
-
line.textCursor = textCursor;
|
|
867
|
-
}
|
|
868
|
-
lines.forEach((l, li) => {
|
|
869
|
-
if (li === lines.length - 1 || l.lastWordEnd !== false) return;
|
|
870
|
-
const pad = l.notesEnd > l.textCursor ? Math.max(0, (l.notesEnd - l.textCursor - dashTextWidth) / 2) : 0;
|
|
871
|
-
const leadPad = GuidoRender.spacer(pad);
|
|
872
|
-
const dash = document.createElement("span");
|
|
873
|
-
dash.className = "dash";
|
|
874
|
-
dash.textContent = "-";
|
|
875
|
-
const trailPad = GuidoRender.spacer(pad);
|
|
876
|
-
if (debug) {
|
|
877
|
-
leadPad.title = `lead pad ${pad.toFixed(1)}px → line-end dash (text end ${l.textCursor.toFixed(1)}, notes end ${l.notesEnd.toFixed(1)})`;
|
|
878
|
-
dash.title = `dash ${dashTextWidth.toFixed(1)}px (line end)`;
|
|
879
|
-
trailPad.title = `trail pad ${pad.toFixed(1)}px`;
|
|
880
|
-
}
|
|
881
|
-
l.textEl.append(leadPad, dash, trailPad);
|
|
882
|
-
});
|
|
883
|
-
const starTarget = maxWidthPx + (styleSet.padding ?? 0);
|
|
884
|
-
const starWidth = measure("*", notesFont);
|
|
885
|
-
lines.forEach((l, li) => {
|
|
886
|
-
if (li === lines.length - 1) return;
|
|
887
|
-
let lineEnd = measure(clefPrefix + l.notesParts.join(""), notesFont);
|
|
888
|
-
while (lineEnd + dashNotesWidth <= starTarget - starWidth && lineEnd + dashNotesWidth < maxWidthPx) {
|
|
889
|
-
l.notesParts.push("-");
|
|
890
|
-
lineEnd += dashNotesWidth;
|
|
891
|
-
}
|
|
892
|
-
l.breakMarkerLeftPx = starTarget - lineEnd - starWidth;
|
|
893
|
-
});
|
|
894
|
-
lines.forEach((l) => {
|
|
895
|
-
l.notesEl.textContent = clefPrefix + l.notesParts.join("");
|
|
896
|
-
});
|
|
897
|
-
lines.forEach((l, li) => {
|
|
898
|
-
if (li === lines.length - 1) return;
|
|
899
|
-
const star = document.createElement("span");
|
|
900
|
-
star.className = "guido-break";
|
|
901
|
-
star.textContent = "*";
|
|
902
|
-
star.style.position = "relative";
|
|
903
|
-
star.style.left = `${l.breakMarkerLeftPx}px`;
|
|
904
|
-
if (debug) star.title = `line break at ${starTarget.toFixed(1)}px (staff filled to ${(starTarget - l.breakMarkerLeftPx - starWidth).toFixed(1)}px)`;
|
|
905
|
-
l.notesEl.appendChild(star);
|
|
906
|
-
});
|
|
907
|
-
container.replaceChildren(...lines.flatMap((l) => [l.notesEl, l.textEl]));
|
|
908
|
-
}
|
|
909
|
-
/** Builds a syllable span from its resolved runs: one nested span per
|
|
910
|
-
* run, carrying the run's inline styles; runs marked `initial` by the
|
|
911
|
-
* `*…*` marker carry the initial class. */
|
|
912
|
-
static sylSpan(parts, textPx) {
|
|
913
|
-
const sylSpan = document.createElement("span");
|
|
914
|
-
sylSpan.className = "syl";
|
|
915
|
-
parts.forEach((part) => {
|
|
916
|
-
const partSpan = document.createElement("span");
|
|
917
|
-
partSpan.textContent = part.text;
|
|
918
|
-
for (const [prop, value] of Object.entries(inlineStylesFor(part.style, textPx))) partSpan.style.setProperty(prop, value);
|
|
919
|
-
if (part.style.initial) partSpan.className = "initial";
|
|
920
|
-
sylSpan.appendChild(partSpan);
|
|
921
|
-
});
|
|
922
|
-
return sylSpan;
|
|
923
|
-
}
|
|
924
|
-
static spacer(width) {
|
|
925
|
-
const spacer = document.createElement("span");
|
|
926
|
-
spacer.className = "spacer";
|
|
927
|
-
spacer.style.display = "inline-block";
|
|
928
|
-
spacer.style.width = `${width}px`;
|
|
929
|
-
return spacer;
|
|
930
|
-
}
|
|
931
|
-
};
|
|
932
|
-
//#endregion
|
|
933
|
-
//#region src/embed/core.ts
|
|
934
|
-
var version = {
|
|
935
|
-
name: "guidex",
|
|
936
|
-
version: "0.2.6",
|
|
937
|
-
description: "Guidex — render plainchant scores from a compact GuidoScript notation, as a web app and an embeddable runtime",
|
|
938
|
-
type: "module",
|
|
939
|
-
workspaces: ["examples/*"],
|
|
940
|
-
main: "./dist/lib/embed/manual.js",
|
|
941
|
-
types: "./dist/lib/embed/manual.d.ts",
|
|
942
|
-
exports: {
|
|
943
|
-
".": {
|
|
944
|
-
"types": "./dist/lib/embed/manual.d.ts",
|
|
945
|
-
"default": "./dist/lib/embed/manual.js"
|
|
946
|
-
},
|
|
947
|
-
"./embed": {
|
|
948
|
-
"types": "./dist/lib/embed/index.d.ts",
|
|
949
|
-
"default": "./dist/lib/embed/index.js"
|
|
950
|
-
},
|
|
951
|
-
"./guidex.css": {
|
|
952
|
-
"types": "./dist/lib/guidex.css.d.ts",
|
|
953
|
-
"default": "./dist/lib/guidex.css"
|
|
954
|
-
},
|
|
955
|
-
"./fonts/*": "./dist/lib/fonts/*",
|
|
956
|
-
"./react": {
|
|
957
|
-
"types": "./dist/lib/react/index.d.ts",
|
|
958
|
-
"default": "./dist/lib/react/index.js"
|
|
959
|
-
}
|
|
960
|
-
},
|
|
961
|
-
files: ["dist-embed", "dist/lib"],
|
|
962
|
-
peerDependencies: { "react": ">=18" },
|
|
963
|
-
peerDependenciesMeta: { "react": { "optional": true } },
|
|
964
|
-
publishConfig: { "access": "public" },
|
|
965
|
-
scripts: {
|
|
966
|
-
"dev": "vite --host",
|
|
967
|
-
"build": "tsc && vite build",
|
|
968
|
-
"build:embed": "vite build --config vite.embed.config.ts",
|
|
969
|
-
"build:lib": "vite build --config vite.lib.config.ts",
|
|
970
|
-
"preview": "vite preview",
|
|
971
|
-
"test": "vitest run",
|
|
972
|
-
"lint": "eslint ."
|
|
973
|
-
},
|
|
974
|
-
keywords: [
|
|
975
|
-
"plainchant",
|
|
976
|
-
"gregorian",
|
|
977
|
-
"guido",
|
|
978
|
-
"score",
|
|
979
|
-
"notation",
|
|
980
|
-
"liturgy"
|
|
981
|
-
],
|
|
982
|
-
repository: {
|
|
983
|
-
"type": "git",
|
|
984
|
-
"url": "git+https://github.com/BrownieMaar/guidex.git"
|
|
985
|
-
},
|
|
986
|
-
bugs: { "url": "https://github.com/BrownieMaar/guidex/issues" },
|
|
987
|
-
homepage: "https://github.com/BrownieMaar/guidex#readme",
|
|
988
|
-
devDependencies: {
|
|
989
|
-
"@eslint/js": "^10.0.1",
|
|
990
|
-
"@types/react": "^19.3.0",
|
|
991
|
-
"@types/react-dom": "^19.3.0",
|
|
992
|
-
"@vitejs/plugin-react": "^6.1.1",
|
|
993
|
-
"eslint": "^10.10.0",
|
|
994
|
-
"jsdom": "^29.1.1",
|
|
995
|
-
"react": "^19.3.0",
|
|
996
|
-
"react-dom": "^19.3.0",
|
|
997
|
-
"typescript": "~6.0.2",
|
|
998
|
-
"typescript-eslint": "^8.70.0",
|
|
999
|
-
"vite": "^8.2.2",
|
|
1000
|
-
"vite-plugin-dts": "^5.1.1",
|
|
1001
|
-
"vitest": "^4.1.11"
|
|
1002
|
-
}
|
|
1003
|
-
}.version;
|
|
1004
|
-
var DEFAULT_SELECTOR = ".guidex-script, .guido-script";
|
|
1005
|
-
var DEFAULTS = {
|
|
1006
|
-
maxWidth: "auto",
|
|
1007
|
-
style: "BNS",
|
|
1008
|
-
bold: false,
|
|
1009
|
-
textPx: 18,
|
|
1010
|
-
transpose: 0,
|
|
1011
|
-
debug: false
|
|
1012
|
-
};
|
|
1013
|
-
var globalOptions = {};
|
|
1014
|
-
/** The raw script of each target, cached across re-renders: rendering
|
|
1015
|
-
* replaces the element's content, so the original text would be lost. */
|
|
1016
|
-
var sources = /* @__PURE__ */ new WeakMap();
|
|
1017
|
-
/** Per-element render race counter: a slow render (font loading) must
|
|
1018
|
-
* never overwrite a newer one's output. */
|
|
1019
|
-
var runs = /* @__PURE__ */ new WeakMap();
|
|
1020
|
-
/** The line-breaking budget each element last rendered at; resize
|
|
1021
|
-
* re-renders are skipped while the width is unchanged (height-only
|
|
1022
|
-
* ResizeObserver entries from our own renders must not loop). */
|
|
1023
|
-
var lastWidths = /* @__PURE__ */ new WeakMap();
|
|
1024
|
-
/** data-* boolean attribute: bare presence or 'true' → true, 'false' →
|
|
1025
|
-
* false, anything else → unset. */
|
|
1026
|
-
function flag(value) {
|
|
1027
|
-
if (value === void 0) return void 0;
|
|
1028
|
-
if (value === "" || value === "true") return true;
|
|
1029
|
-
if (value === "false") return false;
|
|
1030
|
-
}
|
|
1031
|
-
function number(value) {
|
|
1032
|
-
if (value === void 0) return void 0;
|
|
1033
|
-
const n = Number(value);
|
|
1034
|
-
return Number.isFinite(n) ? n : void 0;
|
|
1035
|
-
}
|
|
1036
|
-
function parseMaxWidth(value, fallback) {
|
|
1037
|
-
if (/^auto$/i.test(value.trim())) return "auto";
|
|
1038
|
-
const n = Number(value);
|
|
1039
|
-
if (Number.isFinite(n) && n > 0) return n;
|
|
1040
|
-
console.warn(`[guidex] ignoring invalid data-max-width "${value}"`);
|
|
1041
|
-
return fallback;
|
|
1042
|
-
}
|
|
1043
|
-
/** Per-element option overrides set by `renderScore` (programmatic
|
|
1044
|
-
* callers): element data attributes win over these, these win over
|
|
1045
|
-
* `init` site-wide defaults. */
|
|
1046
|
-
var overrides = /* @__PURE__ */ new WeakMap();
|
|
1047
|
-
/** Element data attributes (or unset) over `renderScore` overrides over
|
|
1048
|
-
* init options over defaults. */
|
|
1049
|
-
function readOptions(el) {
|
|
1050
|
-
const ds = el.dataset;
|
|
1051
|
-
const local = overrides.get(el) ?? {};
|
|
1052
|
-
return {
|
|
1053
|
-
maxWidth: ds.maxWidth !== void 0 ? parseMaxWidth(ds.maxWidth, local.maxWidth ?? globalOptions.maxWidth ?? DEFAULTS.maxWidth) : local.maxWidth ?? globalOptions.maxWidth ?? DEFAULTS.maxWidth,
|
|
1054
|
-
style: ds.style ?? local.style ?? globalOptions.style ?? DEFAULTS.style,
|
|
1055
|
-
bold: flag(ds.bold) ?? local.bold ?? globalOptions.bold ?? DEFAULTS.bold,
|
|
1056
|
-
textPx: number(ds.textPx) ?? local.textPx ?? globalOptions.textPx ?? DEFAULTS.textPx,
|
|
1057
|
-
transpose: number(ds.transpose) ?? local.transpose ?? globalOptions.transpose ?? DEFAULTS.transpose,
|
|
1058
|
-
debug: flag(ds.debug) ?? local.debug ?? globalOptions.debug ?? DEFAULTS.debug
|
|
1059
|
-
};
|
|
1060
|
-
}
|
|
1061
|
-
/** The element's content-box width (the score wrapper spans it), the
|
|
1062
|
-
* line-box width the rendered score actually has to fit. Falls back to
|
|
1063
|
-
* the parent for inline targets; zero means no layout (hidden). */
|
|
1064
|
-
function contentWidthPx(el) {
|
|
1065
|
-
return el.querySelector(":scope > .guidex-render")?.clientWidth || el.clientWidth || el.parentElement?.clientWidth || 0;
|
|
1066
|
-
}
|
|
1067
|
-
/** The line-breaking budget in pixels for this render. Fixed values pass
|
|
1068
|
-
* through; 'auto' fits the element's content box, shrunk by the style
|
|
1069
|
-
* set's break-star padding: the renderer hangs the `guido-break` star
|
|
1070
|
-
* `padding` px past the budget, and when the budget is the line-box
|
|
1071
|
-
* width itself that star would overflow the line and wrap. A zero width
|
|
1072
|
-
* (hidden element) renders unbroken; once it becomes visible the resize
|
|
1073
|
-
* listener re-renders it at the real width. */
|
|
1074
|
-
function resolveWidthPx(el, maxWidth, style) {
|
|
1075
|
-
if (typeof maxWidth === "number") return maxWidth;
|
|
1076
|
-
const width = contentWidthPx(el);
|
|
1077
|
-
if (width <= 0) return Infinity;
|
|
1078
|
-
const budget = width - (STYLE_SETS[style]?.padding ?? 0);
|
|
1079
|
-
return budget > 0 ? budget : width;
|
|
1080
|
-
}
|
|
1081
|
-
/** The element's script source: a fresh non-empty text node wins (so
|
|
1082
|
-
* hosts can update the source by setting textContent and calling
|
|
1083
|
-
* renderAll), otherwise the cached one from the previous render. */
|
|
1084
|
-
function extractSource(el) {
|
|
1085
|
-
for (const node of el.childNodes) if (node.nodeType === Node.TEXT_NODE && node.nodeValue?.trim()) return node.nodeValue.trim();
|
|
1086
|
-
return sources.get(el) ?? "";
|
|
1087
|
-
}
|
|
1088
|
-
/** The score wrapper inside the target; the renderer swaps the score
|
|
1089
|
-
* into it, never touching the target element's own classes or dataset. */
|
|
1090
|
-
function scoreWrapper(el) {
|
|
1091
|
-
const existing = el.querySelector(":scope > .guidex-render");
|
|
1092
|
-
if (existing) return existing;
|
|
1093
|
-
const wrapper = document.createElement("div");
|
|
1094
|
-
wrapper.className = "guidex-render";
|
|
1095
|
-
el.replaceChildren(wrapper);
|
|
1096
|
-
return wrapper;
|
|
1097
|
-
}
|
|
1098
|
-
function renderError(wrapper, message) {
|
|
1099
|
-
const note = document.createElement("p");
|
|
1100
|
-
note.className = "guidex-error";
|
|
1101
|
-
note.textContent = message;
|
|
1102
|
-
wrapper.replaceChildren(note);
|
|
1103
|
-
}
|
|
1104
|
-
/** The transforms a score renders with: the style set's defaults (BNS
|
|
1105
|
-
* marks the first initial) plus the user-requested transpose. An unknown
|
|
1106
|
-
* style name yields no defaults here — the render itself reports it. */
|
|
1107
|
-
function scriptTransforms(style, transpose) {
|
|
1108
|
-
const transforms = [...STYLE_SETS[style]?.scriptTransforms ?? []];
|
|
1109
|
-
if (transpose !== 0) transforms.push(transposeBy(transpose));
|
|
1110
|
-
return transforms;
|
|
1111
|
-
}
|
|
1112
|
-
/** Renders one target element. The score is built into a detached
|
|
1113
|
-
* scratch wrapper and swapped into the live one only when this run is
|
|
1114
|
-
* still the latest — a stale render that finished late leaves no
|
|
1115
|
-
* footprint. */
|
|
1116
|
-
async function renderElement(el) {
|
|
1117
|
-
const run = (runs.get(el) ?? 0) + 1;
|
|
1118
|
-
runs.set(el, run);
|
|
1119
|
-
const options = readOptions(el);
|
|
1120
|
-
const source = extractSource(el);
|
|
1121
|
-
sources.set(el, source);
|
|
1122
|
-
const wrapper = scoreWrapper(el);
|
|
1123
|
-
const widthPx = resolveWidthPx(el, options.maxWidth, options.style);
|
|
1124
|
-
lastWidths.set(el, widthPx);
|
|
1125
|
-
const scratch = document.createElement("div");
|
|
1126
|
-
const script = new GuidoScript(source, { transforms: scriptTransforms(options.style, options.transpose) });
|
|
1127
|
-
try {
|
|
1128
|
-
await new GuidoRender(script).render(scratch, {
|
|
1129
|
-
style: options.style,
|
|
1130
|
-
bold: options.bold,
|
|
1131
|
-
textPx: options.textPx,
|
|
1132
|
-
debug: options.debug,
|
|
1133
|
-
maxWidthPx: widthPx
|
|
1134
|
-
});
|
|
1135
|
-
if (runs.get(el) !== run) return;
|
|
1136
|
-
wrapper.replaceChildren(...scratch.childNodes);
|
|
1137
|
-
wrapper.style.cssText = scratch.style.cssText;
|
|
1138
|
-
if (scratch.dataset.style) wrapper.dataset.style = scratch.dataset.style;
|
|
1139
|
-
} catch (e) {
|
|
1140
|
-
if (runs.get(el) !== run) return;
|
|
1141
|
-
console.error("[guidex]", e);
|
|
1142
|
-
renderError(wrapper, e instanceof Error ? e.message : String(e));
|
|
1143
|
-
}
|
|
1144
|
-
}
|
|
1145
|
-
/** Sets up one resize listener per target element, on first render.
|
|
1146
|
-
* Only a changed line-breaking budget (width) triggers a re-render. */
|
|
1147
|
-
var detachFns = /* @__PURE__ */ new WeakMap();
|
|
1148
|
-
function widthChanged(el) {
|
|
1149
|
-
const options = readOptions(el);
|
|
1150
|
-
const width = resolveWidthPx(el, options.maxWidth, options.style);
|
|
1151
|
-
return Math.abs(width - (lastWidths.get(el) ?? NaN)) > 1;
|
|
1152
|
-
}
|
|
1153
|
-
function attachResizeListener(el) {
|
|
1154
|
-
if (detachFns.has(el)) return;
|
|
1155
|
-
let detach;
|
|
1156
|
-
if (typeof ResizeObserver !== "undefined") {
|
|
1157
|
-
const observer = new ResizeObserver(() => {
|
|
1158
|
-
if (widthChanged(el)) renderElement(el);
|
|
1159
|
-
});
|
|
1160
|
-
observer.observe(el);
|
|
1161
|
-
detach = () => observer.disconnect();
|
|
1162
|
-
} else {
|
|
1163
|
-
const onResize = () => {
|
|
1164
|
-
if (widthChanged(el)) renderElement(el);
|
|
1165
|
-
};
|
|
1166
|
-
window.addEventListener("resize", onResize);
|
|
1167
|
-
detach = () => window.removeEventListener("resize", onResize);
|
|
1168
|
-
}
|
|
1169
|
-
detachFns.set(el, detach);
|
|
1170
|
-
}
|
|
1171
|
-
/** Cleans up a programmatically rendered element: stops resize
|
|
1172
|
-
* re-rendering and drops the cached source and option overrides. Does
|
|
1173
|
-
* not remove the rendered score itself. */
|
|
1174
|
-
function dispose(el) {
|
|
1175
|
-
detachFns.get(el)?.();
|
|
1176
|
-
detachFns.delete(el);
|
|
1177
|
-
sources.delete(el);
|
|
1178
|
-
overrides.delete(el);
|
|
1179
|
-
runs.delete(el);
|
|
1180
|
-
lastWidths.delete(el);
|
|
1181
|
-
}
|
|
1182
|
-
/** Renders a GuidoScript source string into one element
|
|
1183
|
-
* programmatically — no selector scanning, no site-wide state. The
|
|
1184
|
-
* element's own text content is replaced by the rendered score and
|
|
1185
|
-
* re-rendered on resize. Call again with a new source to update.
|
|
1186
|
-
* Options set here override `init` defaults; data attributes on the
|
|
1187
|
-
* element still win. Resolves when the score has finished rendering. */
|
|
1188
|
-
async function renderScore(el, source, options = {}) {
|
|
1189
|
-
overrides.set(el, options);
|
|
1190
|
-
const run = (runs.get(el) ?? 0) + 1;
|
|
1191
|
-
runs.set(el, run);
|
|
1192
|
-
sources.set(el, source);
|
|
1193
|
-
const resolved = readOptions(el);
|
|
1194
|
-
const wrapper = scoreWrapper(el);
|
|
1195
|
-
const widthPx = resolveWidthPx(el, resolved.maxWidth, resolved.style);
|
|
1196
|
-
lastWidths.set(el, widthPx);
|
|
1197
|
-
attachResizeListener(el);
|
|
1198
|
-
const scratch = document.createElement("div");
|
|
1199
|
-
const script = new GuidoScript(source, { transforms: scriptTransforms(resolved.style, resolved.transpose) });
|
|
1200
|
-
try {
|
|
1201
|
-
await new GuidoRender(script).render(scratch, {
|
|
1202
|
-
style: resolved.style,
|
|
1203
|
-
bold: resolved.bold,
|
|
1204
|
-
textPx: resolved.textPx,
|
|
1205
|
-
debug: resolved.debug,
|
|
1206
|
-
maxWidthPx: widthPx
|
|
1207
|
-
});
|
|
1208
|
-
if (runs.get(el) !== run) return;
|
|
1209
|
-
wrapper.replaceChildren(...scratch.childNodes);
|
|
1210
|
-
wrapper.style.cssText = scratch.style.cssText;
|
|
1211
|
-
if (scratch.dataset.style) wrapper.dataset.style = scratch.dataset.style;
|
|
1212
|
-
} catch (e) {
|
|
1213
|
-
if (runs.get(el) !== run) return;
|
|
1214
|
-
console.error("[guidex]", e);
|
|
1215
|
-
renderError(wrapper, e instanceof Error ? e.message : String(e));
|
|
1216
|
-
}
|
|
1217
|
-
}
|
|
1218
|
-
/** Renders every target under `root` (default: the whole document).
|
|
1219
|
-
* Already-rendered targets re-render from their cached source, so a
|
|
1220
|
-
* host can change data attributes or the source text and call this to
|
|
1221
|
-
* refresh. Resolves when every score has finished rendering. */
|
|
1222
|
-
async function renderAll(root = document) {
|
|
1223
|
-
const selector = globalOptions.selector ?? DEFAULT_SELECTOR;
|
|
1224
|
-
const targets = [];
|
|
1225
|
-
if (root instanceof Element && root.matches(selector)) targets.push(root);
|
|
1226
|
-
targets.push(...root.querySelectorAll(selector));
|
|
1227
|
-
return Promise.all(targets.map((el) => {
|
|
1228
|
-
attachResizeListener(el);
|
|
1229
|
-
return renderElement(el);
|
|
1230
|
-
})).then(() => void 0);
|
|
1231
|
-
}
|
|
1232
|
-
/** Late-added elements (AJAX, SPA routing) render too: document-wide
|
|
1233
|
-
* child mutations are scanned for matching targets. Our own score
|
|
1234
|
-
* elements are skipped, so renders never re-trigger the observer. */
|
|
1235
|
-
var observerStarted = false;
|
|
1236
|
-
function startMutationObserver() {
|
|
1237
|
-
if (observerStarted || typeof MutationObserver === "undefined") return;
|
|
1238
|
-
observerStarted = true;
|
|
1239
|
-
const selector = globalOptions.selector ?? DEFAULT_SELECTOR;
|
|
1240
|
-
new MutationObserver((mutations) => {
|
|
1241
|
-
const targets = /* @__PURE__ */ new Set();
|
|
1242
|
-
for (const mutation of mutations) for (const node of mutation.addedNodes) {
|
|
1243
|
-
if (!(node instanceof Element)) continue;
|
|
1244
|
-
if (node.closest(".guidex-render")) continue;
|
|
1245
|
-
if (node.matches(selector)) targets.add(node);
|
|
1246
|
-
for (const match of node.querySelectorAll(selector)) targets.add(match);
|
|
1247
|
-
}
|
|
1248
|
-
for (const el of targets) {
|
|
1249
|
-
attachResizeListener(el);
|
|
1250
|
-
renderElement(el);
|
|
1251
|
-
}
|
|
1252
|
-
}).observe(document.documentElement, {
|
|
1253
|
-
childList: true,
|
|
1254
|
-
subtree: true
|
|
1255
|
-
});
|
|
1256
|
-
}
|
|
1257
|
-
/** Sets site-wide defaults and renders the document. Call again (even
|
|
1258
|
-
* with different options) to re-render everything with new settings. */
|
|
1259
|
-
function init(options = {}) {
|
|
1260
|
-
globalOptions = {
|
|
1261
|
-
...globalOptions,
|
|
1262
|
-
...options
|
|
1263
|
-
};
|
|
1264
|
-
startMutationObserver();
|
|
1265
|
-
renderAll();
|
|
1266
|
-
}
|
|
1267
|
-
//#endregion
|
|
1268
|
-
export { version as a, GuidoScript as c, renderScore as i, chantText as l, init as n, DEFAULT_STYLE_SET as o, renderAll as r, STYLE_SETS as s, dispose as t, unescape as u };
|