guidex 0.3.1 → 0.3.2

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 (33) hide show
  1. package/README.md +53 -3
  2. package/dist/lib/app/EditorContext.d.ts +6 -1
  3. package/dist/lib/app/ExactTransposeControls.d.ts +1 -0
  4. package/dist/lib/app/StanzaControls.d.ts +1 -0
  5. package/dist/lib/app/TransposeSettings.d.ts +1 -0
  6. package/dist/lib/app/editorState.d.ts +78 -6
  7. package/dist/lib/app/shareLink.d.ts +22 -0
  8. package/dist/lib/chantLayout-B0xiaMo9.js +2641 -0
  9. package/dist/lib/chantLayout.d.ts +41 -8
  10. package/dist/lib/composeScript.d.ts +71 -0
  11. package/dist/lib/editorStorage.d.ts +6 -0
  12. package/dist/lib/embed/core.d.ts +28 -2
  13. package/dist/lib/embed/index.js +1 -1
  14. package/dist/lib/embed/manual.d.ts +12 -3
  15. package/dist/lib/embed/manual.js +324 -276
  16. package/dist/lib/exactTranspose.d.ts +54 -0
  17. package/dist/lib/glyphFamilies.d.ts +22 -0
  18. package/dist/lib/guidoRender.d.ts +5 -3
  19. package/dist/lib/guidoScript.d.ts +92 -10
  20. package/dist/lib/guidoScriptTransforms.d.ts +19 -7
  21. package/dist/lib/noteGroups.d.ts +22 -0
  22. package/dist/lib/react/GuidexScore.d.ts +19 -1
  23. package/dist/lib/react/index.d.ts +2 -1
  24. package/dist/lib/react/index.js +23 -3
  25. package/dist/lib/{scoreImage-oVBasBX5.js → scoreImage-DSEupCru.js} +102 -51
  26. package/dist/lib/stanzas.d.ts +135 -0
  27. package/dist/lib/word/index.js +1 -1
  28. package/dist/lib/{wordChecker-C3nJrk_j.js → wordChecker-EQx8frRp.js} +97 -45
  29. package/dist/lib/wordClipboard.d.ts +3 -3
  30. package/dist/lib/wordExport.d.ts +9 -5
  31. package/dist-embed/guidex-embed.min.js +1 -1
  32. package/package.json +1 -1
  33. package/dist/lib/chantLayout-GAfg2iKS.js +0 -1042
@@ -0,0 +1,135 @@
1
+ import { GuidoScript, ScriptToken } from './guidoScript';
2
+ import { ScriptTransform } from './guidoScriptTransforms';
3
+ /** One item of a parsed stanza: a sung syllable (with its word end), a
4
+ * hold (a lone `-`: the previous syllable goes on over this slot), or an
5
+ * empty slot (a lone `~`: the stanza sings nothing here). */
6
+ export type StanzaSyllable = {
7
+ kind: 'syllable';
8
+ text: string;
9
+ wordEnd: boolean;
10
+ } | {
11
+ kind: 'hold';
12
+ } | {
13
+ kind: 'empty';
14
+ };
15
+ /** How the slots not every stanza sings are drawn (a hold counts as
16
+ * singing, a missing syllable does not):
17
+ *
18
+ * - `'normal'`: with the notes as written;
19
+ * - `'small'`: with small heads (cue notes) where the rendered stanza
20
+ * leaves the slot empty while another stanza sings it — stacked (issue
21
+ * #84), where no rendered stanza sings it while a stanza left out does;
22
+ * - `'partial'`: with small heads wherever some stanza of the script
23
+ * sings the slot and another does not, whatever is rendered — normal
24
+ * heads only where every stanza sings it. The same notes come out for
25
+ * any stanza or stack.
26
+ *
27
+ * A slot no stanza sings keeps normal heads in every mode. */
28
+ export type EmptySlots = 'normal' | 'small' | 'partial';
29
+ /** The stanzas stacked under one staff (issue #84): every stanza, or the
30
+ * listed ones (1-based) in the given order. */
31
+ export type StanzaStack = 'all' | number[];
32
+ /** A count mismatch of one stanza: a slot it has no syllable for, or a
33
+ * syllable past the last slot (with its text; `-` for a hold, `~` for an
34
+ * empty slot). Stanza and slot are 1-based. */
35
+ export interface StanzaWarning {
36
+ stanza: number;
37
+ slot: number;
38
+ kind: 'missing' | 'extra';
39
+ text?: string;
40
+ message: string;
41
+ }
42
+ export interface StanzaOptions {
43
+ /** Stanzas 2, 3, … as stanza text; replaces the script's own
44
+ * `(@stanza …)` statements when given. */
45
+ stanzas?: string[];
46
+ }
47
+ /** The options of one stanza swap (`selectStanza`, `withStanza`). */
48
+ export interface SelectStanzaOptions extends StanzaOptions {
49
+ emptySlots?: EmptySlots;
50
+ /** The stanzas rendered together with this one (stacked under one
51
+ * staff, issue #84; default: this one alone), for the small-heads
52
+ * rule. */
53
+ rendered?: number[];
54
+ }
55
+ /** The syllable text that marks a slot a stanza is missing a syllable
56
+ * for: a rubric ellipsis, red in BNS, so the mismatch shows in the
57
+ * render (and in the Word export). */
58
+ export declare const STANZA_PLACEHOLDER = "_\u2026_";
59
+ /**
60
+ * Parses stanza text into its slot items, by Aretino's lyric-line rules:
61
+ *
62
+ * - whitespace separates words, `-` separates the syllables of a word
63
+ * (a soft hyphen U+00AD counts as `-`, and so does the mandatory
64
+ * hyphen `=` — the renderer has no hyphen it may not drop yet);
65
+ * - a lone `-` (or an empty syllable, `Al--le`) holds the slot for the
66
+ * syllable before it; that syllable's word end is its own (`Al- - le`
67
+ * is mid-word, `bunt - gen` ends the word);
68
+ * - a lone `~` is an empty slot; `~` inside a syllable is a
69
+ * non-breaking space;
70
+ * - a backslash makes the next character literal (`\-`, `\~`, `\=`,
71
+ * `\(`, `\\`).
72
+ *
73
+ * There are no `_` extenders: `_…_`, `__…__` and `*…*` stay the
74
+ * syllable formatting of the script notation.
75
+ */
76
+ export declare function parseStanza(text: string): StanzaSyllable[];
77
+ /** Whether a token opens a slot: a syllable with notes that are not all
78
+ * markers. */
79
+ export declare function isSlot(tok: ScriptToken): boolean;
80
+ /** The number of slots (note groups that take a stanza syllable). */
81
+ export declare function slotCount(script: GuidoScript | string): number;
82
+ /** The stanza texts of stanzas 2, 3, …: the `stanzas` option when
83
+ * given, the script's `(@stanza …)` statements otherwise. */
84
+ export declare function stanzaTexts(script: GuidoScript | string, options?: StanzaOptions): string[];
85
+ /** How many stanzas the script has, stanza 1 (the script) included. */
86
+ export declare function stanzaCount(script: GuidoScript | string, options?: StanzaOptions): number;
87
+ /** The count mismatches of one stanza (`options.stanza`), or of every
88
+ * stanza when none is named. Stanza 1 is the script and never warns;
89
+ * an intentional `~` is a syllable like any other. */
90
+ export declare function stanzaWarnings(script: GuidoScript | string, options?: StanzaOptions & {
91
+ stanza?: number;
92
+ }): StanzaWarning[];
93
+ /** Pads stanza text with `~` empty slots up to the script's slot count
94
+ * (unchanged when it already has enough syllables). */
95
+ export declare function padStanza(script: GuidoScript | string, text: string): string;
96
+ /** A note group with its plain heads, virgas and longas swapped for small
97
+ * heads (connectors, markers and signs stay). */
98
+ export declare function smallHeads(notes: string): string;
99
+ /** The `selectStanza` transform factory: rewrites the script to sing
100
+ * stanza `stanza` (1-based; 1 is the script itself). Its syllables go on
101
+ * the slots in order — missing ones become `STANZA_PLACEHOLDER`
102
+ * syllables, extra ones are dropped (`stanzaWarnings` reports both) — and
103
+ * the `(@stanza …)` statements are dropped. Everything that is not a
104
+ * slot (statements, syllables without notes, marker-only groups) stays as
105
+ * written. With `emptySlots: 'small'`, a slot the stanza leaves empty
106
+ * while another stanza sings it gets small heads (`rendered` lists the
107
+ * stanzas stacked with it: then a slot gets small heads when none of
108
+ * them sings it while another stanza does). With `emptySlots:
109
+ * 'partial'`, every slot some stanza sings and another does not gets
110
+ * small heads, whatever is rendered. Stanza 1 with normal
111
+ * empty slots returns the source unchanged. Throws a RangeError for a
112
+ * stanza the script does not have. Register it first, so the other
113
+ * transforms (the initial, the transpositions) see the stanza's text. */
114
+ export declare function selectStanza(stanza: number, options?: SelectStanzaOptions): ScriptTransform;
115
+ /** The script singing stanza `stanza` (see `selectStanza`); `transforms`
116
+ * run after the stanza swap. A GuidoScript argument is taken by its
117
+ * (already transformed) source. */
118
+ export declare function withStanza(script: GuidoScript | string, stanza: number, options?: SelectStanzaOptions & {
119
+ transforms?: ScriptTransform[];
120
+ }): GuidoScript;
121
+ /** The stanza numbers a stack names: every stanza for `'all'`, the
122
+ * listed ones otherwise. Throws a RangeError for an empty list or a
123
+ * stanza the script does not have. */
124
+ export declare function stackedStanzaNumbers(script: GuidoScript | string, stack: StanzaStack, options?: StanzaOptions): number[];
125
+ /** The scripts of stacked stanzas (issue #84): one per stanza of the
126
+ * stack, in its order, each singing its stanza on the shared notes (see
127
+ * `withStanza`; `transforms` run after the swap). Hand them to the layout
128
+ * together (`layoutScore`, `GuidoRender`, the Word export) for one text
129
+ * line per stanza under one staff. With `emptySlots: 'small'`, a slot
130
+ * gets small heads when no stacked stanza sings it while a stanza left
131
+ * out of the stack does, so every script carries the same notes. */
132
+ export declare function stackStanzas(script: GuidoScript | string, stack: StanzaStack, options?: StanzaOptions & {
133
+ emptySlots?: EmptySlots;
134
+ transforms?: ScriptTransform[];
135
+ }): GuidoScript[];
@@ -1,2 +1,2 @@
1
- import { a as DEFAULT_TAB_INTERVAL_PT, c as toWordHtml, i as DEFAULT_SPACER, l as toWordText, n as copyWordHtml, o as SpacerMeter, r as copyWordPlainText, s as layoutForWord, t as checkWordHtml, u as wordLayoutText } from "../wordChecker-C3nJrk_j.js";
1
+ import { a as DEFAULT_TAB_INTERVAL_PT, c as toWordHtml, i as DEFAULT_SPACER, l as toWordText, n as copyWordHtml, o as SpacerMeter, r as copyWordPlainText, s as layoutForWord, t as checkWordHtml, u as wordLayoutText } from "../wordChecker-EQx8frRp.js";
2
2
  export { DEFAULT_SPACER, DEFAULT_TAB_INTERVAL_PT, SpacerMeter, checkWordHtml, copyWordHtml, copyWordPlainText, layoutForWord, toWordHtml, toWordText, wordLayoutText };
@@ -1,5 +1,49 @@
1
- import { a as measure, i as layoutScore, l as measurementFont, n as SCORE_MARKERS, r as SPECIAL_NOTES, t as NOTE_MODIFIERS } from "./chantLayout-GAfg2iKS.js";
1
+ import { B as CLEF_GLYPHS, M as SCORE_MARKERS, c as measurementFont, i as measure, n as SPECIAL_NOTES, r as layoutScore, t as NOTE_MODIFIERS } from "./chantLayout-B0xiaMo9.js";
2
2
  //#region src/wordExport.ts
3
+ /**
4
+ * Word-compatible export: turns the shared layout (chantLayout.ts) into
5
+ * Word-flavoured HTML that pastes into Microsoft Word as alternating
6
+ * `BNS-nota` / `BNS-textus` paragraphs with the notes over their
7
+ * syllables.
8
+ *
9
+ * Word cannot consume the DOM renderer's positioned spacer spans, so every
10
+ * horizontal gap — lead-in, word gaps, syllable junctions alike — is faked
11
+ * by ONE spacer mechanism: a run of `unit × count` spacer characters. Two
12
+ * independent configuration axes tune it: the spacer character (tab, en,
13
+ * em, nbsp, simple space, or custom) and its width (tab-interval for tabs;
14
+ * scale, absolute width, or condensed/expanded letter-spacing for space
15
+ * characters — the latter stays tunable inside Word after pasting).
16
+ *
17
+ * The accounting is self-correcting: the export tracks the emitted position
18
+ * along the line and computes each gap as
19
+ * `count = max(0, round((next ideal anchor − emitted position) ÷ unit))` —
20
+ * never `round(gap ÷ unit)` per gap. An overshoot in one gap is absorbed by
21
+ * the next (possibly to zero), so every syllable anchor lands within ½ unit
22
+ * of its ideal and error never accumulates. Tab stops in Word are absolute
23
+ * positions, so the tab strategy snaps the emitted position onto the
24
+ * interval grid — the absolute-grid version of the same guarantee.
25
+ *
26
+ * Two error sources remain by nature and are named as such: quantization
27
+ * (≤ ½ unit per anchor, bounded, non-accumulating) and Word's font metrics
28
+ * differing from our canvas measurements — the latter is what width tuning
29
+ * and the checker's gap census (wordChecker.ts) address.
30
+ *
31
+ * The layout can run at the preview's px sizes (textPx/notesPx/maxWidthPx)
32
+ * or at the destination document's true Word sizes (textPt/notesPt/
33
+ * maxWidthPt, which take precedence — px = pt × 4/3). Destination sizing
34
+ * is what a real round-trip wants: Word renders the pasted styles at the
35
+ * destination's own pt sizes regardless of the web preview, so laying out
36
+ * at those same sizes makes the width tuning converge on the true grid
37
+ * (a tab unit of 0.5 mm really is 0.5 mm) and the line breaks match the
38
+ * destination column rather than the preview.
39
+ *
40
+ * The default spacer is a no-break space at its natural advance: the
41
+ * natural advance is proportional to the font size — size-invariant under
42
+ * Word's rendering — and plain characters survive any paste path (no
43
+ * mso machinery to lose). Tabs tune to an absolute interval grid; plain
44
+ * spaces (mso-spacerun:yes) are the fragile choice, kept for parity with
45
+ * the old workflow.
46
+ */
3
47
  var PT_PER_PX = .75;
4
48
  var PX_PER_PT = 4 / 3;
