guidex 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -337,13 +337,24 @@ updates when the `script` prop changes. Props mirror the options below:
337
337
 
338
338
  | Option | Values | Default |
339
339
  | ----------- | ------------------------------- | -------------- |
340
- | `maxWidth` | pixels, or `auto` (fits the element, re-rendered on resize) | `auto` |
340
+ | `maxWidth` | pixels, `Infinity` (never break), or `auto` (fits the element, re-rendered on resize) | `auto` |
341
341
  | `style` | `BNS`, `Vesperale` | `BNS` |
342
342
  | `bold` | boolean | `false` |
343
343
  | `textPx` | base text size in px (notes render at 2×) | `18` |
344
344
  | `transpose` | pitch-row shift (see `transposeBy`) | `0` |
345
345
  | `debug` | boolean (measurement titles on spans) | `false` |
346
346
 
347
+ guidex breaks the lines itself and the browser never re-wraps them. With
348
+ `auto` every line fits the element, apart from a single note group too
349
+ wide for it. A number can be wider than the element, and `Infinity` (or
350
+ any large number; `data-max-width="Infinity"` works too) means "never
351
+ break". The score then grows past its container as one box, and the
352
+ overflow is the host page's to handle:
353
+
354
+ ```css
355
+ .my-score { overflow-x: auto; } /* or hidden, to clip */
356
+ ```
357
+
347
358
  ## Embedding with a script tag (no bundler)
348
359
 
349
360
  Host the `dist-embed/` folder (also attached to every GitHub Release)
@@ -400,6 +411,12 @@ its notes:
400
411
  follows: they hang in the junction whitespace, the syllable text is
401
412
  positioned under the note characters only, and a group starting with
402
413
  a modifier needs only a 2-dash junction.
414
+ - A bracketed accidental at the start of a note group (`ÄôŨ¨õÕö`: a
415
+ bracket pair `Â`/`Ã`, `Ä`/`Å` or `Æ`/`Ç` around accidental signs, plus
416
+ any `¨`/`-` right after it) hangs the same way: it adds staff width in
417
+ the white space before the group, the syllable text aligns with the
418
+ note after it, and the group takes the 2-dash junction. A line never
419
+ breaks inside it.
403
420
  - Control statements are groups whose content is an `@`-keyword, set
404
421
  between syllables where a syllable's text would stand:
405
422
  `(@break)` ends the current line pair at its position — the staff fills
@@ -413,6 +430,16 @@ its notes:
413
430
  key and `(@key)` clears it: up to the line end the affected notes (in
414
431
  every octave) get their accidental sign, and later lines open with
415
432
  the new key. Neither forces a line break.
433
+ `(@tight)` … `(@tight off)` sets a run of syllables one dash closer
434
+ (the `E u o u a e` of a psalm termination), `(@keep)` … `(@keep off)`
435
+ keeps a run on one line, and `(@unit)` … `(@unit off)` does both. Runs
436
+ nest, and each `off` closes one level; a run left open lasts to the end
437
+ of the script. Wide text still widens the notes inside a tight run. A
438
+ kept run wider than a whole line wraps normally, and one with kept runs
439
+ inside it dissolves into them, starting on its own line. So a hymn
440
+ written as `(@keep)(@keep)verse 1(@keep off)(@keep)verse 2(@keep off)(@keep off)`
441
+ breaks between pairs of verses first, between verses next, and inside
442
+ a verse last.
416
443
  - Style decorations on syllable text: `__…__` renders in the Liturgy
417
444
  font, bold; `_…_` renders small caps (BNS) or italic (Vesperale);
418
445
  `*…*` marks an initial (bold, red in BNS). A syllable that is exactly
