guidex 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,6 +7,9 @@ export type StanzaSyllable = {
7
7
  kind: 'syllable';
8
8
  text: string;
9
9
  wordEnd: boolean;
10
+ /** The syllable in script notation, when `text` alone would
11
+ * lose an escaped markup character (`\_`, `\*`) */
12
+ source?: string;
10
13
  } | {
11
14
  kind: 'hold';
12
15
  } | {
@@ -68,14 +71,14 @@ export declare const STANZA_PLACEHOLDER = "_\u2026_";
68
71
  * - a lone `~` is an empty slot; `~` inside a syllable is a
69
72
  * non-breaking space;
70
73
  * - a backslash makes the next character literal (`\-`, `\~`, `\=`,
71
- * `\(`, `\\`).
74
+ * `\(`, `\\`), markup characters included (`\_`, `\*`).
72
75
  *
73
76
  * There are no `_` extenders: `_…_`, `__…__` and `*…*` stay the
74
77
  * syllable formatting of the script notation.
75
78
  */
76
79
  export declare function parseStanza(text: string): StanzaSyllable[];
77
- /** Whether a token opens a slot: a syllable with notes that are not all
78
- * markers. */
80
+ /** Whether a token opens a slot: a sung syllable with notes that are not
81
+ * all markers. Labels and signs are never slots. */
79
82
  export declare function isSlot(tok: ScriptToken): boolean;
80
83
  /** The number of slots (note groups that take a stanza syllable). */
81
84
  export declare function slotCount(script: GuidoScript | string): number;
@@ -0,0 +1,67 @@
1
+ /**
2
+ * The markup of syllable text, as written in the script: `{marks:…}` spans,
3
+ * which may cross syllables and words, and their sugar inside one syllable,
4
+ * the `__…__` and `_…_` wrappers, the `*…*` initial, the `**` star and the
5
+ * `*`/`†` signs. Import-free, so the parser and the style sets can share it
6
+ * without an import cycle.
7
+ *
8
+ * Markup is recognised on the text as written, before escapes fold, so an
9
+ * escaped character is a literal one and never markup. This is the only
10
+ * place that reads markup: everything else reads the parsed `TextRun`s.
11
+ */
12
+ /** A mark on a run of text: a built-in one (see `MARK_ARGUMENTS` and the
13
+ * sugar below), or a name a style set or score registers. The sugar's are
14
+ * `liturgy` (`__…__`), `rubric` (`_…_`), `initial` (`*…*`), `star` (`**`),
15
+ * `marker` (the `*`/`†` glyphs) and `plus` (a Liturgy run's `+`). */
16
+ export type Mark = string;
17
+ /** One run of syllable text: its characters, with no markup in them, and
18
+ * the marks on it, in the order they apply (later marks win). */
19
+ export interface TextRun {
20
+ text: string;
21
+ marks: Mark[];
22
+ }
23
+ /** A problem with a `{…}` span: it renders plainly, and warns. */
24
+ export interface SpanProblem {
25
+ kind: 'span';
26
+ text: string;
27
+ message: string;
28
+ }
29
+ /** The pause-marker characters: they split off into runs of their own. */
30
+ export declare const MARKER_CHARS: Set<string>;
31
+ /** The marks that take an argument, written `size:0.8`. */
32
+ export declare const MARK_ARGUMENTS: Set<string>;
33
+ /**
34
+ * Parses text with no `{…}` span in it into the runs it draws: the
35
+ * whole-syllable `**` star (drawn as ∗), a `__…__` or `_…_` wrapper around
36
+ * all of it, paired `*` markers around any part of it (`*sam*ple` → "sam"
37
+ * and "ple"), and the marker characters and a Liturgy run's `+` split off.
38
+ * The wrapper characters are dropped; escaped characters are literal.
39
+ */
40
+ export declare function parseTextRuns(written: string): TextRun[];
41
+ /** The text to read from text with no span in it: every unescaped markup
42
+ * character and sign gone, escapes folded. Empty for a sign alone. */
43
+ export declare function plainText(written: string): string;
44
+ /** One piece of text with its spans resolved (see `resolveSpans`). */
45
+ export interface ResolvedText {
46
+ /** The piece with its braces gone, for the whitespace rules */
47
+ bare: string;
48
+ /** The piece as written, trimmed, standing on its own: a span that
49
+ * reaches past the piece is closed and reopened within it */
50
+ source: string;
51
+ runs: TextRun[];
52
+ /** The text to read */
53
+ text: string;
54
+ /** The span marks the hyphen after this piece takes: the ones its last
55
+ * visible character shares with the next piece's first */
56
+ hyphen?: Mark[];
57
+ }
58
+ /**
59
+ * Resolves the `{…}` spans of consecutive pieces of text, which may open in
60
+ * one piece and close in a later one. A malformed span, a span never closed
61
+ * and a stray `}` are reported in `problems`; their text stays, plain, and
62
+ * their braces go, so no punctuation prints.
63
+ */
64
+ export declare function resolveSpans(pieces: readonly string[]): {
65
+ pieces: ResolvedText[];
66
+ problems: SpanProblem[];
67
+ };
@@ -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-EQx8frRp.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-B_9vyTt6.js";
2
2
  export { DEFAULT_SPACER, DEFAULT_TAB_INTERVAL_PT, SpacerMeter, checkWordHtml, copyWordHtml, copyWordPlainText, layoutForWord, toWordHtml, toWordText, wordLayoutText };
@@ -1,4 +1,4 @@
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";
1
+ import { A as CLEF_GLYPHS, O as SCORE_MARKERS, d as measurementFont, i as measure, n as SPECIAL_NOTES, o as SMALL_CAP_SCALE, r as layoutScore, t as NOTE_MODIFIERS } from "./chantLayout-g_xuQ9nD.js";
2
2
  //#region src/wordExport.ts
