guidex 0.2.1 → 0.2.4

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