5
49
  /** Exact line heights in the target document: 1.2 × the font size, the
@@ -225,9 +269,10 @@ function walkTextLine(line, meter, pieces) {
225
269
  return out;
226
270
  }
227
271
  /** The notes line's raw Guido text: the renderer's own notes model is
228
- * already the Word representation. */
229
- function notesText(layout, line) {
230
- return layout.clefPrefix + line.notesParts.join("");
272
+ * already the Word representation. Each line opens with the clef and key
273
+ * in effect at its start. */
274
+ function notesText(line) {
275
+ return line.clefPrefix + line.notesParts.join("");
231
276
  }
232
277
  /** Spaces faking one tab's width for browser display; Word reads the
233
278
  * mso-tab-count, not the padding. */
@@ -301,8 +346,8 @@ async function toWordHtml(source, options = {}) {
301
346
  for (const line of layout.lines) {
302
347
  const markerStop = line.breakMarkerLeftPx !== void 0 && layout.maxWidthPx === Infinity ? ` style="tab-stops:right ${fmtPt((line.notesEnd + line.breakMarkerLeftPx + layout.starWidth) * PT_PER_PX)}pt"` : "";
303
348
  const marker = line.breakMarkerLeftPx !== void 0 ? `<span style="mso-tab-count:1">${" ".repeat(Math.max(1, Math.round((line.breakMarkerLeftPx + layout.starWidth) / spacePx)))}</span>*` : "";
304
- paragraphs.push(`<p class="${notaClass}"${markerStop}><span style="letter-spacing:-.1pt">${escapeHtml(notesText(layout, line))}</span>${marker}</p>`);
305
- paragraphs.push(`<p class="${textusClass}">` + walkTextLine(line, meter, {
349
+ paragraphs.push(`<p class="${notaClass}"${markerStop}><span style="letter-spacing:-.1pt">${escapeHtml(notesText(line))}</span>${marker}</p>`);
350
+ for (const text of line.texts) paragraphs.push(`<p class="${textusClass}">` + walkTextLine(text, meter, {
306
351
  spacer: spacerHtml,
307
352
  dash: () => "-",
308
353
  syl: (seg) => sylHtml(seg, layout.textPx)
@@ -401,45 +446,50 @@ async function layoutForWord(source, options = {}) {
401
446
  const notesPt = layout.notesPx * PT_PER_PX;
402
447
  const textPt = layout.textPx * PT_PER_PX;
403
448
  const finite = layout.maxWidthPx !== Infinity;
449
+ const textPieces = (line) => {
450
+ const text = [];
451
+ let emitted = 0;
452
+ const spacerTo = (targetPx) => {
453
+ const { count, emittedPx } = meter.advance(targetPx, emitted);
454
+ emitted = emittedPx;
455
+ if (count > 0) text.push({
456
+ type: "spacer",
457
+ count,
458
+ endPt: emitted * PT_PER_PX
459
+ });
460
+ };
461
+ for (const seg of line.segments) switch (seg.kind) {
462
+ case "gap":
463
+ spacerTo(seg.endPx);
464
+ break;
465
+ case "connector":
466
+ case "line-end-dash":
467
+ spacerTo(seg.dashStartPx);
468
+ text.push({ type: "dash" });
469
+ emitted += seg.dashWidth;
470
+ spacerTo(seg.kind === "connector" ? seg.nextAnchorPx : seg.trailEndPx);
471
+ break;
472
+ case "syl":
473
+ for (const part of seg.parts) for (const run of wordRuns(part, layout.textPx)) text.push({
474
+ type: "run",
475
+ run
476
+ });
477
+ emitted += seg.textWidth;
478
+ break;
479
+ case "word-space":
480
+ text.push({ type: "space" });
481
+ emitted += seg.width;
482
+ }
483
+ return text;
484
+ };
404
485
  return {
405
486
  lines: layout.lines.map((line) => {
406
- const text = [];
407
- let emitted = 0;
408
- const spacerTo = (targetPx) => {
409
- const { count, emittedPx } = meter.advance(targetPx, emitted);
410
- emitted = emittedPx;
411
- if (count > 0) text.push({
412
- type: "spacer",
413
- count,
414
- endPt: emitted * PT_PER_PX
415
- });
416
- };
417
- for (const seg of line.segments) switch (seg.kind) {
418
- case "gap":
419
- spacerTo(seg.endPx);
420
- break;
421
- case "connector":
422
- case "line-end-dash":
423
- spacerTo(seg.dashStartPx);
424
- text.push({ type: "dash" });
425
- emitted += seg.dashWidth;
426
- spacerTo(seg.kind === "connector" ? seg.nextAnchorPx : seg.trailEndPx);
427
- break;
428
- case "syl":
429
- for (const part of seg.parts) for (const run of wordRuns(part, layout.textPx)) text.push({
430
- type: "run",
431
- run
432
- });
433
- emitted += seg.textWidth;
434
- break;
435
- case "word-space":
436
- text.push({ type: "space" });
437
- emitted += seg.width;
438
- }
487
+ const texts = line.texts.map(textPieces);
439
488
  const out = {
440
- notes: notesText(layout, line),
489
+ notes: notesText(line),
441
490
  breakMarker: line.breakMarkerLeftPx !== void 0,
442
- text
491
+ text: texts[0],
492
+ texts
443
493
  };
444
494
  if (line.breakMarkerLeftPx !== void 0) out.breakMarkerTabStopPt = finite ? layout.starTarget * PT_PER_PX : (line.notesEnd + line.breakMarkerLeftPx + layout.starWidth) * PT_PER_PX;
445
495
  return out;
@@ -475,7 +525,7 @@ function wordLayoutText(layout) {
475
525
  case "space": return " ";
476
526
  }
477
527
  };
478
- return layout.lines.flatMap((line) => [line.notes + (line.breakMarker ? " *" : ""), line.text.map(pieceText).join("")]).join("\n");
528
+ return layout.lines.flatMap((line) => [line.notes + (line.breakMarker ? " *" : ""), ...line.texts.map((text) => text.map(pieceText).join(""))]).join("\n");
479
529
  }
480
530
  /**
481
531
  * Renders the score as the plain-text equivalent of the Word export: the
@@ -569,7 +619,8 @@ async function copyPlainText(text) {
569
619
  * - class check: every character classified into its expected role — the
570
620
  * Guido HU neume repertoire on notes lines, text characters and marker
571
621
  * glyphs on text lines — with unknown characters reported at position;
572
- * - construction check: alternating nota/textus paragraphs, a clef
622
+ * - construction check: alternating nota/textus paragraphs (one or more
623
+ * textus per nota, for stacked stanzas), a clef
573
624
  * starting each notes line, legal group syntax, spacer structure, and
574
625
  * the tab + `*` break marker on broken notes lines;
575
626
  * - gap census: which spacer mechanism the pasted text uses and the
@@ -643,6 +694,7 @@ function buildNotesRepertoire() {
643
694
  for (const c of SCORE_MARKERS) chars.add(c);
644
695
  for (const c of SPECIAL_NOTES) chars.add(c);
645
696
  for (const c of NOTE_MODIFIERS) chars.add(c);
697
+ for (const c of Object.keys(CLEF_GLYPHS)) chars.add(c);
646
698
  for (let i = 0; i < 10; i++) chars.add(String(i));
647
699
  for (let i = 0; i < 26; i++) {
648
700
  chars.add(String.fromCharCode(97 + i));
@@ -920,7 +972,7 @@ function checkWordHtml(html) {
920
972
  }
921
973
  const prev = paragraphs[i - 1];
922
974
  if (i === 0 && para.kind !== "nota") error("The first paragraph must be the notes line (the nota style)", i);
923
- if (prev && prev.kind === para.kind) error(`Paragraphs ${i} and ${i + 1} are both ${para.kind} — the notes and text lines must alternate`, i);
975
+ if (prev && prev.kind === "nota" && para.kind === "nota") error(`Paragraphs ${i} and ${i + 1} are both nota — the notes and text lines must alternate`, i);
924
976
  });
925
977
  paragraphs.forEach((para, i) => {
926
978
  if (para.kind !== "nota") return;
@@ -984,7 +1036,7 @@ function checkNotesParagraph(para, error, warn) {
984
1036
  warn("Empty notes line", para.index);
985
1037
  return;
986
1038
  }
987
- if (!/[A-Za-z<=]/.test(text[0])) error(`Notes line does not start with a clef (found ${JSON.stringify(text[0])})`, para.index, 0);
1039
+ if (!/[A-Za-z<=]/.test(text[0]) && !Object.hasOwn(CLEF_GLYPHS, text[0])) error(`Notes line does not start with a clef (found ${JSON.stringify(text[0])})`, para.index, 0);
988
1040
  const isNotesWhitespace = (ch) => ch === " " || ch === "\xA0" || ch === " ";
989
1041
  const MARKER_TAIL = /* @__PURE__ */ new Set([
990
1042
  ...SCORE_MARKERS,
@@ -1,4 +1,4 @@
1
- import { GuidoScript } from './guidoScript';
1
+ import { LayoutSource } from './chantLayout';
2
2
  import { WordExportOptions } from './wordExport';
3
3
  export interface CopyResult {
4
4
  /** The Word-flavoured HTML document (the text/html flavour) */
@@ -11,12 +11,12 @@ export interface CopyResult {
11
11
  * with text/plain as the fallback flavour. Returns what was prepared.
12
12
  * Throws when no clipboard path works.
13
13
  */
14
- export declare function copyWordHtml(source: GuidoScript | string, options?: WordExportOptions): Promise<CopyResult>;
14
+ export declare function copyWordHtml(source: LayoutSource, options?: WordExportOptions): Promise<CopyResult>;
15
15
  /**
16
16
  * The deliberate plain-text-only copy: the same layout and spacer counts
17
17
  * without the HTML envelope, for workflows that want the raw text.
18
18
  */
19
- export declare function copyWordPlainText(source: GuidoScript | string, options?: WordExportOptions): Promise<string>;
19
+ export declare function copyWordPlainText(source: LayoutSource, options?: WordExportOptions): Promise<string>;
20
20
  /**
21
21
  * Copies raw text with no export flavour — the same write path as the
22
22
  * Word copy's plain fallback, for copies of the script source itself.
@@ -1,5 +1,5 @@
1
- import { GuidoScript } from './guidoScript';
2
1
  import { ChantRunKind, StyleSetName } from './guidoStyles';
2
+ import { LayoutSource } from './chantLayout';
3
3
  /** The spacer character faking every horizontal gap. A custom character
4
4
  * (any non-empty string) is emitted verbatim. */
5
5
  export type SpacerChar = 'tab' | 'en' | 'em' | 'nbsp' | 'space' | (string & {});
@@ -122,7 +122,7 @@ export declare class SpacerMeter {
122
122
  * at finite width; an inline per-line stop at natural width, where no
123
123
  * shared star target exists).
124
124
  */
125
- export declare function toWordHtml(source: GuidoScript | string, options?: WordExportOptions): Promise<string>;
125
+ export declare function toWordHtml(source: LayoutSource, options?: WordExportOptions): Promise<string>;
126
126
  /** One styled syllable run of a structured Word text line, resolved to
127
127
  * Word's terms: absent fields inherit the textus paragraph style. */
128
128
  export interface WordRun {
@@ -185,8 +185,12 @@ export interface WordLine {
185
185
  * shared style stop at finite width, a per-line stop at natural
186
186
  * width; absent without a break marker */
187
187
  breakMarkerTabStopPt?: number;
188
- /** The text paragraph, gaps faked by spacer counts */
188
+ /** The text paragraph, gaps faked by spacer counts (the first of
189
+ * `texts`) */
189
190
  text: WordTextPiece[];
191
+ /** Every text paragraph under the notes, one per stacked stanza
192
+ * (issue #84) in order; a single stanza's is `[text]` */
193
+ texts: WordTextPiece[][];
190
194
  }
191
195
  /** The structured Word layout: everything toWordHtml emits, as data, for
192
196
  * consumers building Word documents directly (e.g. the `docx` library). */
@@ -231,7 +235,7 @@ export interface WordLayout {
231
235
  *
232
236
  * Browser-only: the layout measures with canvas and loaded webfonts.
233
237
  */
234
- export declare function layoutForWord(source: GuidoScript | string, options?: WordExportOptions): Promise<WordLayout>;
238
+ export declare function layoutForWord(source: LayoutSource, options?: WordExportOptions): Promise<WordLayout>;
235
239
  /** Serializes a structured Word layout to the plain-text export:
236
240
  * alternating notes / text lines, `\t*` after broken notes lines. */
237
241
  export declare function wordLayoutText(layout: WordLayout): string;
@@ -241,4 +245,4 @@ export declare function wordLayoutText(layout: WordLayout): string;
241
245
  * envelope, no letter-spacing tuning, and no mso runs. The clipboard
242
246
  * writer sends this as the text/plain fallback.
243
247
  */
244
- export declare function toWordText(source: GuidoScript | string, options?: WordExportOptions): Promise<string>;
248
+ export declare function toWordText(source: LayoutSource, options?: WordExportOptions): Promise<string>;
@@ -1 +1 @@
1
- var GuidexEmbed=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});function t(e){return e.trim().startsWith(`@`)}var n=class{source;constructor(e,t={}){this.source=(t.transforms??[]).reduce((e,t)=>t.apply(e),e)}get clef(){let e=this.normalized.match(/^\s*\(([^)]*)\)/);if(!(!e||t(e[1])))return e[1]}get tokens(){let e=this.normalized,n=e.match(/^\s*\(([^)]*)\)/),i=[...(n&&!t(n[1])?e.slice(n[0].length):e).matchAll(/((?:[^()\\]|\\.)*)\(((?:[^)\\]|\\.)*)\)/g)].map(([,e,n])=>{if(t(n)){let t=n.trim();if(t!==`@break`)throw Error(`Unknown statement "${t}"`);if(e.trim()!==``)throw Error(`statement must not carry syllable text: "${r(e.trim())}"`);return{kind:`break`,spaceBefore:/^\s/.test(e)}}return{kind:`syllable`,text:r(e.trim()),notes:r(n),spaceBefore:/^\s/.test(e)}}),a=i.reduce((e,t,n)=>t.kind===`syllable`?n:e,-1);for(let[e,t]of i.entries())if(t.kind===`syllable`){t.wordEnd=e===a;for(let n=e+1;!t.wordEnd&&n<i.length;n++){let e=i[n];if(e.spaceBefore&&(t.wordEnd=!0),e.kind===`syllable`)break}}return i}get syllables(){return this.tokens.filter(e=>e.kind===`syllable`).map(({text:e,notes:t,wordEnd:n})=>({text:e,notes:t,wordEnd:n}))}get normalized(){let e=this.source;return(e.match(/(^|[^\\])\(/g)??[]).length>(e.match(/(^|[^\\])\)/g)??[]).length&&(e+=`)`),/(^|[^\\])\)$/.test(e)||(e+=`()`),e}get words(){let e=[],t;for(let n of this.syllables)t??={text:``,syllables:[]},t.syllables.push({text:n.text,notes:n.notes}),t.text=t.syllables.map(e=>e.text).join(``),n.wordEnd&&(e.push(t),t=void 0);return e}toString(){let e=this.tokens.map((e,t)=>{let n=t>0&&e.spaceBefore?` `:``;return e.kind===`break`?`${n}(@break)`:`${n}${i(e.text)}(${i(e.notes)})`});return`${this.clef===void 0?``:`(${this.clef})`}${e.join(``)}`}};function r(e){return e.replace(/\\(.)/g,`$1`)}function i(e){return e.replace(/\\/g,`\\\\`).replace(/[()]/g,e=>`\\${e}`)}function a(e){let t=[...e];for(let e=0;e<t.length;e++){let n=t[e];if(!/\s/.test(n))return{unit:n===`\\`&&t[e+1]!==void 0?n+t[e+1]:n,index:e}}return null}function o(e){let n=e.match(/^\s*\(([^)]*)\)/),i=n?n[0].length:0,o=e.slice(i);for(let n of o.matchAll(/((?:[^()\\]|\\.)*)\(((?:[^)\\]|\\.)*)\)/g)){let[,o,s]=n;if(r(s).trim().length===0||t(s))continue;let c=a(o);if(!c||o.trimStart().startsWith(`*`))return e;let l=i+n.index+c.index,u=l+c.unit.length;return`${e.slice(0,l)}*${e.slice(l,u)}*${e.slice(u)}`}return e}var s={startWithInitial:{name:`startWithInitial`,apply:o}},c=[`ðñ0123456789öüó`,`^]qwertzuiopõú`,`ÝÞQWERTZUIOPÕÚ`,`×sdfghjkléáû`,`ØÙDFGHJKLÉÁÛ`,`÷øaASÍYXCVBN$m`,`ÈÊËÌÎÏÐÑÒþßòôùý`,`“”•–—˜™š›œº»`,`®−§ÿ"+!%/=()ÖÜÓ`,`Ÿ¡¢£[¥¦©ª«¬`,`~¯‚ƒ„…†‡ˆ‰Š‹Œ‘’`,`àâãäåæçèêëìîï`,`½°±²³´μ·¾¸¹`];function l(e,t,n){for(let r of c){let i=r.indexOf(e);if(i===-1)continue;let a=i+t;return a<0||a>=r.length?n===`null`?`\0`:r[Math.max(0,Math.min(r.length-1,a))]:r[a]}}function u(e,t,n){let r=``;for(let i=0;i<e.length;i++){let a=e[i],o=a===`\\`&&e[i+1]!==void 0,s=l(o?e[i+1]:a,t,n);if(s===void 0){r+=o?a+e[i+1]:a,o&&i++;continue}r+=`\\()`.includes(s)?`\\${s}`:s,o&&i++}return r}function d(e,n={}){let r=n.overflow??`clamp`;return{name:`transpose`,apply:n=>{if(e===0)return n;let i=n.match(/^\s*\(([^)]*)\)/),a=i?i[0].length:0;return n.slice(0,a)+n.slice(a).replace(/((?:[^()\\]|\\.)*)\(((?:[^)\\]|\\.)*)\)/g,(n,i,a)=>t(a)?`${i}(${a})`:`${i}(${u(a,e,r)})`)}}}var f=new Set([`*`,`†`]),p={chars:f,fontFamily:`'Times New Roman', Times, serif`},m={weight:`400`,scale:.7,raise:.2},h={BNS:{textFontStack:`'Book Antiqua', Georgia, serif`,notesFontStack:`'Guidohu'`,markerGlyphs:p,verifiedFonts:[{family:`'Book Antiqua'`,weight:`400`},{family:`'Book Antiqua'`,weight:`700`},{family:`'Guidohu'`,weight:`400`},{family:`'Liturgy'`,weight:`700`}],decorations:{__:{fontFamily:`'Liturgy', serif`,weight:`700`,color:`var(--red)`},_:{uppercase:!0,scale:.7,color:`var(--red)`},"*":{weight:`700`,color:`var(--red)`,initial:!0}},specialStarStyle:{fontFamily:p.fontFamily,weight:`700`,scale:1,measureScale:.95,raise:.1,color:`var(--red)`},padding:12,scriptTransforms:[s.startWithInitial]},Vesperale:{textFontStack:`'Times New Roman', Times, serif`,notesFontStack:`'Guidohu'`,verifiedFonts:[{family:`'Times New Roman', Times, serif`,weight:`400`},{family:`'Times New Roman', Times, serif`,weight:`700`},{family:`'Guidohu'`,weight:`400`},{family:`'Liturgy'`,weight:`700`}],decorations:{__:{fontFamily:`'Liturgy', serif`,weight:`700`},_:{scale:.8,italic:!0},"*":{weight:`700`,initial:!0}},specialStarStyle:{fontFamily:p.fontFamily,weight:`700`,scale:1,measureScale:.95,raise:.2},padding:12,scriptTransforms:[]}};function g(e,t,n,r={}){if(e.length===0)return[];if(e===`**`)return[{text:`∗`,style:{...t.specialStarStyle},kind:`star`}];let i=e,a={},o;for(let n of[`__`,`_`]){let r=t.decorations[n];if(r&&e.length>=n.length*2+1&&e.startsWith(n)&&e.endsWith(n)){i=e.slice(n.length,-n.length),a={...r},o=n===`__`?`liturgy`:`rubric`;break}}let s=t.decorations[`*`],c=[],l=i,u=``;for(let e=/\*([^*]+)\*/.exec(l);e;e=/\*([^*]+)\*/.exec(l))u+=l.slice(0,e.index),u&&=(c.push({text:u,marked:!1}),``),c.push({text:e[1],marked:!0}),l=l.slice(e.index+e[0].length);u+=l,u&&c.push({text:u,marked:!1});let d=c.map(({text:e,marked:t})=>({text:e,style:t?{...a,...s,initial:!0}:{...a},kind:o})),p=t.markerGlyphs,h=[];for(let e of d){e.style.uppercase&&!r.rawCase&&(e.text=e.text.toUpperCase()),n&&(e.style={...e.style,weight:`700`});let t=[...e.text],i=e.style.fontFamily?.includes(`Liturgy`)??!1,a=e=>f.has(e)||p&&p.chars.has(e)?`marker`:i&&e===`+`?`plus`:`text`;if(t.every(e=>a(e)===`text`)){h.push({text:e.text,style:{...e.style},kind:e.kind});continue}let o=``,s=null,c=()=>{if(!o)return;let t={...e.style},n=e.kind;s===`marker`?(n=`marker`,p&&p.chars.has(o[0])&&(t={...t,fontFamily:p.fontFamily})):s===`plus`&&(t={...t,...m},n=`plus`),h.push({text:o,style:t,kind:n}),o=``};for(let e of t){let t=a(e);t!==s&&c(),s=t,o+=e}c()}return h}function _(e,t,n){return[e.italic?`italic`:`normal`,`normal`,e.weight??`400`,`${t*(e.measureScale??e.scale??1)}px`,e.fontFamily??n].join(` `)}function v(e,t){let n={};return e.fontFamily&&(n[`font-family`]=e.fontFamily),e.weight&&(n[`font-weight`]=e.weight),e.italic&&(n[`font-style`]=`italic`),e.scale!==void 0&&(n[`font-size`]=`${t*e.scale}px`),e.color&&(n.color=e.color),e.raise&&(n.position=`relative`,n.top=`${-t*e.raise}px`),n}function y(e,t){return e.verifiedFonts.map(e=>`${e.weight} ${t}px ${e.family}`)}var b=new Set(`,.:?'"+!%/=()ÖÜÓ;`.split(``)),x=new Set(`Ÿ¡¢£[¥¦©ª«¬`.split(``)),ee=new Set(`÷øaASÍYXCVBN$mÈÊËÌÎÏÐÑÒþßòôùý“”•–—˜™š›œº»`.split(``)),S=[`-`,`¨`];function C(e){let t=0;for(;t<e.length&&b.has(e[t]);)t++;t>0&&t<e.length&&e[t]===`-`&&t++;let n=e.length;for(;n>t&&b.has(e[n-1]);)n--;return n<e.length&&n>t&&e[n-1]===`-`&&n--,{leading:e.slice(0,t),core:e.slice(t,n),trailing:e.slice(n)}}var w=null;function T(e,t){return w||=document.createElement(`canvas`).getContext(`2d`),w.font=t,w.measureText(e).width}function te(e,t){w||=document.createElement(`canvas`).getContext(`2d`),w.font=t;let n=w.measureText(e);return{left:n.actualBoundingBoxLeft,right:n.actualBoundingBoxRight}}async function E(e,t={}){let{style:r=`BNS`,bold:i=!1,textPx:a=18,notesPx:o=a*2,maxWidthPx:s=1/0}=t,c=typeof e==`string`?new n(e):e,l=h[r];if(!l)throw Error(`Unknown style set: "${r}"`);for(let e of y(l,a)){try{await document.fonts.load(e)}catch{}if(!document.fonts.check(e))throw Error(`Font could not be loaded: ${e} (style "${r}")`)}let u=`400 ${o}px ${l.notesFontStack}`,d=l.textFontStack,f=_({weight:i?`700`:`400`},a,d),p=e=>g(e,l,i),m=e=>e.reduce((e,t)=>e+T(t.text,_(t.style,a,d)),0),v=T(`-`,u),w=T(`-`,f),E=c.clef===void 0?``:`${c.clef}-`,D=[],O,k,A,j,M=!1,N=[],P=()=>{O&&(O.textCursor=A,O.notesEnd=O.notesParts.length?T(E+O.notesParts.join(``),u):0),O={notesParts:[],segments:[],textCursor:0,notesEnd:0,lastWordEnd:null},D.push(O),k=E,A=0,j=!1,M=!1};P();let F=c.tokens,I=F.filter(e=>e.kind===`syllable`),L=[],R=0;for(let e of F)e.kind===`break`?L.push({kind:`break`}):L.push({kind:`syl`,syl:e,i:R++,text:e.text,notes:e.notes,first:!0,lastSeg:!0});let z=(e,t,n)=>{for(let r=e.length-1;r>0;r--){if(!S.includes(e[r]))continue;let i=r+1;for(;i<e.length&&b.has(e[i]);)i++;if(!(i>=e.length)&&n(e.slice(0,i))<=t)return r}return-1},B=(e,t)=>{let n=e.notes,r=t+1;for(;r<n.length&&b.has(n[r]);)r++;return e.notes=n.slice(0,t)+n.slice(t+1,r),n.slice(r)},V=(e,t,n)=>{e.lastSeg=!1,L.splice(t+1,0,{kind:`syl`,syl:e.syl,i:e.i,text:``,notes:n,first:!1,lastSeg:!0}),H=!0},ne=e=>{for(;N.length>0;){let t=N[0];if(A>0&&A+t.textWidth+(t.wordEnd?0:w)>s){P();continue}N.shift(),O.segments.push({kind:`syl`,parts:t.sylParts,textStart:A,textWidth:t.textWidth,contentWidth:0,contentStart:0,extraDashes:0,tight:!1,noNotes:!0,...e&&N.length===0?{trailing:!0}:{}}),A+=t.textWidth,t.spaceWidth>0&&(O.segments.push({kind:`word-space`,width:t.spaceWidth}),A+=t.spaceWidth),O.lastWordEnd=t.wordEnd,O.textCursor=A}},H=!1,U,W=0;for(;W<L.length;){let e=L[W];if(e.kind===`break`){(O.segments.length>0||N.length>0)&&(ne(!1),H=!0),W++;continue}let t=e.syl,n=e.i;H&&=(P(),!1);let r=e.lastSeg&&n===I.length-1,i=e.text,a=p(i),o=m(a),c=!r&&t.wordEnd?T(` `,f):0,l=N.reduce((e,t)=>e+t.textWidth+t.spaceWidth,0),d=t.notes.length===1&&x.has(t.notes),h=A===0||A+l+o+(t.wordEnd?0:w)<=s;if(t.notes.length===0){N.push({sylParts:a,textWidth:o,spaceWidth:c,wordEnd:t.wordEnd}),W++;continue}if(e.first&&e.lastSeg&&t.text.trim()===``&&C(t.notes).core===``){let e=k[k.length-1],n=e&&e!==`-`&&!b.has(e)&&!t.notes.startsWith(`-`)?`-`:``;O.notesParts.push(n+t.notes),k+=n+t.notes,j=!0,M=!1,U=t.wordEnd,W++;continue}let g=I[n-1]?.notes!==t.notes;if(d&&!g&&O.notesParts.length>0&&!h&&P(),!e.first){for(;!(T(k+e.notes,u)<=s);){let t=z(e.notes,s,e=>T(k+e,u));if(t<0||t+1>=e.notes.length)break;let n=B(e,t);V(e,W,n)}let n=C(e.notes);O.notesParts.push(e.notes),k+=e.notes,e.lastSeg&&(j=n.trailing.length>0),O.lastWordEnd=!0,U=t.wordEnd,e.lastSeg||(H=!0),W++;continue}let _=C(e.notes),y=O.notesParts.length===0||M?``:j||ee.has(_.core[0])?`--`:`---`,S=(e=0)=>{let t=0;for(;t<_.core.length&&ee.has(_.core[t]);)t++;t===_.core.length&&(t=0);let n=_.core.slice(t),r=T(n,u),i=T(k+y+`-`.repeat(e)+_.leading+_.core.slice(0,t),u),a=te(n,u),s=-a.left,c=(a.right-a.left)/2;return{contentWidth:r,contentStart:i,textStart:r>=o||d?i+s:i+c-o/2}},{contentWidth:E,contentStart:D,textStart:F}=S();for(;;){let n=T(k+y+e.notes,u)>s,r=F+o+(t.wordEnd?0:w)>s;if(!n&&!r)break;if(n){let t=z(e.notes,s,e=>T(k+y+e,u));if(t>=0&&t+1<e.notes.length){let n=B(e,t);V(e,W,n),_=C(e.notes),{contentWidth:E,contentStart:D,textStart:F}=S();break}}if(O.notesParts.length===0&&A===0){if(n){let t=z(e.notes,s,e=>T(k+e,u));if(t>=0&&t+1<e.notes.length){let n=B(e,t);e.notes=e.notes.slice(0,t),V(e,W,n),_=C(e.notes),{contentWidth:E,contentStart:D,textStart:F}=S()}}break}P(),y=``,{contentWidth:E,contentStart:D,textStart:F}=S()}let R=O.notesParts.length>0&&!U&&l===0,G=A+w,K=A+l+(M&&R?w:0),q=y+e.notes,J=0,Y=!1,X=t=>{J=t,q=y+`-`.repeat(t)+e.notes,{contentWidth:E,contentStart:D,textStart:F}=S(t)},Z=d&&!g&&O.notesParts.length>0;if(Z){y=``,F=A+l;let t=F+o+c-T(k,u),n=s-T(k+y,u),r=t>0?Math.min(Math.ceil(t/v),Math.max(0,Math.floor(n/v))):0;e.notes=`-`.repeat(r),_=C(e.notes),q=y+e.notes,Y=R}if(!Z){if(!M&&R&&F<G&&(o>E||F<A)){Y=!0,F=A;let t=E>=o?F:F+(o-E)/2;t>D&&(J=Math.round((t-D)/v),q=y+`-`.repeat(J)+e.notes)}else if(F<K){let t=E>=o?K:K+(o-E)/2;if(t>D){let n=Math.max(0,Math.floor((t-D)/v));for(X(n);F<K;)n++,X(n);if(O.notesParts.length>0&&T(k+q,u)>s&&(P(),y=``,q=y+e.notes,J=0,{contentWidth:E,contentStart:D,textStart:F}=S(),F<A+l)){let e=E>=o?A+l:A+l+(o-E)/2;if(e>D){let t=Math.max(0,Math.floor((e-D)/v));for(X(t);F<A+l;)t++,X(t)}}}}}l>0&&F<A+l&&(F=A+l);let Q=Math.max(0,F-l-A);if(O.notesParts.length===0)O.segments.push({kind:`gap`,role:`lead-in`,width:Q,endPx:F-l,textStartPx:F});else if(U)O.segments.push({kind:`gap`,role:`word-gap`,width:Q,endPx:F-l,textStartPx:F});else if(!(l===0&&Y)&&l===0){let e=Math.max(0,(Q-w)/2);O.segments.push({kind:`connector`,pad:e,gapWidth:Q,dashWidth:w,dashStartPx:A+e,nextAnchorPx:F})}let $=F-l;for(let e of N)O.segments.push({kind:`syl`,parts:e.sylParts,textStart:$,textWidth:e.textWidth,contentWidth:0,contentStart:0,extraDashes:0,tight:!1,noNotes:!0}),$+=e.textWidth,e.spaceWidth>0&&(O.segments.push({kind:`word-space`,width:e.spaceWidth}),$+=e.spaceWidth);N=[],O.segments.push({kind:`syl`,parts:a,textStart:F,textWidth:o,contentWidth:E,contentStart:D,extraDashes:J,tight:Y,noNotes:!1}),c>0&&O.segments.push({kind:`word-space`,width:c}),A=F+o+c,k+=q,O.notesParts.push(q),O.lastWordEnd=t.wordEnd,U=t.wordEnd,e.lastSeg&&(j=_.trailing.length>0,M=d),e.lastSeg||(H=!0),W++}ne(!0),O.textCursor=A,O.notesEnd=O.notesParts.length?T(E+O.notesParts.join(``),u):0,D.forEach((e,t)=>{if(t===D.length-1||e.lastWordEnd!==!1)return;let n=e.notesEnd>e.textCursor?Math.max(0,(e.notesEnd-e.textCursor-w)/2):0;e.segments.push({kind:`line-end-dash`,pad:n,dashWidth:w,dashStartPx:e.textCursor+n,trailEndPx:e.notesEnd,textEndPx:e.textCursor})});let G=s+(l.padding??0),K=T(`*`,u);return D.forEach((e,t)=>{if(t===D.length-1)return;if(s===1/0){e.breakMarkerLeftPx=l.padding??0;return}let n=T(E+e.notesParts.join(``),u);for(;n+v<=G-K&&n+v<s;)e.notesParts.push(`-`),n+=v;e.breakMarkerLeftPx=G-n-K}),{lines:D,clefPrefix:E,styleSet:l,styleName:r,textPx:a,notesPx:o,bold:i,maxWidthPx:s,starTarget:G,starWidth:K}}var D=class e{script;constructor(e){this.script=typeof e==`string`?new n(e):e}async render(t,n={}){let{debug:r=!1}=n,{lines:i,clefPrefix:a,styleSet:o,styleName:s,textPx:c,notesPx:l,bold:u,starTarget:d,starWidth:f}=await E(this.script,n);t.style.fontSize=`${c}px`,t.style.fontFamily=o.textFontStack,t.dataset.style=s,t.replaceChildren(...i.flatMap(t=>[e.notesLine(t,a,l,d,f,r),e.textLine(t,c,u,r)]))}static notesLine(e,t,n,r,i,a){let o=document.createElement(`div`);if(o.className=`guido`,o.style.fontSize=`${n}px`,o.textContent=t+e.notesParts.join(``),e.breakMarkerLeftPx!==void 0){let t=document.createElement(`span`);t.className=`guido-break`,t.textContent=`*`,t.style.position=`relative`,t.style.left=`${e.breakMarkerLeftPx}px`,a&&(t.title=`line break at ${r.toFixed(1)}px (staff filled to ${(r-e.breakMarkerLeftPx-i).toFixed(1)}px)`),o.appendChild(t)}return o}static textLine(t,n,r,i){let a=document.createElement(`p`);r&&(a.style.fontWeight=`700`);for(let r of t.segments)switch(r.kind){case`gap`:{let t=e.spacer(r.width);i&&(t.title=`${r.role===`lead-in`?`lead-in`:`word gap`} ${r.width.toFixed(1)}px → text ${r.textStartPx.toFixed(1)}`),a.appendChild(t);break}case`connector`:{let t=e.spacer(r.pad),n=document.createElement(`span`);n.className=`dash`,n.textContent=`-`;let o=e.spacer(r.pad);i&&(t.title=`lead pad ${r.pad.toFixed(1)}px (gap ${r.gapWidth.toFixed(1)} − dash ${r.dashWidth.toFixed(1)}, halved)`,n.title=`dash ${r.dashWidth.toFixed(1)}px`,o.title=`trail pad ${r.pad.toFixed(1)}px`),a.append(t,n,o);break}case`syl`:{let t=e.sylSpan(r.parts,n);if(i){if(r.noNotes)t.title=`no notes, text w ${r.textWidth.toFixed(1)}, ${r.trailing?`end of score`:`before the next syllable with notes`}`;else{let e=(r.textWidth-r.contentWidth)/2,n=r.textStart-r.contentStart;t.title=[`text w ${r.textWidth.toFixed(1)}`,`notes w ${r.contentWidth.toFixed(1)}`,r.extraDashes?`+${r.extraDashes} pad dash(es)`:null,`text start ${r.textStart.toFixed(1)}`,`notes start ${r.contentStart.toFixed(1)}`,`theoDiff: ${e.toFixed(1)}`,`cursDiff: ${n.toFixed(1)}`].filter(Boolean).join(`, `)}}a.appendChild(t);break}case`word-space`:{let e=document.createElement(`span`);e.className=`word-space`,e.textContent=` `,i&&(e.title=`word space ${r.width.toFixed(1)}px`),a.appendChild(e);break}case`line-end-dash`:{let t=e.spacer(r.pad),n=document.createElement(`span`);n.className=`dash`,n.textContent=`-`;let o=e.spacer(r.pad);i&&(t.title=`lead pad ${r.pad.toFixed(1)}px → line-end dash (text end ${r.textEndPx.toFixed(1)}, notes end ${r.trailEndPx.toFixed(1)})`,n.title=`dash ${r.dashWidth.toFixed(1)}px (line end)`,o.title=`trail pad ${r.pad.toFixed(1)}px`),a.append(t,n,o);break}}return a}static sylSpan(e,t){let n=document.createElement(`span`);return n.className=`syl`,e.forEach(e=>{let r=document.createElement(`span`);r.textContent=e.text;for(let[n,i]of Object.entries(v(e.style,t)))r.style.setProperty(n,i);let i=[...e.kind?[e.kind]:[],...e.style.initial?[`initial`]:[]].join(` `);i&&(r.className=i),n.appendChild(r)}),n}static spacer(e){let t=document.createElement(`span`);return t.className=`spacer`,t.style.display=`inline-block`,t.style.width=`${e}px`,t}},O={name:`guidex`,version:`0.3.1`,description:`Guidex — render plainchant scores from a compact GuidoScript notation, as a web app and an embeddable runtime`,type:`module`,workspaces:[`examples/*`],main:`./dist/lib/embed/manual.js`,types:`./dist/lib/embed/manual.d.ts`,exports:{".":{types:`./dist/lib/embed/manual.d.ts`,default:`./dist/lib/embed/manual.js`},"./embed":{types:`./dist/lib/embed/index.d.ts`,default:`./dist/lib/embed/index.js`},"./guidex.css":{types:`./dist/lib/guidex.css.d.ts`,default:`./dist/lib/guidex.css`},"./fonts/*":`./dist/lib/fonts/*`,"./react":{types:`./dist/lib/react/index.d.ts`,default:`./dist/lib/react/index.js`},"./word":{types:`./dist/lib/word/index.d.ts`,default:`./dist/lib/word/index.js`}},files:[`dist-embed`,`dist/lib`],peerDependencies:{react:`>=18`},peerDependenciesMeta:{react:{optional:!0}},publishConfig:{access:`public`},scripts:{dev:`vite --host`,build:`tsc && vite build`,"build:embed":`vite build --config vite.embed.config.ts`,"build:lib":`vite build --config vite.lib.config.ts`,preview:`vite preview`,test:`vitest run`,lint:`eslint .`},keywords:[`plainchant`,`gregorian`,`guido`,`score`,`notation`,`liturgy`],repository:{type:`git`,url:`git+https://github.com/BrownieMaar/guidex.git`},bugs:{url:`https://github.com/BrownieMaar/guidex/issues`},homepage:`https://github.com/BrownieMaar/guidex#readme`,devDependencies:{"@eslint/js":`^10.0.1`,"@testing-library/dom":`^10.4.2`,"@testing-library/react":`^16.3.3`,"@testing-library/user-event":`^14.6.7`,"@types/react":`^19.3.0`,"@types/react-dom":`^19.3.0`,"@vitejs/plugin-react":`^6.1.1`,eslint:`^10.10.0`,jsdom:`^29.1.1`,react:`^19.3.0`,"react-dom":`^19.3.0`,typescript:`~6.0.2`,"typescript-eslint":`^8.70.0`,vite:`^8.2.2`,"vite-plugin-dts":`^5.1.1`,vitest:`^4.1.11`}}.version,k=`.guidex-script, .guido-script`,A={maxWidth:`auto`,style:`BNS`,bold:!1,textPx:18,transpose:0,debug:!1},j={},M=new WeakMap,N=new WeakMap,P=new WeakMap;function F(e){if(e!==void 0){if(e===``||e===`true`)return!0;if(e===`false`)return!1}}function I(e){if(e===void 0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function L(e,t){if(/^auto$/i.test(e.trim()))return`auto`;let n=Number(e);return Number.isFinite(n)&&n>0?n:(console.warn(`[guidex] ignoring invalid data-max-width "${e}"`),t)}var R=new WeakMap;function z(e){let t=e.dataset,n=R.get(e)??{};return{maxWidth:t.maxWidth===void 0?n.maxWidth??j.maxWidth??A.maxWidth:L(t.maxWidth,n.maxWidth??j.maxWidth??A.maxWidth),style:t.style??n.style??j.style??A.style,bold:F(t.bold)??n.bold??j.bold??A.bold,textPx:I(t.textPx)??n.textPx??j.textPx??A.textPx,transpose:I(t.transpose)??n.transpose??j.transpose??A.transpose,debug:F(t.debug)??n.debug??j.debug??A.debug}}function B(e){return e.querySelector(`:scope > .guidex-render`)?.clientWidth||e.clientWidth||e.parentElement?.clientWidth||0}function V(e,t,n){if(typeof t==`number`)return t;let r=B(e);if(r<=0)return 1/0;let i=r-(h[n]?.padding??0);return i>0?i:r}function ne(e){for(let t of e.childNodes)if(t.nodeType===Node.TEXT_NODE&&t.nodeValue?.trim())return t.nodeValue.trim();return M.get(e)??``}function H(e){let t=e.querySelector(`:scope > .guidex-render`);if(t)return t;let n=document.createElement(`div`);return n.className=`guidex-render`,e.replaceChildren(n),n}function U(e,t){let n=document.createElement(`p`);n.className=`guidex-error`,n.textContent=t,e.replaceChildren(n)}function W(e,t){let n=[...h[e]?.scriptTransforms??[]];return t!==0&&n.push(d(t)),n}async function G(e){let t=(N.get(e)??0)+1;N.set(e,t);let r=z(e),i=ne(e);M.set(e,i);let a=H(e),o=V(e,r.maxWidth,r.style);P.set(e,o);let s=document.createElement(`div`),c=new n(i,{transforms:W(r.style,r.transpose)});try{if(await new D(c).render(s,{style:r.style,bold:r.bold,textPx:r.textPx,debug:r.debug,maxWidthPx:o}),N.get(e)!==t)return;a.replaceChildren(...s.childNodes),a.style.cssText=s.style.cssText,s.dataset.style&&(a.dataset.style=s.dataset.style)}catch(n){if(N.get(e)!==t)return;console.error(`[guidex]`,n),U(a,n instanceof Error?n.message:String(n))}}var K=new WeakMap;function q(e){let t=z(e),n=V(e,t.maxWidth,t.style);return Math.abs(n-(P.get(e)??NaN))>1}function J(e){if(K.has(e))return;let t;if(typeof ResizeObserver<`u`){let n=new ResizeObserver(()=>{q(e)&&G(e)});n.observe(e),t=()=>n.disconnect()}else{let n=()=>{q(e)&&G(e)};window.addEventListener(`resize`,n),t=()=>window.removeEventListener(`resize`,n)}K.set(e,t)}function Y(e){K.get(e)?.(),K.delete(e),M.delete(e),R.delete(e),N.delete(e),P.delete(e)}async function X(e,t,r={}){R.set(e,r);let i=(N.get(e)??0)+1;N.set(e,i),M.set(e,t);let a=z(e),o=H(e),s=V(e,a.maxWidth,a.style);P.set(e,s),J(e);let c=document.createElement(`div`),l=new n(t,{transforms:W(a.style,a.transpose)});try{if(await new D(l).render(c,{style:a.style,bold:a.bold,textPx:a.textPx,debug:a.debug,maxWidthPx:s}),N.get(e)!==i)return;o.replaceChildren(...c.childNodes),o.style.cssText=c.style.cssText,c.dataset.style&&(o.dataset.style=c.dataset.style)}catch(t){if(N.get(e)!==i)return;console.error(`[guidex]`,t),U(o,t instanceof Error?t.message:String(t))}}async function Z(e=document){let t=j.selector??k,n=[];return e instanceof Element&&e.matches(t)&&n.push(e),n.push(...e.querySelectorAll(t)),Promise.all(n.map(e=>(J(e),G(e)))).then(()=>void 0)}var Q=!1;function $(){if(Q||typeof MutationObserver>`u`)return;Q=!0;let e=j.selector??k;new MutationObserver(t=>{let n=new Set;for(let r of t)for(let t of r.addedNodes)if(t instanceof Element&&!t.closest(`.guidex-render`)){t.matches(e)&&n.add(t);for(let r of t.querySelectorAll(e))n.add(r)}for(let e of n)J(e),G(e)}).observe(document.documentElement,{childList:!0,subtree:!0})}function re(e={}){j={...j,...e},$(),Z()}var ie=[`font-family`,`font-size`,`font-style`,`font-weight`,`line-height`,`letter-spacing`,`text-transform`,`color`,`position`,`top`,`left`,`margin-top`,`margin-bottom`,`padding-top`,`padding-bottom`],ae=[`font-family`,`font-size`,`font-style`,`font-weight`,`line-height`,`letter-spacing`,`color`];function oe(e){return e.classList.contains(`max-width-guide`)||e.hasAttribute(`data-score-image-ignore`)}function se(e){let t=e.querySelector(`.guido`)?.parentElement;if(!t)throw Error(`No rendered score found to export — render a score into the element first.`);return t}function ce(e){let t=e.getBoundingClientRect(),n=[],r=document.createRange();return r.selectNodeContents(e),typeof r.getBoundingClientRect==`function`&&n.push(r.getBoundingClientRect()),e.querySelectorAll(`*`).forEach(e=>n.push(e.getBoundingClientRect())),n.length===0&&n.push(t),{left:Math.min(...n.map(e=>e.left))-t.left,top:Math.min(...n.map(e=>e.top))-t.top,right:Math.max(...n.map(e=>e.right))-t.left,bottom:Math.max(...n.map(e=>e.bottom))-t.top}}function le(e){let t=document.createRange();if(t.selectNodeContents(e),typeof t.getClientRects!=`function`)return 1;let n=Array.from(t.getClientRects()).filter(e=>e.width>0||e.height>0);if(n.length===0)return 1;n.sort((e,t)=>e.top-t.top);let r=0,i=-1/0;for(let e of n)e.top>=i?(r++,i=e.bottom):e.bottom>i&&(i=e.bottom);return r}function ue(e){let t=[],n=``,r=null;for(let i of e)r?i===r?r=null:n+=i:i===`"`||i===`'`?r=i:i===`,`?(t.push(n.trim()),n=``):n+=i;return t.push(n.trim()),t.filter(Boolean)}function de(e){return e===`normal`?`400`:e===`bold`?`700`:e}function fe(e){return e.replace(/&/g,`&amp;`).replace(/"/g,`&quot;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function pe(e,t,n,r,i){let a=/url\(\s*(['"]?)([^'")]+)\1\s*\)/.exec(r);if(!a)return;let o;try{o=new URL(a[2],i??location.href).toString()}catch{return}return{family:e,style:t||`normal`,weight:de(n||`400`),url:o,format:/format\(\s*['"]?([^'")]+?)['"]?\s*\)/.exec(r)?.[1]}}function me(e,t){let n=[];for(let r of e.matchAll(/@font-face\s*{([^}]*)}/g)){let e=r[1],i=t=>{let n=RegExp(`(?:^|[;\\s])${t}\\s*:\\s*([^;]+)`,`i`).exec(e);return n?n[1].trim():``},a=i(`font-family`),o=i(`src`);if(!a||!o)continue;let s=ue(a)[0];if(!s)continue;let c=pe(s,i(`font-style`),i(`font-weight`),o,t);c&&n.push(c)}return n}async function he(e){let t=[],n=new Set,r=e=>{let r=`${e.family}|${e.style}|${e.weight}`;n.has(r)||(n.add(r),t.push(e))},i=[];for(let t of document.styleSheets){let n;try{n=t.cssRules}catch{t.href&&i.push(t.href);continue}for(let i of Array.from(n)){let n=i.style;if(!n)continue;let a=n.getPropertyValue(`src`),o=n.getPropertyValue(`font-family`);if(!a||!o)continue;let s=ue(o)[0];if(!s||!e.has(s))continue;let c=pe(s,n.getPropertyValue(`font-style`),n.getPropertyValue(`font-weight`),a,t.href??void 0);c&&r(c)}}for(let t of i)try{let n=await fetch(t);if(!n.ok)throw Error(String(n.status));let i=await n.text();for(let n of me(i,t))e.has(n.family)&&r(n)}catch{console.warn(`[guidex] scoreImage: a cross-origin stylesheet (${t}) could not be read — fonts declared only there are missing from the export`)}return t}async function ge(e){let t=await fetch(e);if(!t.ok)return;let n=await t.blob();return new Promise(e=>{let t=new FileReader;t.onload=()=>e(typeof t.result==`string`?t.result:void 0),t.onerror=()=>e(void 0),t.readAsDataURL(n)})}async function _e(e,t){let n=[],r=new Set,i=new Map,a=e=>{let t=i.get(e);return t||(t=ge(e).catch(()=>void 0),i.set(e,t)),t},o=new Map;for(let t of e){let e=o.get(t.family)??[];e.push(t),o.set(t.family,e)}for(let[e,i]of o){let o=i.filter(e=>e.style===`normal`),s=o.length>0?[...o,...t?i.filter(e=>e.style!==`normal`):[]]:i;for(let t of s){let i=await a(t.url);if(!i){r.add(e);continue}let o=t.format?` format('${t.format}')`:``;n.push(`@font-face{font-family:'${t.family}';font-style:${t.style};font-weight:${t.weight};src:url(${i})${o}}`)}}for(let e of r)console.warn(`[guidex] scoreImage: could not embed the ${e} webfont — the export falls back to the next family in its stack`);return n.join(``)}function ve(e){let t=document.createElement(`span`);return t.style.color=e,getComputedStyle(t).color}function ye(e){let t=getComputedStyle(e).getPropertyValue(`--red`).trim();return t?ve(t):``}function be(e,t,n){return n&&t&&ve(t)===n?!0:e.style?.getPropertyValue(`color`).replace(/\s+/g,``)===`var(--red)`}function xe(e,t,n){let r=new Set,i=!1;for(let a=0;a<e.length;a++){let o=e[a],s=t[a],c=getComputedStyle(o);for(let e of a===0?ae:ie){if(e===`color`){let e=c.getPropertyValue(`color`);if(!e)continue;let t=be(o,e,n.accentProbe)?n.accent:n.foreground;s.style.setProperty(`color`,t||e);continue}let t=c.getPropertyValue(e);t&&s.style.setProperty(e,t)}let l=c.getPropertyValue(`font-family`);if(l)for(let e of ue(l))r.add(e);c.getPropertyValue(`font-style`)===`italic`&&(i=!0)}return{families:r,italics:i}}async function Se(){let e=document.fonts;e?.ready&&await e.ready}async function Ce(e,t){let n=Math.max(0,t.padding??0),r=se(e);if(!r.isConnected)throw Error(`scoreImage: the score left the document before the export — re-render it and try again`);await Se();let i=Array.from(r.children).filter(e=>e.classList.contains(`guido`)||e.tagName===`P`);if(i.length===0)throw Error(`No rendered score found to export — render a score into the element first.`);let a=i.map(e=>e.getBoundingClientRect()),o=a[0],s=i.map((e,t)=>{let n=ce(e),r=a[t],i=r.left-o.left,s=le(e)>1;return{left:n.left+i,top:n.top+(r.top-o.top),right:(s?Math.max(r.width,n.right):n.right)+i,bottom:n.bottom+(r.top-o.top),pinWidth:s?r.width:void 0}}),c=Math.min(0,...s.map(e=>e.left)),l=Math.min(0,...s.map(e=>e.top)),u=Math.max(...s.map(e=>e.right)),d=Math.max(...s.map(e=>e.bottom)),f=Math.max(1,Math.ceil(u-c))+n*2,p=Math.max(1,Math.ceil(d-l))+n*2,m=r.cloneNode(!0);m.querySelectorAll(`.max-width-guide, [data-score-image-ignore]`).forEach(e=>e.remove());let h=[r],g=[m],_=(e,t)=>{for(let n of e.children)oe(n)||(t.push(n),_(n,t))};if(_(r,h),_(m,g),g.length!==h.length)throw Error(`scoreImage: the cloned tree diverged from the live one`);for(let e of[m,...m.querySelectorAll(`*`)])e.removeAttribute(`title`);let{families:v,italics:y}=xe(h,g,{foreground:t.foreground,accent:t.accent,accentProbe:ye(r)});m.style.setProperty(`white-space`,`nowrap`);let b=Array.from(m.children).filter(e=>e.classList.contains(`guido`)||e.tagName===`P`);s.forEach((e,t)=>{let n=b[t];e.pinWidth!==void 0&&n&&n.style.setProperty(`width`,`${e.pinWidth}px`)}),m.style.setProperty(`padding-top`,`${n-l}px`),m.style.setProperty(`padding-left`,`${n-c}px`),m.style.setProperty(`padding-right`,`${n}px`),m.style.setProperty(`padding-bottom`,`${n}px`);let x=await _e(await he(v),y),ee=new XMLSerializer().serializeToString(m),S=t.background?`<rect width="100%" height="100%" fill="${fe(t.background)}"/>`:``;return{svg:`<svg xmlns="http://www.w3.org/2000/svg" width="${f}" height="${p}" viewBox="0 0 ${f} ${p}">`+S+(x?`<style>${x}</style>`:``)+`<foreignObject x="0" y="0" width="${f}" height="${p}">`+ee+`</foreignObject></svg>`,width:f,height:p}}async function we(e,t={}){return(await Ce(e,t)).svg}async function Te(e,t={}){let{svg:n,width:r,height:i}=await Ce(e,t),a=Math.max(1,t.scale??2),o=new Image;o.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(n)}`,await new Promise((e,t)=>{o.onload=()=>e(),o.onerror=()=>t(Error(`scoreImage: the exported SVG failed to rasterize`))});try{await o.decode()}catch{}let s=document.createElement(`canvas`);s.width=Math.ceil(r*a),s.height=Math.ceil(i*a);let c=s.getContext(`2d`);if(!c)throw Error(`scoreImage: this environment provides no 2D canvas`);c.scale(a,a),t.background&&(c.fillStyle=t.background,c.fillRect(0,0,r,i));let l=()=>c.drawImage(o,0,0,r,i);l(),/^((?!chrome|android|crios|fxios).)*safari/i.test(navigator.userAgent)&&(await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(e))),l());let u=await new Promise(e=>s.toBlob(e,`image/png`));if(!u)throw Error(`scoreImage: PNG encoding failed`);return u}function Ee(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,r.click(),setTimeout(()=>URL.revokeObjectURL(n),1e4)}async function De(e,t={}){let n=t.filename??`score.png`;return Ee(await Te(e,t),n),n}async function Oe(e,t={}){let n=t.filename??`score.svg`;return Ee(new Blob([await we(e,t)],{type:`image/svg+xml;charset=utf-8`}),n),n}return document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>re(),{once:!0}):re(),e.dispose=Y,e.downloadScorePng=De,e.downloadScoreSvg=Oe,e.init=re,e.renderAll=Z,e.renderScore=X,e.scorePngBlob=Te,e.scoreSvg=we,e.version=O,e})({});
1
+ var GuidexEmbed=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t={ð:{smallHead:`~`,modifyUp:`È`,cephalicus:`®`},ñ:{virga:`^`,smallHead:`¯`,modifyUp:`Ê`,modifyDown:`÷`,cephalicus:`−`,connectOneDown:`Ý`},0:{virga:`]`,smallHead:`‚`,modifyUp:`Ë`,modifyDown:`ø`,modifyNatural:`“`,cephalicus:`§`,connectOneDown:`Þ`},1:{virga:`q`,longa:`Ÿ`,smallHead:`ƒ`,modifyUp:`Ì`,modifyDown:`a`,modifyNatural:`”`,cephalicus:`ÿ`,connectOneDown:`Q`,connectTwoDown:`×`,connectThreeDown:`Ø`,smallPoint:`í`},2:{virga:`w`,longa:`¡`,smallHead:`„`,modifyUp:`Î`,modifyDown:`A`,modifyNatural:`•`,cephalicus:`"`,connectOneDown:`W`,connectTwoDown:`s`,connectThreeDown:`Ù`,connectFourDown:`½`},3:{virga:`e`,longa:`¢`,smallHead:`…`,modifyUp:`Ï`,modifyDown:`S`,modifyNatural:`–`,cephalicus:`+`,connectOneDown:`E`,connectTwoDown:`d`,connectThreeDown:`D`,connectFourDown:`°`,smallPoint:`y`},4:{virga:`r`,longa:`£`,smallHead:`†`,modifyUp:`Ð`,modifyDown:`Í`,modifyNatural:`—`,cephalicus:`!`,connectOneDown:`R`,connectTwoDown:`f`,connectThreeDown:`F`,connectFourDown:`±`},5:{virga:`t`,longa:`[`,smallHead:`‡`,modifyUp:`Ñ`,modifyDown:`Y`,modifyNatural:`˜`,cephalicus:`%`,connectOneDown:`T`,connectTwoDown:`g`,connectThreeDown:`G`,connectFourDown:`²`,smallPoint:`x`},6:{virga:`z`,longa:`¥`,smallHead:`ˆ`,modifyUp:`Ò`,modifyDown:`X`,modifyNatural:`™`,cephalicus:`/`,connectOneDown:`Z`,connectTwoDown:`h`,connectThreeDown:`H`,connectFourDown:`³`},7:{virga:`u`,longa:`¦`,smallHead:`‰`,modifyUp:`þ`,modifyDown:`C`,modifyNatural:`š`,cephalicus:`=`,connectOneDown:`U`,connectTwoDown:`j`,connectThreeDown:`J`,connectFourDown:`´`,smallPoint:`c`},8:{virga:`i`,longa:`©`,smallHead:`Š`,modifyUp:`ß`,modifyDown:`V`,modifyNatural:`›`,cephalicus:`(`,connectOneDown:`I`,connectTwoDown:`k`,connectThreeDown:`K`,connectFourDown:`μ`},9:{virga:`o`,longa:`ª`,smallHead:`‹`,modifyUp:`ò`,modifyDown:`B`,modifyNatural:`œ`,cephalicus:`)`,connectOneDown:`O`,connectTwoDown:`l`,connectThreeDown:`L`,connectFourDown:`·`,smallPoint:`v`},ö:{virga:`p`,longa:`«`,smallHead:`Œ`,modifyUp:`ô`,modifyDown:`N`,modifyNatural:`º`,cephalicus:`Ö`,connectOneDown:`P`,connectTwoDown:`é`,connectThreeDown:`É`,connectFourDown:`¾`},ü:{virga:`õ`,longa:`¬`,smallHead:`‘`,modifyUp:`ù`,modifyDown:`$`,modifyNatural:`»`,cephalicus:`Ü`,connectOneDown:`Õ`,connectTwoDown:`á`,connectThreeDown:`Á`,connectFourDown:`¸`,smallPoint:`b`},ó:{virga:`ú`,smallHead:`’`,modifyUp:`ý`,modifyDown:`m`,cephalicus:`Ó`,connectOneDown:`Ú`,connectTwoDown:`û`,connectThreeDown:`Û`,connectFourDown:`¹`}},n={ð:`a`,ñ:`b`,0:`c'`,1:`d'`,2:`e'`,3:`f'`,4:`g'`,5:`a'`,6:`b'`,7:`c''`,8:`d''`,9:`e''`,ö:`f''`,ü:`g''`,ó:`a''`};function r(e){return n[e]??n[c(e)?.base??``]}var i=new Map;for(let[e,n]of Object.entries(t))for(let t of Object.keys(n))i.set(n[t],{base:e,role:t});function a(e,n){return t[e]?.[n]}function o(e){return a(e,`smallHead`)}function s(e){return a(e,`modifyNatural`)}function c(e){let t=i.get(e);return t?{...t}:void 0}var l=[`modifyUp`,`modifyDown`,`modifyNatural`];function u(e){let t=i.get(e)?.role;return t!==void 0&&l.includes(t)}var d={">":{clef:`c`,line:1},"#":{clef:`c`,line:2},"&":{clef:`c`,line:3},"@":{clef:`c`,line:4},"{":{clef:`f`,line:3},"}":{clef:`f`,line:4},M:{clef:`g`,line:2},"<":{clef:`g`,line:2}};function f(e){return Object.hasOwn(d,e)}var p=[...`ðñ0123456789öüó`],m=`abcdefg`;function h(e,t=`M`){let n=p.indexOf(p.includes(e)?e:c(e)?.base??``),i=d[t];if(n<0||!i)return;let a=p.indexOf(`2`)+2*(i.line-1),o=m.indexOf(i.clef)-m.indexOf(r(p[a])[0]);return m[((m.indexOf(r(p[n])[0])+o)%7+7)%7]}function g(e){return e.trim().startsWith(`@`)}function _(e){let[t,...n]=e;return t===`@`&&n.every(u)}function v(e){return!g(e)||_(e)}function y(e,t){for(let n of e)if(!u(n))throw Error(`"${n}" is not a key modifier glyph in "${t}"`);return e}function b(e){let t=e.trim();if(_(t))throw Error(`a clef group is only allowed at the start; write "(@clef ${t})" to change the clef`);let[,n,r=``]=t.match(/^@(\S*)(?: (.*))?$/)??[];switch(n){case`break`:if(r!==``)throw Error(`"@break" takes no argument: "${t}"`);return{kind:`break`};case`clef`:{let[e,...n]=r;if(e===void 0)throw Error(`"@clef" needs a clef group argument, e.g. "(@clef MX)"`);if(!f(e))throw Error(`"${e}" is not a clef glyph in "${t}"`);return{kind:`clef`,clef:e,key:y(n.join(``),t)}}case`key`:return{kind:`key`,key:y(r,t)};default:throw Error(`Unknown statement "${t}"`)}}function x(e){switch(e.kind){case`break`:return`(@break)`;case`clef`:return`(@clef ${e.clef}${e.key})`;case`key`:return e.key===``?`(@key)`:`(@key ${e.key})`}}function S(e){let t=e.match(/^@stanza(?:\s+([\s\S]*))?$/);return t?t[1]??``:void 0}var C=class{source;constructor(e,t={}){this.source=(t.transforms??[]).reduce((e,t)=>t.apply(e),e)}get clef(){let e=this.normalized.match(/^\s*\(([^)]*)\)/);if(!(!e||!v(e[1])))return e[1]}get tokens(){return this.parse().tokens}get stanzas(){return this.parse().stanzas}get tokenSpans(){return this.parse().spans}parse(){let e=this.normalized,t=e.match(/^\s*\(([^)]*)\)/),n=t&&v(t[1])?t[0].length:0,r=[...e.slice(n).matchAll(/((?:[^()\\]|\\.)*)\(((?:[^)\\]|\\.)*)\)/g)],i,a=[],o=[],s=[];for(let e of r){let[,t,r]=e,c=n+e.index,l=c+t.length+1,u={start:c+(t.length-t.trimStart().length),notesStart:l,notesEnd:l+r.length,end:l+r.length+1},d=g(r)?S(r.trim()):void 0;if(d!==void 0){if(t.trim()!==``)throw Error(`statement must not carry syllable text: "${w(t.trim())}"`);a.push(d);continue}if(a.length>0){if(t.trim()===``&&r===``)continue;throw Error(`"(@stanza …)" statements must stand at the end of the script`)}if(g(r)){let e=b(r);if(t.trim()!==``)throw Error(`statement must not carry syllable text: "${w(t.trim())}"`);o.push({...e,spaceBefore:/^\s/.test(t)}),s.push(u);continue}let f=t.trim(),p={kind:`syllable`,text:f===`~`?``:w(f),notes:w(r),spaceBefore:/^\s/.test(t)};if(f===`~`||f===``&&i===void 0&&p.notes!==``)p.empty=!0;else if(f===``&&p.notes!==``){if(i.notes===``)throw Error(`the group "(${p.notes})" has no syllable to hold it: "${i.text}" has no notes; write "~(${p.notes})" for an empty slot`);p.held=!0}i=p,o.push(p),s.push(u)}let c;for(let[e,t]of o.entries()){if(t.kind!==`syllable`)continue;if(t.held){t.wordEnd=c.wordEnd;continue}t.wordEnd=!0;let n=!1;for(let r=e+1;r<o.length;r++){let e=o[r];if(e.spaceBefore&&(n=!0),e.kind===`syllable`&&!e.held&&!e.empty){t.wordEnd=n;break}}c=t}return{tokens:o,stanzas:a,spans:s}}get syllables(){return this.tokens.filter(e=>e.kind===`syllable`).map(({text:e,notes:t,wordEnd:n,held:r,empty:i})=>({text:e,notes:t,wordEnd:n,...r?{held:r}:{},...i?{empty:i}:{}}))}get normalized(){let e=this.source;return(e.match(/(^|[^\\])\(/g)??[]).length>(e.match(/(^|[^\\])\)/g)??[]).length&&(e+=`)`),/(^|[^\\])\)$/.test(e)||(e+=`()`),e}get words(){let e=[],t;for(let n of this.syllables)n.held||n.empty||(t??={text:``,syllables:[]},t.syllables.push({text:n.text,notes:n.notes}),t.text=t.syllables.map(e=>e.text).join(``),n.wordEnd&&(e.push(t),t=void 0));return e}toString(){let e=this.tokens.map((e,t)=>{let n=t>0&&e.spaceBefore?` `:``;return e.kind===`syllable`?`${n}${e.empty?`~`:e.text===`~`?`\\~`:T(e.text)}(${T(e.notes)})`:`${n}${x(e)}`}),t=this.stanzas.map(e=>`(@stanza ${e})`);return`${this.clef===void 0?``:`(${this.clef})`}${e.join(``)}${t.join(``)}`}};function w(e){return e.replace(/\\(.)/g,`$1`)}function T(e){return e.replace(/\\/g,`\\\\`).replace(/[()]/g,e=>`\\${e}`)}var E=new Set(`,.:?'"+!%/=()ÖÜÓ;`.split(``));function D(e){let t=0;for(;t<e.length&&E.has(e[t]);)t++;t>0&&t<e.length&&(t=e[t]===`-`?t+1:0);let n=e.length;for(;n>t&&E.has(e[n-1]);)n--;return n<e.length&&n>t&&(n=e[n-1]===`-`?n-1:e.length),{leading:e.slice(0,t),core:e.slice(t,n),trailing:e.slice(n)}}var O=`_…_`,k=`-=­`;function A(e){let t=[],n=null,r=Array.from(e);for(let e=0;e<r.length;e++){let i=r[e],a=i===`\\`&&e+1<r.length;if(a&&(i=r[++e]),!a&&/\s/.test(i)){n=null;continue}n===null&&(n=[],t.push(n)),n.push({ch:i,escaped:a})}let i=[];for(let e of t){if(e.length===1&&!e[0].escaped&&e[0].ch===`~`){i.push({kind:`empty`});continue}let t=[``];for(let{ch:n,escaped:r}of e)!r&&k.includes(n)?t.push(``):t[t.length-1]+=!r&&n===`~`?`\xA0`:n;let n=t.length-1;for(let[e,r]of t.entries()){if(r===``){e<n&&i.push({kind:`hold`});continue}i.push({kind:`syllable`,text:r,wordEnd:e===n})}}return i}function j(e){return e.kind===`syllable`&&e.notes!==``&&D(e.notes).core!==``}function M(e){return typeof e==`string`?new C(e):e}function N(e){return M(e).tokens.filter(j).length}function P(e,t={}){return t.stanzas??M(e).stanzas}function F(e,t={}){return P(e,t).length+1}function I(e){return e.kind===`syllable`||e.kind===`hold`}function ee(e){return e.map(e=>e.empty?{kind:`empty`}:e.held?{kind:`hold`}:{kind:`syllable`,text:e.text,wordEnd:e.wordEnd})}function L(e,t,n){let r=A(e),i=[],a=[];for(let e=0;e<t;e++){let o=r[e];i.push(o??{kind:`missing`}),o===void 0&&a.push({stanza:n,slot:e+1,kind:`missing`,message:`Stanza ${n} has no syllable for slot ${e+1} of ${t}`})}for(let[e,i]of r.slice(t).entries()){let r=i.kind===`syllable`?i.text:i.kind===`hold`?`-`:`~`;a.push({stanza:n,slot:t+e+1,kind:`extra`,text:r,message:`Stanza ${n} has an extra syllable "${r}" past the last slot (${t})`})}return{fills:i,warnings:a}}function R(e,t){if(!Number.isInteger(e)||e<1||e>t)throw RangeError(`Stanza ${e} does not exist: the script has ${t} stanza${t===1?``:`s`}`)}function z(e,t={}){let n=P(e,t),r=N(e);return t.stanza===void 0?n.flatMap((e,t)=>L(e,r,t+2).warnings):(R(t.stanza,n.length+1),t.stanza===1?[]:L(n[t.stanza-2],r,t.stanza).warnings)}function B(e){return Array.from(e,e=>{let t=o(e);if(t!==void 0)return t;let n=c(e);return n&&(n.role===`virga`||n.role===`longa`)?o(n.base)??e:e}).join(``)}function V(e){return e===`~`?`\\~`:T(e)}function H(e,t,n){let r=new C(e),i=P(r,n);R(t,i.length+1);let a=n.rendered??[t];for(let e of a)R(e,i.length+1);let o=n.emptySlots??`normal`;if(t===1&&o===`normal`)return e;let s=r.tokens,c=s.filter(e=>j(e)),l=[ee(c),...i.map((e,t)=>L(e,c.length,t+2).fills)],u=l[t-1],d=e=>o===`partial`?l.some(t=>I(t[e]))&&!l.every(t=>I(t[e])):o===`small`&&a.every(t=>!I(l[t-1][e]))&&l.some((t,n)=>!a.includes(n+1)&&I(t[e])),f=r.clef===void 0?``:`(${r.clef})`,p=!0,m=!1,h=!1,g=(e,t)=>{f+=(t&&!p?` `:``)+e,p=!1},_=0;for(let e of s){if(e.kind!==`syllable`){g(x(e),m),m=!1;continue}if(!j(e)){e.held?(g(`(${T(e.notes)})`,m),m=!1):(g(`${V(e.text)}(${T(e.notes)})`,m||e.spaceBefore),m=e.wordEnd,h=e.notes!==``);continue}let t=u[_],n=T(d(_)?B(e.notes):e.notes);switch(_++,t.kind){case`syllable`:g(`${V(t.text)}(${n})`,m),m=t.wordEnd;break;case`hold`:g(`${h?``:`~`}(${n})`,!1);break;case`empty`:g(`~(${n})`,!1);break;case`missing`:g(`${O}(${n})`,!0),m=!0}h=!0}return f}function U(e,t={}){return{name:`selectStanza`,apply:n=>H(n,e,t)}}function te(e,t,n={}){return new C(typeof e==`string`?e:e.source,{transforms:[U(t,n),...n.transforms??[]]})}function W(e,t,n={}){let r=F(e,n);if(t===`all`)return Array.from({length:r},(e,t)=>t+1);if(t.length===0)throw RangeError(`No stanza to stack: the list is empty`);for(let e of t)R(e,r);return[...t]}function G(e,t,n={}){let r=W(e,t,n);return r.map(t=>te(e,t,{...n,rendered:r}))}function K(e){let t=[...e];for(let e=0;e<t.length;e++){let n=t[e];if(!/\s/.test(n))return{unit:n===`\\`&&t[e+1]!==void 0?n+t[e+1]:n,index:e}}return null}function q(e){let t=e.match(/^\s*\(([^)]*)\)/),n=t?t[0].length:0,r=e.slice(n);for(let t of r.matchAll(/((?:[^()\\]|\\.)*)\(((?:[^)\\]|\\.)*)\)/g)){let[,r,i]=t;if(w(i).trim().length===0||g(i))continue;let a=K(r);if(!a||r.trim()===`~`)continue;if(r.trimStart().startsWith(`*`))return e;let o=n+t.index+a.index,s=o+a.unit.length;return`${e.slice(0,o)}*${e.slice(o,s)}*${e.slice(s)}`}return e}var ne={startWithInitial:{name:`startWithInitial`,apply:q}},re=[`ðñ0123456789öüó`,`^]qwertzuiopõú`,`ÝÞQWERTZUIOPÕÚ`,`×sdfghjkléáû`,`ØÙDFGHJKLÉÁÛ`,`÷øaASÍYXCVBN$m`,`ÈÊËÌÎÏÐÑÒþßòôùý`,`“”•–—˜™š›œº»`,`®−§ÿ"+!%/=()ÖÜÓ`,`Ÿ¡¢£[¥¦©ª«¬`,`~¯‚ƒ„…†‡ˆ‰Š‹Œ‘’`,`àâãäåæçèêëìîï`,`½°±²³´μ·¾¸¹`];function ie(e,t,n){for(let r of re){let i=r.indexOf(e);if(i===-1)continue;let a=i+t;if(a<0||a>=r.length){if(n===`null`)return`\0`;if(n===`error`)throw Error(`Transposing "${e}" by ${t} runs past the glyph range`);return r[Math.max(0,Math.min(r.length-1,a))]}return r[a]}}function ae(e,t,n={}){if(t===0||g(e))return e;let r=n.overflow??`clamp`,i=``;for(let n=0;n<e.length;n++){let a=e[n],o=a===`\\`&&e[n+1]!==void 0,s=ie(o?e[n+1]:a,t,r);if(s===void 0){i+=o?a+e[n+1]:a,o&&n++;continue}i+=`\\()`.includes(s)?`\\${s}`:s,o&&n++}return i}function oe(e,t={}){let n=t.overflow??`clamp`;return{name:`transpose`,apply:t=>{if(e===0)return t;let r=t.match(/^\s*\(([^)]*)\)/),i=r?r[0].length:0;return t.slice(0,i)+t.slice(i).replace(/((?:[^()\\]|\\.)*)\(((?:[^)\\]|\\.)*)\)/g,(t,r,i)=>`${r}(${ae(i,e,{overflow:n})})`)}}}var se=new Set([`*`,`†`]),ce={chars:se,fontFamily:`'Times New Roman', Times, serif`},le={weight:`400`,scale:.7,raise:.2},ue={BNS:{textFontStack:`'Book Antiqua', Georgia, serif`,notesFontStack:`'Guidohu'`,markerGlyphs:ce,verifiedFonts:[{family:`'Book Antiqua'`,weight:`400`},{family:`'Book Antiqua'`,weight:`700`},{family:`'Guidohu'`,weight:`400`},{family:`'Liturgy'`,weight:`700`}],decorations:{__:{fontFamily:`'Liturgy', serif`,weight:`700`,color:`var(--red)`},_:{uppercase:!0,scale:.7,color:`var(--red)`},"*":{weight:`700`,color:`var(--red)`,initial:!0}},specialStarStyle:{fontFamily:ce.fontFamily,weight:`700`,scale:1,measureScale:.95,raise:.1,color:`var(--red)`},padding:12,scriptTransforms:[ne.startWithInitial]},Vesperale:{textFontStack:`'Times New Roman', Times, serif`,notesFontStack:`'Guidohu'`,verifiedFonts:[{family:`'Times New Roman', Times, serif`,weight:`400`},{family:`'Times New Roman', Times, serif`,weight:`700`},{family:`'Guidohu'`,weight:`400`},{family:`'Liturgy'`,weight:`700`}],decorations:{__:{fontFamily:`'Liturgy', serif`,weight:`700`},_:{scale:.8,italic:!0},"*":{weight:`700`,initial:!0}},specialStarStyle:{fontFamily:ce.fontFamily,weight:`700`,scale:1,measureScale:.95,raise:.2},padding:12,scriptTransforms:[]}};function de(e,t,n,r={}){if(e.length===0)return[];if(e===`**`)return[{text:`∗`,style:{...t.specialStarStyle},kind:`star`}];let i=e,a={},o;for(let n of[`__`,`_`]){let r=t.decorations[n];if(r&&e.length>=n.length*2+1&&e.startsWith(n)&&e.endsWith(n)){i=e.slice(n.length,-n.length),a={...r},o=n===`__`?`liturgy`:`rubric`;break}}let s=t.decorations[`*`],c=[],l=i,u=``;for(let e=/\*([^*]+)\*/.exec(l);e;e=/\*([^*]+)\*/.exec(l))u+=l.slice(0,e.index),u&&=(c.push({text:u,marked:!1}),``),c.push({text:e[1],marked:!0}),l=l.slice(e.index+e[0].length);u+=l,u&&c.push({text:u,marked:!1});let d=c.map(({text:e,marked:t})=>({text:e,style:t?{...a,...s,initial:!0}:{...a},kind:o})),f=t.markerGlyphs,p=[];for(let e of d){e.style.uppercase&&!r.rawCase&&(e.text=e.text.toUpperCase()),n&&(e.style={...e.style,weight:`700`});let t=[...e.text],i=e.style.fontFamily?.includes(`Liturgy`)??!1,a=e=>se.has(e)||f&&f.chars.has(e)?`marker`:i&&e===`+`?`plus`:`text`;if(t.every(e=>a(e)===`text`)){p.push({text:e.text,style:{...e.style},kind:e.kind});continue}let o=``,s=null,c=()=>{if(!o)return;let t={...e.style},n=e.kind;s===`marker`?(n=`marker`,f&&f.chars.has(o[0])&&(t={...t,fontFamily:f.fontFamily})):s===`plus`&&(t={...t,...le},n=`plus`),p.push({text:o,style:t,kind:n}),o=``};for(let e of t){let t=a(e);t!==s&&c(),s=t,o+=e}c()}return p}function fe(e,t,n){return[e.italic?`italic`:`normal`,`normal`,e.weight??`400`,`${t*(e.measureScale??e.scale??1)}px`,e.fontFamily??n].join(` `)}function pe(e,t){let n={};return e.fontFamily&&(n[`font-family`]=e.fontFamily),e.weight&&(n[`font-weight`]=e.weight),e.italic&&(n[`font-style`]=`italic`),e.scale!==void 0&&(n[`font-size`]=`${t*e.scale}px`),e.color&&(n.color=e.color),e.raise&&(n.position=`relative`,n.top=`${-t*e.raise}px`),n}function me(e,t){return e.verifiedFonts.map(e=>`${e.weight} ${t}px ${e.family}`)}var he=new Set(`Ÿ¡¢£[¥¦©ª«¬`.split(``));function ge(e){return e.length===1&&he.has(e)||e.length===2&&J.has(e[0])&&he.has(e[1])}var J=new Set(`÷øaASÍYXCVBN$mÈÊËÌÎÏÐÑÒþßòôùý“”•–—˜™š›œº»`.split(``)),_e=[`-`,`¨`];function ve(e,t,n=!0){let r=new Map;for(let i of e){if(!u(i))continue;let a=h(i,ye(t));if(n&&r.has(a))throw Error(`Key "${e}" alters the pitch ${a} twice`);r.set(a,c(i).role)}return r}function ye(e){return e!==void 0&&f(e)?e:`M`}function be(e){if(E.has(e))return;if(a(e,`smallHead`)!==void 0)return e;let t=c(e);if(!(!t||t.role===`smallPoint`||u(e)))return t.base}function xe(e,t,n,r,i=[]){let o=``;for(let c of[e,...i])for(let e=0;e<c.length;e++){let i=c[e],l=be(i),d=l===void 0?void 0:h(l,ye(r)),f=d===void 0?void 0:n.get(d),p=e>0&&u(c[e-1]);if(d!==void 0&&f!==t.get(d)&&!p){let e=f??`modifyNatural`,t=f?a(l,f):s(l);if(t===void 0)throw Error(`The note "${i}" has no ${e} glyph for the key change`);o.includes(t)||(o+=t)}}let c=D(e).leading.length;return{notes:e.slice(0,c)+o+e.slice(c),inserted:[...o].map((e,t)=>c+t)}}function Se(e,t,n=0){return[...e].filter((e,r)=>!t.includes(r+n)).join(``)}var Y=null;function X(e,t){return Y||=document.createElement(`canvas`).getContext(`2d`),Y.font=t,Y.measureText(e).width}function Ce(e,t){Y||=document.createElement(`canvas`).getContext(`2d`),Y.font=t;let n=Y.measureText(e);return{left:n.actualBoundingBoxLeft,right:n.actualBoundingBoxRight}}function we(e){let t=typeof e==`string`||e instanceof C?[e]:e;if(t.length===0)throw Error(`Nothing to lay out: no script given`);let n=t.map(e=>(typeof e==`string`?new C(e):e).tokens),[r]=n;for(let[e,t]of n.entries())if(!(t.length===r.length&&t.every((e,t)=>{let n=r[t];return e.kind===n.kind&&(e.kind!==`syllable`||e.notes===n.notes)})))throw Error(`Stacked underlay ${e+1} does not share the first one's notes`);return n}function Te(e){return!!(e.held||e.empty)}async function Ee(e,t={}){let{style:n=`BNS`,bold:r=!1,textPx:i=18,notesPx:a=i*2,maxWidthPx:o=1/0}=t,s=we(e),c=typeof e==`string`||e instanceof C?typeof e==`string`?new C(e):e:typeof e[0]==`string`?new C(e[0]):e[0],l=ue[n];if(!l)throw Error(`Unknown style set: "${n}"`);for(let e of me(l,i)){try{await document.fonts.load(e)}catch{}if(!document.fonts.check(e))throw Error(`Font could not be loaded: ${e} (style "${n}")`)}let d=`400 ${a}px ${l.notesFontStack}`,f=l.textFontStack,p=fe({weight:r?`700`:`400`},i,f),m=e=>de(e,l,r),h=e=>e.reduce((e,t)=>e+X(t.text,fe(t.style,i,f)),0),g=X(`-`,d),_=X(`-`,p),v=c.clef?.[0],y=[...(c.clef??``).slice(1)].filter(u).join(``),b=c.clef,x=e=>e?`${e}-`:``,S=ve(y,v,!1),w=S,T=s.map(e=>{let t=e.filter(e=>e.kind===`syllable`);return{syls:t,lastTextSyl:t.reduce((e,t,n)=>Te(t)?e:n,-1),cursor:0,pending:[],prevWordEnd:void 0}}),O=[],k,A,j,M=!1,N,P=!1,F=()=>{k&&(T.forEach((e,t)=>{k.texts[t].textCursor=e.cursor}),k.notesEnd=k.notesParts.length?X(k.clefPrefix+k.notesParts.join(``),d):0);let e=T.map(()=>({segments:[],textCursor:0,lastWordEnd:null}));k={clefPrefix:x(b),notesParts:[],segments:e[0].segments,textCursor:0,notesEnd:0,lastWordEnd:null,texts:e},O.push(k),A=k.clefPrefix;for(let e of T)e.cursor=0;j=!1,P=!1,M=!1,w=S,N&&N.inserted.length>0&&(N.notes=Se(N.notes,N.inserted),N.inserted=[],N.first&&(B[N.i]=N.notes))};F();let I=s[0],ee=e=>T.every(t=>t.syls[e].held),L=[],R=0,z;for(let e of I)if(e.kind!==`syllable`)L.push(e),z=void 0;else{let t={kind:`syl`,syl:e,i:R++,notes:e.notes,inserted:[],first:!0,lastSeg:!0,heldRun:[],signedByRun:!1};ee(t.i)&&z?(z.heldRun.push(e.notes),t.signedByRun=!0):z=t,L.push(t)}let B=[],V=(e,t,n)=>{for(let r=e.length-1;r>0;r--){if(!_e.includes(e[r]))continue;let i=r+1;for(;i<e.length&&E.has(e[i]);)i++;if(!(i>=e.length)&&n(e.slice(0,i))<=t)return r}return-1},H=(e,t)=>{let n=e.notes,r=t+1;for(;r<n.length&&E.has(n[r]);)r++;e.notes=n.slice(0,t)+n.slice(t+1,r);let i=Se(n.slice(r),e.inserted,r);return e.inserted=e.inserted.filter(e=>e<t),i},U=(e,t,n)=>{e.lastSeg=!1,L.splice(t+1,0,{kind:`syl`,syl:e.syl,i:e.i,notes:n,inserted:[],first:!1,lastSeg:!0,heldRun:[],signedByRun:!1}),W=!0},te=e=>{T.forEach((t,n)=>{for(;t.pending.length>0;){let r=t.pending[0];if(t.cursor>0&&t.cursor+r.textWidth+(r.wordEnd?0:_)>o){F();continue}t.pending.shift();let i=k.texts[n];i.segments.push({kind:`syl`,parts:r.sylParts,textStart:t.cursor,textWidth:r.textWidth,contentWidth:0,contentStart:0,extraDashes:0,tight:!1,noNotes:!0,...e&&t.pending.length===0?{trailing:!0}:{}}),t.cursor+=r.textWidth,r.spaceWidth>0&&(i.segments.push({kind:`word-space`,width:r.spaceWidth}),t.cursor+=r.spaceWidth),i.lastWordEnd=r.wordEnd,i.textCursor=t.cursor}})},W=!1,G=0;for(;G<L.length;){let e=L[G];if(e.kind===`break`){(k.texts.some(e=>e.segments.length>0)||T.some(e=>e.pending.length>0))&&(te(!1),W=!0),G++;continue}if(e.kind===`clef`||e.kind===`key`){if(e.kind===`clef`&&(v=e.clef),y=e.key,b=(v??``)+y,S=ve(y,v),!W){if(k.notesParts.length===0)k.clefPrefix=x(b),A=k.clefPrefix,w=S;else if(e.kind===`clef`){let e=(j?`--`:`---`)+b+`-`;X(A+e,d)>o?W=!0:(k.notesParts.push(e),A+=e,w=S,M=!0,j=!1,P=!1)}}G++;continue}let t=e.syl,n=e.i;if(W&&=(F(),!1),N=e,w!==S&&!e.signedByRun){let t=xe(e.notes,w,S,v,e.first?e.heldRun:[]);e.notes=t.notes,e.inserted=t.inserted}e.first&&(B[n]=e.signedByRun&&w!==S?xe(e.notes,w,S,v).notes:e.notes);let r=T.map(t=>{let r=t.syls[n],i=e.lastSeg&&n>=t.lastTextSyl,a=m(e.first?r.text:``);return{t,own:r,sylParts:a,textWidth:h(a),spaceWidth:!i&&r.wordEnd?X(` `,p):0,pendingTotal:t.pending.reduce((e,t)=>e+t.textWidth+t.spaceWidth,0)}}),i=ge(e.notes);if(t.empty&&e.notes.length===0){G++;continue}if(e.notes.length===0){for(let e of r)e.own.empty||e.t.pending.push({sylParts:e.sylParts,textWidth:e.textWidth,spaceWidth:e.spaceWidth,wordEnd:e.own.wordEnd});G++;continue}if(e.first&&e.lastSeg&&!t.empty&&t.text.trim()===``&&D(e.notes).core===``){let e=A[A.length-1],n=e&&e!==`-`&&!j&&!t.notes.startsWith(`-`)?`-`:``;k.notesParts.push(n+t.notes),A+=n+t.notes,j=!0,P=!1;for(let e of r)e.t.prevWordEnd=e.own.wordEnd;G++;continue}let a=(e,t)=>{e.own.held?(t&&(k.texts[T.indexOf(e.t)].lastWordEnd=!0),e.t.prevWordEnd=e.own.wordEnd):e.t.prevWordEnd===void 0&&(e.t.prevWordEnd=!0)};if(e.first&&r.every(e=>Te(e.own))){let t=ee(n),i=ge(e.notes);if(t&&i&&B[n-1]===B[n]&&k.notesParts.length>0&&!M){P=!0,G++;continue}let s=D(e.notes),c=()=>k.notesParts.length===0||M?``:t?j?`--`:`-`:j||J.has(s.core[0])?`--`:`---`,l=c();k.notesParts.length>0&&X(A+l+e.notes,d)>o&&(F(),l=c());let u=k.notesParts.length===0;if(u&&X(A+e.notes,d)>o){let t=V(e.notes,o,e=>X(A+e,d));if(t>=0&&t+1<e.notes.length){let n=H(e,t);U(e,G,n),s=D(e.notes)}}k.notesParts.push(l+e.notes),A+=l+e.notes;for(let e of r)a(e,u);M=!1,e.lastSeg&&(j=s.trailing.length>0,P=i),G++;continue}let s=e.first?r.filter(e=>!Te(e.own)):r,c=B[n-1]!==e.notes,l=s.every(e=>e.t.cursor===0||e.t.cursor+e.pendingTotal+e.textWidth+(e.own.wordEnd?0:_)<=o);if(i&&!c&&k.notesParts.length>0&&!l&&F(),!e.first){for(;!(X(A+e.notes,d)<=o);){let t=V(e.notes,o,e=>X(A+e,d));if(t<0||t+1>=e.notes.length)break;let n=H(e,t);U(e,G,n)}let t=D(e.notes);k.notesParts.push(e.notes),A+=e.notes,e.lastSeg&&(j=t.trailing.length>0);for(let[e,t]of r.entries())k.texts[e].lastWordEnd=!0,t.t.prevWordEnd=t.own.wordEnd;e.lastSeg||(W=!0),G++;continue}let u=D(e.notes),f=k.notesParts.length===0||M||P?``:j||J.has(u.core[0])?`--`:`---`,C=(e=0)=>{let t=0;for(;t<u.core.length&&J.has(u.core[t]);)t++;t===u.core.length&&(t=0);let n=u.core.slice(t),r=X(n,d),a=X(A+f+`-`.repeat(e)+u.leading+u.core.slice(0,t),d),o=Ce(n,d),s=-o.left,c=(o.right-o.left)/2;return{contentWidth:r,contentStart:a,textStartOf:e=>r>=e||i?a+s:a+c-e/2}},E=C();for(;;){let t=X(A+f+e.notes,d)>o,n=s.some(e=>E.textStartOf(e.textWidth)+e.textWidth+(e.own.wordEnd?0:_)>o);if(!t&&!n)break;if(t){let t=V(e.notes,o,e=>X(A+f+e,d));if(t>=0&&t+1<e.notes.length){let n=H(e,t);U(e,G,n),u=D(e.notes),E=C();break}}if(k.notesParts.length===0&&T.every(e=>e.cursor===0)){if(t){let t=V(e.notes,o,e=>X(A+e,d));if(t>=0&&t+1<e.notes.length){let n=H(e,t);e.notes=e.notes.slice(0,t),U(e,G,n),u=D(e.notes),E=C()}}break}F(),f=``,u=D(e.notes),E=C()}let O=t=>{let{t:n,textWidth:r}=t,{contentWidth:i}=E,a=k.notesParts.length>0&&!n.prevWordEnd&&t.pendingTotal===0,s=n.cursor+_,c=n.cursor+t.pendingTotal+(P&&a?_:0),l=E.textStartOf(r),u=E.contentStart,p=0,m=!1,h=!1;if(!P&&a&&l<s&&(r>i||l<n.cursor)){m=!0,l=n.cursor;let e=i>=r?l:l+(r-i)/2;return e>u&&(p=Math.round((e-u)/g)),{textStart:l,contentStart:u,pads:p,tight:m,floor:n.cursor,minStart:s,wantsBreak:h}}if(l<c){let t=i>=r?c:c+(r-i)/2;if(t>u){p=Math.max(0,Math.floor((t-u)/g));let n=C(p);for(;n.textStartOf(r)<c;)p++,n=C(p);l=n.textStartOf(r),u=n.contentStart,h=k.notesParts.length>0&&X(A+f+`-`.repeat(p)+e.notes,d)>o}}return{textStart:l,contentStart:u,pads:p,tight:m,floor:c,minStart:s,wantsBreak:h}},I=i&&!c&&k.notesParts.length>0&&!M,R,z=0;if(I){f=``,R=s.map(e=>{let t=e.t.cursor+e.pendingTotal;return{textStart:t,contentStart:E.contentStart,pads:0,tight:k.notesParts.length>0&&!e.t.prevWordEnd&&e.pendingTotal===0,floor:t,minStart:t,wantsBreak:!1}});let t=Math.max(...s.map((e,t)=>R[t].textStart+e.textWidth+e.spaceWidth))-X(A,d),n=o-X(A+f,d),r=t>0?Math.min(Math.ceil(t/g),Math.max(0,Math.floor(n/g))):0;e.notes=`-`.repeat(r),e.inserted=[],u=D(e.notes)}else if(R=s.map(O),R.some(e=>e.wantsBreak)&&(F(),f=``,u=D(e.notes),E=C(),R=s.map(O)),z=Math.max(0,...R.map(e=>e.pads)),R.some(e=>e.pads<z)){let e=C(z);R=R.map((t,n)=>{if(t.pads===z)return t;let r=Math.max(e.textStartOf(s[n].textWidth),t.floor);return{...t,textStart:r,contentStart:e.contentStart,pads:z,tight:t.tight&&r<t.minStart}})}let K=f+`-`.repeat(z)+e.notes,q=k.notesParts.length===0;s.forEach((e,t)=>{let{t:n,sylParts:r,textWidth:i,spaceWidth:a,pendingTotal:o}=e,s=k.texts[T.indexOf(n)],c=R[t],l=c.textStart;o>0&&l<n.cursor+o&&(l=n.cursor+o);let u=Math.max(0,l-o-n.cursor);if(q)s.segments.push({kind:`gap`,role:`lead-in`,width:u,endPx:l-o,textStartPx:l});else if(n.prevWordEnd)s.segments.push({kind:`gap`,role:`word-gap`,width:u,endPx:l-o,textStartPx:l});else if(!(o===0&&c.tight)&&o===0){let e=Math.max(0,(u-_)/2);s.segments.push({kind:`connector`,pad:e,gapWidth:u,dashWidth:_,dashStartPx:n.cursor+e,nextAnchorPx:l})}let d=l-o;for(let e of n.pending)s.segments.push({kind:`syl`,parts:e.sylParts,textStart:d,textWidth:e.textWidth,contentWidth:0,contentStart:0,extraDashes:0,tight:!1,noNotes:!0}),d+=e.textWidth,e.spaceWidth>0&&(s.segments.push({kind:`word-space`,width:e.spaceWidth}),d+=e.spaceWidth);n.pending=[],s.segments.push({kind:`syl`,parts:r,textStart:l,textWidth:i,contentWidth:E.contentWidth,contentStart:c.contentStart,extraDashes:z,tight:c.tight,noNotes:!1}),a>0&&s.segments.push({kind:`word-space`,width:a}),n.cursor=l+i+a,s.lastWordEnd=e.own.wordEnd,n.prevWordEnd=e.own.wordEnd});for(let e of r)s.includes(e)||a(e,q);A+=K,k.notesParts.push(K),M=!1,e.lastSeg&&(j=u.trailing.length>0,P=i),e.lastSeg||(W=!0),G++}te(!0),T.forEach((e,t)=>{k.texts[t].textCursor=e.cursor}),k.notesEnd=k.notesParts.length?X(k.clefPrefix+k.notesParts.join(``),d):0,O.forEach((e,t)=>{if(t!==O.length-1)for(let t of e.texts){if(t.lastWordEnd!==!1)continue;let n=e.notesEnd>t.textCursor?Math.max(0,(e.notesEnd-t.textCursor-_)/2):0;t.segments.push({kind:`line-end-dash`,pad:n,dashWidth:_,dashStartPx:t.textCursor+n,trailEndPx:e.notesEnd,textEndPx:t.textCursor})}});for(let e of O)e.textCursor=e.texts[0].textCursor,e.lastWordEnd=e.texts[0].lastWordEnd;let K=o+(l.padding??0),q=X(`*`,d);return O.forEach((e,t)=>{if(t===O.length-1)return;if(o===1/0){e.breakMarkerLeftPx=l.padding??0;return}let n=X(e.clefPrefix+e.notesParts.join(``),d);for(;n+g<=K-q&&n+g<o;)e.notesParts.push(`-`),n+=g;e.breakMarkerLeftPx=K-n-q}),{lines:O,clefPrefix:O[0].clefPrefix,styleSet:l,styleName:n,textPx:i,notesPx:a,bold:r,maxWidthPx:o,starTarget:K,starWidth:q}}var De=class e{script;constructor(e){let t=e=>typeof e==`string`?new C(e):e;this.script=typeof e==`string`||e instanceof C?t(e):e.map(t)}async render(t,n={}){let{debug:r=!1}=n,{lines:i,styleSet:a,styleName:o,textPx:s,notesPx:c,bold:l,starTarget:u,starWidth:d}=await Ee(this.script,n);t.style.fontSize=`${s}px`,t.style.fontFamily=a.textFontStack,t.dataset.style=o,t.replaceChildren(...i.flatMap(t=>[e.notesLine(t,c,u,d,r),...t.texts.map(t=>e.textLine(t,s,l,r))]))}static notesLine(e,t,n,r,i){let a=document.createElement(`div`);if(a.className=`guido`,a.style.fontSize=`${t}px`,a.textContent=e.clefPrefix+e.notesParts.join(``),e.breakMarkerLeftPx!==void 0){let t=document.createElement(`span`);t.className=`guido-break`,t.textContent=`*`,t.style.position=`relative`,t.style.left=`${e.breakMarkerLeftPx}px`,i&&(t.title=`line break at ${n.toFixed(1)}px (staff filled to ${(n-e.breakMarkerLeftPx-r).toFixed(1)}px)`),a.appendChild(t)}return a}static textLine(t,n,r,i){let a=document.createElement(`p`);r&&(a.style.fontWeight=`700`);for(let r of t.segments)switch(r.kind){case`gap`:{let t=e.spacer(r.width);i&&(t.title=`${r.role===`lead-in`?`lead-in`:`word gap`} ${r.width.toFixed(1)}px → text ${r.textStartPx.toFixed(1)}`),a.appendChild(t);break}case`connector`:{let t=e.spacer(r.pad),n=document.createElement(`span`);n.className=`dash`,n.textContent=`-`;let o=e.spacer(r.pad);i&&(t.title=`lead pad ${r.pad.toFixed(1)}px (gap ${r.gapWidth.toFixed(1)} − dash ${r.dashWidth.toFixed(1)}, halved)`,n.title=`dash ${r.dashWidth.toFixed(1)}px`,o.title=`trail pad ${r.pad.toFixed(1)}px`),a.append(t,n,o);break}case`syl`:{let t=e.sylSpan(r.parts,n);if(i){if(r.noNotes)t.title=`no notes, text w ${r.textWidth.toFixed(1)}, ${r.trailing?`end of score`:`before the next syllable with notes`}`;else{let e=(r.textWidth-r.contentWidth)/2,n=r.textStart-r.contentStart;t.title=[`text w ${r.textWidth.toFixed(1)}`,`notes w ${r.contentWidth.toFixed(1)}`,r.extraDashes?`+${r.extraDashes} pad dash(es)`:null,`text start ${r.textStart.toFixed(1)}`,`notes start ${r.contentStart.toFixed(1)}`,`theoDiff: ${e.toFixed(1)}`,`cursDiff: ${n.toFixed(1)}`].filter(Boolean).join(`, `)}}a.appendChild(t);break}case`word-space`:{let e=document.createElement(`span`);e.className=`word-space`,e.textContent=` `,i&&(e.title=`word space ${r.width.toFixed(1)}px`),a.appendChild(e);break}case`line-end-dash`:{let t=e.spacer(r.pad),n=document.createElement(`span`);n.className=`dash`,n.textContent=`-`;let o=e.spacer(r.pad);i&&(t.title=`lead pad ${r.pad.toFixed(1)}px → line-end dash (text end ${r.textEndPx.toFixed(1)}, notes end ${r.trailEndPx.toFixed(1)})`,n.title=`dash ${r.dashWidth.toFixed(1)}px (line end)`,o.title=`trail pad ${r.pad.toFixed(1)}px`),a.append(t,n,o);break}}return a}static sylSpan(e,t){let n=document.createElement(`span`);return n.className=`syl`,e.forEach(e=>{let r=document.createElement(`span`);r.textContent=e.text;for(let[n,i]of Object.entries(pe(e.style,t)))r.style.setProperty(n,i);let i=[...e.kind?[e.kind]:[],...e.style.initial?[`initial`]:[]].join(` `);i&&(r.className=i),n.appendChild(r)}),n}static spacer(e){let t=document.createElement(`span`);return t.className=`spacer`,t.style.display=`inline-block`,t.style.width=`${e}px`,t}},Oe={name:`guidex`,version:`0.3.2`,description:`Guidex — render plainchant scores from a compact GuidoScript notation, as a web app and an embeddable runtime`,type:`module`,workspaces:[`examples/*`],main:`./dist/lib/embed/manual.js`,types:`./dist/lib/embed/manual.d.ts`,exports:{".":{types:`./dist/lib/embed/manual.d.ts`,default:`./dist/lib/embed/manual.js`},"./embed":{types:`./dist/lib/embed/index.d.ts`,default:`./dist/lib/embed/index.js`},"./guidex.css":{types:`./dist/lib/guidex.css.d.ts`,default:`./dist/lib/guidex.css`},"./fonts/*":`./dist/lib/fonts/*`,"./react":{types:`./dist/lib/react/index.d.ts`,default:`./dist/lib/react/index.js`},"./word":{types:`./dist/lib/word/index.d.ts`,default:`./dist/lib/word/index.js`}},files:[`dist-embed`,`dist/lib`],peerDependencies:{react:`>=18`},peerDependenciesMeta:{react:{optional:!0}},publishConfig:{access:`public`},scripts:{dev:`vite --host`,build:`tsc && vite build`,"build:embed":`vite build --config vite.embed.config.ts`,"build:lib":`vite build --config vite.lib.config.ts`,preview:`vite preview`,test:`vitest run`,lint:`eslint .`},keywords:[`plainchant`,`gregorian`,`guido`,`score`,`notation`,`liturgy`],repository:{type:`git`,url:`git+https://github.com/BrownieMaar/guidex.git`},bugs:{url:`https://github.com/BrownieMaar/guidex/issues`},homepage:`https://github.com/BrownieMaar/guidex#readme`,devDependencies:{"@eslint/js":`^10.0.1`,"@testing-library/dom":`^10.4.2`,"@testing-library/react":`^16.3.3`,"@testing-library/user-event":`^14.6.7`,"@types/react":`^19.3.0`,"@types/react-dom":`^19.3.0`,"@vitejs/plugin-react":`^6.1.1`,eslint:`^10.10.0`,jsdom:`^29.1.1`,react:`^19.3.0`,"react-dom":`^19.3.0`,typescript:`~6.0.2`,"typescript-eslint":`^8.70.0`,vite:`^8.2.2`,"vite-plugin-dts":`^5.1.1`,vitest:`^4.1.11`}}.version,ke=`.guidex-script, .guido-script`,Z={maxWidth:`auto`,style:`BNS`,bold:!1,textPx:18,transpose:0,stanza:1,stack:void 0,emptySlots:`normal`,stanzas:void 0,debug:!1},Q={},Ae=new WeakMap,$=new WeakMap,je=new WeakMap;function Me(e){if(e!==void 0){if(e===``||e===`true`)return!0;if(e===`false`)return!1}}function Ne(e){if(e===void 0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function Pe(e,t){if(/^auto$/i.test(e.trim()))return`auto`;let n=Number(e);return Number.isFinite(n)&&n>0?n:(console.warn(`[guidex] ignoring invalid data-max-width "${e}"`),t)}var Fe=new WeakMap;function Ie(e){if(e!==void 0){if(e===`normal`||e===`small`||e===`partial`)return e;console.warn(`[guidex] ignoring invalid data-empty-slots "${e}"`)}}function Le(e){if(e===void 0)return;if(/^\s*all\s*$/i.test(e))return`all`;let t=e.split(`,`).map(e=>Number(e.trim()));if(e.trim()!==``&&t.every(e=>Number.isInteger(e)&&e>0))return t;console.warn(`[guidex] ignoring invalid data-stack "${e}"`)}function Re(e){let t=e.dataset,n=Fe.get(e)??{};return{maxWidth:t.maxWidth===void 0?n.maxWidth??Q.maxWidth??Z.maxWidth:Pe(t.maxWidth,n.maxWidth??Q.maxWidth??Z.maxWidth),style:t.style??n.style??Q.style??Z.style,bold:Me(t.bold)??n.bold??Q.bold??Z.bold,textPx:Ne(t.textPx)??n.textPx??Q.textPx??Z.textPx,transpose:Ne(t.transpose)??n.transpose??Q.transpose??Z.transpose,stanza:Ne(t.stanza)??n.stanza??Q.stanza??Z.stanza,stack:Le(t.stack)??n.stack??Q.stack??Z.stack,emptySlots:Ie(t.emptySlots)??n.emptySlots??Q.emptySlots??Z.emptySlots,stanzas:n.stanzas??Z.stanzas,debug:Me(t.debug)??n.debug??Q.debug??Z.debug}}function ze(e){return e.querySelector(`:scope > .guidex-render`)?.clientWidth||e.clientWidth||e.parentElement?.clientWidth||0}function Be(e,t,n){if(typeof t==`number`)return t;let r=ze(e);if(r<=0)return 1/0;let i=r-(ue[n]?.padding??0);return i>0?i:r}function Ve(e){for(let t of e.childNodes)if(t.nodeType===Node.TEXT_NODE&&t.nodeValue?.trim())return t.nodeValue.trim();return Ae.get(e)??``}function He(e){let t=e.querySelector(`:scope > .guidex-render`);if(t)return t;let n=document.createElement(`div`);return n.className=`guidex-render`,e.replaceChildren(n),n}function Ue(e,t){let n=document.createElement(`p`);n.className=`guidex-error`,n.textContent=t,e.replaceChildren(n)}function We(e){let t=[...ue[e.style]?.scriptTransforms??[]];return e.transpose!==0&&t.push(oe(e.transpose)),t}function Ge(e,t){let n=We(t),{stanzas:r,emptySlots:i}=t;if(t.stack!==void 0){let a=W(e,t.stack,{stanzas:r});return{scripts:G(e,a,{stanzas:r,emptySlots:i,transforms:n}),warnings:a.flatMap(t=>z(e,{stanzas:r,stanza:t}))}}return(t.stanza!==1||i!==`normal`)&&n.unshift(U(t.stanza,{stanzas:r,emptySlots:i})),{scripts:[new C(e,{transforms:n})],warnings:z(e,{stanzas:r,stanza:t.stanza})}}async function Ke(e,t,n,r,i){let a=He(e),o=document.createElement(`div`);try{let{scripts:s,warnings:c}=Ge(n,r);if(await new De(s).render(o,{style:r.style,bold:r.bold,textPx:r.textPx,debug:r.debug,maxWidthPx:i}),$.get(e)!==t)return{warnings:c};for(let e of c)console.warn(`[guidex] ${e.message}`);return a.replaceChildren(...o.childNodes),a.style.cssText=o.style.cssText,o.dataset.style&&(a.dataset.style=o.dataset.style),{warnings:c}}catch(n){return $.get(e)===t?(console.error(`[guidex]`,n),Ue(a,n instanceof Error?n.message:String(n)),{warnings:[]}):{warnings:[]}}}async function qe(e){let t=($.get(e)??0)+1;$.set(e,t);let n=Re(e),r=Ve(e);Ae.set(e,r),He(e);let i=Be(e,n.maxWidth,n.style);je.set(e,i),await Ke(e,t,r,n,i)}var Je=new WeakMap;function Ye(e){let t=Re(e),n=Be(e,t.maxWidth,t.style);return Math.abs(n-(je.get(e)??NaN))>1}function Xe(e){if(Je.has(e))return;let t;if(typeof ResizeObserver<`u`){let n=new ResizeObserver(()=>{Ye(e)&&qe(e)});n.observe(e),t=()=>n.disconnect()}else{let n=()=>{Ye(e)&&qe(e)};window.addEventListener(`resize`,n),t=()=>window.removeEventListener(`resize`,n)}Je.set(e,t)}function Ze(e){Je.get(e)?.(),Je.delete(e),Ae.delete(e),Fe.delete(e),$.delete(e),je.delete(e)}async function Qe(e,t,n={}){Fe.set(e,n);let r=($.get(e)??0)+1;$.set(e,r),Ae.set(e,t);let i=Re(e);He(e);let a=Be(e,i.maxWidth,i.style);return je.set(e,a),Xe(e),Ke(e,r,t,i,a)}async function $e(e=document){let t=Q.selector??ke,n=[];return e instanceof Element&&e.matches(t)&&n.push(e),n.push(...e.querySelectorAll(t)),Promise.all(n.map(e=>(Xe(e),qe(e)))).then(()=>void 0)}var et=!1;function tt(){if(et||typeof MutationObserver>`u`)return;et=!0;let e=Q.selector??ke;new MutationObserver(t=>{let n=new Set;for(let r of t)for(let t of r.addedNodes)if(t instanceof Element&&!t.closest(`.guidex-render`)){t.matches(e)&&n.add(t);for(let r of t.querySelectorAll(e))n.add(r)}for(let e of n)Xe(e),qe(e)}).observe(document.documentElement,{childList:!0,subtree:!0})}function nt(e={}){Q={...Q,...e},tt(),$e()}var rt=[`font-family`,`font-size`,`font-style`,`font-weight`,`line-height`,`letter-spacing`,`text-transform`,`color`,`position`,`top`,`left`,`margin-top`,`margin-bottom`,`padding-top`,`padding-bottom`],it=[`font-family`,`font-size`,`font-style`,`font-weight`,`line-height`,`letter-spacing`,`color`];function at(e){return e.classList.contains(`max-width-guide`)||e.hasAttribute(`data-score-image-ignore`)}function ot(e){let t=e.querySelector(`.guido`)?.parentElement;if(!t)throw Error(`No rendered score found to export — render a score into the element first.`);return t}function st(e){let t=e.getBoundingClientRect(),n=[],r=document.createRange();return r.selectNodeContents(e),typeof r.getBoundingClientRect==`function`&&n.push(r.getBoundingClientRect()),e.querySelectorAll(`*`).forEach(e=>n.push(e.getBoundingClientRect())),n.length===0&&n.push(t),{left:Math.min(...n.map(e=>e.left))-t.left,top:Math.min(...n.map(e=>e.top))-t.top,right:Math.max(...n.map(e=>e.right))-t.left,bottom:Math.max(...n.map(e=>e.bottom))-t.top}}function ct(e){let t=document.createRange();if(t.selectNodeContents(e),typeof t.getClientRects!=`function`)return 1;let n=Array.from(t.getClientRects()).filter(e=>e.width>0||e.height>0);if(n.length===0)return 1;n.sort((e,t)=>e.top-t.top);let r=0,i=-1/0;for(let e of n)e.top>=i?(r++,i=e.bottom):e.bottom>i&&(i=e.bottom);return r}function lt(e){let t=[],n=``,r=null;for(let i of e)r?i===r?r=null:n+=i:i===`"`||i===`'`?r=i:i===`,`?(t.push(n.trim()),n=``):n+=i;return t.push(n.trim()),t.filter(Boolean)}function ut(e){return e===`normal`?`400`:e===`bold`?`700`:e}function dt(e){return e.replace(/&/g,`&amp;`).replace(/"/g,`&quot;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function ft(e,t,n,r,i){let a=/url\(\s*(['"]?)([^'")]+)\1\s*\)/.exec(r);if(!a)return;let o;try{o=new URL(a[2],i??location.href).toString()}catch{return}return{family:e,style:t||`normal`,weight:ut(n||`400`),url:o,format:/format\(\s*['"]?([^'")]+?)['"]?\s*\)/.exec(r)?.[1]}}function pt(e,t){let n=[];for(let r of e.matchAll(/@font-face\s*{([^}]*)}/g)){let e=r[1],i=t=>{let n=RegExp(`(?:^|[;\\s])${t}\\s*:\\s*([^;]+)`,`i`).exec(e);return n?n[1].trim():``},a=i(`font-family`),o=i(`src`);if(!a||!o)continue;let s=lt(a)[0];if(!s)continue;let c=ft(s,i(`font-style`),i(`font-weight`),o,t);c&&n.push(c)}return n}async function mt(e){let t=[],n=new Set,r=e=>{let r=`${e.family}|${e.style}|${e.weight}`;n.has(r)||(n.add(r),t.push(e))},i=[];for(let t of document.styleSheets){let n;try{n=t.cssRules}catch{t.href&&i.push(t.href);continue}for(let i of Array.from(n)){let n=i.style;if(!n)continue;let a=n.getPropertyValue(`src`),o=n.getPropertyValue(`font-family`);if(!a||!o)continue;let s=lt(o)[0];if(!s||!e.has(s))continue;let c=ft(s,n.getPropertyValue(`font-style`),n.getPropertyValue(`font-weight`),a,t.href??void 0);c&&r(c)}}for(let t of i)try{let n=await fetch(t);if(!n.ok)throw Error(String(n.status));let i=await n.text();for(let n of pt(i,t))e.has(n.family)&&r(n)}catch{console.warn(`[guidex] scoreImage: a cross-origin stylesheet (${t}) could not be read — fonts declared only there are missing from the export`)}return t}async function ht(e){let t=await fetch(e);if(!t.ok)return;let n=await t.blob();return new Promise(e=>{let t=new FileReader;t.onload=()=>e(typeof t.result==`string`?t.result:void 0),t.onerror=()=>e(void 0),t.readAsDataURL(n)})}async function gt(e,t){let n=[],r=new Set,i=new Map,a=e=>{let t=i.get(e);return t||(t=ht(e).catch(()=>void 0),i.set(e,t)),t},o=new Map;for(let t of e){let e=o.get(t.family)??[];e.push(t),o.set(t.family,e)}for(let[e,i]of o){let o=i.filter(e=>e.style===`normal`),s=o.length>0?[...o,...t?i.filter(e=>e.style!==`normal`):[]]:i;for(let t of s){let i=await a(t.url);if(!i){r.add(e);continue}let o=t.format?` format('${t.format}')`:``;n.push(`@font-face{font-family:'${t.family}';font-style:${t.style};font-weight:${t.weight};src:url(${i})${o}}`)}}for(let e of r)console.warn(`[guidex] scoreImage: could not embed the ${e} webfont — the export falls back to the next family in its stack`);return n.join(``)}function _t(e){let t=document.createElement(`span`);return t.style.color=e,getComputedStyle(t).color}function vt(e){let t=getComputedStyle(e).getPropertyValue(`--red`).trim();return t?_t(t):``}function yt(e,t,n){return n&&t&&_t(t)===n?!0:e.style?.getPropertyValue(`color`).replace(/\s+/g,``)===`var(--red)`}function bt(e,t,n){let r=new Set,i=!1;for(let a=0;a<e.length;a++){let o=e[a],s=t[a],c=getComputedStyle(o);for(let e of a===0?it:rt){if(e===`color`){let e=c.getPropertyValue(`color`);if(!e)continue;let t=yt(o,e,n.accentProbe)?n.accent:n.foreground;s.style.setProperty(`color`,t||e);continue}let t=c.getPropertyValue(e);t&&s.style.setProperty(e,t)}let l=c.getPropertyValue(`font-family`);if(l)for(let e of lt(l))r.add(e);c.getPropertyValue(`font-style`)===`italic`&&(i=!0)}return{families:r,italics:i}}async function xt(){let e=document.fonts;e?.ready&&await e.ready}async function St(e,t){let n=Math.max(0,t.padding??0),r=ot(e);if(!r.isConnected)throw Error(`scoreImage: the score left the document before the export — re-render it and try again`);await xt();let i=Array.from(r.children).filter(e=>e.classList.contains(`guido`)||e.tagName===`P`);if(i.length===0)throw Error(`No rendered score found to export — render a score into the element first.`);let a=i.map(e=>e.getBoundingClientRect()),o=a[0],s=i.map((e,t)=>{let n=st(e),r=a[t],i=r.left-o.left,s=ct(e)>1;return{left:n.left+i,top:n.top+(r.top-o.top),right:(s?Math.max(r.width,n.right):n.right)+i,bottom:n.bottom+(r.top-o.top),pinWidth:s?r.width:void 0}}),c=Math.min(0,...s.map(e=>e.left)),l=Math.min(0,...s.map(e=>e.top)),u=Math.max(...s.map(e=>e.right)),d=Math.max(...s.map(e=>e.bottom)),f=Math.max(1,Math.ceil(u-c))+n*2,p=Math.max(1,Math.ceil(d-l))+n*2,m=r.cloneNode(!0);m.querySelectorAll(`.max-width-guide, [data-score-image-ignore]`).forEach(e=>e.remove());let h=[r],g=[m],_=(e,t)=>{for(let n of e.children)at(n)||(t.push(n),_(n,t))};if(_(r,h),_(m,g),g.length!==h.length)throw Error(`scoreImage: the cloned tree diverged from the live one`);for(let e of[m,...m.querySelectorAll(`*`)])e.removeAttribute(`title`);let{families:v,italics:y}=bt(h,g,{foreground:t.foreground,accent:t.accent,accentProbe:vt(r)});m.style.setProperty(`white-space`,`nowrap`);let b=Array.from(m.children).filter(e=>e.classList.contains(`guido`)||e.tagName===`P`);s.forEach((e,t)=>{let n=b[t];e.pinWidth!==void 0&&n&&n.style.setProperty(`width`,`${e.pinWidth}px`)}),m.style.setProperty(`padding-top`,`${n-l}px`),m.style.setProperty(`padding-left`,`${n-c}px`),m.style.setProperty(`padding-right`,`${n}px`),m.style.setProperty(`padding-bottom`,`${n}px`);let x=await gt(await mt(v),y),S=new XMLSerializer().serializeToString(m),C=t.background?`<rect width="100%" height="100%" fill="${dt(t.background)}"/>`:``;return{svg:`<svg xmlns="http://www.w3.org/2000/svg" width="${f}" height="${p}" viewBox="0 0 ${f} ${p}">`+C+(x?`<style>${x}</style>`:``)+`<foreignObject x="0" y="0" width="${f}" height="${p}">`+S+`</foreignObject></svg>`,width:f,height:p}}async function Ct(e,t={}){return(await St(e,t)).svg}async function wt(e,t={}){let{svg:n,width:r,height:i}=await St(e,t),a=Math.max(1,t.scale??2),o=new Image;o.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(n)}`,await new Promise((e,t)=>{o.onload=()=>e(),o.onerror=()=>t(Error(`scoreImage: the exported SVG failed to rasterize`))});try{await o.decode()}catch{}let s=document.createElement(`canvas`);s.width=Math.ceil(r*a),s.height=Math.ceil(i*a);let c=s.getContext(`2d`);if(!c)throw Error(`scoreImage: this environment provides no 2D canvas`);c.scale(a,a),t.background&&(c.fillStyle=t.background,c.fillRect(0,0,r,i));let l=()=>c.drawImage(o,0,0,r,i);l(),/^((?!chrome|android|crios|fxios).)*safari/i.test(navigator.userAgent)&&(await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(e))),l());let u=await new Promise(e=>s.toBlob(e,`image/png`));if(!u)throw Error(`scoreImage: PNG encoding failed`);return u}function Tt(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,r.click(),setTimeout(()=>URL.revokeObjectURL(n),1e4)}async function Et(e,t={}){let n=t.filename??`score.png`;return Tt(await wt(e,t),n),n}async function Dt(e,t={}){let n=t.filename??`score.svg`;return Tt(new Blob([await Ct(e,t)],{type:`image/svg+xml;charset=utf-8`}),n),n}return document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>nt(),{once:!0}):nt(),e.dispose=Ze,e.downloadScorePng=Et,e.downloadScoreSvg=Dt,e.init=nt,e.renderAll=$e,e.renderScore=Qe,e.scorePngBlob=wt,e.scoreSvg=Ct,e.version=Oe,e})({});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "guidex",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "description": "Guidex — render plainchant scores from a compact GuidoScript notation, as a web app and an embeddable runtime",
5
5
  "type": "module",
6
6
  "workspaces": [