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