3
3
  /**
4
4
  * Word-compatible export: turns the shared layout (chantLayout.ts) into
@@ -201,6 +201,11 @@ function firstFontFamily(stack) {
201
201
  function fmtPt(pt) {
202
202
  return String(parseFloat(pt.toFixed(2)));
203
203
  }
204
+ /** A run's size in Word: real small caps take the full size, and Word
205
+ * draws the small capitals itself. */
206
+ function wordScale(style) {
207
+ return style.smallCaps ? (style.scale ?? 1) / SMALL_CAP_SCALE : style.scale;
208
+ }
204
209
  /** One syllable run as Word HTML: a `<b>` wrapper for weight, inline
205
210
  * styles for family, size, color, and raise. Characters with no glyph in
206
211
  * the destination fonts (the `**` star) ride the Symbol font as their
@@ -210,7 +215,10 @@ function partHtml(part, textPx) {
210
215
  const css = [];
211
216
  if (style.fontFamily) css.push(`font-family:'${firstFontFamily(style.fontFamily)}'`);
212
217
  if (style.italic) css.push("font-style:italic");
213
- if (style.scale !== void 0 && style.scale !== 1) css.push(`font-size:${fmtPt(textPx * style.scale * PT_PER_PX)}pt`);
218
+ const scale = wordScale(style);
219
+ if (scale !== void 0 && scale !== 1) css.push(`font-size:${fmtPt(textPx * scale * PT_PER_PX)}pt`);
220
+ if (style.smallCaps) css.push("font-variant:small-caps");
221
+ else if (style.uppercase) css.push("text-transform:uppercase");
214
222
  const color = resolveColor(style.color);
215
223
  if (color) css.push(`color:${color}`);
216
224
  if (style.raise) css.push(`vertical-align:${fmtPt(textPx * style.raise * PT_PER_PX)}pt`);
@@ -248,7 +256,7 @@ function walkTextLine(line, meter, pieces) {
248
256
  break;
249
257
  case "connector":
250
258
  spacerTo(seg.dashStartPx);
251
- out += pieces.dash();
259
+ out += pieces.dash(seg.parts);
252
260
  emitted += seg.dashWidth;
253
261
  spacerTo(seg.nextAnchorPx);
254
262
  break;
@@ -262,7 +270,7 @@ function walkTextLine(line, meter, pieces) {
262
270
  break;
263
271
  case "line-end-dash":
264
272
  spacerTo(seg.dashStartPx);
265
- out += pieces.dash();
273
+ out += pieces.dash(seg.parts);
266
274
  emitted += seg.dashWidth;
267
275
  spacerTo(seg.trailEndPx);
268
276
  }
@@ -302,9 +310,19 @@ function resolveSizing(options) {
302
310
  bold: options.bold,
303
311
  textPx: textPt !== void 0 ? textPt * PX_PER_PT : options.textPx,
304
312
  notesPx: notesPt !== void 0 ? notesPt * PX_PER_PT : options.notesPx,
305
- maxWidthPx: options.maxWidthPt !== void 0 ? options.maxWidthPt * PX_PER_PT : options.maxWidthPx
313
+ maxWidthPx: options.maxWidthPt !== void 0 ? options.maxWidthPt * PX_PER_PT : options.maxWidthPx,
314
+ junctionDashes: options.junctionDashes,
315
+ marks: options.marks,
316
+ staffFill: options.staffFill,
317
+ staffFillSnapPx: options.staffFillSnapPx
306
318
  };
307
319
  }
320
+ /** A broken line's break marker stop, in px: its right edge. Most lines
321
+ * share the layout's star target, which the paragraph style carries. */
322
+ function markerStopPx(layout, line) {
323
+ const stop = line.staffEnd + line.breakMarkerLeftPx + layout.starWidth;
324
+ return Math.abs(stop - layout.starTarget) < .01 ? layout.starTarget : stop;
325
+ }
308
326
  /**
309
327
  * Renders the score as Word-flavoured HTML: one `nota` paragraph (notes)
310
328
  * followed by one `textus` paragraph (text) per rendered line, the
@@ -344,12 +362,13 @@ async function toWordHtml(source, options = {}) {
344
362
  };
345
363
  const paragraphs = [];
346
364
  for (const line of layout.lines) {
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"` : "";
365
+ const stopPx = line.breakMarkerLeftPx !== void 0 ? markerStopPx(layout, line) : layout.starTarget;
366
+ const markerStop = stopPx !== layout.starTarget ? ` style="tab-stops:right ${fmtPt(stopPx * PT_PER_PX)}pt"` : "";
348
367
  const marker = line.breakMarkerLeftPx !== void 0 ? `<span style="mso-tab-count:1">${" ".repeat(Math.max(1, Math.round((line.breakMarkerLeftPx + layout.starWidth) / spacePx)))}</span>*` : "";
349
368
  paragraphs.push(`<p class="${notaClass}"${markerStop}><span style="letter-spacing:-.1pt">${escapeHtml(notesText(line))}</span>${marker}</p>`);
350
369
  for (const text of line.texts) paragraphs.push(`<p class="${textusClass}">` + walkTextLine(text, meter, {
351
370
  spacer: spacerHtml,
352
- dash: () => "-",
371
+ dash: (parts) => parts ? partHtml(parts[0], layout.textPx) : "-",
353
372
  syl: (seg) => sylHtml(seg, layout.textPx)
354
373
  }) + "</p>");
355
374
  }
@@ -394,7 +413,10 @@ function wordRuns(part, textPx) {
394
413
  italic: !!style.italic
395
414
  };
396
415
  if (style.fontFamily) base.fontFamily = firstFontFamily(style.fontFamily);
397
- if (style.scale !== void 0 && style.scale !== 1) base.sizePt = textPx * style.scale * PT_PER_PX;
416
+ const scale = wordScale(style);
417
+ if (scale !== void 0 && scale !== 1) base.sizePt = textPx * scale * PT_PER_PX;
418
+ if (style.smallCaps) base.smallCaps = true;
419
+ else if (style.uppercase) base.allCaps = true;
398
420
  const color = resolveColor(style.color);
399
421
  if (color) base.color = color;
400
422
  if (style.raise) base.raisePt = textPx * style.raise * PT_PER_PX;
@@ -465,7 +487,10 @@ async function layoutForWord(source, options = {}) {
465
487
  case "connector":
466
488
  case "line-end-dash":
467
489
  spacerTo(seg.dashStartPx);
468
- text.push({ type: "dash" });
490
+ text.push(seg.parts ? {
491
+ type: "dash",
492
+ run: wordRuns(seg.parts[0], layout.textPx)[0]
493
+ } : { type: "dash" });
469
494
  emitted += seg.dashWidth;
470
495
  spacerTo(seg.kind === "connector" ? seg.nextAnchorPx : seg.trailEndPx);
471
496
  break;
@@ -491,7 +516,7 @@ async function layoutForWord(source, options = {}) {
491
516
  text: texts[0],
492
517
  texts
493
518
  };
494
- if (line.breakMarkerLeftPx !== void 0) out.breakMarkerTabStopPt = finite ? layout.starTarget * PT_PER_PX : (line.notesEnd + line.breakMarkerLeftPx + layout.starWidth) * PT_PER_PX;
519
+ if (line.breakMarkerLeftPx !== void 0) out.breakMarkerTabStopPt = markerStopPx(layout, line) * PT_PER_PX;
495
520
  return out;
496
521
  }),
497
522
  style: layout.styleName,
@@ -979,7 +1004,8 @@ function checkWordHtml(html) {
979
1004
  const next = paragraphs[i + 1];
980
1005
  if (next === void 0 || next.kind !== "textus") error(`Paragraph ${i + 1} is a notes line without a text line after it — every notes line pairs with a text line`, i);
981
1006
  });
982
- for (const para of paragraphs) if (para.kind === "nota") checkNotesParagraph(para, error, warn);
1007
+ const lastNota = paragraphs.findLast((para) => para.kind === "nota");
1008
+ for (const para of paragraphs) if (para.kind === "nota") checkNotesParagraph(para, para === lastNota, error, warn);
983
1009
  else if (para.kind === "textus") checkTextParagraph(para, error, warn);
984
1010
  const gapMap = /* @__PURE__ */ new Map();
985
1011
  let letterSpacingPt = null;
@@ -1030,7 +1056,7 @@ function checkWordHtml(html) {
1030
1056
  }
1031
1057
  };
1032
1058
  }