@@ -99,6 +99,9 @@ export type EditorAction = {
99
99
  } | {
100
100
  type: 'SET_BOLD';
101
101
  bold: boolean;
102
+ } | {
103
+ type: 'SET_JUNCTION_DASHES';
104
+ dashes: number;
102
105
  } | {
103
106
  type: 'SET_INITIAL';
104
107
  initial: boolean;
@@ -214,7 +217,7 @@ export declare function settingsSnapshot(state: EditorState): EditorSettings;
214
217
  * ride the same handoff: a decoupled chant without a custom size adopts
215
218
  * the derived 2× base size of the chant's own base font size. */
216
219
  export declare function chantPrefsOverlay(prefs: ChantPrefs): {
217
- settings: Pick<RenderSettings, 'style' | 'bold' | 'transpose' | 'basePx' | 'decoupleNotes' | 'notesPx' | 'notesCustom'>;
220
+ settings: Pick<RenderSettings, 'style' | 'bold' | 'transpose' | 'basePx' | 'decoupleNotes' | 'notesPx' | 'notesCustom' | 'junctionDashes'>;
218
221
  transforms: ScriptTransform[];
219
222
  inputs: {
220
223
  basePx: string;
@@ -280,6 +280,28 @@ function isModifierGlyph(ch) {
280
280
  const role = BASES.get(ch)?.role;
281
281
  return role !== void 0 && MODIFIER_ROLES.includes(role);
282
282
  }
283
+ /** The bracket pairs that set a cautionary accidental off (issue #95). */
284
+ var ACCIDENTAL_BRACKETS = /* @__PURE__ */ new Map([
285
+ ["Â", "Ã"],
286
+ ["Ä", "Å"],
287
+ ["Æ", "Ç"]
288
+ ]);
289
+ /**
290
+ * The length of the bracketed accidental that opens `notes` at `from`:
291
+ * an opening bracket, one or more accidental signs, the matching closing
292
+ * bracket, and the `¨`/`-` spacing right after it (`ÄôŨ¨` in `ÄôŨ¨õ`).
293
+ * 0 when no such unit stands there.
294
+ */
295
+ function bracketedAccidentalLength(notes, from = 0) {
296
+ const close = ACCIDENTAL_BRACKETS.get(notes[from] ?? "");
297
+ if (close === void 0) return 0;
298
+ let at = from + 1;
299
+ while (at < notes.length && isModifierGlyph(notes[at])) at++;
300
+ if (at === from + 1 || notes[at] !== close) return 0;
301
+ at++;
302
+ while (notes[at] === "¨" || notes[at] === "-") at++;
303
+ return at - from;
304
+ }
283
305
  /** The clef glyphs (issue #49) and the staff line each one sits on,
284
306
  * counted from the bottom. The g-clef has two keybindings. */
285
307
  var CLEF_GLYPHS = {
@@ -368,7 +390,9 @@ function pitchLetterOf(ch, clef = "M") {
368
390
  * Control statements are groups whose content is an `@`-keyword with
369
391
  * optional arguments after one space: `(@break)` ends the current line
370
392
  * pair at its position, `(@clef MX)` changes the clef (and key) inline,
371
- * `(@key X)` replaces the key and `(@key)` clears it. Statements are
393
+ * `(@key X)` replaces the key and `(@key)` clears it. `(@tight)` tightens
394
+ * the junctions up to `(@tight off)`, `(@keep)` keeps its run on one line
395
+ * up to `(@keep off)`, and `(@unit)` / `(@unit off)` do both. Statements are
372
396
  * positional — the text run before one must be whitespace-only — and
373
397
  * they are invisible to the sung-text accessors.
374
398
  *
@@ -382,6 +406,10 @@ function pitchLetterOf(ch, clef = "M") {
382
406
  * `@` is also the c4 clef glyph: an opening group of `@` and nothing but
383
407
  * modifier glyphs (`(@)`, `(@X)`) is the opening clef, not a statement.
384
408
  */
409
+ /** The run properties a run statement sets. */
410
+ function runProperties(kind) {
411
+ return kind === "unit" ? ["tight", "keep"] : [kind];
412
+ }
385
413
  /** Whether a group's content is a control statement (`@`-keyword,
386
414
  * trimmed). Shared with the transforms, which must leave statement
387
415
  * groups alone — their keyword characters are pitch glyphs otherwise.
@@ -431,6 +459,14 @@ function parseStatement(content) {
431
459
  kind: "key",
432
460
  key: parseKey(args, statement)
433
461
  };
462
+ case "tight":
463
+ case "keep":
464
+ case "unit":
465
+ if (args !== "" && args !== "off") throw new Error(`"@${keyword}" takes only "off": "${statement}"`);
466
+ return {
467
+ kind: keyword,
468
+ on: args === ""
469
+ };
434
470
  default: throw new Error(`Unknown statement "${statement}"`);
435
471
  }
436
472
  }
@@ -440,6 +476,9 @@ function statementSource(tok) {
440
476
  case "break": return "(@break)";
441
477
  case "clef": return `(@clef ${tok.clef}${tok.key})`;
442
478
  case "key": return tok.key === "" ? "(@key)" : `(@key ${tok.key})`;
479
+ case "tight":
480
+ case "keep":
481
+ case "unit": return tok.on ? `(@${tok.kind})` : `(@${tok.kind} off)`;
443
482
  }
444
483
  }
445
484
  /** The stanza text of a `(@stanza …)` statement's trimmed content, or
@@ -1888,7 +1927,32 @@ function isRecitationGroup(notes) {
1888
1927
  */
1889
1928
  var NOTE_MODIFIERS = "÷øaASÍYXCVBN$mÈÊËÌÎÏÐÑÒþßòôùý“”•–—˜™š›œº»";
1890
1929
  var MODIFIER_CHARS = new Set(NOTE_MODIFIERS.split(""));
1930
+ /**
1931
+ * The length of what hangs at the start of a group's core: its leading
1932
+ * modifiers and bracketed accidentals (issue #95), which stand in the
1933
+ * junction whitespace before the group's first note.
1934
+ */
1935
+ function hangingLength(core) {
1936
+ let at = 0;
1937
+ for (;;) {
1938
+ const unit = MODIFIER_CHARS.has(core[at] ?? "") ? 1 : bracketedAccidentalLength(core, at);
1939
+ if (unit === 0) return at;
1940
+ at += unit;
1941
+ }
1942
+ }
1943
+ /** The index in `notes` right after its hanging run (leading markers
1944
+ * counted), or 0 when nothing hangs. */
1945
+ function hangEnd(notes) {
1946
+ const { leading, core } = splitNoteMarkers(notes);
1947
+ const hang = hangingLength(core);
1948
+ return hang === 0 ? 0 : leading.length + hang;
1949
+ }
1891
1950
  var NOTE_GROUP_SPLITTERS = ["-", "¨"];
1951
+ /** A junction `thirds` thirds of a dash wide: whole dashes, then one `¨`
1952
+ * per leftover third (`--¨¨` is 2⅔). */
1953
+ function junctionSpacer(thirds) {
1954
+ return "-".repeat(Math.floor(thirds / 3)) + "¨".repeat(thirds % 3);
1955
+ }
1892
1956
  /** The key written by a run of modifier glyphs, under `clef` (a clef
1893
1957
  * glyph; the standard g-clef when unknown — matching pitches by staff
1894
1958
  * position does not depend on it). A statement's key throws when two
@@ -1925,25 +1989,29 @@ function noteBaseOf(ch) {
1925
1989
  * signs stand before the note group, not before their notes: they go at
1926
1990
  * the start of the group's notes (after its leading markers), one per
1927
1991
  * affected pitch glyph, in order of first appearance. Notes the source
1928
- * already marks with a modifier are left alone. The groups a syllable
1929
- * holds (`held`, issue #83) are scanned too: a held run writes its signs
1992
+ * already marks with a modifier are left alone (a bracketed accidental
1993
+ * opening the group, issue #95, marks the note after it). The groups a
1994
+ * syllable holds (`held`, issue #83) are scanned too: a held run writes its signs
1930
1995
  * once, before its first group. Returns the rewritten group and the
1931
1996
  * indices of the inserted signs. Throws when a needed sign does not
1932
1997
  * exist.
1933
1998
  */
1934
1999
  function applyKeyChange(notes, staff, active, clef, held = []) {
1935
2000
  let signs = "";
1936
- for (const group of [notes, ...held]) for (let i = 0; i < group.length; i++) {
1937
- const ch = group[i];
1938
- const base = noteBaseOf(ch);
1939
- const letter = base !== void 0 ? pitchLetterOf(base, clefOrDefault(clef)) : void 0;
1940
- const want = letter !== void 0 ? active.get(letter) : void 0;
1941
- const marked = i > 0 && isModifierGlyph(group[i - 1]);
1942
- if (letter !== void 0 && want !== staff.get(letter) && !marked) {
1943
- const role = want ?? "modifyNatural";
1944
- const sign = want ? variantOf(base, want) : modifyNatural(base);
1945
- if (sign === void 0) throw new Error(`The note "${ch}" has no ${role} glyph for the key change`);
1946
- if (!signs.includes(sign)) signs += sign;
2001
+ for (const group of [notes, ...held]) {
2002
+ const hang = hangEnd(group);
2003
+ for (let i = 0; i < group.length; i++) {
2004
+ const ch = group[i];
2005
+ const base = noteBaseOf(ch);
2006
+ const letter = base !== void 0 ? pitchLetterOf(base, clefOrDefault(clef)) : void 0;
2007
+ const want = letter !== void 0 ? active.get(letter) : void 0;
2008
+ const marked = i > 0 && (isModifierGlyph(group[i - 1]) || i === hang);
2009
+ if (letter !== void 0 && want !== staff.get(letter) && !marked) {
2010
+ const role = want ?? "modifyNatural";
2011
+ const sign = want ? variantOf(base, want) : modifyNatural(base);
2012
+ if (sign === void 0) throw new Error(`The note "${ch}" has no ${role} glyph for the key change`);
2013
+ if (!signs.includes(sign)) signs += sign;
2014
+ }
1947
2015
  }
1948
2016
  }
1949
2017
  const at = splitNoteMarkers(notes).leading.length;
@@ -2020,7 +2088,29 @@ function silent(tok) {
2020
2088
  * fonts cannot be loaded.
2021
2089
  */
2022
2090
  async function layoutScore(source, options = {}) {
2023
- const { style: styleName = "BNS", bold = false, textPx = 18, notesPx = textPx * 2, maxWidthPx = Infinity } = options;
2091
+ const breakBefore = /* @__PURE__ */ new Set();
2092
+ const wraps = /* @__PURE__ */ new Set();
2093
+ for (;;) {
2094
+ const { result, splitRuns } = await layoutPass(source, options, breakBefore);
2095
+ const open = splitRuns.filter((r) => !wraps.has(r.run));
2096
+ if (open.length === 0) return result;
2097
+ const split = open.reduce((a, b) => b.run < a.run ? b : a);
2098
+ if (breakBefore.has(split.run) || split.atLineStart) {
2099
+ wraps.add(split.run);
2100
+ if (split.nested) breakBefore.add(split.run);
2101
+ else breakBefore.delete(split.run);
2102
+ } else breakBefore.add(split.run);
2103
+ }
2104
+ }
2105
+ /** One pass of `layoutScore`: `breakBefore` lists the `(@keep)` runs (by
2106
+ * position in the script) that open a fresh line; `splitRuns` reports the
2107
+ * ones that crossed a line break. */
2108
+ async function layoutPass(source, options, breakBefore) {
2109
+ const { style: styleName = "BNS", bold = false, textPx = 18, notesPx = textPx * 2, maxWidthPx = Infinity, junctionDashes = 3 } = options;
2110
+ const junctionThirds = Math.round(junctionDashes * 3);
2111
+ if (!(junctionDashes >= 1 && Math.abs(junctionDashes - junctionThirds / 3) <= .01)) throw new Error(`junctionDashes must be at least 1, in steps of a third: ${junctionDashes}`);
2112
+ const fullJunction = junctionSpacer(junctionThirds);
2113
+ const reducedJunction = junctionSpacer(Math.max(3, junctionThirds - 3));
2024
2114
  const underlays = underlayTokens(source);
2025
2115
  const script = typeof source === "string" || source instanceof GuidoScript ? typeof source === "string" ? new GuidoScript(source) : source : typeof source[0] === "string" ? new GuidoScript(source[0]) : source[0];
2026
2116
  const styleSet = STYLE_SETS[styleName];
@@ -2101,9 +2191,15 @@ async function layoutScore(source, options = {}) {
2101
2191
  const items = [];
2102
2192
  let sylIndex = 0;
2103
2193
  let runHead;
2194
+ let tightDepth = 0;
2195
+ let tightGroupPlaced = false;
2104
2196
  for (const tok of tokens) if (tok.kind !== "syllable") {
2105
2197
  items.push(tok);
2106
2198
  runHead = void 0;
2199
+ if (tok.kind === "tight" || tok.kind === "unit") {
2200
+ tightDepth = Math.max(0, tightDepth + (tok.on ? 1 : -1));
2201
+ if (tightDepth === 0) tightGroupPlaced = false;
2202
+ }
2107
2203
  } else {
2108
2204
  const item = {
2109
2205
  kind: "syl",
@@ -2114,8 +2210,10 @@ async function layoutScore(source, options = {}) {
2114
2210
  first: true,
2115
2211
  lastSeg: true,
2116
2212
  heldRun: [],
2117
- signedByRun: false
2213
+ signedByRun: false,
2214
+ tightJoin: tightGroupPlaced
2118
2215
  };
2216
+ if (tok.notes !== "") tightGroupPlaced = tightDepth > 0;
2119
2217
  if (allHeld(item.i) && runHead) {
2120
2218
  runHead.heldRun.push(tok.notes);
2121
2219
  item.signedByRun = true;
@@ -2124,7 +2222,8 @@ async function layoutScore(source, options = {}) {
2124
2222
  }
2125
2223
  const placedNotes = [];
2126
2224
  const findBreakCut = (notes, room, measureFromLineStart) => {
2127
- for (let c = notes.length - 1; c > 0; c--) {
2225
+ const first = hangEnd(notes);
2226
+ for (let c = notes.length - 1; c >= first && c > 0; c--) {
2128
2227
  if (!NOTE_GROUP_SPLITTERS.includes(notes[c])) continue;
2129
2228
  let end = c + 1;
2130
2229
  while (end < notes.length && MARKER_CHARS$1.has(notes[end])) end++;
@@ -2153,7 +2252,8 @@ async function layoutScore(source, options = {}) {
2153
2252
  first: false,
2154
2253
  lastSeg: true,
2155
2254
  heldRun: [],
2156
- signedByRun: false
2255
+ signedByRun: false,
2256
+ tightJoin: false
2157
2257
  });
2158
2258
  forceBreak = true;
2159
2259
  };
@@ -2193,6 +2293,13 @@ async function layoutScore(source, options = {}) {
2193
2293
  });
2194
2294
  };
2195
2295
  let forceBreak = false;
2296
+ let keepRuns = 0;
2297
+ const keepStack = [];
2298
+ const splitRuns = [];
2299
+ const closeKeepRun = () => {
2300
+ const run = keepStack.pop();
2301
+ if (run && lines.length - 1 > run.line) splitRuns.push(run);
2302
+ };
2196
2303
  let idx = 0;
2197
2304
  while (idx < items.length) {
2198
2305
  const item = items[idx];
@@ -2204,6 +2311,29 @@ async function layoutScore(source, options = {}) {
2204
2311
  idx++;
2205
2312
  continue;
2206
2313
  }
2314
+ if (item.kind === "tight") {
2315
+ idx++;
2316
+ continue;
2317
+ }
2318
+ if (item.kind === "keep" || item.kind === "unit") {
2319
+ if (!item.on) closeKeepRun();
2320
+ else {
2321
+ const hasContent = line.texts.some((x) => x.segments.length > 0) || tracks.some((t) => t.pending.length > 0);
2322
+ if (breakBefore.has(keepRuns) && hasContent) {
2323
+ flushPending(false);
2324
+ forceBreak = true;
2325
+ }
2326
+ if (keepStack.length > 0) keepStack[keepStack.length - 1].nested = true;
2327
+ keepStack.push({
2328
+ run: keepRuns++,
2329
+ line: forceBreak ? lines.length : lines.length - 1,
2330
+ atLineStart: !hasContent || forceBreak,
2331
+ nested: false
2332
+ });
2333
+ }
2334
+ idx++;
2335
+ continue;
2336
+ }
2207
2337
  if (item.kind === "clef" || item.kind === "key") {
2208
2338
  if (item.kind === "clef") clefGlyph = item.clef;
2209
2339
  keyGlyphs = item.key;
@@ -2214,7 +2344,7 @@ async function layoutScore(source, options = {}) {
2214
2344
  notesSoFar = line.clefPrefix;
2215
2345
  staffKey = activeKey;
2216
2346
  } else if (item.kind === "clef") {
2217
- const part = (lastGroupTrailingMarker ? "--" : "---") + clefGroup + "-";
2347
+ const part = (lastGroupTrailingMarker ? reducedJunction : fullJunction) + clefGroup + "-";
2218
2348
  if (measure(notesSoFar + part, notesFont) > maxWidthPx) forceBreak = true;
2219
2349
  else {
2220
2350
  line.notesParts.push(part);
@@ -2298,7 +2428,7 @@ async function layoutScore(source, options = {}) {
2298
2428
  continue;
2299
2429
  }
2300
2430
  let parts = splitNoteMarkers(item.notes);
2301
- const joinOf = () => line.notesParts.length === 0 || afterInlineClef ? "" : held ? lastGroupTrailingMarker ? "--" : "-" : lastGroupTrailingMarker || MODIFIER_CHARS.has(parts.core[0]) ? "--" : "---";
2431
+ const joinOf = () => line.notesParts.length === 0 || afterInlineClef ? "" : held ? lastGroupTrailingMarker ? "--" : "-" : lastGroupTrailingMarker || item.tightJoin || hangingLength(parts.core) > 0 ? reducedJunction : fullJunction;
2302
2432
  let join = joinOf();
2303
2433
  if (line.notesParts.length > 0 && measure(notesSoFar + join + item.notes, notesFont) > maxWidthPx) {
2304
2434
  startLine();
@@ -2349,10 +2479,13 @@ async function layoutScore(source, options = {}) {
2349
2479
  continue;
2350
2480
  }
2351
2481
  let parts = splitNoteMarkers(item.notes);
2352
- let junctionPrefix = line.notesParts.length === 0 || afterInlineClef ? "" : prevRecited ? "" : lastGroupTrailingMarker || MODIFIER_CHARS.has(parts.core[0]) ? "--" : "---";
2482
+ let junctionPrefix = line.notesParts.length === 0 || afterInlineClef ? "" : lastGroupTrailingMarker || item.tightJoin || hangingLength(parts.core) > 0 ? reducedJunction : fullJunction;
2483
+ if (prevRecited) {
2484
+ const closing = /-*$/.exec(notesSoFar)[0].length;
2485
+ junctionPrefix = special && !runStart || closing > /^-*/.exec(junctionPrefix)[0].length ? "" : junctionPrefix.slice(closing);
2486
+ }
2353
2487
  const place = (padDashes = 0) => {
2354
- let mods = 0;
2355
- while (mods < parts.core.length && MODIFIER_CHARS.has(parts.core[mods])) mods++;
2488
+ let mods = hangingLength(parts.core);
2356
2489
  if (mods === parts.core.length) mods = 0;
2357
2490
  const anchorText = parts.core.slice(mods);
2358
2491
  const contentWidth = measure(anchorText, notesFont);
@@ -2410,7 +2543,6 @@ async function layoutScore(source, options = {}) {
2410
2543
  let contentStart = placed.contentStart;
2411
2544
  let pads = 0;
2412
2545
  let tight = false;
2413
- let wantsBreak = false;
2414
2546
  if (!prevRecited && connectorDash && textStart < minStart && (textWidth > contentWidth || textStart < t.cursor)) {
2415
2547
  tight = true;
2416
2548
  textStart = t.cursor;
@@ -2422,8 +2554,7 @@ async function layoutScore(source, options = {}) {
2422
2554
  pads,
2423
2555
  tight,
2424
2556
  floor: t.cursor,
2425
- minStart,
2426
- wantsBreak
2557
+ minStart
2427
2558
  };
2428
2559
  }
2429
2560
  if (textStart < minTextStart) {
@@ -2437,7 +2568,6 @@ async function layoutScore(source, options = {}) {
2437
2568
  }
2438
2569
  textStart = padded.textStartOf(textWidth);
2439
2570
  contentStart = padded.contentStart;
2440
- wantsBreak = line.notesParts.length > 0 && measure(notesSoFar + junctionPrefix + "-".repeat(pads) + item.notes, notesFont) > maxWidthPx;
2441
2571
  }
2442
2572
  }
2443
2573
  return {
@@ -2446,8 +2576,7 @@ async function layoutScore(source, options = {}) {
2446
2576
  pads,
2447
2577
  tight,
2448
2578
  floor: minTextStart,
2449
- minStart,
2450
- wantsBreak
2579
+ minStart
2451
2580
  };
2452
2581
  };
2453
2582
  const hiddenSpecial = special && !runStart && line.notesParts.length > 0 && !afterInlineClef;
@@ -2463,8 +2592,7 @@ async function layoutScore(source, options = {}) {
2463
2592
  pads: 0,
2464
2593
  tight: line.notesParts.length > 0 && !s.t.prevWordEnd && s.pendingTotal === 0,
2465
2594
  floor: textStart,
2466
- minStart: textStart,
2467
- wantsBreak: false
2595
+ minStart: textStart
2468
2596
  };
2469
2597
  });
2470
2598
  const deficit = Math.max(...voiced.map((s, v) => placements[v].textStart + s.textWidth + s.spaceWidth)) - measure(notesSoFar, notesFont);
@@ -2474,28 +2602,33 @@ async function layoutScore(source, options = {}) {
2474
2602
  item.inserted = [];
2475
2603
  parts = splitNoteMarkers(item.notes);
2476
2604
  } else {
2477
- placements = voiced.map(decide);
2478
- if (placements.some((p) => p.wantsBreak)) {
2605
+ const settle = () => {
2606
+ placements = voiced.map(decide);
2607
+ padDashes = Math.max(0, ...placements.map((p) => p.pads));
2608
+ if (placements.some((p) => p.pads < padDashes)) {
2609
+ const padded = place(padDashes);
2610
+ placements = placements.map((p, v) => {
2611
+ if (p.pads === padDashes) return p;
2612
+ const textStart = Math.max(padded.textStartOf(voiced[v].textWidth), p.floor);
2613
+ return {
2614
+ ...p,
2615
+ textStart,
2616
+ contentStart: padded.contentStart,
2617
+ pads: padDashes,
2618
+ tight: p.tight && textStart < p.minStart
2619
+ };
2620
+ });
2621
+ }
2622
+ };
2623
+ settle();
2624
+ if (line.notesParts.length > 0 && (measure(notesSoFar + junctionPrefix + "-".repeat(padDashes) + item.notes, notesFont) > maxWidthPx || voiced.some((s, v) => {
2625
+ return Math.max(placements[v].textStart, s.t.cursor + s.pendingTotal) + s.textWidth + (s.own.wordEnd ? 0 : dashTextWidth) > maxWidthPx;
2626
+ }))) {
2479
2627
  startLine();
2480
2628
  junctionPrefix = "";
2481
2629
  parts = splitNoteMarkers(item.notes);
2482
2630
  placed = place();
2483
- placements = voiced.map(decide);
2484
- }
2485
- padDashes = Math.max(0, ...placements.map((p) => p.pads));
2486
- if (placements.some((p) => p.pads < padDashes)) {
2487
- const padded = place(padDashes);
2488
- placements = placements.map((p, v) => {
2489
- if (p.pads === padDashes) return p;
2490
- const textStart = Math.max(padded.textStartOf(voiced[v].textWidth), p.floor);
2491
- return {
2492
- ...p,
2493
- textStart,
2494
- contentStart: padded.contentStart,
2495
- pads: padDashes,
2496
- tight: p.tight && textStart < p.minStart
2497
- };
2498
- });
2631
+ settle();
2499
2632
  }
2500
2633
  }
2501
2634
  const notesStr = junctionPrefix + "-".repeat(padDashes) + item.notes;
@@ -2586,6 +2719,7 @@ async function layoutScore(source, options = {}) {
2586
2719
  idx++;
2587
2720
  }
2588
2721
  flushPending(true);
2722
+ while (keepStack.length > 0) closeKeepRun();
2589
2723
  tracks.forEach((t, u) => {
2590
2724
  line.texts[u].textCursor = t.cursor;
2591
2725
  });
@@ -2625,17 +2759,20 @@ async function layoutScore(source, options = {}) {
2625
2759
  l.breakMarkerLeftPx = starTarget - lineEnd - starWidth;
2626
2760
  });
2627
2761
  return {
2628
- lines,
2629
- clefPrefix: lines[0].clefPrefix,
2630
- styleSet,
2631
- styleName,
2632
- textPx,
2633
- notesPx,
2634
- bold,
2635
- maxWidthPx,
2636
- starTarget,
2637
- starWidth
2762
+ result: {
2763
+ lines,
2764
+ clefPrefix: lines[0].clefPrefix,
2765
+ styleSet,
2766
+ styleName,
2767
+ textPx,
2768
+ notesPx,
2769
+ bold,
2770
+ maxWidthPx,
2771
+ starTarget,
2772
+ starWidth
2773
+ },
2774
+ splitRuns
2638
2775
  };
2639
2776
  }
2640
2777
  //#endregion
2641
- export { variantOf as $, stanzaWarnings as A, CLEF_GLYPHS as B, selectStanza as C, stackedStanzaNumbers as D, stackStanzas as E, chantText as F, modifyNatural as G, gClefPitchOf as H, escape as I, toConnectDown as J, modifyUp as K, scriptSyllables as L, SCORE_MARKERS as M, splitNoteMarkers as N, stanzaCount as O, GuidoScript as P, toVirga as Q, statementSource as R, parseStanza as S, smallHeads as T, isClefGlyph as U, baseOf as V, modifyDown as W, toSmallHead as X, toLonga as Y, toSmallPoint as Z, transposeExact as _, DEFAULT_STYLE_SET as a, isSlot as b, measurementFont as c, transposeBy as d, transposeNotes as f, sameKeyGlyphs as g, parseInterval as h, measure as i, withStanza as j, stanzaTexts as k, resolveSyllableParts as l, TranspositionRangeError as m, SPECIAL_NOTES as n, STYLE_SETS as o, KEY_SIGNATURES as p, toCephalicus as q, layoutScore as r, inlineStylesFor as s, NOTE_MODIFIERS as t, PITCH_ROWS as u, transposeScript as v, slotCount as w, padStanza as x, STANZA_PLACEHOLDER as y, unescape as z };
2778
+ export { toVirga as $, stanzaWarnings as A, unescape as B, selectStanza as C, stackedStanzaNumbers as D, stackStanzas as E, chantText as F, modifyDown as G, baseOf as H, escape as I, toCephalicus as J, modifyNatural as K, runProperties as L, SCORE_MARKERS as M, splitNoteMarkers as N, stanzaCount as O, GuidoScript as P, toSmallPoint as Q, scriptSyllables as R, parseStanza as S, smallHeads as T, gClefPitchOf as U, CLEF_GLYPHS as V, isClefGlyph as W, toLonga as X, toConnectDown as Y, toSmallHead as Z, transposeExact as _, DEFAULT_STYLE_SET as a, isSlot as b, measurementFont as c, transposeBy as d, variantOf as et, transposeNotes as f, sameKeyGlyphs as g, parseInterval as h, measure as i, withStanza as j, stanzaTexts as k, resolveSyllableParts as l, TranspositionRangeError as m, SPECIAL_NOTES as n, STYLE_SETS as o, KEY_SIGNATURES as p, modifyUp as q, layoutScore as r, inlineStylesFor as s, NOTE_MODIFIERS as t, PITCH_ROWS as u, transposeScript as v, slotCount as w, padStanza as x, STANZA_PLACEHOLDER as y, statementSource as z };
@@ -35,6 +35,13 @@ export interface LayoutOptions {
35
35
  notesPx?: number;
36
36
  /** Maximum notes-line width before a staff break (default: none) */
37
37
  maxWidthPx?: number;
38
+ /** Dashes in a normal junction between note groups: at least 1, in
39
+ * steps of a third (default 3; 2.67 reads as 2⅔). Three `¨` are about
40
+ * as wide as a `-`, so thirds are written with `¨` after the whole
41
+ * dashes (`--¨¨`). A group ending in markers or starting with an
42
+ * accidental takes one less, never under 1. Held groups keep their
43
+ * own join. */
44
+ junctionDashes?: number;
38
45
  }
39
46
  /** A horizontal whitespace gap on the text line: the lead-in shared with
40
47
  * the clef, or the gap after a word-ending syllable. Both emitters fake it
@@ -19,6 +19,8 @@ export declare const MAX_WIDTH_PX_DEFAULT = 700;
19
19
  export declare const MAX_WIDTH_PX_MIN = 300;
20
20
  export declare const MAX_WIDTH_PX_MAX = 1400;
21
21
  /** Declared range of the transpose slider. */
22
+ export declare const JUNCTION_DASHES_MIN = 1;
23
+ export declare const JUNCTION_DASHES_MAX = 8;
22
24
  export declare const TRANSPOSE_MIN = -6;
23
25
  export declare const TRANSPOSE_MAX = 6;
24
26
  /** The destination Word text size default (notes ride at twice it) and the
@@ -54,6 +56,8 @@ export interface EditorSettings {
54
56
  notesPx: number;
55
57
  /** True once the user typed a chant size of their own. */
56
58
  notesCustom: boolean;
59
+ /** Dashes in a normal junction between note groups. */
60
+ junctionDashes: number;
57
61
  customColors: boolean;
58
62
  colorFg: string;
59
63
  colorAccent: string;
@@ -148,6 +152,7 @@ export interface ChantPrefs {
148
152
  notesPx: number;
149
153
  /** True once the user typed a chant size of their own. */
150
154
  notesCustom: boolean;
155
+ junctionDashes: number;
151
156
  transpose: number;
152
157
  }
153
158
  export interface SavedChant {
@@ -2,7 +2,10 @@ import { EmptySlots, StanzaStack, StanzaWarning } from '../stanzas';
2
2
  import { StyleSetName } from '../guidoStyles';
3
3
  export declare const version: string;
4
4
  /** Line-breaking budget: a fixed pixel width, or 'auto' to fit the
5
- * target element (re-rendered on resize). */
5
+ * target element (re-rendered on resize). `Infinity` (or any large
6
+ * number) means "never break": the score stays on one line, wider than
7
+ * its container if need be, and the host handles the overflow
8
+ * (`overflow-x: auto` to scroll, `hidden` to clip). */
6
9
  export type MaxWidth = number | 'auto';
7
10
  /** Site-wide defaults, settable through `GuidexEmbed.init`. */
8
11
  export interface EmbedOptions {
@@ -12,6 +15,8 @@ export interface EmbedOptions {
12
15
  style?: StyleSetName;
13
16
  bold?: boolean;
14
17
  textPx?: number;
18
+ /** Dashes in a normal junction between note groups, in steps of a third (default 3) */
19
+ junctionDashes?: number;
15
20
  transpose?: number;
16
21
  /** The stanza sung under the notes (1-based; 1 is the script's own
17
22
  * text, 2… its `(@stanza …)` statements or the `stanzas` option). */
@@ -1,4 +1,4 @@
1
- import { a as dispose, c as renderScore, i as scoreSvg, l as version, n as downloadScoreSvg, o as init, r as scorePngBlob, s as renderAll, t as downloadScorePng } from "../scoreImage-DSEupCru.js";
1
+ import { a as dispose, c as renderScore, i as scoreSvg, l as version, n as downloadScoreSvg, o as init, r as scorePngBlob, s as renderAll, t as downloadScorePng } from "../scoreImage-lvOrTbG-.js";
2
2
  //#region src/embed/index.ts
3
3
  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", () => init(), { once: true });
4
4
  else init();
@@ -1,6 +1,6 @@
1
- import { a as dispose, c as renderScore, i as scoreSvg, l as version, n as downloadScoreSvg, o as init, r as scorePngBlob, s as renderAll, t as downloadScorePng } from "../scoreImage-DSEupCru.js";
2
- import { $ as variantOf, A as stanzaWarnings, C as selectStanza, D as stackedStanzaNumbers, E as stackStanzas, F as chantText, G as modifyNatural, H as gClefPitchOf, I as escape, J as toConnectDown, K as modifyUp, L as scriptSyllables, M as SCORE_MARKERS, N as splitNoteMarkers, O as stanzaCount, P as GuidoScript, Q as toVirga, R as statementSource, S as parseStanza, T as smallHeads, U as isClefGlyph, V as baseOf, W as modifyDown, X as toSmallHead, Y as toLonga, Z as toSmallPoint, _ as transposeExact, a as DEFAULT_STYLE_SET, b as isSlot, d as transposeBy, f as transposeNotes, g as sameKeyGlyphs, h as parseInterval, j as withStanza, k as stanzaTexts, l as resolveSyllableParts, m as TranspositionRangeError, o as STYLE_SETS, p as KEY_SIGNATURES, q as toCephalicus, u as PITCH_ROWS, v as transposeScript, w as slotCount, x as padStanza, y as STANZA_PLACEHOLDER, z as unescape } from "../chantLayout-B0xiaMo9.js";
3
- 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 dispose, c as renderScore, i as scoreSvg, l as version, n as downloadScoreSvg, o as init, r as scorePngBlob, s as renderAll, t as downloadScorePng } from "../scoreImage-lvOrTbG-.js";
2
+ import { $ as toVirga, A as stanzaWarnings, B as unescape, C as selectStanza, D as stackedStanzaNumbers, E as stackStanzas, F as chantText, G as modifyDown, H as baseOf, I as escape, J as toCephalicus, K as modifyNatural, L as runProperties, M as SCORE_MARKERS, N as splitNoteMarkers, O as stanzaCount, P as GuidoScript, Q as toSmallPoint, R as scriptSyllables, S as parseStanza, T as smallHeads, U as gClefPitchOf, W as isClefGlyph, X as toLonga, Y as toConnectDown, Z as toSmallHead, _ as transposeExact, a as DEFAULT_STYLE_SET, b as isSlot, d as transposeBy, et as variantOf, f as transposeNotes, g as sameKeyGlyphs, h as parseInterval, j as withStanza, k as stanzaTexts, l as resolveSyllableParts, m as TranspositionRangeError, o as STYLE_SETS, p as KEY_SIGNATURES, q as modifyUp, u as PITCH_ROWS, v as transposeScript, w as slotCount, x as padStanza, y as STANZA_PLACEHOLDER, z as statementSource } from "../chantLayout-CVVuJUJl.js";
3
+ 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-DG09l_ol.js";
4
4
  //#region src/composeScript.ts
5
5
  /**
6
6
  * Combining scripts (issue #71): one GuidoScript built from parts of
@@ -46,6 +46,18 @@ function stateAfter(tokens, state) {
46
46
  };
47
47
  return state;
48
48
  }
49
+ /** The run properties still open after `tokens`, one entry per level. */
50
+ function openRuns(tokens) {
51
+ const depth = {
52
+ tight: 0,
53
+ keep: 0
54
+ };
55
+ for (const tok of tokens) {
56
+ if (tok.kind !== "tight" && tok.kind !== "keep" && tok.kind !== "unit") continue;
57
+ for (const prop of runProperties(tok.kind)) depth[prop] = Math.max(0, depth[prop] + (tok.on ? 1 : -1));
58
+ }
59
+ return ["tight", "keep"].flatMap((prop) => Array(depth[prop]).fill(prop));
60
+ }
49
61
  /** Tokens written back as script source (the `GuidoScript.toString`
50
62
  * rules: an empty slot always writes its `~`). */
51
63
  function writeTokens(tokens) {
@@ -115,6 +127,18 @@ function scriptChunk(part, state, first, options) {
115
127
  const opening = stateAfter(tokens.slice(0, start), readClef(script.clef)) ?? state;
116
128
  const slice = tokens.slice(start, end);
117
129
  if (part.stripTrailingMarkers) stripTrailing(slice);
130
+ const opened = openRuns(tokens.slice(0, start));
131
+ const closed = openRuns(tokens.slice(0, end));
132
+ slice.unshift(...opened.map((kind) => ({
133
+ kind,
134
+ on: true,
135
+ spaceBefore: false
136
+ })));
137
+ slice.push(...closed.map((kind) => ({
138
+ kind,
139
+ on: false,
140
+ spaceBefore: false
141
+ })));
118
142
  const slotIndices = tokens.flatMap((tok, i) => isSlot(tok) ? [i] : []);
119
143
  const before = slotIndices.filter((i) => i < start).length;
120
144
  const inside = slotIndices.filter((i) => i >= start && i < end).length;
@@ -46,6 +46,13 @@ export declare function baseOf(ch: string): {
46
46
  } | undefined;
47
47
  /** Whether `ch` is a modifier glyph (a sharp, flat or natural sign). */
48
48
  export declare function isModifierGlyph(ch: string): boolean;
49
+ /**
50
+ * The length of the bracketed accidental that opens `notes` at `from`:
51
+ * an opening bracket, one or more accidental signs, the matching closing
52
+ * bracket, and the `¨`/`-` spacing right after it (`ÄôŨ¨` in `ÄôŨ¨õ`).
53
+ * 0 when no such unit stands there.
54
+ */
55
+ export declare function bracketedAccidentalLength(notes: string, from?: number): number;
49
56
  /** The clef glyphs (issue #49) and the staff line each one sits on,
50
57
  * counted from the bottom. The g-clef has two keybindings. */
51
58
  export declare const CLEF_GLYPHS: Readonly<Record<string, {
@@ -63,13 +63,34 @@
63
63
 
64
64
  color: var(--text);
65
65
 
66
+ /* The lines keep to one column. A fr track counts as zero under a
67
+ min-content constraint, so the nowrap lines below don't turn into
68
+ the host's minimum width: an 'auto' score in a flex or grid column
69
+ can still shrink and re-lay out. Its max-content size stays the
70
+ longest line, so shrink-to-fit hosts size to the score as before. */
71
+ display: grid;
72
+ grid-template-columns: minmax(0, 1fr);
73
+ align-content: start;
74
+
66
75
  /* Score alignment is precomputed in px; Safari's text inflation on
67
76
  rotation would resize the text but not the baked-in spacers. Host
68
- pages don't necessarily set this, so do it here. */
77
+ pages don't necessarily set this, so do it here.
78
+ iOS Safari reads only the prefixed property, and a host's Autoprefixer
79
+ deletes it when its browserslist omits ios_saf (Next.js's default),
80
+ so it is exempted here. */
81
+ /* autoprefixer: ignore next */
69
82
  -webkit-text-size-adjust: 100%;
70
83
  text-size-adjust: 100%;
71
84
  }
72
85
 
86
+ /* A fixed maxWidth may lay lines out wider than the container. The
87
+ render then grows to its longest line and overflows as one box; the
88
+ host decides whether that scrolls or clips (issue #93). 'auto' leaves
89
+ this off: the render's width is what it measures. */
90
+ .guidex-render[data-fixed-width] {
91
+ min-width: max-content;
92
+ }
93
+
73
94
  @media (prefers-color-scheme: dark) {
74
95
  .guidex-render {
75
96
  --red: #ff4d4d;
@@ -89,13 +110,18 @@
89
110
  color: var(--text-h);
90
111
  padding-block: 0.3em;
91
112
  position: relative;
113
+ /* The layout pass owns every line break; a browser wrap would part
114
+ the syllables from their notes */
115
+ white-space: nowrap;
92
116
  }
93
117
 
94
118
  /* The score's text line: margins reset (host pages style p freely) and
95
- natural leading, like the app's .score p */
119
+ natural leading, like the app's .score p; never re-wrapped, like the
120
+ notes line */
96
121
  .guidex-render p {
97
122
  margin: 0;
98
123
  line-height: normal;
124
+ white-space: nowrap;
99
125
  }
100
126
 
101
127
  /* Host pages often drop-cap paragraphs (::first-letter rules like the
@@ -123,6 +149,7 @@
123
149
  .guidex-render .guidex-error {
124
150
  margin: 0;
125
151
  color: var(--red);
152
+ white-space: normal;
126
153
  font: 14px/1.4 'Book Antiqua', 'Palatino Linotype', Palatino, Georgia, serif;
127
154
  }
128
155
  /*$vite$:1*/
@@ -16,6 +16,8 @@ export interface RenderOptions {
16
16
  debug?: boolean;
17
17
  /** Maximum notes-line width before a staff break (default: none) */
18
18
  maxWidthPx?: number;
19
+ /** Dashes in a normal junction between note groups, in steps of a third (default 3) */
20
+ junctionDashes?: number;
19
21
  }
20
22
  /**
21
23
  * Renders a GuidoScript into a tidy score: a notes line in the chant font,
@@ -44,7 +44,24 @@ export type StatementToken = {
44
44
  kind: 'key';
45
45
  key: string;
46
46
  spaceBefore: boolean;
47
+ } | {
48
+ kind: 'tight';
49
+ on: boolean;
50
+ spaceBefore: boolean;
51
+ } | {
52
+ kind: 'keep';
53
+ on: boolean;
54
+ spaceBefore: boolean;
55
+ } | {
56
+ kind: 'unit';
57
+ on: boolean;
58
+ spaceBefore: boolean;
47
59
  };
60
+ /** The statements that open and close a run of syllables (issue #100):
61
+ * `tight` spacing, `keep` on one line, `unit` both. */
62
+ export type RunStatementKind = 'tight' | 'keep' | 'unit';
63
+ /** The run properties a run statement sets. */
64
+ export declare function runProperties(kind: RunStatementKind): ('tight' | 'keep')[];
48
65
  /** Whether a group's content is a control statement (`@`-keyword,
49
66
  * trimmed). Shared with the transforms, which must leave statement
50
67
  * groups alone — their keyword characters are pitch glyphs otherwise.
@@ -11,6 +11,8 @@ export interface GuidexScoreProps {
11
11
  bold?: boolean;
12
12
  /** Text size in px (default 18). */
13
13
  textPx?: number;
14
+ /** Dashes in a normal junction between note groups, in steps of a third (default 3). */
15
+ junctionDashes?: number;
14
16
  /** Transpose the score by N diatonic steps. */
15
17
  transpose?: number;
16
18
  /** The stanza sung under the notes (1-based, default 1: the
@@ -34,4 +36,4 @@ export interface GuidexScoreProps {
34
36
  debug?: boolean;
35
37
  className?: string;
36
38
  }
37
- export declare function GuidexScore({ script, maxWidth, style, bold, textPx, transpose, stanza, stack, stanzas, emptySlots, onWarnings, debug, className, }: GuidexScoreProps): import('react').JSX.Element;
39
+ export declare function GuidexScore({ script, maxWidth, style, bold, textPx, junctionDashes, transpose, stanza, stack, stanzas, emptySlots, onWarnings, debug, className, }: GuidexScoreProps): import('react').JSX.Element;
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import { a as dispose, c as renderScore, i as scoreSvg, l as version, n as downloadScoreSvg, o as init, r as scorePngBlob, s as renderAll, t as downloadScorePng } from "../scoreImage-DSEupCru.js";
2
+ import { a as dispose, c as renderScore, i as scoreSvg, l as version, n as downloadScoreSvg, o as init, r as scorePngBlob, s as renderAll, t as downloadScorePng } from "../scoreImage-lvOrTbG-.js";
3
3
  import { useEffect, useRef } from "react";
4
4
  import { jsx } from "react/jsx-runtime";
5
5
  //#region src/react/GuidexScore.tsx
@@ -10,7 +10,7 @@ import { jsx } from "react/jsx-runtime";
10
10
  * client'` directive marks it for React Server Components (Next.js App
11
11
  * Router); in plain client-side React it is a no-op.
12
12
  */
13
- function GuidexScore({ script, maxWidth, style, bold, textPx, transpose, stanza, stack, stanzas, emptySlots, onWarnings, debug, className }) {
13
+ function GuidexScore({ script, maxWidth, style, bold, textPx, junctionDashes, transpose, stanza, stack, stanzas, emptySlots, onWarnings, debug, className }) {
14
14
  const ref = useRef(null);
15
15
  const onWarningsRef = useRef(onWarnings);
16
16
  onWarningsRef.current = onWarnings;
@@ -27,6 +27,7 @@ function GuidexScore({ script, maxWidth, style, bold, textPx, transpose, stanza,
27
27
  style,
28
28
  bold,
29
29
  textPx,
30
+ junctionDashes,
30
31
  transpose,
31
32
  stanza,
32
33
  stack: stacked,
@@ -46,6 +47,7 @@ function GuidexScore({ script, maxWidth, style, bold, textPx, transpose, stanza,
46
47
  style,
47
48
  bold,
48
49
  textPx,
50
+ junctionDashes,
49
51
  transpose,
50
52
  stanza,
51
53
  stackKey,
@@ -1,4 +1,4 @@
1
- import { A as stanzaWarnings, C as selectStanza, D as stackedStanzaNumbers, E as stackStanzas, P as GuidoScript, d as transposeBy, o as STYLE_SETS, r as layoutScore, s as inlineStylesFor } from "./chantLayout-B0xiaMo9.js";
1
+ import { A as stanzaWarnings, C as selectStanza, D as stackedStanzaNumbers, E as stackStanzas, P as GuidoScript, d as transposeBy, o as STYLE_SETS, r as layoutScore, s as inlineStylesFor } from "./chantLayout-CVVuJUJl.js";
2
2
  //#region src/guidoRender.ts
3
3
  /**
4
4
  * Renders a GuidoScript into a tidy score: a notes line in the chant font,
@@ -158,7 +158,7 @@ var GuidoRender = class GuidoRender {
158
158
  //#region src/embed/core.ts
159
159
  var version = {
160
160
  name: "guidex",
161
- version: "0.3.2",
161
+ version: "0.3.3",
162
162
  description: "Guidex — render plainchant scores from a compact GuidoScript notation, as a web app and an embeddable runtime",
163
163
  type: "module",
164
164
  workspaces: ["examples/*"],
@@ -239,6 +239,7 @@ var DEFAULTS = {
239
239
  style: "BNS",
240
240
  bold: false,
241
241
  textPx: 18,
242
+ junctionDashes: 3,
242
243
  transpose: 0,
243
244
  stanza: 1,
244
245
  stack: void 0,
@@ -272,7 +273,7 @@ function number(value) {
272
273
  function parseMaxWidth(value, fallback) {
273
274
  if (/^auto$/i.test(value.trim())) return "auto";
274
275
  const n = Number(value);
275
- if (Number.isFinite(n) && n > 0) return n;
276
+ if (n > 0) return n;
276
277
  console.warn(`[guidex] ignoring invalid data-max-width "${value}"`);
277
278
  return fallback;
278
279
  }
@@ -303,6 +304,7 @@ function readOptions(el) {
303
304
  style: ds.style ?? local.style ?? globalOptions.style ?? DEFAULTS.style,
304
305
  bold: flag(ds.bold) ?? local.bold ?? globalOptions.bold ?? DEFAULTS.bold,
305
306
  textPx: number(ds.textPx) ?? local.textPx ?? globalOptions.textPx ?? DEFAULTS.textPx,
307
+ junctionDashes: number(ds.junctionDashes) ?? local.junctionDashes ?? globalOptions.junctionDashes ?? DEFAULTS.junctionDashes,
306
308
  transpose: number(ds.transpose) ?? local.transpose ?? globalOptions.transpose ?? DEFAULTS.transpose,
307
309
  stanza: number(ds.stanza) ?? local.stanza ?? globalOptions.stanza ?? DEFAULTS.stanza,
308
310
  stack: stackValue(ds.stack) ?? local.stack ?? globalOptions.stack ?? DEFAULTS.stack,
@@ -315,7 +317,9 @@ function readOptions(el) {
315
317
  * line-box width the rendered score actually has to fit. Falls back to
316
318
  * the parent for inline targets; zero means no layout (hidden). */
317
319
  function contentWidthPx(el) {
318
- return el.querySelector(":scope > .guidex-render")?.clientWidth || el.clientWidth || el.parentElement?.clientWidth || 0;
320
+ const wrapper = el.querySelector(":scope > .guidex-render");
321
+ wrapper?.removeAttribute("data-fixed-width");
322
+ return wrapper?.clientWidth || el.clientWidth || el.parentElement?.clientWidth || 0;
319
323
  }
320
324
  /** The line-breaking budget in pixels for this render. Fixed values pass
321
325
  * through; 'auto' fits the element's content box, shrunk by the style
@@ -352,6 +356,7 @@ function renderError(wrapper, message) {
352
356
  const note = document.createElement("p");
353
357
  note.className = "guidex-error";
354
358
  note.textContent = message;
359
+ wrapper.removeAttribute("data-fixed-width");
355
360
  wrapper.replaceChildren(note);
356
361
  }
357
362
  /** The transforms a score renders with after the stanza swap: the style
@@ -410,6 +415,7 @@ async function drawScore(el, run, source, options, widthPx) {
410
415
  style: options.style,
411
416
  bold: options.bold,
412
417
  textPx: options.textPx,
418
+ junctionDashes: options.junctionDashes,
413
419
  debug: options.debug,
414
420
  maxWidthPx: widthPx
415
421
  });
@@ -418,6 +424,7 @@ async function drawScore(el, run, source, options, widthPx) {
418
424
  wrapper.replaceChildren(...scratch.childNodes);
419
425
  wrapper.style.cssText = scratch.style.cssText;
420
426
  if (scratch.dataset.style) wrapper.dataset.style = scratch.dataset.style;
427
+ wrapper.toggleAttribute("data-fixed-width", typeof options.maxWidth === "number");
421
428
  return { warnings };
422
429
  } catch (e) {
423
430
  if (runs.get(el) !== run) return { warnings: [] };
@@ -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-DG09l_ol.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 { M as SCORE_MARKERS, V as CLEF_GLYPHS, c as measurementFont, i as measure, n as SPECIAL_NOTES, r as layoutScore, t as NOTE_MODIFIERS } from "./chantLayout-CVVuJUJl.js";
2
2
  //#region src/wordExport.ts
3
3
  /**
4
4
  * Word-compatible export: turns the shared layout (chantLayout.ts) into
@@ -302,7 +302,8 @@ function resolveSizing(options) {
302
302
  bold: options.bold,
303
303
  textPx: textPt !== void 0 ? textPt * PX_PER_PT : options.textPx,
304
304
  notesPx: notesPt !== void 0 ? notesPt * PX_PER_PT : options.notesPx,
305
- maxWidthPx: options.maxWidthPt !== void 0 ? options.maxWidthPt * PX_PER_PT : options.maxWidthPx
305
+ maxWidthPx: options.maxWidthPt !== void 0 ? options.maxWidthPt * PX_PER_PT : options.maxWidthPx,
306
+ junctionDashes: options.junctionDashes
306
307
  };
307
308
  }
308
309
  /**
@@ -60,6 +60,8 @@ export interface WordExportOptions {
60
60
  * unbroken line pair, no break markers). The caller always resolves a
61
61
  * concrete width before exporting; `auto` never reaches the emitter. */
62
62
  maxWidthPx?: number;
63
+ /** Dashes in a normal junction between note groups, in steps of a third (default 3) */
64
+ junctionDashes?: number;
63
65
  /** Text line size in pt at the DESTINATION document (default: none —
64
66
  * textPx governs). Takes precedence over textPx; notes default to
65
67
  * twice the text size (the established BNS ratio). Laying out at the
@@ -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]}function v(e){return e.trim().startsWith(`@`)}function ee(e){let[t,...n]=e;return t===`@`&&n.every(u)}function te(e){return!v(e)||ee(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(ee(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:y(n.join(``),t)}}case`key`:return{kind:`key`,key:y(r,t)};case`tight`:case`keep`:case`unit`:if(r!==``&&r!==`off`)throw Error(`"@${n}" takes only "off": "${t}"`);return{kind:n,on:r===``};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})`;case`tight`:case`keep`:case`unit`:return e.on?`(@${e.kind})`:`(@${e.kind} off)`}}function ne(e){let t=e.match(/^@stanza(?:\s+([\s\S]*))?$/);return t?t[1]??``:void 0}var S=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||!te(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&&te(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=v(r)?ne(r.trim()):void 0;if(d!==void 0){if(t.trim()!==``)throw Error(`statement must not carry syllable text: "${C(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(v(r)){let e=b(r);if(t.trim()!==``)throw Error(`statement must not carry syllable text: "${C(t.trim())}"`);o.push({...e,spaceBefore:/^\s/.test(t)}),s.push(u);continue}let f=t.trim(),p={kind:`syllable`,text:f===`~`?``:C(f),notes:C(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===`~`?`\\~`:w(e.text)}(${w(e.notes)})`:`${n}${x(e)}`}),t=this.stanzas.map(e=>`(@stanza ${e})`);return`${this.clef===void 0?``:`(${this.clef})`}${e.join(``)}${t.join(``)}`}};function C(e){return e.replace(/\\(.)/g,`$1`)}function w(e){return e.replace(/\\/g,`\\\\`).replace(/[()]/g,e=>`\\${e}`)}var T=new Set(`,.:?'"+!%/=()ÖÜÓ;`.split(``));function E(e){let t=0;for(;t<e.length&&T.has(e[t]);)t++;t>0&&t<e.length&&(t=e[t]===`-`?t+1:0);let n=e.length;for(;n>t&&T.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 D=`_…_`,O=`-=­`;function k(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&&O.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 A(e){return e.kind===`syllable`&&e.notes!==``&&E(e.notes).core!==``}function j(e){return typeof e==`string`?new S(e):e}function M(e){return j(e).tokens.filter(A).length}function N(e,t={}){return t.stanzas??j(e).stanzas}function P(e,t={}){return N(e,t).length+1}function F(e){return e.kind===`syllable`||e.kind===`hold`}function I(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=k(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 re(e,t={}){let n=N(e,t),r=M(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 z(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 B(e){return e===`~`?`\\~`:w(e)}function V(e,t,n){let r=new S(e),i=N(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=>A(e)),l=[I(c),...i.map((e,t)=>L(e,c.length,t+2).fills)],u=l[t-1],d=e=>o===`partial`?l.some(t=>F(t[e]))&&!l.every(t=>F(t[e])):o===`small`&&a.every(t=>!F(l[t-1][e]))&&l.some((t,n)=>!a.includes(n+1)&&F(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(!A(e)){e.held?(g(`(${w(e.notes)})`,m),m=!1):(g(`${B(e.text)}(${w(e.notes)})`,m||e.spaceBefore),m=e.wordEnd,h=e.notes!==``);continue}let t=u[_],n=w(d(_)?z(e.notes):e.notes);switch(_++,t.kind){case`syllable`:g(`${B(t.text)}(${n})`,m),m=t.wordEnd;break;case`hold`:g(`${h?``:`~`}(${n})`,!1);break;case`empty`:g(`~(${n})`,!1);break;case`missing`:g(`${D}(${n})`,!0),m=!0}h=!0}return f}function H(e,t={}){return{name:`selectStanza`,apply:n=>V(n,e,t)}}function ie(e,t,n={}){return new S(typeof e==`string`?e:e.source,{transforms:[H(t,n),...n.transforms??[]]})}function U(e,t,n={}){let r=P(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 W(e,t,n={}){let r=U(e,t,n);return r.map(t=>ie(e,t,{...n,rendered:r}))}function G(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 ae(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(C(i).trim().length===0||v(i))continue;let a=G(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 oe={startWithInitial:{name:`startWithInitial`,apply:ae}},K=[`ðñ0123456789öüó`,`^]qwertzuiopõú`,`ÝÞQWERTZUIOPÕÚ`,`×sdfghjkléáû`,`ØÙDFGHJKLÉÁÛ`,`÷øaASÍYXCVBN$m`,`ÈÊËÌÎÏÐÑÒþßòôùý`,`“”•–—˜™š›œº»`,`®−§ÿ"+!%/=()ÖÜÓ`,`Ÿ¡¢£[¥¦©ª«¬`,`~¯‚ƒ„…†‡ˆ‰Š‹Œ‘’`,`àâãäåæçèêëìîï`,`½°±²³´μ·¾¸¹`];function se(e,t,n){for(let r of K){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 q(e,t,n={}){if(t===0||v(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=se(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 ce(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}(${q(i,e,{overflow:n})})`)}}}var le=new Set([`*`,`†`]),J={chars:le,fontFamily:`'Times New Roman', Times, serif`},ue={weight:`400`,scale:.7,raise:.2},de={BNS:{textFontStack:`'Book Antiqua', Georgia, serif`,notesFontStack:`'Guidohu'`,markerGlyphs:J,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:J.fontFamily,weight:`700`,scale:1,measureScale:.95,raise:.1,color:`var(--red)`},padding:12,scriptTransforms:[oe.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:J.fontFamily,weight:`700`,scale:1,measureScale:.95,raise:.2},padding:12,scriptTransforms:[]}};function fe(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=>le.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,...ue},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 pe(e,t,n){return[e.italic?`italic`:`normal`,`normal`,e.weight??`400`,`${t*(e.measureScale??e.scale??1)}px`,e.fontFamily??n].join(` `)}function me(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 he(e,t){return e.verifiedFonts.map(e=>`${e.weight} ${t}px ${e.family}`)}var ge=new Set(`Ÿ¡¢£[¥¦©ª«¬`.split(``));function _e(e){return e.length===1&&ge.has(e)||e.length===2&&ve.has(e[0])&&ge.has(e[1])}var ve=new Set(`÷øaASÍYXCVBN$mÈÊËÌÎÏÐÑÒþßòôùý“”•–—˜™š›œº»`.split(``));function ye(e){let t=0;for(;;){let n=ve.has(e[t]??``)?1:f(e,t);if(n===0)return t;t+=n}}function be(e){let{leading:t,core:n}=E(e),r=ye(n);return r===0?0:t.length+r}var xe=[`-`,`¨`];function Se(e){return`-`.repeat(Math.floor(e/3))+`¨`.repeat(e%3)}function Ce(e,t,n=!0){let r=new Map;for(let i of e){if(!u(i))continue;let a=_(i,we(t));if(n&&r.has(a))throw Error(`Key "${e}" alters the pitch ${a} twice`);r.set(a,c(i).role)}return r}function we(e){return e!==void 0&&m(e)?e:`M`}function Te(e){if(T.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 Ee(e,t,n,r,i=[]){let o=``;for(let c of[e,...i]){let e=be(c);for(let i=0;i<c.length;i++){let l=c[i],d=Te(l),f=d===void 0?void 0:_(d,we(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=E(e).leading.length;return{notes:e.slice(0,c)+o+e.slice(c),inserted:[...o].map((e,t)=>c+t)}}function De(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 Oe(e,t){Y||=document.createElement(`canvas`).getContext(`2d`),Y.font=t;let n=Y.measureText(e);return{left:n.actualBoundingBoxLeft,right:n.actualBoundingBoxRight}}function ke(e){let t=typeof e==`string`||e instanceof S?[e]:e;if(t.length===0)throw Error(`Nothing to lay out: no script given`);let n=t.map(e=>(typeof e==`string`?new S(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 Ae(e){return!!(e.held||e.empty)}async function je(e,t={}){let n=new Set,r=new Set;for(;;){let{result:i,splitRuns:a}=await Me(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 Me(e,t,n){let{style:r=`BNS`,bold:i=!1,textPx:a=18,notesPx:o=a*2,maxWidthPx:s=1/0,junctionDashes:c=3}=t,l=Math.round(c*3);if(!(c>=1&&Math.abs(c-l/3)<=.01))throw Error(`junctionDashes must be at least 1, in steps of a third: ${c}`);let d=Se(l),f=Se(Math.max(3,l-3)),p=ke(e),m=typeof e==`string`||e instanceof S?typeof e==`string`?new S(e):e:typeof e[0]==`string`?new S(e[0]):e[0],h=de[r];if(!h)throw Error(`Unknown style set: "${r}"`);for(let e of he(h,a)){try{await document.fonts.load(e)}catch{}if(!document.fonts.check(e))throw Error(`Font could not be loaded: ${e} (style "${r}")`)}let g=`400 ${o}px ${h.notesFontStack}`,_=h.textFontStack,v=pe({weight:i?`700`:`400`},a,_),ee=e=>fe(e,h,i),te=e=>e.reduce((e,t)=>e+X(t.text,pe(t.style,a,_)),0),y=X(`-`,g),b=X(`-`,v),x=m.clef?.[0],ne=[...(m.clef??``).slice(1)].filter(u).join(``),C=m.clef,w=e=>e?`${e}-`:``,D=Ce(ne,x,!1),O=D,k=p.map(e=>{let t=e.filter(e=>e.kind===`syllable`);return{syls:t,lastTextSyl:t.reduce((e,t,n)=>Ae(t)?e:n,-1),cursor:0,pending:[],prevWordEnd:void 0}}),A=[],j,M,N,P=!1,F,I=!1,L=()=>{j&&(k.forEach((e,t)=>{j.texts[t].textCursor=e.cursor}),j.notesEnd=j.notesParts.length?X(j.clefPrefix+j.notesParts.join(``),g):0);let e=k.map(()=>({segments:[],textCursor:0,lastWordEnd:null}));j={clefPrefix:w(C),notesParts:[],segments:e[0].segments,textCursor:0,notesEnd:0,lastWordEnd:null,texts:e},A.push(j),M=j.clefPrefix;for(let e of k)e.cursor=0;N=!1,I=!1,P=!1,O=D,F&&F.inserted.length>0&&(F.notes=De(F.notes,F.inserted),F.inserted=[],F.first&&(U[F.i]=F.notes))};L();let R=p[0],re=e=>k.every(t=>t.syls[e].held),z=[],B=0,V,H=0,ie=!1;for(let e of R)if(e.kind!==`syllable`)z.push(e),V=void 0,(e.kind===`tight`||e.kind===`unit`)&&(H=Math.max(0,H+(e.on?1:-1)),H===0&&(ie=!1));else{let t={kind:`syl`,syl:e,i:B++,notes:e.notes,inserted:[],first:!0,lastSeg:!0,heldRun:[],signedByRun:!1,tightJoin:ie};e.notes!==``&&(ie=H>0),re(t.i)&&V?(V.heldRun.push(e.notes),t.signedByRun=!0):V=t,z.push(t)}let U=[],W=(e,t,n)=>{let r=be(e);for(let i=e.length-1;i>=r&&i>0;i--){if(!xe.includes(e[i]))continue;let r=i+1;for(;r<e.length&&T.has(e[r]);)r++;if(!(r>=e.length)&&n(e.slice(0,r))<=t)return i}return-1},G=(e,t)=>{let n=e.notes,r=t+1;for(;r<n.length&&T.has(n[r]);)r++;e.notes=n.slice(0,t)+n.slice(t+1,r);let i=De(n.slice(r),e.inserted,r);return e.inserted=e.inserted.filter(e=>e<t),i},ae=(e,t,n)=>{e.lastSeg=!1,z.splice(t+1,0,{kind:`syl`,syl:e.syl,i:e.i,notes:n,inserted:[],first:!1,lastSeg:!0,heldRun:[],signedByRun:!1,tightJoin:!1}),K=!0},oe=e=>{k.forEach((t,n)=>{for(;t.pending.length>0;){let r=t.pending[0];if(t.cursor>0&&t.cursor+r.textWidth+(r.wordEnd?0:b)>s){L();continue}t.pending.shift();let i=j.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}})},K=!1,se=0,q=[],ce=[],le=()=>{let e=q.pop();e&&A.length-1>e.line&&ce.push(e)},J=0;for(;J<z.length;){let e=z[J];if(e.kind===`break`){(j.texts.some(e=>e.segments.length>0)||k.some(e=>e.pending.length>0))&&(oe(!1),K=!0),J++;continue}if(e.kind===`tight`){J++;continue}if(e.kind===`keep`||e.kind===`unit`){if(!e.on)le();else{let e=j.texts.some(e=>e.segments.length>0)||k.some(e=>e.pending.length>0);n.has(se)&&e&&(oe(!1),K=!0),q.length>0&&(q[q.length-1].nested=!0),q.push({run:se++,line:K?A.length:A.length-1,atLineStart:!e||K,nested:!1})}J++;continue}if(e.kind===`clef`||e.kind===`key`){if(e.kind===`clef`&&(x=e.clef),ne=e.key,C=(x??``)+ne,D=Ce(ne,x),!K){if(j.notesParts.length===0)j.clefPrefix=w(C),M=j.clefPrefix,O=D;else if(e.kind===`clef`){let e=(N?f:d)+C+`-`;X(M+e,g)>s?K=!0:(j.notesParts.push(e),M+=e,O=D,P=!0,N=!1,I=!1)}}J++;continue}let t=e.syl,r=e.i;if(K&&=(L(),!1),F=e,O!==D&&!e.signedByRun){let t=Ee(e.notes,O,D,x,e.first?e.heldRun:[]);e.notes=t.notes,e.inserted=t.inserted}e.first&&(U[r]=e.signedByRun&&O!==D?Ee(e.notes,O,D,x).notes:e.notes);let i=k.map(t=>{let n=t.syls[r],i=e.lastSeg&&r>=t.lastTextSyl,a=ee(e.first?n.text:``);return{t,own:n,sylParts:a,textWidth:te(a),spaceWidth:!i&&n.wordEnd?X(` `,v):0,pendingTotal:t.pending.reduce((e,t)=>e+t.textWidth+t.spaceWidth,0)}}),a=_e(e.notes);if(t.empty&&e.notes.length===0){J++;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});J++;continue}if(e.first&&e.lastSeg&&!t.empty&&t.text.trim()===``&&E(e.notes).core===``){let e=M[M.length-1],n=e&&e!==`-`&&!N&&!t.notes.startsWith(`-`)?`-`:``;j.notesParts.push(n+t.notes),M+=n+t.notes,N=!0,I=!1;for(let e of i)e.t.prevWordEnd=e.own.wordEnd;J++;continue}let o=(e,t)=>{e.own.held?(t&&(j.texts[k.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=>Ae(e.own))){let t=re(r),n=_e(e.notes);if(t&&n&&U[r-1]===U[r]&&j.notesParts.length>0&&!P){I=!0,J++;continue}let a=E(e.notes),c=()=>j.notesParts.length===0||P?``:t?N?`--`:`-`:N||e.tightJoin||ye(a.core)>0?f:d,l=c();j.notesParts.length>0&&X(M+l+e.notes,g)>s&&(L(),l=c());let u=j.notesParts.length===0;if(u&&X(M+e.notes,g)>s){let t=W(e.notes,s,e=>X(M+e,g));if(t>=0&&t+1<e.notes.length){let n=G(e,t);ae(e,J,n),a=E(e.notes)}}j.notesParts.push(l+e.notes),M+=l+e.notes;for(let e of i)o(e,u);P=!1,e.lastSeg&&(N=a.trailing.length>0,I=n),J++;continue}let c=e.first?i.filter(e=>!Ae(e.own)):i,l=U[r-1]!==e.notes,u=c.every(e=>e.t.cursor===0||e.t.cursor+e.pendingTotal+e.textWidth+(e.own.wordEnd?0:b)<=s);if(a&&!l&&j.notesParts.length>0&&!u&&L(),!e.first){for(;!(X(M+e.notes,g)<=s);){let t=W(e.notes,s,e=>X(M+e,g));if(t<0||t+1>=e.notes.length)break;let n=G(e,t);ae(e,J,n)}let t=E(e.notes);j.notesParts.push(e.notes),M+=e.notes,e.lastSeg&&(N=t.trailing.length>0);for(let[e,t]of i.entries())j.texts[e].lastWordEnd=!0,t.t.prevWordEnd=t.own.wordEnd;e.lastSeg||(K=!0),J++;continue}let p=E(e.notes),m=j.notesParts.length===0||P?``:N||e.tightJoin||ye(p.core)>0?f:d;if(I){let e=/-*$/.exec(M)[0].length;m=a&&!l||e>/^-*/.exec(m)[0].length?``:m.slice(e)}let h=(e=0)=>{let t=ye(p.core);t===p.core.length&&(t=0);let n=p.core.slice(t),r=X(n,g),i=X(M+m+`-`.repeat(e)+p.leading+p.core.slice(0,t),g),o=Oe(n,g),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}},_=h();for(;;){let t=X(M+m+e.notes,g)>s,n=c.some(e=>_.textStartOf(e.textWidth)+e.textWidth+(e.own.wordEnd?0:b)>s);if(!t&&!n)break;if(t){let t=W(e.notes,s,e=>X(M+m+e,g));if(t>=0&&t+1<e.notes.length){let n=G(e,t);ae(e,J,n),p=E(e.notes),_=h();break}}if(j.notesParts.length===0&&k.every(e=>e.cursor===0)){if(t){let t=W(e.notes,s,e=>X(M+e,g));if(t>=0&&t+1<e.notes.length){let n=G(e,t);e.notes=e.notes.slice(0,t),ae(e,J,n),p=E(e.notes),_=h()}}break}L(),m=``,p=E(e.notes),_=h()}let S=e=>{let{t,textWidth:n}=e,{contentWidth:r}=_,i=j.notesParts.length>0&&!t.prevWordEnd&&e.pendingTotal===0,a=t.cursor+b,o=t.cursor+e.pendingTotal+(I&&i?b:0),s=_.textStartOf(n),c=_.contentStart,l=0,u=!1;if(!I&&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)/y)),{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)/y));let t=h(l);for(;t.textStartOf(n)<o;)l++,t=h(l);s=t.textStartOf(n),c=t.contentStart}}return{textStart:s,contentStart:c,pads:l,tight:u,floor:o,minStart:a}},T=a&&!l&&j.notesParts.length>0&&!P,R,B=0;if(T){m=``,R=c.map(e=>{let t=e.t.cursor+e.pendingTotal;return{textStart:t,contentStart:_.contentStart,pads:0,tight:j.notesParts.length>0&&!e.t.prevWordEnd&&e.pendingTotal===0,floor:t,minStart:t}});let t=Math.max(...c.map((e,t)=>R[t].textStart+e.textWidth+e.spaceWidth))-X(M,g),n=s-X(M+m,g),r=t>0?Math.min(Math.ceil(t/y),Math.max(0,Math.floor(n/y))):0;e.notes=`-`.repeat(r),e.inserted=[],p=E(e.notes)}else{let t=()=>{if(R=c.map(S),B=Math.max(0,...R.map(e=>e.pads)),R.some(e=>e.pads<B)){let e=h(B);R=R.map((t,n)=>{if(t.pads===B)return t;let r=Math.max(e.textStartOf(c[n].textWidth),t.floor);return{...t,textStart:r,contentStart:e.contentStart,pads:B,tight:t.tight&&r<t.minStart}})}};t(),j.notesParts.length>0&&(X(M+m+`-`.repeat(B)+e.notes,g)>s||c.some((e,t)=>Math.max(R[t].textStart,e.t.cursor+e.pendingTotal)+e.textWidth+(e.own.wordEnd?0:b)>s))&&(L(),m=``,p=E(e.notes),_=h(),t())}let V=m+`-`.repeat(B)+e.notes,H=j.notesParts.length===0;c.forEach((e,t)=>{let{t:n,sylParts:r,textWidth:i,spaceWidth:a,pendingTotal:o}=e,s=j.texts[k.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(H)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-b)/2);s.segments.push({kind:`connector`,pad:e,gapWidth:u,dashWidth:b,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:_.contentWidth,contentStart:c.contentStart,extraDashes:B,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 i)c.includes(e)||o(e,H);M+=V,j.notesParts.push(V),P=!1,e.lastSeg&&(N=p.trailing.length>0,I=a),e.lastSeg||(K=!0),J++}for(oe(!0);q.length>0;)le();k.forEach((e,t)=>{j.texts[t].textCursor=e.cursor}),j.notesEnd=j.notesParts.length?X(j.clefPrefix+j.notesParts.join(``),g):0,A.forEach((e,t)=>{if(t!==A.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-b)/2):0;t.segments.push({kind:`line-end-dash`,pad:n,dashWidth:b,dashStartPx:t.textCursor+n,trailEndPx:e.notesEnd,textEndPx:t.textCursor})}});for(let e of A)e.textCursor=e.texts[0].textCursor,e.lastWordEnd=e.texts[0].lastWordEnd;let ue=s+(h.padding??0),me=X(`*`,g);return A.forEach((e,t)=>{if(t===A.length-1)return;if(s===1/0){e.breakMarkerLeftPx=h.padding??0;return}let n=X(e.clefPrefix+e.notesParts.join(``),g);for(;n+y<=ue-me&&n+y<s;)e.notesParts.push(`-`),n+=y;e.breakMarkerLeftPx=ue-n-me}),{result:{lines:A,clefPrefix:A[0].clefPrefix,styleSet:h,styleName:r,textPx:a,notesPx:o,bold:i,maxWidthPx:s,starTarget:ue,starWidth:me},splitRuns:ce}}var Ne=class e{script;constructor(e){let t=e=>typeof e==`string`?new S(e):e;this.script=typeof e==`string`||e instanceof S?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 je(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(me(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}},Pe={name:`guidex`,version:`0.3.3`,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,Fe=`.guidex-script, .guido-script`,Z={maxWidth:`auto`,style:`BNS`,bold:!1,textPx:18,junctionDashes:3,transpose:0,stanza:1,stack:void 0,emptySlots:`normal`,stanzas:void 0,debug:!1},Q={},Ie=new WeakMap,$=new WeakMap,Le=new WeakMap;function Re(e){if(e!==void 0){if(e===``||e===`true`)return!0;if(e===`false`)return!1}}function ze(e){if(e===void 0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function Be(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 Ve=new WeakMap;function He(e){if(e!==void 0){if(e===`normal`||e===`small`||e===`partial`)return e;console.warn(`[guidex] ignoring invalid data-empty-slots "${e}"`)}}function Ue(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 We(e){let t=e.dataset,n=Ve.get(e)??{};return{maxWidth:t.maxWidth===void 0?n.maxWidth??Q.maxWidth??Z.maxWidth:Be(t.maxWidth,n.maxWidth??Q.maxWidth??Z.maxWidth),style:t.style??n.style??Q.style??Z.style,bold:Re(t.bold)??n.bold??Q.bold??Z.bold,textPx:ze(t.textPx)??n.textPx??Q.textPx??Z.textPx,junctionDashes:ze(t.junctionDashes)??n.junctionDashes??Q.junctionDashes??Z.junctionDashes,transpose:ze(t.transpose)??n.transpose??Q.transpose??Z.transpose,stanza:ze(t.stanza)??n.stanza??Q.stanza??Z.stanza,stack:Ue(t.stack)??n.stack??Q.stack??Z.stack,emptySlots:He(t.emptySlots)??n.emptySlots??Q.emptySlots??Z.emptySlots,stanzas:n.stanzas??Z.stanzas,debug:Re(t.debug)??n.debug??Q.debug??Z.debug}}function Ge(e){let t=e.querySelector(`:scope > .guidex-render`);return t?.removeAttribute(`data-fixed-width`),t?.clientWidth||e.clientWidth||e.parentElement?.clientWidth||0}function Ke(e,t,n){if(typeof t==`number`)return t;let r=Ge(e);if(r<=0)return 1/0;let i=r-(de[n]?.padding??0);return i>0?i:r}function qe(e){for(let t of e.childNodes)if(t.nodeType===Node.TEXT_NODE&&t.nodeValue?.trim())return t.nodeValue.trim();return Ie.get(e)??``}function Je(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 Ye(e,t){let n=document.createElement(`p`);n.className=`guidex-error`,n.textContent=t,e.removeAttribute(`data-fixed-width`),e.replaceChildren(n)}function Xe(e){let t=[...de[e.style]?.scriptTransforms??[]];return e.transpose!==0&&t.push(ce(e.transpose)),t}function Ze(e,t){let n=Xe(t),{stanzas:r,emptySlots:i}=t;if(t.stack!==void 0){let a=U(e,t.stack,{stanzas:r});return{scripts:W(e,a,{stanzas:r,emptySlots:i,transforms:n}),warnings:a.flatMap(t=>re(e,{stanzas:r,stanza:t}))}}return(t.stanza!==1||i!==`normal`)&&n.unshift(H(t.stanza,{stanzas:r,emptySlots:i})),{scripts:[new S(e,{transforms:n})],warnings:re(e,{stanzas:r,stanza:t.stanza})}}async function Qe(e,t,n,r,i){let a=Je(e),o=document.createElement(`div`);try{let{scripts:s,warnings:c}=Ze(n,r);if(await new Ne(s).render(o,{style:r.style,bold:r.bold,textPx:r.textPx,junctionDashes:r.junctionDashes,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),Ye(a,n instanceof Error?n.message:String(n)),{warnings:[]}):{warnings:[]}}}async function $e(e){let t=($.get(e)??0)+1;$.set(e,t);let n=We(e),r=qe(e);Ie.set(e,r),Je(e);let i=Ke(e,n.maxWidth,n.style);Le.set(e,i),await Qe(e,t,r,n,i)}var et=new WeakMap;function tt(e){let t=We(e),n=Ke(e,t.maxWidth,t.style);return Math.abs(n-(Le.get(e)??NaN))>1}function nt(e){if(et.has(e))return;let t;if(typeof ResizeObserver<`u`){let n=new ResizeObserver(()=>{tt(e)&&$e(e)});n.observe(e),t=()=>n.disconnect()}else{let n=()=>{tt(e)&&$e(e)};window.addEventListener(`resize`,n),t=()=>window.removeEventListener(`resize`,n)}et.set(e,t)}function rt(e){et.get(e)?.(),et.delete(e),Ie.delete(e),Ve.delete(e),$.delete(e),Le.delete(e)}async function it(e,t,n={}){Ve.set(e,n);let r=($.get(e)??0)+1;$.set(e,r),Ie.set(e,t);let i=We(e);Je(e);let a=Ke(e,i.maxWidth,i.style);return Le.set(e,a),nt(e),Qe(e,r,t,i,a)}async function at(e=document){let t=Q.selector??Fe,n=[];return e instanceof Element&&e.matches(t)&&n.push(e),n.push(...e.querySelectorAll(t)),Promise.all(n.map(e=>(nt(e),$e(e)))).then(()=>void 0)}var ot=!1;function st(){if(ot||typeof MutationObserver>`u`)return;ot=!0;let e=Q.selector??Fe;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)nt(e),$e(e)}).observe(document.documentElement,{childList:!0,subtree:!0})}function ct(e={}){Q={...Q,...e},st(),at()}var lt=[`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`],ut=[`font-family`,`font-size`,`font-style`,`font-weight`,`line-height`,`letter-spacing`,`color`];function dt(e){return e.classList.contains(`max-width-guide`)||e.hasAttribute(`data-score-image-ignore`)}function ft(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 pt(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 mt(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 ht(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 gt(e){return e===`normal`?`400`:e===`bold`?`700`:e}function _t(e){return e.replace(/&/g,`&amp;`).replace(/"/g,`&quot;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function vt(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:gt(n||`400`),url:o,format:/format\(\s*['"]?([^'")]+?)['"]?\s*\)/.exec(r)?.[1]}}function yt(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=ht(a)[0];if(!s)continue;let c=vt(s,i(`font-style`),i(`font-weight`),o,t);c&&n.push(c)}return n}async function bt(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=ht(o)[0];if(!s||!e.has(s))continue;let c=vt(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 yt(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 xt(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 St(e,t){let n=[],r=new Set,i=new Map,a=e=>{let t=i.get(e);return t||(t=xt(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 Ct(e){let t=document.createElement(`span`);return t.style.color=e,getComputedStyle(t).color}function wt(e){let t=getComputedStyle(e).getPropertyValue(`--red`).trim();return t?Ct(t):``}function Tt(e,t,n){return n&&t&&Ct(t)===n?!0:e.style?.getPropertyValue(`color`).replace(/\s+/g,``)===`var(--red)`}function Et(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?ut:lt){if(e===`color`){let e=c.getPropertyValue(`color`);if(!e)continue;let t=Tt(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 ht(l))r.add(e);c.getPropertyValue(`font-style`)===`italic`&&(i=!0)}return{families:r,italics:i}}async function Dt(){let e=document.fonts;e?.ready&&await e.ready}async function Ot(e,t){let n=Math.max(0,t.padding??0),r=ft(e);if(!r.isConnected)throw Error(`scoreImage: the score left the document before the export — re-render it and try again`);await Dt();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=pt(e),r=a[t],i=r.left-o.left,s=mt(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)dt(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:ee}=Et(h,g,{foreground:t.foreground,accent:t.accent,accentProbe:wt(r)});m.style.setProperty(`white-space`,`nowrap`);let te=Array.from(m.children).filter(e=>e.classList.contains(`guido`)||e.tagName===`P`);s.forEach((e,t)=>{let n=te[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 y=await St(await bt(v),ee),b=new XMLSerializer().serializeToString(m),x=t.background?`<rect width="100%" height="100%" fill="${_t(t.background)}"/>`:``;return{svg:`<svg xmlns="http://www.w3.org/2000/svg" width="${f}" height="${p}" viewBox="0 0 ${f} ${p}">`+x+(y?`<style>${y}</style>`:``)+`<foreignObject x="0" y="0" width="${f}" height="${p}">`+b+`</foreignObject></svg>`,width:f,height:p}}async function kt(e,t={}){return(await Ot(e,t)).svg}async function At(e,t={}){let{svg:n,width:r,height:i}=await Ot(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 jt(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 Mt(e,t={}){let n=t.filename??`score.png`;return jt(await At(e,t),n),n}async function Nt(e,t={}){let n=t.filename??`score.svg`;return jt(new Blob([await kt(e,t)],{type:`image/svg+xml;charset=utf-8`}),n),n}return document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>ct(),{once:!0}):ct(),e.dispose=rt,e.downloadScorePng=Mt,e.downloadScoreSvg=Nt,e.init=ct,e.renderAll=at,e.renderScore=it,e.scorePngBlob=At,e.scoreSvg=kt,e.version=Pe,e})({});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "guidex",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
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": [