1033
- function checkNotesParagraph(para, error, warn) {
1059
+ function checkNotesParagraph(para, last, error, warn) {
1034
1060
  const text = para.text;
1035
1061
  if (text.length === 0) {
1036
1062
  warn("Empty notes line", para.index);
@@ -1066,7 +1092,7 @@ function checkNotesParagraph(para, error, warn) {
1066
1092
  if (last?.kind !== "text" || !last.text.endsWith(NOTES_MARKER)) warn("Break marker found in an unexpected token position", para.index);
1067
1093
  else if (!beforeIsTab) error("The line-end break marker must follow a tab (the right-aligned tab stop)", para.index);
1068
1094
  }
1069
- if (/-{4,}/.test(text) && !text.endsWith(NOTES_MARKER)) warn("More than three consecutive staff dashes — staff fill dashes belong on broken lines only", para.index);
1095
+ if (/-{4,}/.test(text) && !text.endsWith(NOTES_MARKER) && !last) warn("More than three consecutive staff dashes — staff fill dashes belong on broken lines and the last line only", para.index);
1070
1096
  }
1071
1097
  function checkTextParagraph(para, error, warn) {
1072
1098
  let offset = 0;
@@ -1,5 +1,5 @@
1
- import { ChantRunKind, StyleSetName } from './guidoStyles';
2
- import { LayoutSource } from './chantLayout';
1
+ import { ChantRunKind, MarkDefinitions, StyleSetName } from './guidoStyles';
2
+ import { LayoutSource, StaffFill } 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 & {});
@@ -47,8 +47,10 @@ export interface WordStyleNames {
47
47
  textusChar: string;
48
48
  }
49
49
  export interface WordExportOptions {
50
- /** Named style set from STYLE_SETS (default: BNS) */
50
+ /** Named style set (default: BNS) */
51
51
  style?: StyleSetName;
52
+ /** Marks this score adds to its style set's */
53
+ marks?: MarkDefinitions;
52
54
  /** Export all text bold, measurements included */
53
55
  bold?: boolean;
54
56
  /** Text line size in px (default 18; 13.5pt in Word) */
@@ -60,6 +62,13 @@ export interface WordExportOptions {
60
62
  * unbroken line pair, no break markers). The caller always resolves a
61
63
  * concrete width before exporting; `auto` never reaches the emitter. */
62
64
  maxWidthPx?: number;
65
+ /** Dashes in a normal junction between note groups, in steps of a third (default 3) */
66
+ junctionDashes?: number;
67
+ /** How far each staff line runs (default `all-but-last`) */
68
+ staffFill?: StaffFill;
69
+ /** With `staffFill: 'longest'`: the distance from the available width
70
+ * within which every line runs to it instead (default 0) */
71
+ staffFillSnapPx?: number;
63
72
  /** Text line size in pt at the DESTINATION document (default: none —
64
73
  * textPx governs). Takes precedence over textPx; notes default to
65
74
  * twice the text size (the established BNS ratio). Laying out at the
@@ -136,6 +145,10 @@ export interface WordRun {
136
145
  sizePt?: number;
137
146
  /** Resolved color literal (CSS variables already resolved) */
138
147
  color?: string;
148
+ /** Word's All Caps: the text stays as written */
149
+ allCaps?: boolean;
150
+ /** Word's Small Caps: the text stays as written */
151
+ smallCaps?: boolean;
139
152
  /** Raise above the baseline, pt */
140
153
  raisePt?: number;
141
154
  /** Set when the text has no glyph in the destination fonts: emit
@@ -166,9 +179,11 @@ export type WordTextPiece =
166
179
  type: 'run';
167
180
  run: WordRun;
168
181
  }
169
- /** The connector / line-end hyphen, plain text style */
182
+ /** The connector / line-end hyphen: plain text style, unless a `{…}`
183
+ * span runs on across it */
170
184
  | {
171
185
  type: 'dash';
186
+ run?: WordRun;
172
187
  }
173
188
  /** A word-end space, plain text style */
174
189
  | {
@@ -1,2 +1,2 @@
1
- @font-face{font-family:Book Antiqua;src:url(./fonts/bkant.ttf)format("truetype");font-weight:400;font-style:normal;font-display:swap}@font-face{font-family:Book Antiqua;src:url(./fonts/antquai.ttf)format("truetype");font-weight:400;font-style:italic;font-display:swap}@font-face{font-family:Book Antiqua;src:url(./fonts/antquab.ttf)format("truetype");font-weight:700;font-style:normal;font-display:swap}@font-face{font-family:Book Antiqua;src:url(./fonts/antquabi.ttf)format("truetype");font-weight:700;font-style:italic;font-display:swap}@font-face{font-family:Guidohu;src:url(./fonts/guidohu.ttf)format("truetype");font-display:swap}@font-face{font-family:Liturgy;src:url(./fonts/liturgy.ttf)format("truetype");font-weight:400;font-display:swap}.guidex-render{--red:#d40000;--text:#2b2b2b;--text-h:#1a1a1a;color:var(--text);-webkit-text-size-adjust:100%;-moz-text-size-adjust:100%;text-size-adjust:100%}@media (prefers-color-scheme:dark){.guidex-render{--red:#ff4d4d;--text:#d4cdc7;--text-h:#f5f0ea}}.guidex-render .guido{color:var(--text-h);padding-block:.3em;font-family:Guidohu,Book Antiqua,Palatino Linotype,Palatino,Georgia,serif;font-size:200%;line-height:120%;position:relative}.guidex-render p{margin:0;line-height:normal}.guidex-render p:first-letter{color:inherit;font-weight:inherit;float:none}.guidex-render .syl,.guidex-render .guido-break{position:relative}.guidex-render .guidex-error{color:var(--red);margin:0;font:14px/1.4 Book Antiqua,Palatino Linotype,Palatino,Georgia,serif}
1
+ @font-face{font-family:Book Antiqua;src:url(./fonts/bkant.ttf)format("truetype");font-weight:400;font-style:normal;font-display:swap}@font-face{font-family:Book Antiqua;src:url(./fonts/antquai.ttf)format("truetype");font-weight:400;font-style:italic;font-display:swap}@font-face{font-family:Book Antiqua;src:url(./fonts/antquab.ttf)format("truetype");font-weight:700;font-style:normal;font-display:swap}@font-face{font-family:Book Antiqua;src:url(./fonts/antquabi.ttf)format("truetype");font-weight:700;font-style:italic;font-display:swap}@font-face{font-family:Guidohu;src:url(./fonts/guidohu.ttf)format("truetype");font-display:swap}@font-face{font-family:Liturgy;src:url(./fonts/liturgy.ttf)format("truetype");font-weight:400;font-display:swap}.guidex-render{--red:#d40000;--text:#2b2b2b;--text-h:#1a1a1a;color:var(--text);-webkit-text-size-adjust:100%;-moz-text-size-adjust:100%;text-size-adjust:100%;grid-template-columns:minmax(0,1fr);align-content:start;display:grid}.guidex-render[data-fixed-width]{min-width:max-content}@media (prefers-color-scheme:dark){.guidex-render{--red:#ff4d4d;--text:#d4cdc7;--text-h:#f5f0ea}}.guidex-render .guido{color:var(--text-h);white-space:nowrap;padding-block:.3em;font-family:Guidohu,Book Antiqua,Palatino Linotype,Palatino,Georgia,serif;font-size:200%;line-height:120%;position:relative}.guidex-render p{white-space:nowrap;margin:0;line-height:normal}.guidex-render p:first-letter{color:inherit;font-weight:inherit;float:none}.guidex-render .syl,.guidex-render .guido-break{position:relative}.guidex-render .guidex-error{color:var(--red);white-space:normal;margin:0;font:14px/1.4 Book Antiqua,Palatino Linotype,Palatino,Georgia,serif}
2
2
  /*$vite$:1*/
@@ -1 +1 @@
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})({});
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=new Map([[`Â`,`Ã`],[`Ä`,`Å`],[`Æ`,`Ç`]]);function f(e,t=0){let n=d.get(e[t]??``);if(n===void 0)return 0;let r=t+1;for(;r<e.length&&u(e[r]);)r++;if(r===t+1||e[r]!==n)return 0;for(r++;e[r]===`¨`||e[r]===`-`;)r++;return r-t}var p={">":{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 m(e){return Object.hasOwn(p,e)}var h=[...`ðñ0123456789öüó`],g=`abcdefg`;function _(e,t=`M`){let n=h.indexOf(h.includes(e)?e:c(e)?.base??``),i=p[t];if(n<0||!i)return;let a=h.indexOf(`2`)+2*(i.line-1),o=g.indexOf(i.clef)-g.indexOf(r(h[a])[0]);return g[((g.indexOf(r(h[n])[0])+o)%7+7)%7]}var v=new Set(`,.:?'"+!%/=()ÖÜÓ;`.split(``));function y(e){let t=0;for(;t<e.length&&v.has(e[t]);)t++;t>0&&t<e.length&&(t=e[t]===`-`?t+1:0);let n=e.length;for(;n>t&&v.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 b=new Set([`*`,`†`]),x=new Set([`color`,`size`,`raise`,`font`]),S={_:``,"*":``,"†":``,"∗":``},ee=new Map(Object.entries(S).map(([e,t])=>[t,e]));function te(e){return e.replace(/\\(.)/gsu,(e,t)=>S[t]??t)}function ne(e){return e.replace(/[-]/g,e=>ee.get(e))}function C(e){return[`__`,`_`].find(t=>e.length>=t.length*2+1&&e.startsWith(t)&&e.endsWith(t))}function w(e){let t=[],n=e,r=``;for(let e=/\*([^*]+)\*/.exec(n);e;e=/\*([^*]+)\*/.exec(n))r+=n.slice(0,e.index),r&&=(t.push({text:r,initial:!1}),``),t.push({text:e[1],initial:!0}),n=n.slice(e.index+e[0].length);return r+=n,r&&t.push({text:r,initial:!1}),t}function T(e,t,n){let r=e=>b.has(e)?`marker`:n&&e===`+`?`plus`:void 0,i=[];for(let t of e){let e=r(t),n=i[i.length-1];n&&n.glyph===e?n.text+=t:i.push({text:t,glyph:e})}return i.map(e=>({text:e.text,marks:e.glyph?[...t,e.glyph]:[...t]}))}function E(e){if(e.length===0)return[];let t=te(e);if(t===`**`)return[{text:`∗`,marks:[`star`]}];let n=C(t),r=n?t.slice(n.length,-n.length):t,i=n?[n===`__`?`liturgy`:`rubric`]:[];return w(r).flatMap(({text:e,initial:t})=>T(ne(e),t?[...i,`initial`]:i,n===`__`))}function re(e){return ne(te(e).replace(/[_*†∗]/g,``))}function D(e){let t=[],n=0;for(;;){let r=/^[A-Za-z][\w-]*/.exec(e.slice(n))?.[0];if(!r)return;if(n+=r.length,e[n]===`:`&&x.has(r)){let i=/^[^\s,:{}]+/.exec(e.slice(n+1))?.[0];if(!i)return;t.push(`${r}:${i}`),n+=1+i.length}else t.push(r);if(e[n]===`:`)return{marks:t,length:n+1};if(e[n]!==`,`)return;n+=1}}function ie(e){let t=[],n=``,r=()=>{n&&t.push({type:`text`,written:n}),n=``};for(let i=0;i<e.length;i++){let a=e[i];if(a===`\\`&&i+1<e.length)n+=a+e[++i];else if(a===`{`){r();let n=D(e.slice(i+1));t.push({type:`open`,marks:n?.marks}),n&&(i+=n.length)}else a===`}`?(r(),t.push({type:`close`})):n+=a}return r(),t}function O(e){let t=[],n=e.map(ie),r=new Map,i=[],a=new Set;for(let[o,s]of n.entries())for(let n of s)if(n.type===`open`){n.marks||t.push({kind:`span`,text:e[o].trim(),message:`A "{" needs its marks and a colon, as in "{red:text}" (in "${e[o].trim()}")`});let a={marks:n.marks??[]};r.set(n,a),i.push(a)}else n.type===`close`&&!i.pop()&&(a.add(n),t.push({kind:`span`,text:e[o].trim(),message:`A "}" closes nothing (in "${e[o].trim()}")`}));for(let e of i)e.marks.length>0&&t.push({kind:`span`,text:e.marks.join(`,`),message:`The span "{${e.marks.join(`,`)}:" is never closed`}),e.marks=[];let o=[],s=[],c;for(let[t,i]of n.entries()){let n=o.length>0,l=[],u={bare:``,source:``,runs:[],text:``};for(let e of i)e.type===`open`?o.push(r.get(e)):e.type===`close`?a.has(e)||o.pop():l.push({marks:o.flatMap(e=>e.marks),written:e.written});u.bare=l.map(e=>e.written).join(``);let d=k(l);u.runs=d.flatMap(({marks:e,written:t})=>E(t).map(t=>({text:t.text,marks:[...e,...t.marks]}))),u.text=d.map(({written:e})=>re(e)).join(``);let f=i.some(e=>a.has(e)||e.type===`open`&&r.get(e).marks.length===0),p=i.some(e=>e.type===`open`||e.type===`close`);u.source=n||o.length>0||f||p&&u.bare.trim()===``?d.map(({marks:e,written:t})=>e.length>0?`{${e.join(`,`)}:${t}}`:t).join(``):e[t].trim();let m=d.filter(e=>e.written.trim()!==``);if(m.length>0){if(c){let e=new Set(m[0].marks),t=c.marks.filter(t=>e.has(t));t.length>0&&(c.piece.hyphen=t)}c={piece:u,marks:m[m.length-1].marks}}s.push(u)}return{pieces:s,problems:t}}function k(e){let t=e.map(e=>({...e})),n=t[0],r=t[t.length-1];return n&&(n.written=n.written.trimStart()),r&&(r.written=r.written.trimEnd()),t.filter(e=>e.written!==``)}function A(e){return e.trim().startsWith(`@`)}function j(e){let[t,...n]=e;return t===`@`&&n.every(u)}function M(e){return!A(e)||j(e)}function N(e,t){for(let n of e)if(!u(n))throw Error(`"${n}" is not a key modifier glyph in "${t}"`);return e}function P(e){let t=e.trim();if(j(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(!m(e))throw Error(`"${e}" is not a clef glyph in "${t}"`);return{kind:`clef`,clef:e,key:N(n.join(``),t)}}case`key`:return{kind:`key`,key:N(r,t)};case`tight`:case`keep`:case`unit`:case`aid`:if(r!==``&&r!==`off`)throw Error(`"@${n}" takes only "off": "${t}"`);return{kind:n,on:r===``};default:throw Error(`Unknown statement "${t}"`)}}function F(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})`;case`tight`:case`keep`:case`unit`:case`aid`:return e.on?`(@${e.kind})`:`(@${e.kind} off)`}}function I(e){let t=e.match(/^@stanza(?:\s+([\s\S]*))?$/);return t?t[1]??``:void 0}var L=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||!M(e[1])))return e[1]}get tokens(){return this.parse().tokens}get stanzas(){return this.parse().stanzas}get tokenSpans(){return this.parse().spans}get spanProblems(){return this.parse().problems}parse(){let e=this.normalized,t=e.match(/^\s*\(([^)]*)\)/),n=t&&M(t[1])?t[0].length:0,r=[...e.slice(n).matchAll(/((?:[^()\\]|\\.)*)\(((?:[^)\\]|\\.)*)\)/g)],i=O(r.map(e=>e[1])),a,o=[],s=[],c=[];for(let[e,t]of r.entries()){let[,r,l]=t,u=i.pieces[e],d=u.bare,f=n+t.index,p=f+r.length+1,m={start:f+(r.length-r.trimStart().length),notesStart:p,notesEnd:p+l.length,end:p+l.length+1},h=A(l)?I(l.trim()):void 0;if(h!==void 0){if(d.trim()!==``)throw Error(`statement must not carry syllable text: "${se(d.trim())}"`);o.push(h);continue}if(o.length>0){if(d.trim()===``&&l===``)continue;throw Error(`"(@stanza …)" statements must stand at the end of the script`)}if(A(l)){let e=P(l);if(d.trim()!==``)throw Error(`statement must not carry syllable text: "${se(d.trim())}"`);s.push({...e,spaceBefore:/^\s/.test(d)}),c.push(m);continue}let g=d.trim();if(g===``&&l===``&&r.trim()!==``)continue;let _={kind:`syllable`,...z(g===`~`?R:u),role:`sung`,notes:se(l),spaceBefore:/^\s/.test(d)};if(g===`~`||g===``&&a===void 0&&_.notes!==``)_.empty=!0;else if(g===``&&_.notes!==``){if(a.notes===``)throw Error(`the group "(${_.notes})" has no syllable to hold it: "${a.text}" has no notes; write "~(${_.notes})" for an empty slot`);_.held=!0}a=_,s.push(_),c.push(m)}let l;for(let[e,t]of s.entries()){if(t.kind!==`syllable`)continue;if(t.held){t.wordEnd=l.wordEnd;continue}t.wordEnd=!0;let n=!1;for(let r=e+1;r<s.length;r++){let e=s[r];if(e.spaceBefore&&(n=!0),e.kind===`syllable`&&!e.held&&!e.empty){t.wordEnd=n;break}}l=t}return B(s),{tokens:s,stanzas:o,spans:c,problems:i.problems}}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.tokens){if(n.kind!==`syllable`||n.held||n.empty)continue;t??={text:``,syllables:[]};let{text:r,source:i,runs:a,role:o,notes:s}=n;t.syllables.push({text:r,source:i,runs:a,role:o,notes:s}),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.source}(${V(e.notes)})`:`${n}${F(e)}`}),t=this.stanzas.map(e=>`(@stanza ${e})`);return`${this.clef===void 0?``:`(${this.clef})`}${e.join(``)}${t.join(``)}`}},R={bare:``,source:``,runs:[],text:``};function z(e){let{text:t,source:n,runs:r,hyphen:i}=e;return{text:t,source:n,runs:r,...i?{hyphen:i}:{}}}var ae=[`liturgy`,`rubric`];function oe(e){return/[^-¨]/.test(y(e).core)}function B(e){let t=0,n=`sung`,r=(e,t)=>e.runs.every(e=>e.marks.some(e=>t.includes(e)));for(let i of e)if(i.kind===`aid`&&(t=Math.max(0,t+(i.on?1:-1))),i.kind===`syllable`){if(i.held){i.role=n;continue}i.role=i.runs.length===0?!i.empty&&i.notes===``?`sign`:t>0?`aid`:`sung`:i.text===``||r(i,[`plus`])?`sign`:r(i,ae)&&!oe(i.notes)?`label`:t>0?`aid`:`sung`,n=i.role}}function se(e){return e.replace(/\\(.)/g,`$1`)}function V(e){return e.replace(/\\/g,`\\\\`).replace(/[()]/g,e=>`\\${e}`)}var ce=`_…_`,le=`-=­`,H=`_*†∗{}`;function ue(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=[``],n=[``];for(let{ch:r,escaped:i}of e){if(!i&&le.includes(r)){t.push(``),n.push(``);continue}let e=!i&&r===`~`?`\xA0`:r;t[t.length-1]+=e,n[n.length-1]+=i&&H.includes(r)?`\\${r}`:V(e)}let r=t.length-1;for(let[e,a]of t.entries()){if(a===``){e<r&&i.push({kind:`hold`});continue}let t=n[e];i.push({kind:`syllable`,text:a,wordEnd:e===r,...t===V(a)?{}:{source:t}})}}return de(i)}function de(e){let t=e.filter(e=>e.kind===`syllable`),n=t.map(e=>e.source??V(e.text));if(!n.some(e=>/[{}]/.test(e)))return e;let{pieces:r}=O(n);for(let[e,n]of t.entries())n.source=r[e].source;return e}function U(e){return e.kind===`syllable`&&e.role!==`label`&&e.role!==`sign`&&e.notes!==``&&y(e.notes).core!==``}function fe(e){return typeof e==`string`?new L(e):e}function W(e){return fe(e).tokens.filter(U).length}function pe(e,t={}){return t.stanzas??fe(e).stanzas}function G(e,t={}){return pe(e,t).length+1}function K(e){return e.kind===`syllable`||e.kind===`hold`}function me(e){return e.map(e=>e.empty?{kind:`empty`}:e.held?{kind:`hold`}:{kind:`syllable`,text:e.text,source:e.source,wordEnd:e.wordEnd})}function q(e,t,n){let r=ue(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 J(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 he(e,t={}){let n=pe(e,t),r=W(e);return t.stanza===void 0?n.flatMap((e,t)=>q(e,r,t+2).warnings):(J(t.stanza,n.length+1),t.stanza===1?[]:q(n[t.stanza-2],r,t.stanza).warnings)}function ge(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 _e({text:e,source:t}){return t??(e===`~`?`\\~`:V(e))}function ve(e,t,n){let r=new L(e),i=pe(r,n);J(t,i.length+1);let a=n.rendered??[t];for(let e of a)J(e,i.length+1);let o=n.emptySlots??`normal`;if(t===1&&o===`normal`)return e;let s=r.tokens,c=s.filter(e=>U(e)),l=[me(c),...i.map((e,t)=>q(e,c.length,t+2).fills)],u=l[t-1],d=e=>o===`partial`?l.some(t=>K(t[e]))&&!l.every(t=>K(t[e])):o===`small`&&a.every(t=>!K(l[t-1][e]))&&l.some((t,n)=>!a.includes(n+1)&&K(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(F(e),m),m=!1;continue}if(!U(e)){e.held?(g(`(${V(e.notes)})`,m),m=!1):(g(`${e.source}(${V(e.notes)})`,m||e.spaceBefore),m=e.wordEnd,h=e.notes!==``);continue}let t=u[_],n=V(d(_)?ge(e.notes):e.notes);switch(_++,t.kind){case`syllable`:g(`${_e(t)}(${n})`,m),m=t.wordEnd;break;case`hold`:g(`${h?``:`~`}(${n})`,!1);break;case`empty`:g(`~(${n})`,!1);break;case`missing`:g(`${ce}(${n})`,!0),m=!0}h=!0}return f}function ye(e,t={}){return{name:`selectStanza`,apply:n=>ve(n,e,t)}}function be(e,t,n={}){return new L(typeof e==`string`?e:e.source,{transforms:[ye(t,n),...n.transforms??[]]})}function xe(e,t,n={}){let r=G(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)J(e,r);return[...t]}function Se(e,t,n={}){let r=xe(e,t,n);return r.map(t=>be(e,t,{...n,rendered:r}))}var Ce=[`ðñ0123456789öüó`,`^]qwertzuiopõú`,`ÝÞQWERTZUIOPÕÚ`,`×sdfghjkléáû`,`ØÙDFGHJKLÉÁÛ`,`÷øaASÍYXCVBN$m`,`ÈÊËÌÎÏÐÑÒþßòôùý`,`“”•–—˜™š›œº»`,`®−§ÿ"+!%/=()ÖÜÓ`,`Ÿ¡¢£[¥¦©ª«¬`,`~¯‚ƒ„…†‡ˆ‰Š‹Œ‘’`,`àâãäåæçèêëìîï`,`½°±²³´μ·¾¸¹`];function we(e,t,n){for(let r of Ce){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 Te(e,t,n={}){if(t===0||A(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=we(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 Ee(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}(${Te(i,e,{overflow:n})})`)}}}var De={chars:b,fontFamily:`'Times New Roman', Times, serif`},Oe={weight:`400`,scale:.7,raise:.2},ke={BNS:{textFontStack:`'Book Antiqua', Georgia, serif`,notesFontStack:`'Guidohu'`,markerGlyphs:De,verifiedFonts:[{family:`'Book Antiqua'`,weight:`400`},{family:`'Book Antiqua'`,weight:`700`},{family:`'Guidohu'`,weight:`400`},{family:`'Liturgy'`,weight:`700`}],marks:{liturgy:{fontFamily:`'Liturgy', serif`,weight:`700`,color:`var(--red)`},rubric:{uppercase:!0,scale:.7,color:`var(--red)`},initial:{weight:`700`,color:`var(--red)`,initial:!0},star:{fontFamily:De.fontFamily,weight:`700`,scale:1,measureScale:.95,raise:.1,color:`var(--red)`},plus:Oe},padding:12},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`}],marks:{liturgy:{fontFamily:`'Liturgy', serif`,weight:`700`},rubric:{scale:.8,italic:!0},initial:{weight:`700`,initial:!0},star:{fontFamily:De.fontFamily,weight:`700`,scale:1,measureScale:.95,raise:.2},plus:Oe},padding:12}},Ae=new Map;function je(e){return Ae.get(e)??ke[e]}var Me={red:`var(--red)`},Ne={liturgy:`'Liturgy', serif`,times:`'Times New Roman', Times, serif`},Pe=.75,Fe=new Set([`liturgy`,`rubric`,`star`,`marker`,`plus`]);function Ie(e){return e.filter(e=>Fe.has(e)).pop()}function Le(e,t,n,r,i){let a=e=>r.colors?.[e]??Me[e],o=t.indexOf(`:`),s=o<0?t:t.slice(0,o),c=o<0?``:t.slice(o+1),l=Number(c);switch(s){case`plain`:return{};case`red`:return{...e,color:Me.red};case`b`:return{...e,weight:`700`};case`i`:return{...e,italic:!0};case`sc`:return{...e,smallCaps:!0};case`up`:return{...e,uppercase:!0};case`color`:{let t=a(c);return t?{...e,color:t}:void 0}case`size`:return l>0?{...e,scale:l,measureScale:void 0}:void 0;case`raise`:return Number.isFinite(l)&&c!==``?{...e,raise:l}:void 0;case`font`:{let t=r.fonts?.[c]??Ne[c];return t?{...e,fontFamily:t}:void 0}case`marker`:return r.markerGlyphs?.chars.has(n[0])?{...e,fontFamily:r.markerGlyphs.fontFamily}:e}let u=i?.[t]??r.marks[t];if(!u)return;let d=u.color&&a(u.color);return{...e,...u,...d?{color:d}:{}}}function Re(e,t,n,r){return t.reduce((t,i)=>Le(t,i,e,n,r)??t,{})}function ze(e,t,n){return e.filter(e=>Le({},e,``,t,n)===void 0)}function Be(e){let t=[];for(let n of e){let e=n.toUpperCase()!==n,r=t[t.length-1];r&&r.small===e?r.text+=n:t.push({text:n,small:e})}return t}function Ve(e,t,n,r){return e.flatMap(({text:e,marks:i})=>{let a=Re(e,i,t,r),o=n?{...a,weight:`700`}:a,s=Ie(i);if(!o.smallCaps)return[{text:e,style:o,kind:s}];let c={...o,smallCaps:void 0};return Be(e).map(e=>({text:e.text,kind:s,style:e.small?{...c,smallCaps:!0,uppercase:!0,scale:(c.scale??1)*Pe,measureScale:void 0}:c}))})}function He(e){return e.style.uppercase?e.text.toUpperCase():e.text}function Ue(e,t,n){return[e.italic?`italic`:`normal`,`normal`,e.weight??`400`,`${t*(e.measureScale??e.scale??1)}px`,e.fontFamily??n].join(` `)}function We(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.uppercase&&(n[`text-transform`]=`uppercase`),e.raise&&(n.position=`relative`,n.top=`${-t*e.raise}px`),n}function Ge(e,t){return e.verifiedFonts.map(e=>`${e.weight} ${t}px ${e.family}`)}var Ke=new Set([`+`,`.`,`/`,`R`,`V`]);function qe(e,t={}){let n=typeof e==`string`?new L(e):e,r=je(t.style??`BNS`);if(!r)return n.spanProblems;let i=[...n.spanProblems],a=new Set;for(let e of n.tokens){if(e.kind!==`syllable`)continue;for(let n of ze([...new Set(e.runs.flatMap(e=>e.marks))],r,t.marks))a.has(n)||(a.add(n),i.push({kind:`mark`,mark:n,text:e.source,message:`Unknown mark "${n}" (in "${e.source}")`}));let n=Ve(e.runs,r,!1,t.marks).filter(e=>e.style.fontFamily?.includes(`Liturgy`)&&e.kind!==`marker`).flatMap(e=>[...e.text]);for(let t of new Set(n))Ke.has(t)||/\s/.test(t)||i.push({kind:`glyph`,char:t,text:e.source,message:`The Liturgy font has no "${t}" (in "${e.source}"); it has only + . / R V`})}return i}var Je=new Set(`Ÿ¡¢£[¥¦©ª«¬`.split(``));function Ye(e){return e.length===1&&Je.has(e)||e.length===2&&Xe.has(e[0])&&Je.has(e[1])}var Xe=new Set(`÷øaASÍYXCVBN$mÈÊËÌÎÏÐÑÒþßòôùý“”•–—˜™š›œº»`.split(``));function Ze(e){let t=0;for(;;){let n=Xe.has(e[t]??``)?1:f(e,t);if(n===0)return t;t+=n}}function Qe(e){let{leading:t,core:n}=y(e),r=Ze(n);return r===0?0:t.length+r}var $e=[`-`,`¨`];function et(e){return`-`.repeat(Math.floor(e/3))+`¨`.repeat(e%3)}function tt(e,t,n=!0){let r=new Map;for(let i of e){if(!u(i))continue;let a=_(i,nt(t));if(n&&r.has(a))throw Error(`Key "${e}" alters the pitch ${a} twice`);r.set(a,c(i).role)}return r}function nt(e){return e!==void 0&&m(e)?e:`M`}function rt(e){if(v.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 it(e,t,n,r,i=[]){let o=``;for(let c of[e,...i]){let e=Qe(c);for(let i=0;i<c.length;i++){let l=c[i],d=rt(l),f=d===void 0?void 0:_(d,nt(r)),p=f===void 0?void 0:n.get(f),m=i>0&&(u(c[i-1])||i===e);if(f!==void 0&&p!==t.get(f)&&!m){let e=p??`modifyNatural`,t=p?a(d,p):s(d);if(t===void 0)throw Error(`The note "${l}" has no ${e} glyph for the key change`);o.includes(t)||(o+=t)}}}let c=y(e).leading.length;return{notes:e.slice(0,c)+o+e.slice(c),inserted:[...o].map((e,t)=>c+t)}}function at(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 ot(e,t){Y||=document.createElement(`canvas`).getContext(`2d`),Y.font=t;let n=Y.measureText(e);return{left:n.actualBoundingBoxLeft,right:n.actualBoundingBoxRight}}var st=[`all-but-last`,`none`,`all`,`longest`];function ct(e){let t=typeof e==`string`||e instanceof L?[e]:e;if(t.length===0)throw Error(`Nothing to lay out: no script given`);let n=t.map(e=>(typeof e==`string`?new L(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 lt(e){return!!(e.held||e.empty)}async function ut(e,t={}){let n=new Set,r=new Set;for(;;){let{result:i,splitRuns:a}=await dt(e,t,n),o=a.filter(e=>!r.has(e.run));if(o.length===0)return i;let s=o.reduce((e,t)=>t.run<e.run?t:e);n.has(s.run)||s.atLineStart?(r.add(s.run),s.nested?n.add(s.run):n.delete(s.run)):n.add(s.run)}}async function dt(e,t,n){let{style:r=`BNS`,marks:i,bold:a=!1,textPx:o=18,notesPx:s=o*2,maxWidthPx:c=1/0,junctionDashes:l=3,staffFill:d=`all-but-last`,staffFillSnapPx:f=0}=t;if(!st.includes(d))throw Error(`Unknown staffFill: "${d}"`);if(!(f>=0&&Number.isFinite(f)))throw Error(`staffFillSnapPx must be zero or more: ${f}`);let p=Math.round(l*3);if(!(l>=1&&Math.abs(l-p/3)<=.01))throw Error(`junctionDashes must be at least 1, in steps of a third: ${l}`);let m=et(p),h=et(Math.max(3,p-3)),g=ct(e),_=typeof e==`string`||e instanceof L?typeof e==`string`?new L(e):e:typeof e[0]==`string`?new L(e[0]):e[0],b=je(r);if(!b)throw Error(`Unknown style set: "${r}"`);for(let e of Ge(b,o)){try{await document.fonts.load(e)}catch{}if(!document.fonts.check(e))throw Error(`Font could not be loaded: ${e} (style "${r}")`)}let x=`400 ${s}px ${b.notesFontStack}`,S=b.textFontStack,ee=Ue({weight:a?`700`:`400`},o,S),te=e=>Ve(e,b,a,i),ne=e=>e.reduce((e,t)=>e+X(He(t),Ue(t.style,o,S)),0),C=X(`-`,x),w=X(`-`,ee),T=e=>{if(!e)return{width:w};let t=te([{text:`-`,marks:e}]);return{parts:t,width:ne(t)}},E=_.clef?.[0],re=[...(_.clef??``).slice(1)].filter(u).join(``),D=_.clef,ie=e=>e?`${e}-`:``,O=tt(re,E,!1),k=O,A=g.map(e=>{let t=e.filter(e=>e.kind===`syllable`);return{syls:t,lastTextSyl:t.reduce((e,t,n)=>lt(t)?e:n,-1),cursor:0,pending:[],prevWordEnd:void 0,hyphen:{width:w}}}),j=[],M,N,P,F=!1,I,R=!1,z=()=>{M&&(A.forEach((e,t)=>{M.texts[t].textCursor=e.cursor}),M.notesEnd=M.notesParts.length?X(M.clefPrefix+M.notesParts.join(``),x):0);let e=A.map(()=>({segments:[],textCursor:0,lastWordEnd:null}));M={clefPrefix:ie(D),notesParts:[],segments:e[0].segments,textCursor:0,notesEnd:0,staffEnd:0,lastWordEnd:null,texts:e},j.push(M),N=M.clefPrefix;for(let e of A)e.cursor=0;P=!1,R=!1,F=!1,k=O,I&&I.inserted.length>0&&(I.notes=at(I.notes,I.inserted),I.inserted=[],I.first&&(H[I.i]=I.notes))};z();let ae=g[0],oe=e=>A.every(t=>t.syls[e].held),B=[],se=0,V,ce=0,le=!1;for(let e of ae)if(e.kind!==`syllable`)B.push(e),V=void 0,(e.kind===`tight`||e.kind===`unit`)&&(ce=Math.max(0,ce+(e.on?1:-1)),ce===0&&(le=!1));else{let t={kind:`syl`,syl:e,i:se++,notes:e.notes,inserted:[],first:!0,lastSeg:!0,heldRun:[],signedByRun:!1,tightJoin:le};e.notes!==``&&(le=ce>0),oe(t.i)&&V?(V.heldRun.push(e.notes),t.signedByRun=!0):V=t,B.push(t)}let H=[],ue=(e,t,n)=>{let r=Qe(e);for(let i=e.length-1;i>=r&&i>0;i--){if(!$e.includes(e[i]))continue;let r=i+1;for(;r<e.length&&v.has(e[r]);)r++;if(!(r>=e.length)&&n(e.slice(0,r))<=t)return i}return-1},de=(e,t)=>{let n=e.notes,r=t+1;for(;r<n.length&&v.has(n[r]);)r++;e.notes=n.slice(0,t)+n.slice(t+1,r);let i=at(n.slice(r),e.inserted,r);return e.inserted=e.inserted.filter(e=>e<t),i},U=(e,t,n)=>{e.lastSeg=!1,B.splice(t+1,0,{kind:`syl`,syl:e.syl,i:e.i,notes:n,inserted:[],first:!1,lastSeg:!0,heldRun:[],signedByRun:!1,tightJoin:!1}),W=!0},fe=e=>{A.forEach((t,n)=>{for(;t.pending.length>0;){let r=t.pending[0];if(t.cursor>0&&t.cursor+r.textWidth+(r.wordEnd?0:r.hyphen.width)>c){z();continue}t.pending.shift();let i=M.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.hyphen=r.hyphen,t.hyphen=r.hyphen,i.textCursor=t.cursor}})},W=!1,pe=0,G=[],K=[],me=()=>{let e=G.pop();e&&j.length-1>e.line&&K.push(e)},q=0;for(;q<B.length;){let e=B[q];if(e.kind===`break`){(M.texts.some(e=>e.segments.length>0)||A.some(e=>e.pending.length>0))&&(fe(!1),W=!0),q++;continue}if(e.kind===`tight`||e.kind===`aid`){q++;continue}if(e.kind===`keep`||e.kind===`unit`){if(!e.on)me();else{let e=M.texts.some(e=>e.segments.length>0)||A.some(e=>e.pending.length>0);n.has(pe)&&e&&(fe(!1),W=!0),G.length>0&&(G[G.length-1].nested=!0),G.push({run:pe++,line:W?j.length:j.length-1,atLineStart:!e||W,nested:!1})}q++;continue}if(e.kind===`clef`||e.kind===`key`){if(e.kind===`clef`&&(E=e.clef),re=e.key,D=(E??``)+re,O=tt(re,E),!W){if(M.notesParts.length===0)M.clefPrefix=ie(D),N=M.clefPrefix,k=O;else if(e.kind===`clef`){let e=(P?h:m)+D+`-`;X(N+e,x)>c?W=!0:(M.notesParts.push(e),N+=e,k=O,F=!0,P=!1,R=!1)}}q++;continue}let t=e.syl,r=e.i;if(W&&=(z(),!1),I=e,k!==O&&!e.signedByRun){let t=it(e.notes,k,O,E,e.first?e.heldRun:[]);e.notes=t.notes,e.inserted=t.inserted}e.first&&(H[r]=e.signedByRun&&k!==O?it(e.notes,k,O,E).notes:e.notes);let i=A.map(t=>{let n=t.syls[r],i=e.lastSeg&&r>=t.lastTextSyl,a=te(e.first?n.runs:[]);return{t,own:n,sylParts:a,textWidth:ne(a),spaceWidth:!i&&n.wordEnd?X(` `,ee):0,pendingTotal:t.pending.reduce((e,t)=>e+t.textWidth+t.spaceWidth,0)}}),a=Ye(e.notes);if(t.empty&&e.notes.length===0){q++;continue}if(e.notes.length===0){for(let e of i)e.own.empty||e.t.pending.push({sylParts:e.sylParts,textWidth:e.textWidth,spaceWidth:e.spaceWidth,wordEnd:e.own.wordEnd,hyphen:T(e.own.hyphen)});q++;continue}if(e.first&&e.lastSeg&&!t.empty&&t.runs.length===0&&y(e.notes).core===``){let e=N[N.length-1],n=e&&e!==`-`&&!P&&!t.notes.startsWith(`-`)?`-`:``;M.notesParts.push(n+t.notes),N+=n+t.notes,P=!0,R=!1;for(let e of i)e.t.prevWordEnd=e.own.wordEnd;q++;continue}let o=(e,t)=>{e.own.held?(t&&(M.texts[A.indexOf(e.t)].lastWordEnd=!0),e.t.prevWordEnd=e.own.wordEnd):e.t.prevWordEnd===void 0&&(e.t.prevWordEnd=!0)};if(e.first&&i.every(e=>lt(e.own))){let t=oe(r),n=Ye(e.notes);if(t&&n&&H[r-1]===H[r]&&M.notesParts.length>0&&!F){R=!0,q++;continue}let a=y(e.notes),s=()=>M.notesParts.length===0||F?``:t?P?`--`:`-`:P||e.tightJoin||Ze(a.core)>0?h:m,l=s();M.notesParts.length>0&&X(N+l+e.notes,x)>c&&(z(),l=s());let u=M.notesParts.length===0;if(u&&X(N+e.notes,x)>c){let t=ue(e.notes,c,e=>X(N+e,x));if(t>=0&&t+1<e.notes.length){let n=de(e,t);U(e,q,n),a=y(e.notes)}}M.notesParts.push(l+e.notes),N+=l+e.notes;for(let e of i)o(e,u);F=!1,e.lastSeg&&(P=a.trailing.length>0,R=n),q++;continue}let s=e.first?i.filter(e=>!lt(e.own)):i,l=H[r-1]!==e.notes,u=s.every(e=>e.t.cursor===0||e.t.cursor+e.pendingTotal+e.textWidth+(e.own.wordEnd?0:T(e.own.hyphen).width)<=c);if(a&&!l&&M.notesParts.length>0&&!u&&z(),!e.first){for(;!(X(N+e.notes,x)<=c);){let t=ue(e.notes,c,e=>X(N+e,x));if(t<0||t+1>=e.notes.length)break;let n=de(e,t);U(e,q,n)}let t=y(e.notes);M.notesParts.push(e.notes),N+=e.notes,e.lastSeg&&(P=t.trailing.length>0);for(let[e,t]of i.entries())M.texts[e].lastWordEnd=!0,t.t.prevWordEnd=t.own.wordEnd;e.lastSeg||(W=!0),q++;continue}let d=y(e.notes),f=M.notesParts.length===0||F?``:P||e.tightJoin||Ze(d.core)>0?h:m;if(R){let e=/-*$/.exec(N)[0].length;f=a&&!l||e>/^-*/.exec(f)[0].length?``:f.slice(e)}let p=(e=0)=>{let t=Ze(d.core);t===d.core.length&&(t=0);let n=d.core.slice(t),r=X(n,x),i=X(N+f+`-`.repeat(e)+d.leading+d.core.slice(0,t),x),o=ot(n,x),s=-o.left,c=(o.right-o.left)/2;return{contentWidth:r,contentStart:i,textStartOf:e=>r>=e||a?i+s:i+c-e/2}},g=p();for(;;){let t=X(N+f+e.notes,x)>c,n=s.some(e=>g.textStartOf(e.textWidth)+e.textWidth+(e.own.wordEnd?0:T(e.own.hyphen).width)>c);if(!t&&!n)break;if(t){let t=ue(e.notes,c,e=>X(N+f+e,x));if(t>=0&&t+1<e.notes.length){let n=de(e,t);U(e,q,n),d=y(e.notes),g=p();break}}if(M.notesParts.length===0&&A.every(e=>e.cursor===0)){if(t){let t=ue(e.notes,c,e=>X(N+e,x));if(t>=0&&t+1<e.notes.length){let n=de(e,t);e.notes=e.notes.slice(0,t),U(e,q,n),d=y(e.notes),g=p()}}break}z(),f=``,d=y(e.notes),g=p()}let _=e=>{let{t,textWidth:n}=e,{contentWidth:r}=g,i=M.notesParts.length>0&&!t.prevWordEnd&&e.pendingTotal===0,a=t.cursor+t.hyphen.width,o=t.cursor+e.pendingTotal+(R&&i?t.hyphen.width:0),s=g.textStartOf(n),c=g.contentStart,l=0,u=!1;if(!R&&i&&s<a&&(n>r||s<t.cursor)){u=!0,s=t.cursor;let e=r>=n?s:s+(n-r)/2;return e>c&&(l=Math.round((e-c)/C)),{textStart:s,contentStart:c,pads:l,tight:u,floor:t.cursor,minStart:a}}if(s<o){let e=r>=n?o:o+(n-r)/2;if(e>c){l=Math.max(0,Math.floor((e-c)/C));let t=p(l);for(;t.textStartOf(n)<o;)l++,t=p(l);s=t.textStartOf(n),c=t.contentStart}}return{textStart:s,contentStart:c,pads:l,tight:u,floor:o,minStart:a}},v=a&&!l&&M.notesParts.length>0&&!F,b,S=0;if(v){f=``,b=s.map(e=>{let t=e.t.cursor+e.pendingTotal;return{textStart:t,contentStart:g.contentStart,pads:0,tight:M.notesParts.length>0&&!e.t.prevWordEnd&&e.pendingTotal===0,floor:t,minStart:t}});let t=Math.max(...s.map((e,t)=>b[t].textStart+e.textWidth+e.spaceWidth))-X(N,x),n=c-X(N+f,x),r=t>0?Math.min(Math.ceil(t/C),Math.max(0,Math.floor(n/C))):0;e.notes=`-`.repeat(r),e.inserted=[],d=y(e.notes)}else{let t=()=>{if(b=s.map(_),S=Math.max(0,...b.map(e=>e.pads)),b.some(e=>e.pads<S)){let e=p(S);b=b.map((t,n)=>{if(t.pads===S)return t;let r=Math.max(e.textStartOf(s[n].textWidth),t.floor);return{...t,textStart:r,contentStart:e.contentStart,pads:S,tight:t.tight&&r<t.minStart}})}};t(),M.notesParts.length>0&&(X(N+f+`-`.repeat(S)+e.notes,x)>c||s.some((e,t)=>Math.max(b[t].textStart,e.t.cursor+e.pendingTotal)+e.textWidth+(e.own.wordEnd?0:T(e.own.hyphen).width)>c))&&(z(),f=``,d=y(e.notes),g=p(),t())}let w=f+`-`.repeat(S)+e.notes,L=M.notesParts.length===0;s.forEach((e,t)=>{let{t:n,sylParts:r,textWidth:i,spaceWidth:a,pendingTotal:o}=e,s=M.texts[A.indexOf(n)],c=b[t],l=c.textStart;o>0&&l<n.cursor+o&&(l=n.cursor+o);let u=Math.max(0,l-o-n.cursor);if(L)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-n.hyphen.width)/2);s.segments.push({kind:`connector`,pad:e,gapWidth:u,dashWidth:n.hyphen.width,...n.hyphen.parts?{parts:n.hyphen.parts}:{},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:g.contentWidth,contentStart:c.contentStart,extraDashes:S,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,n.hyphen=T(e.own.hyphen),s.hyphen=n.hyphen});for(let e of i)s.includes(e)||o(e,L);N+=w,M.notesParts.push(w),F=!1,e.lastSeg&&(P=d.trailing.length>0,R=a),e.lastSeg||(W=!0),q++}for(fe(!0);G.length>0;)me();A.forEach((e,t)=>{M.texts[t].textCursor=e.cursor}),M.notesEnd=M.notesParts.length?X(M.clefPrefix+M.notesParts.join(``),x):0,j.forEach((e,t)=>{if(t!==j.length-1)for(let t of e.texts){if(t.lastWordEnd!==!1)continue;let n=t.hyphen??{width:w},r=e.notesEnd>t.textCursor?Math.max(0,(e.notesEnd-t.textCursor-n.width)/2):0;t.segments.push({kind:`line-end-dash`,pad:r,dashWidth:n.width,...n.parts?{parts:n.parts}:{},dashStartPx:t.textCursor+r,trailEndPx:e.notesEnd,textEndPx:t.textCursor})}});for(let e of j)e.textCursor=e.texts[0].textCursor,e.lastWordEnd=e.texts[0].lastWordEnd;let J=b.padding??0,he=c+J,ge=X(`*`,x),_e=d===`all`&&c===1/0?`longest`:d,ve=_e===`all`||_e===`longest`,ye=Math.max(...j.map(e=>Math.max(e.notesEnd,...e.texts.map(e=>e.textCursor)))),be=_e===`none`||c===1/0&&!ve?null:_e===`longest`&&c-ye>f?ye:c;return j.forEach((e,t)=>{let n=t===j.length-1;if(e.staffEnd=e.notesEnd,n&&(!ve||e.notesParts.length===0))return;if(be===null){e.breakMarkerLeftPx=J;return}let r=be+J,i=X(e.clefPrefix+e.notesParts.join(``),x);for(;n?i+C<=r:i+C<=r-ge&&i+C<be;)e.notesParts.push(`-`),i+=C;if(n){let t=X(`¨`,x);for(;i+t<=r;)e.notesParts.push(`¨`),i+=t}e.staffEnd=i,n||(e.breakMarkerLeftPx=r-i-ge)}),{result:{lines:j,clefPrefix:j[0].clefPrefix,styleSet:b,styleName:r,textPx:o,notesPx:s,bold:a,maxWidthPx:c,starTarget:he,starWidth:ge},splitRuns:K}}var ft=class e{script;constructor(e){let t=e=>typeof e==`string`?new L(e):e;this.script=typeof e==`string`||e instanceof L?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,starWidth:u}=await ut(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,r),...t.texts.map(t=>e.textLine(t,s,l,r))]))}static notesLine(e,t,n,r){let i=document.createElement(`div`);if(i.className=`guido`,i.style.fontSize=`${t}px`,i.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`,r&&(t.title=`line break at ${(e.staffEnd+e.breakMarkerLeftPx+n).toFixed(1)}px (staff filled to ${e.staffEnd.toFixed(1)}px)`),i.appendChild(t)}return i}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),o=e.dashSpan(r.parts,n),s=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)`,o.title=`dash ${r.dashWidth.toFixed(1)}px`,s.title=`trail pad ${r.pad.toFixed(1)}px`),a.append(t,o,s);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),o=e.dashSpan(r.parts,n),s=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)})`,o.title=`dash ${r.dashWidth.toFixed(1)}px (line end)`,s.title=`trail pad ${r.pad.toFixed(1)}px`),a.append(t,o,s);break}}return a}static dashSpan(e,t){let n=document.createElement(`span`);n.className=`dash`,n.textContent=`-`;let r=e?.[0]?.style;if(r)for(let[e,i]of Object.entries(We(r,t)))n.style.setProperty(e,i);return n}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(We(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}},pt={name:`guidex`,version:`0.4.0`,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,mt=`.guidex-script, .guido-script`,Z={maxWidth:`auto`,style:`BNS`,marks:void 0,bold:!1,textPx:18,junctionDashes:3,staffFill:`all-but-last`,staffFillSnapPx:0,transpose:0,stanza:1,stack:void 0,emptySlots:`normal`,stanzas:void 0,debug:!1},Q={},ht=new WeakMap,$=new WeakMap,gt=new WeakMap;function _t(e){if(e!==void 0){if(e===``||e===`true`)return!0;if(e===`false`)return!1}}function vt(e){if(e===void 0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function yt(e,t){if(/^auto$/i.test(e.trim()))return`auto`;let n=Number(e);return n>0?n:(console.warn(`[guidex] ignoring invalid data-max-width "${e}"`),t)}var bt=new WeakMap;function xt(e){if(e!==void 0){if(e===`normal`||e===`small`||e===`partial`)return e;console.warn(`[guidex] ignoring invalid data-empty-slots "${e}"`)}}function St(e){if(e!==void 0){if(e===`all-but-last`||e===`none`||e===`all`||e===`longest`)return e;console.warn(`[guidex] ignoring invalid data-staff-fill "${e}"`)}}function Ct(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 wt(e){let t=e.dataset,n=bt.get(e)??{},r=t.maxWidth===void 0?n.maxWidth??Q.maxWidth??Z.maxWidth:yt(t.maxWidth,n.maxWidth??Q.maxWidth??Z.maxWidth);return{marks:n.marks??Q.marks,maxWidth:r,style:t.style??n.style??Q.style??Z.style,bold:_t(t.bold)??n.bold??Q.bold??Z.bold,textPx:vt(t.textPx)??n.textPx??Q.textPx??Z.textPx,junctionDashes:vt(t.junctionDashes)??n.junctionDashes??Q.junctionDashes??Z.junctionDashes,staffFill:St(t.staffFill)??n.staffFill??Q.staffFill??Z.staffFill,staffFillSnapPx:vt(t.staffFillSnap)??n.staffFillSnapPx??Q.staffFillSnapPx??Z.staffFillSnapPx,transpose:vt(t.transpose)??n.transpose??Q.transpose??Z.transpose,stanza:vt(t.stanza)??n.stanza??Q.stanza??Z.stanza,stack:Ct(t.stack)??n.stack??Q.stack??Z.stack,emptySlots:xt(t.emptySlots)??n.emptySlots??Q.emptySlots??Z.emptySlots,stanzas:n.stanzas??Z.stanzas,debug:_t(t.debug)??n.debug??Q.debug??Z.debug}}function Tt(e){let t=e.querySelector(`:scope > .guidex-render`);return t?.removeAttribute(`data-fixed-width`),t?.clientWidth||e.clientWidth||e.parentElement?.clientWidth||0}function Et(e,t,n){if(typeof t==`number`)return t;let r=Tt(e);if(r<=0)return 1/0;let i=r-(je(n)?.padding??0);return i>0?i:r}function Dt(e){for(let t of e.childNodes)if(t.nodeType===Node.TEXT_NODE&&t.nodeValue?.trim())return t.nodeValue.trim();return ht.get(e)??``}function Ot(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 kt(e,t){let n=document.createElement(`p`);n.className=`guidex-error`,n.textContent=t,e.removeAttribute(`data-fixed-width`),e.replaceChildren(n)}function At(e){return e.transpose===0?[]:[Ee(e.transpose)]}function jt(e,t){let n=(e,n)=>({scripts:e,warnings:[...n,...e.flatMap(e=>qe(e,t))]}),r=At(t),{stanzas:i,emptySlots:a}=t;if(t.stack!==void 0){let o=xe(e,t.stack,{stanzas:i});return n(Se(e,o,{stanzas:i,emptySlots:a,transforms:r}),o.flatMap(t=>he(e,{stanzas:i,stanza:t})))}return(t.stanza!==1||a!==`normal`)&&r.unshift(ye(t.stanza,{stanzas:i,emptySlots:a})),n([new L(e,{transforms:r})],he(e,{stanzas:i,stanza:t.stanza}))}async function Mt(e,t,n,r,i){let a=Ot(e),o=document.createElement(`div`);try{let{scripts:s,warnings:c}=jt(n,r);if(await new ft(s).render(o,{style:r.style,marks:r.marks,bold:r.bold,textPx:r.textPx,junctionDashes:r.junctionDashes,staffFill:r.staffFill,staffFillSnapPx:r.staffFillSnapPx,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),a.toggleAttribute(`data-fixed-width`,typeof r.maxWidth==`number`),{warnings:c}}catch(n){return $.get(e)===t?(console.error(`[guidex]`,n),kt(a,n instanceof Error?n.message:String(n)),{warnings:[]}):{warnings:[]}}}async function Nt(e){let t=($.get(e)??0)+1;$.set(e,t);let n=wt(e),r=Dt(e);ht.set(e,r),Ot(e);let i=Et(e,n.maxWidth,n.style);gt.set(e,i),await Mt(e,t,r,n,i)}var Pt=new WeakMap;function Ft(e){let t=wt(e),n=Et(e,t.maxWidth,t.style);return Math.abs(n-(gt.get(e)??NaN))>1}function It(e){if(Pt.has(e))return;let t;if(typeof ResizeObserver<`u`){let n=new ResizeObserver(()=>{Ft(e)&&Nt(e)});n.observe(e),t=()=>n.disconnect()}else{let n=()=>{Ft(e)&&Nt(e)};window.addEventListener(`resize`,n),t=()=>window.removeEventListener(`resize`,n)}Pt.set(e,t)}function Lt(e){Pt.get(e)?.(),Pt.delete(e),ht.delete(e),bt.delete(e),$.delete(e),gt.delete(e)}async function Rt(e,t,n={}){bt.set(e,n);let r=($.get(e)??0)+1;$.set(e,r),ht.set(e,t);let i=wt(e);Ot(e);let a=Et(e,i.maxWidth,i.style);return gt.set(e,a),It(e),Mt(e,r,t,i,a)}async function zt(e=document){let t=Q.selector??mt,n=[];return e instanceof Element&&e.matches(t)&&n.push(e),n.push(...e.querySelectorAll(t)),Promise.all(n.map(e=>(It(e),Nt(e)))).then(()=>void 0)}var Bt=!1;function Vt(){if(Bt||typeof MutationObserver>`u`)return;Bt=!0;let e=Q.selector??mt;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)It(e),Nt(e)}).observe(document.documentElement,{childList:!0,subtree:!0})}function Ht(e={}){Q={...Q,...e},Vt(),zt()}var Ut=[`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`],Wt=[`font-family`,`font-size`,`font-style`,`font-weight`,`line-height`,`letter-spacing`,`color`];function Gt(e){return e.classList.contains(`max-width-guide`)||e.hasAttribute(`data-score-image-ignore`)}function Kt(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 qt(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 Jt(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 Yt(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 Xt(e){return e===`normal`?`400`:e===`bold`?`700`:e}function Zt(e){return e.replace(/&/g,`&amp;`).replace(/"/g,`&quot;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function Qt(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:Xt(n||`400`),url:o,format:/format\(\s*['"]?([^'")]+?)['"]?\s*\)/.exec(r)?.[1]}}function $t(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=Yt(a)[0];if(!s)continue;let c=Qt(s,i(`font-style`),i(`font-weight`),o,t);c&&n.push(c)}return n}async function en(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=Yt(o)[0];if(!s||!e.has(s))continue;let c=Qt(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 $t(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 tn(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 nn(e,t){let n=[],r=new Set,i=new Map,a=e=>{let t=i.get(e);return t||(t=tn(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 rn(e){let t=document.createElement(`span`);return t.style.color=e,getComputedStyle(t).color}function an(e){let t=getComputedStyle(e).getPropertyValue(`--red`).trim();return t?rn(t):``}function on(e,t,n){return n&&t&&rn(t)===n?!0:e.style?.getPropertyValue(`color`).replace(/\s+/g,``)===`var(--red)`}function sn(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?Wt:Ut){if(e===`color`){let e=c.getPropertyValue(`color`);if(!e)continue;let t=on(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 Yt(l))r.add(e);c.getPropertyValue(`font-style`)===`italic`&&(i=!0)}return{families:r,italics:i}}async function cn(){let e=document.fonts;e?.ready&&await e.ready}async function ln(e,t){let n=Math.max(0,t.padding??0),r=Kt(e);if(!r.isConnected)throw Error(`scoreImage: the score left the document before the export — re-render it and try again`);await cn();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=qt(e),r=a[t],i=r.left-o.left,s=Jt(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)Gt(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}=sn(h,g,{foreground:t.foreground,accent:t.accent,accentProbe:an(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 nn(await en(v),y),S=new XMLSerializer().serializeToString(m),ee=t.background?`<rect width="100%" height="100%" fill="${Zt(t.background)}"/>`:``;return{svg:`<svg xmlns="http://www.w3.org/2000/svg" width="${f}" height="${p}" viewBox="0 0 ${f} ${p}">`+ee+(x?`<style>${x}</style>`:``)+`<foreignObject x="0" y="0" width="${f}" height="${p}">`+S+`</foreignObject></svg>`,width:f,height:p}}async function un(e,t={}){return(await ln(e,t)).svg}async function dn(e,t={}){let{svg:n,width:r,height:i}=await ln(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 fn(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 pn(e,t={}){let n=t.filename??`score.png`;return fn(await dn(e,t),n),n}async function mn(e,t={}){let n=t.filename??`score.svg`;return fn(new Blob([await un(e,t)],{type:`image/svg+xml;charset=utf-8`}),n),n}return document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>Ht(),{once:!0}):Ht(),e.dispose=Lt,e.downloadScorePng=pn,e.downloadScoreSvg=mn,e.init=Ht,e.renderAll=zt,e.renderScore=Rt,e.scorePngBlob=dn,e.scoreSvg=un,e.version=pt,e})({});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "guidex",
3
- "version": "0.3.2",
3
+ "version": "0.4.0",
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": [