guidex 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 = {
@@ -324,7 +346,7 @@ function isClefGlyph(ch) {
324
346
  * (spelled out: `Object.keys` would list the digit keys first). The
325
347
  * index is the staff position the exact transposition counts with. */
326
348
  var STAFF = [..."ðñ0123456789öüó"];
327
- var LETTERS$1 = "abcdefg";
349
+ var LETTERS = "abcdefg";
328
350
  /** The pitch letter (`a`…`g`, octave dropped) of a pitch glyph — a base
329
351
  * glyph or any of its variants — under `clef` (a clef glyph; default the
330
352
  * standard g-clef). Undefined when the glyph has no pitch or the clef
@@ -334,8 +356,287 @@ function pitchLetterOf(ch, clef = "M") {
334
356
  const entry = CLEF_GLYPHS[clef];
335
357
  if (position < 0 || !entry) return void 0;
336
358
  const linePosition = STAFF.indexOf("2") + 2 * (entry.line - 1);
337
- const shift = LETTERS$1.indexOf(entry.clef) - LETTERS$1.indexOf(gClefPitchOf(STAFF[linePosition])[0]);
338
- return LETTERS$1[((LETTERS$1.indexOf(gClefPitchOf(STAFF[position])[0]) + shift) % 7 + 7) % 7];
359
+ const shift = LETTERS.indexOf(entry.clef) - LETTERS.indexOf(gClefPitchOf(STAFF[linePosition])[0]);
360
+ return LETTERS[((LETTERS.indexOf(gClefPitchOf(STAFF[position])[0]) + shift) % 7 + 7) % 7];
361
+ }
362
+ //#endregion
363
+ //#region src/noteGroups.ts
364
+ /**
365
+ * Note-group anatomy shared by the layout pass and the exact
366
+ * transposition: the score markers and the split of a group into its
367
+ * leading markers, notes and trailing markers. Kept free of imports, so
368
+ * the transforms can use it without pulling in the style sets.
369
+ */
370
+ /**
371
+ * Score marker characters: they carry no pitch, and when they sit at the
372
+ * start or end of a note group (with the adjacent dash) they act as
373
+ * whitespace rather than note width.
374
+ */
375
+ var SCORE_MARKERS = ",.:?'\"+!%/=()ÖÜÓ;";
376
+ var MARKER_CHARS$1 = new Set(SCORE_MARKERS.split(""));
377
+ function splitNoteMarkers(notes) {
378
+ let start = 0;
379
+ while (start < notes.length && MARKER_CHARS$1.has(notes[start])) start++;
380
+ if (start > 0 && start < notes.length) start = notes[start] === "-" ? start + 1 : 0;
381
+ let end = notes.length;
382
+ while (end > start && MARKER_CHARS$1.has(notes[end - 1])) end--;
383
+ if (end < notes.length && end > start) end = notes[end - 1] === "-" ? end - 1 : notes.length;
384
+ return {
385
+ leading: notes.slice(0, start),
386
+ core: notes.slice(start, end),
387
+ trailing: notes.slice(end)
388
+ };
389
+ }
390
+ //#endregion
391
+ //#region src/textMarkup.ts
392
+ /** The pause-marker characters: they split off into runs of their own. */
393
+ var MARKER_CHARS = /* @__PURE__ */ new Set(["*", "†"]);
394
+ /** The marks that take an argument, written `size:0.8`. */
395
+ var MARK_ARGUMENTS = /* @__PURE__ */ new Set([
396
+ "color",
397
+ "size",
398
+ "raise",
399
+ "font"
400
+ ]);
401
+ /** Stand-ins for escaped markup characters, from the private use area:
402
+ * the matching below never mistakes them for markup. Only ever held by a
403
+ * masked string, inside the functions that work on one. */
404
+ var MASKED = {
405
+ _: "",
406
+ "*": "",
407
+ "†": "",
408
+ "∗": ""
409
+ };
410
+ var UNMASKED = new Map(Object.entries(MASKED).map(([ch, mask]) => [mask, ch]));
411
+ function maskEscapes(written) {
412
+ return written.replace(/\\(.)/gsu, (_, ch) => MASKED[ch] ?? ch);
413
+ }
414
+ function unmask(masked) {
415
+ return masked.replace(/[-]/g, (mask) => UNMASKED.get(mask));
416
+ }
417
+ /** The whole-syllable wrapper of masked text, the longer `__` first so
418
+ * `__V.__` never matches the `_` rubric rule: the same characters on both
419
+ * ends, content between. */
420
+ function wrapperOf(masked) {
421
+ return ["__", "_"].find((wrapper) => masked.length >= wrapper.length * 2 + 1 && masked.startsWith(wrapper) && masked.endsWith(wrapper));
422
+ }
423
+ /** The `*…*` initial pairs of masked text, as segments: only non-empty
424
+ * pairs count, so an unmatched (or doubled) star stays a character. */
425
+ function initialSegments(masked) {
426
+ const segments = [];
427
+ let rest = masked;
428
+ let plain = "";
429
+ for (let m = /\*([^*]+)\*/.exec(rest); m; m = /\*([^*]+)\*/.exec(rest)) {
430
+ plain += rest.slice(0, m.index);
431
+ if (plain) {
432
+ segments.push({
433
+ text: plain,
434
+ initial: false
435
+ });
436
+ plain = "";
437
+ }
438
+ segments.push({
439
+ text: m[1],
440
+ initial: true
441
+ });
442
+ rest = rest.slice(m.index + m[0].length);
443
+ }
444
+ plain += rest;
445
+ if (plain) segments.push({
446
+ text: plain,
447
+ initial: false
448
+ });
449
+ return segments;
450
+ }
451
+ /** Splits one segment's characters into its plain, marker and plus runs. */
452
+ function splitGlyphRuns(text, marks, liturgy) {
453
+ const glyphOf = (ch) => MARKER_CHARS.has(ch) ? "marker" : liturgy && ch === "+" ? "plus" : void 0;
454
+ const runs = [];
455
+ for (const ch of text) {
456
+ const glyph = glyphOf(ch);
457
+ const last = runs[runs.length - 1];
458
+ if (last && last.glyph === glyph) last.text += ch;
459
+ else runs.push({
460
+ text: ch,
461
+ glyph
462
+ });
463
+ }
464
+ return runs.map((run) => ({
465
+ text: run.text,
466
+ marks: run.glyph ? [...marks, run.glyph] : [...marks]
467
+ }));
468
+ }
469
+ /**
470
+ * Parses text with no `{…}` span in it into the runs it draws: the
471
+ * whole-syllable `**` star (drawn as ∗), a `__…__` or `_…_` wrapper around
472
+ * all of it, paired `*` markers around any part of it (`*sam*ple` → "sam"
473
+ * and "ple"), and the marker characters and a Liturgy run's `+` split off.
474
+ * The wrapper characters are dropped; escaped characters are literal.
475
+ */
476
+ function parseTextRuns(written) {
477
+ if (written.length === 0) return [];
478
+ const masked = maskEscapes(written);
479
+ if (masked === "**") return [{
480
+ text: "∗",
481
+ marks: ["star"]
482
+ }];
483
+ const wrapper = wrapperOf(masked);
484
+ const content = wrapper ? masked.slice(wrapper.length, -wrapper.length) : masked;
485
+ const base = wrapper ? [wrapper === "__" ? "liturgy" : "rubric"] : [];
486
+ return initialSegments(content).flatMap(({ text, initial }) => splitGlyphRuns(unmask(text), initial ? [...base, "initial"] : base, wrapper === "__"));
487
+ }
488
+ /** The text to read from text with no span in it: every unescaped markup
489
+ * character and sign gone, escapes folded. Empty for a sign alone. */
490
+ function plainText(written) {
491
+ return unmask(maskEscapes(written).replace(/[_*†∗]/g, ""));
492
+ }
493
+ /** The marks of a span's opening, read just past its `{`: comma-separated
494
+ * names, those of `MARK_ARGUMENTS` with a `:argument`, closed by a colon.
495
+ * Returns undefined when the text does not start with such a list. */
496
+ function spanHead(text) {
497
+ const marks = [];
498
+ let at = 0;
499
+ for (;;) {
500
+ const name = /^[A-Za-z][\w-]*/.exec(text.slice(at))?.[0];
501
+ if (!name) return void 0;
502
+ at += name.length;
503
+ if (text[at] === ":" && MARK_ARGUMENTS.has(name)) {
504
+ const argument = /^[^\s,:{}]+/.exec(text.slice(at + 1))?.[0];
505
+ if (!argument) return void 0;
506
+ marks.push(`${name}:${argument}`);
507
+ at += 1 + argument.length;
508
+ } else marks.push(name);
509
+ if (text[at] === ":") return {
510
+ marks,
511
+ length: at + 1
512
+ };
513
+ if (text[at] !== ",") return void 0;
514
+ at += 1;
515
+ }
516
+ }
517
+ /** Splits text into what stands between its braces, and its braces. */
518
+ function lexSpans(text) {
519
+ const lexemes = [];
520
+ let written = "";
521
+ const flush = () => {
522
+ if (written) lexemes.push({
523
+ type: "text",
524
+ written
525
+ });
526
+ written = "";
527
+ };
528
+ for (let i = 0; i < text.length; i++) {
529
+ const ch = text[i];
530
+ if (ch === "\\" && i + 1 < text.length) written += ch + text[++i];
531
+ else if (ch === "{") {
532
+ flush();
533
+ const head = spanHead(text.slice(i + 1));
534
+ lexemes.push({
535
+ type: "open",
536
+ marks: head?.marks
537
+ });
538
+ if (head) i += head.length;
539
+ } else if (ch === "}") {
540
+ flush();
541
+ lexemes.push({ type: "close" });
542
+ } else written += ch;
543
+ }
544
+ flush();
545
+ return lexemes;
546
+ }
547
+ /**
548
+ * Resolves the `{…}` spans of consecutive pieces of text, which may open in
549
+ * one piece and close in a later one. A malformed span, a span never closed
550
+ * and a stray `}` are reported in `problems`; their text stays, plain, and
551
+ * their braces go, so no punctuation prints.
552
+ */
553
+ function resolveSpans(pieces) {
554
+ const problems = [];
555
+ const lexed = pieces.map(lexSpans);
556
+ const opens = /* @__PURE__ */ new Map();
557
+ const stack = [];
558
+ const strays = /* @__PURE__ */ new Set();
559
+ for (const [p, lexemes] of lexed.entries()) for (const lexeme of lexemes) if (lexeme.type === "open") {
560
+ if (!lexeme.marks) problems.push({
561
+ kind: "span",
562
+ text: pieces[p].trim(),
563
+ message: `A "{" needs its marks and a colon, as in "{red:text}" (in "${pieces[p].trim()}")`
564
+ });
565
+ const span = { marks: lexeme.marks ?? [] };
566
+ opens.set(lexeme, span);
567
+ stack.push(span);
568
+ } else if (lexeme.type === "close" && !stack.pop()) {
569
+ strays.add(lexeme);
570
+ problems.push({
571
+ kind: "span",
572
+ text: pieces[p].trim(),
573
+ message: `A "}" closes nothing (in "${pieces[p].trim()}")`
574
+ });
575
+ }
576
+ for (const span of stack) {
577
+ if (span.marks.length > 0) problems.push({
578
+ kind: "span",
579
+ text: span.marks.join(","),
580
+ message: `The span "{${span.marks.join(",")}:" is never closed`
581
+ });
582
+ span.marks = [];
583
+ }
584
+ const open = [];
585
+ const resolved = [];
586
+ let lastVisible;
587
+ for (const [p, lexemes] of lexed.entries()) {
588
+ const crossesIn = open.length > 0;
589
+ const segments = [];
590
+ const piece = {
591
+ bare: "",
592
+ source: "",
593
+ runs: [],
594
+ text: ""
595
+ };
596
+ for (const lexeme of lexemes) if (lexeme.type === "open") open.push(opens.get(lexeme));
597
+ else if (lexeme.type === "close") {
598
+ if (!strays.has(lexeme)) open.pop();
599
+ } else segments.push({
600
+ marks: open.flatMap((span) => span.marks),
601
+ written: lexeme.written
602
+ });
603
+ piece.bare = segments.map((s) => s.written).join("");
604
+ const body = trimSegments(segments);
605
+ piece.runs = body.flatMap(({ marks, written }) => parseTextRuns(written).map((run) => ({
606
+ text: run.text,
607
+ marks: [...marks, ...run.marks]
608
+ })));
609
+ piece.text = body.map(({ written }) => plainText(written)).join("");
610
+ const dropped = lexemes.some((l) => strays.has(l) || l.type === "open" && opens.get(l).marks.length === 0);
611
+ const live = lexemes.some((l) => l.type === "open" || l.type === "close");
612
+ piece.source = crossesIn || open.length > 0 || dropped || live && piece.bare.trim() === "" ? body.map(({ marks, written }) => marks.length > 0 ? `{${marks.join(",")}:${written}}` : written).join("") : pieces[p].trim();
613
+ const visible = body.filter((s) => s.written.trim() !== "");
614
+ if (visible.length > 0) {
615
+ if (lastVisible) {
616
+ const next = new Set(visible[0].marks);
617
+ const shared = lastVisible.marks.filter((mark) => next.has(mark));
618
+ if (shared.length > 0) lastVisible.piece.hyphen = shared;
619
+ }
620
+ lastVisible = {
621
+ piece,
622
+ marks: visible[visible.length - 1].marks
623
+ };
624
+ }
625
+ resolved.push(piece);
626
+ }
627
+ return {
628
+ pieces: resolved,
629
+ problems
630
+ };
631
+ }
632
+ /** The segments with the piece's outer whitespace gone. */
633
+ function trimSegments(segments) {
634
+ const body = segments.map((s) => ({ ...s }));
635
+ const first = body[0];
636
+ const last = body[body.length - 1];
637
+ if (first) first.written = first.written.trimStart();
638
+ if (last) last.written = last.written.trimEnd();
639
+ return body.filter((s) => s.written !== "");
339
640
  }
340
641
  //#endregion
341
642
  //#region src/guidoScript.ts
@@ -368,7 +669,9 @@ function pitchLetterOf(ch, clef = "M") {
368
669
  * Control statements are groups whose content is an `@`-keyword with
369
670
  * optional arguments after one space: `(@break)` ends the current line
370
671
  * pair at its position, `(@clef MX)` changes the clef (and key) inline,
371
- * `(@key X)` replaces the key and `(@key)` clears it. Statements are
672
+ * `(@key X)` replaces the key and `(@key)` clears it. `(@tight)` tightens
673
+ * the junctions up to `(@tight off)`, `(@keep)` keeps its run on one line
674
+ * up to `(@keep off)`, and `(@unit)` / `(@unit off)` do both. Statements are
372
675
  * positional — the text run before one must be whitespace-only — and
373
676
  * they are invisible to the sung-text accessors.
374
677
  *
@@ -382,6 +685,10 @@ function pitchLetterOf(ch, clef = "M") {
382
685
  * `@` is also the c4 clef glyph: an opening group of `@` and nothing but
383
686
  * modifier glyphs (`(@)`, `(@X)`) is the opening clef, not a statement.
384
687
  */
688
+ /** The run properties a run statement sets. */
689
+ function runProperties(kind) {
690
+ return kind === "unit" ? ["tight", "keep"] : [kind];
691
+ }
385
692
  /** Whether a group's content is a control statement (`@`-keyword,
386
693
  * trimmed). Shared with the transforms, which must leave statement
387
694
  * groups alone — their keyword characters are pitch glyphs otherwise.
@@ -431,6 +738,15 @@ function parseStatement(content) {
431
738
  kind: "key",
432
739
  key: parseKey(args, statement)
433
740
  };
741
+ case "tight":
742
+ case "keep":
743
+ case "unit":
744
+ case "aid":
745
+ if (args !== "" && args !== "off") throw new Error(`"@${keyword}" takes only "off": "${statement}"`);
746
+ return {
747
+ kind: keyword,
748
+ on: args === ""
749
+ };
434
750
  default: throw new Error(`Unknown statement "${statement}"`);
435
751
  }
436
752
  }
@@ -440,6 +756,10 @@ function statementSource(tok) {
440
756
  case "break": return "(@break)";
441
757
  case "clef": return `(@clef ${tok.clef}${tok.key})`;
442
758
  case "key": return tok.key === "" ? "(@key)" : `(@key ${tok.key})`;
759
+ case "tight":
760
+ case "keep":
761
+ case "unit":
762
+ case "aid": return tok.on ? `(@${tok.kind})` : `(@${tok.kind} off)`;
443
763
  }
444
764
  }
445
765
  /** The stanza text of a `(@stanza …)` statement's trimmed content, or
@@ -480,21 +800,29 @@ var GuidoScript = class {
480
800
  get tokenSpans() {
481
801
  return this.parse().spans;
482
802
  }
803
+ /** What is wrong with the script's `{…}` spans: such a span renders
804
+ * plainly instead of failing the score. */
805
+ get spanProblems() {
806
+ return this.parse().problems;
807
+ }
483
808
  parse() {
484
809
  const script = this.normalized;
485
810
  const head = script.match(/^\s*\(([^)]*)\)/);
486
811
  const skipped = head && isOpeningClef(head[1]) ? head[0].length : 0;
487
812
  const matches = [...script.slice(skipped).matchAll(/((?:[^()\\]|\\.)*)\(((?:[^)\\]|\\.)*)\)/g)];
813
+ const resolved = resolveSpans(matches.map((match) => match[1]));
488
814
  let prev;
489
815
  const stanzas = [];
490
816
  const tokens = [];
491
817
  const spans = [];
492
- for (const match of matches) {
493
- const [, text, notes] = match;
818
+ for (const [m, match] of matches.entries()) {
819
+ const [, written, notes] = match;
820
+ const piece = resolved.pieces[m];
821
+ const text = piece.bare;
494
822
  const at = skipped + match.index;
495
- const notesStart = at + text.length + 1;
823
+ const notesStart = at + written.length + 1;
496
824
  const span = {
497
- start: at + (text.length - text.trimStart().length),
825
+ start: at + (written.length - written.trimStart().length),
498
826
  notesStart,
499
827
  notesEnd: notesStart + notes.length,
500
828
  end: notesStart + notes.length + 1
@@ -520,9 +848,11 @@ var GuidoScript = class {
520
848
  continue;
521
849
  }
522
850
  const raw = text.trim();
851
+ if (raw === "" && notes === "" && written.trim() !== "") continue;
523
852
  const tok = {
524
853
  kind: "syllable",
525
- text: raw === "~" ? "" : unescape(raw),
854
+ ...textFields(raw === "~" ? NO_TEXT : piece),
855
+ role: "sung",
526
856
  notes: unescape(notes),
527
857
  spaceBefore: /^\s/.test(text)
528
858
  };
@@ -554,10 +884,12 @@ var GuidoScript = class {
554
884
  }
555
885
  holder = t;
556
886
  }
887
+ assignRoles(tokens);
557
888
  return {
558
889
  tokens,
559
890
  stanzas,
560
- spans
891
+ spans,
892
+ problems: resolved.problems
561
893
  };
562
894
  }
563
895
  /** The script broken into syllables, each with its sung text and
@@ -591,15 +923,19 @@ var GuidoScript = class {
591
923
  get words() {
592
924
  const words = [];
593
925
  let word;
594
- for (const syl of this.syllables) {
595
- if (syl.held || syl.empty) continue;
926
+ for (const syl of this.tokens) {
927
+ if (syl.kind !== "syllable" || syl.held || syl.empty) continue;
596
928
  word ??= {
597
929
  text: "",
598
930
  syllables: []
599
931
  };
932
+ const { text, source, runs, role, notes } = syl;
600
933
  word.syllables.push({
601
- text: syl.text,
602
- notes: syl.notes
934
+ text,
935
+ source,
936
+ runs,
937
+ role,
938
+ notes
603
939
  });
604
940
  word.text = word.syllables.map((s) => s.text).join("");
605
941
  if (syl.wordEnd) {
@@ -614,26 +950,29 @@ var GuidoScript = class {
614
950
  toString() {
615
951
  const parts = this.tokens.map((tok, i) => {
616
952
  const prefix = i > 0 && tok.spaceBefore ? " " : "";
617
- return tok.kind === "syllable" ? `${prefix}${tok.empty ? "~" : tok.text === "~" ? "\\~" : escape(tok.text)}(${escape(tok.notes)})` : `${prefix}${statementSource(tok)}`;
953
+ return tok.kind === "syllable" ? `${prefix}${tok.empty ? "~" : tok.source}(${escape(tok.notes)})` : `${prefix}${statementSource(tok)}`;
618
954
  });
619
955
  const stanzas = this.stanzas.map((text) => `(@stanza ${text})`);
620
956
  return `${this.clef !== void 0 ? `(${this.clef})` : ""}${parts.join("")}${stanzas.join("")}`;
621
957
  }
622
958
  };
959
+ /** The roles `scriptSyllables` lists by default: what is sung. */
960
+ var SUNG_ROLES = ["sung", "aid"];
623
961
  /**
624
- * The syllables of a script that carry text, in order — the ones the
625
- * sung text is made of, so their count and texts match `chantText`
626
- * (and `GuidoScript.words`). Held groups ride on their syllable
627
- * (`held`), `~` empty slots, statements and `(@stanza …)` are skipped.
628
- * Offsets index the script's source; index i is the "syllable i" of
629
- * `composeScript`'s `from`/`to`.
962
+ * The syllables of a script, in order: by default the sung ones, labels and
963
+ * signs left out (`roles` chooses others). Held groups ride on their
964
+ * syllable (`held`); `~` empty slots, statements and `(@stanza …)` are
965
+ * skipped. Word starts and ends are the listed syllables' own, so a word
966
+ * end on a left-out syllable lands on the one before it. Offsets index the
967
+ * script's source; index i is the "syllable i" of `composeScript`'s
968
+ * `from`/`to`.
630
969
  */
631
- function scriptSyllables(script) {
970
+ function scriptSyllables(script, options = {}) {
632
971
  const parsed = typeof script === "string" ? new GuidoScript(script) : script;
972
+ const roles = options.roles ?? SUNG_ROLES;
633
973
  const tokens = parsed.tokens;
634
974
  const spans = parsed.tokenSpans;
635
- const out = [];
636
- let prevWordEnd = true;
975
+ const all = [];
637
976
  let holder;
638
977
  for (const [i, tok] of tokens.entries()) {
639
978
  if (tok.kind !== "syllable") continue;
@@ -651,9 +990,11 @@ function scriptSyllables(script) {
651
990
  const span = spans[i];
652
991
  holder = {
653
992
  text: tok.text,
993
+ source: tok.source,
994
+ role: tok.role,
654
995
  notes: tok.notes,
655
996
  held: [],
656
- wordStart: prevWordEnd,
997
+ wordStart: false,
657
998
  wordEnd: tok.wordEnd,
658
999
  start: span.start,
659
1000
  notesStart: span.notesStart,
@@ -661,919 +1002,83 @@ function scriptSyllables(script) {
661
1002
  end: span.end,
662
1003
  token: i
663
1004
  };
664
- out.push(holder);
665
- prevWordEnd = tok.wordEnd;
1005
+ all.push(holder);
666
1006
  }
667
- return out;
668
- }
669
- /** The sung text of the script: the clef stripped, syllables joined
670
- * into words, and the words joined with single spaces. */
671
- function chantText(script) {
672
- return new GuidoScript(script).words.map((word) => word.text).join(" ");
673
- }
674
- /** Folds backslash escapes into the characters they stand for. Shared
675
- * with the transforms module (guidoScriptTransforms.ts). */
676
- function unescape(text) {
677
- return text.replace(/\\(.)/g, "$1");
678
- }
679
- /** Turns literal parentheses and backslashes into their escape sequences. */
680
- function escape(text) {
681
- return text.replace(/\\/g, "\\\\").replace(/[()]/g, (ch) => `\\${ch}`);
682
- }
683
- //#endregion
684
- //#region src/noteGroups.ts
685
- /**
686
- * Note-group anatomy shared by the layout pass and the exact
687
- * transposition: the score markers and the split of a group into its
688
- * leading markers, notes and trailing markers. Kept free of imports, so
689
- * the transforms can use it without pulling in the style sets.
690
- */
691
- /**
692
- * Score marker characters: they carry no pitch, and when they sit at the
693
- * start or end of a note group (with the adjacent dash) they act as
694
- * whitespace rather than note width.
695
- */
696
- var SCORE_MARKERS = ",.:?'\"+!%/=()ÖÜÓ;";
697
- var MARKER_CHARS$1 = new Set(SCORE_MARKERS.split(""));
698
- function splitNoteMarkers(notes) {
699
- let start = 0;
700
- while (start < notes.length && MARKER_CHARS$1.has(notes[start])) start++;
701
- if (start > 0 && start < notes.length) start = notes[start] === "-" ? start + 1 : 0;
702
- let end = notes.length;
703
- while (end > start && MARKER_CHARS$1.has(notes[end - 1])) end--;
704
- if (end < notes.length && end > start) end = notes[end - 1] === "-" ? end - 1 : notes.length;
705
- return {
706
- leading: notes.slice(0, start),
707
- core: notes.slice(start, end),
708
- trailing: notes.slice(end)
709
- };
710
- }
711
- //#endregion
712
- //#region src/stanzas.ts
713
- /**
714
- * Stanzas on one melody (issue #69): a hymn stores its melody once, as
715
- * stanza 1's GuidoScript, and every further stanza as syllabified text
716
- * whose syllables map one-to-one onto the melody's note groups — the
717
- * slots.
718
- *
719
- * A slot is one note group: held groups and `~` empty slots included
720
- * (issue #83), syllables without notes and marker-only groups not. The
721
- * further stanzas ride the script as `(@stanza …)` statements at its end
722
- * (`GuidoScript.stanzas`), or come from a `stanzas` option that replaces
723
- * them. Stanza numbers and slot numbers are 1-based: stanza 1 is the
724
- * script itself, and they are what the warnings report.
725
- *
726
- * Stanza text follows Aretino's lyric-line rules (see `parseStanza`).
727
- * Rendering stanza k is a script rewrite (`selectStanza`, `withStanza`):
728
- * its syllables are swapped onto the slots, the notes never change, so
729
- * every emitter (DOM, image, Word) works on the result unchanged.
730
- */
731
- /** The syllable text that marks a slot a stanza is missing a syllable
732
- * for: a rubric ellipsis, red in BNS, so the mismatch shows in the
733
- * render (and in the Word export). */
734
- var STANZA_PLACEHOLDER = "_…_";
735
- /** The unescaped characters that end a syllable within a word: the
736
- * hyphen, the mandatory hyphen and the soft hyphen. */
737
- var SYLLABLE_BREAKS = "-=­";
738
- /**
739
- * Parses stanza text into its slot items, by Aretino's lyric-line rules:
740
- *
741
- * - whitespace separates words, `-` separates the syllables of a word
742
- * (a soft hyphen U+00AD counts as `-`, and so does the mandatory
743
- * hyphen `=` — the renderer has no hyphen it may not drop yet);
744
- * - a lone `-` (or an empty syllable, `Al--le`) holds the slot for the
745
- * syllable before it; that syllable's word end is its own (`Al- - le`
746
- * is mid-word, `bunt - gen` ends the word);
747
- * - a lone `~` is an empty slot; `~` inside a syllable is a
748
- * non-breaking space;
749
- * - a backslash makes the next character literal (`\-`, `\~`, `\=`,
750
- * `\(`, `\\`).
751
- *
752
- * There are no `_` extenders: `_…_`, `__…__` and `*…*` stay the
753
- * syllable formatting of the script notation.
754
- */
755
- function parseStanza(text) {
756
- const words = [];
757
- let word = null;
758
- const chars = Array.from(text);
759
- for (let i = 0; i < chars.length; i++) {
760
- let ch = chars[i];
761
- const escaped = ch === "\\" && i + 1 < chars.length;
762
- if (escaped) ch = chars[++i];
763
- if (!escaped && /\s/.test(ch)) {
764
- word = null;
765
- continue;
766
- }
767
- if (word === null) {
768
- word = [];
769
- words.push(word);
770
- }
771
- word.push({
772
- ch,
773
- escaped
774
- });
775
- }
776
- const out = [];
777
- for (const w of words) {
778
- if (w.length === 1 && !w[0].escaped && w[0].ch === "~") {
779
- out.push({ kind: "empty" });
780
- continue;
781
- }
782
- const pieces = [""];
783
- for (const { ch, escaped } of w) if (!escaped && SYLLABLE_BREAKS.includes(ch)) pieces.push("");
784
- else pieces[pieces.length - 1] += !escaped && ch === "~" ? "\xA0" : ch;
785
- const last = pieces.length - 1;
786
- for (const [p, piece] of pieces.entries()) {
787
- if (piece === "") {
788
- if (p < last) out.push({ kind: "hold" });
789
- continue;
790
- }
791
- out.push({
792
- kind: "syllable",
793
- text: piece,
794
- wordEnd: p === last
795
- });
796
- }
797
- }
798
- return out;
799
- }
800
- /** Whether a token opens a slot: a syllable with notes that are not all
801
- * markers. */
802
- function isSlot(tok) {
803
- return tok.kind === "syllable" && tok.notes !== "" && splitNoteMarkers(tok.notes).core !== "";
804
- }
805
- function parsed(script) {
806
- return typeof script === "string" ? new GuidoScript(script) : script;
807
- }
808
- /** The number of slots (note groups that take a stanza syllable). */
809
- function slotCount(script) {
810
- return parsed(script).tokens.filter(isSlot).length;
811
- }
812
- /** The stanza texts of stanzas 2, 3, …: the `stanzas` option when
813
- * given, the script's `(@stanza …)` statements otherwise. */
814
- function stanzaTexts(script, options = {}) {
815
- return options.stanzas ?? parsed(script).stanzas;
816
- }
817
- /** How many stanzas the script has, stanza 1 (the script) included. */
818
- function stanzaCount(script, options = {}) {
819
- return stanzaTexts(script, options).length + 1;
820
- }
821
- function sings(fill) {
822
- return fill.kind === "syllable" || fill.kind === "hold";
823
- }
824
- /** Stanza 1's fills: the slot tokens themselves. */
825
- function scriptFills(slots) {
826
- return slots.map((tok) => tok.empty ? { kind: "empty" } : tok.held ? { kind: "hold" } : {
827
- kind: "syllable",
828
- text: tok.text,
829
- wordEnd: tok.wordEnd
830
- });
831
- }
832
- /** A stanza's syllables laid on `count` slots, with its mismatches. */
833
- function alignStanza(text, count, stanza) {
834
- const syllables = parseStanza(text);
835
- const fills = [];
836
- const warnings = [];
837
- for (let i = 0; i < count; i++) {
838
- const syl = syllables[i];
839
- fills.push(syl ?? { kind: "missing" });
840
- if (syl === void 0) warnings.push({
841
- stanza,
842
- slot: i + 1,
843
- kind: "missing",
844
- message: `Stanza ${stanza} has no syllable for slot ${i + 1} of ${count}`
845
- });
846
- }
847
- for (const [i, syl] of syllables.slice(count).entries()) {
848
- const shown = syl.kind === "syllable" ? syl.text : syl.kind === "hold" ? "-" : "~";
849
- warnings.push({
850
- stanza,
851
- slot: count + i + 1,
852
- kind: "extra",
853
- text: shown,
854
- message: `Stanza ${stanza} has an extra syllable "${shown}" past the last slot (${count})`
855
- });
856
- }
857
- return {
858
- fills,
859
- warnings
860
- };
861
- }
862
- /** Throws when `stanza` is not one of the script's stanzas. */
863
- function checkStanzaNumber(stanza, count) {
864
- if (!Number.isInteger(stanza) || stanza < 1 || stanza > count) throw new RangeError(`Stanza ${stanza} does not exist: the script has ${count} stanza${count === 1 ? "" : "s"}`);
865
- }
866
- /** The count mismatches of one stanza (`options.stanza`), or of every
867
- * stanza when none is named. Stanza 1 is the script and never warns;
868
- * an intentional `~` is a syllable like any other. */
869
- function stanzaWarnings(script, options = {}) {
870
- const texts = stanzaTexts(script, options);
871
- const count = slotCount(script);
872
- if (options.stanza !== void 0) {
873
- checkStanzaNumber(options.stanza, texts.length + 1);
874
- if (options.stanza === 1) return [];
875
- return alignStanza(texts[options.stanza - 2], count, options.stanza).warnings;
876
- }
877
- return texts.flatMap((text, i) => alignStanza(text, count, i + 2).warnings);
878
- }
879
- /** Pads stanza text with `~` empty slots up to the script's slot count
880
- * (unchanged when it already has enough syllables). */
881
- function padStanza(script, text) {
882
- const missing = slotCount(script) - parseStanza(text).length;
883
- return missing > 0 ? `${text.trimEnd()}${" ~".repeat(missing)}` : text;
884
- }
885
- /** A note group with its plain heads, virgas and longas swapped for small
886
- * heads (connectors, markers and signs stay). */
887
- function smallHeads(notes) {
888
- return Array.from(notes, (ch) => {
889
- const small = toSmallHead(ch);
890
- if (small !== void 0) return small;
891
- const variant = baseOf(ch);
892
- if (variant && (variant.role === "virga" || variant.role === "longa")) return toSmallHead(variant.base) ?? ch;
893
- return ch;
894
- }).join("");
895
- }
896
- /** A syllable's text written back into the script notation. */
897
- function syllableSource(text) {
898
- return text === "~" ? "\\~" : escape(text);
899
- }
900
- /** Rewrites a script's source to sing stanza `stanza`. */
901
- function stanzaSource(source, stanza, options) {
902
- const script = new GuidoScript(source);
903
- const texts = stanzaTexts(script, options);
904
- checkStanzaNumber(stanza, texts.length + 1);
905
- const rendered = options.rendered ?? [stanza];
906
- for (const k of rendered) checkStanzaNumber(k, texts.length + 1);
907
- const mode = options.emptySlots ?? "normal";
908
- if (stanza === 1 && mode === "normal") return source;
909
- const tokens = script.tokens;
910
- const slotTokens = tokens.filter((t) => isSlot(t));
911
- const allFills = [scriptFills(slotTokens), ...texts.map((text, i) => alignStanza(text, slotTokens.length, i + 2).fills)];
912
- const fills = allFills[stanza - 1];
913
- const cue = (slot) => mode === "partial" ? allFills.some((f) => sings(f[slot])) && !allFills.every((f) => sings(f[slot])) : mode === "small" && rendered.every((k) => !sings(allFills[k - 1][slot])) && allFills.some((f, j) => !rendered.includes(j + 1) && sings(f[slot]));
914
- let out = script.clef !== void 0 ? `(${script.clef})` : "";
915
- let first = true;
916
- let pendingSpace = false;
917
- let canHold = false;
918
- const emit = (piece, space) => {
919
- out += (space && !first ? " " : "") + piece;
920
- first = false;
921
- };
922
- let slot = 0;
923
- for (const tok of tokens) {
924
- if (tok.kind !== "syllable") {
925
- emit(statementSource(tok), pendingSpace);
926
- pendingSpace = false;
927
- continue;
928
- }
929
- if (!isSlot(tok)) {
930
- if (tok.held) {
931
- emit(`(${escape(tok.notes)})`, pendingSpace);
932
- pendingSpace = false;
933
- } else {
934
- emit(`${syllableSource(tok.text)}(${escape(tok.notes)})`, pendingSpace || tok.spaceBefore);
935
- pendingSpace = tok.wordEnd;
936
- canHold = tok.notes !== "";
937
- }
938
- continue;
939
- }
940
- const fill = fills[slot];
941
- const notes = escape(cue(slot) ? smallHeads(tok.notes) : tok.notes);
942
- slot++;
943
- switch (fill.kind) {
944
- case "syllable":
945
- emit(`${syllableSource(fill.text)}(${notes})`, pendingSpace);
946
- pendingSpace = fill.wordEnd;
947
- break;
948
- case "hold":
949
- emit(`${canHold ? "" : "~"}(${notes})`, false);
950
- break;
951
- case "empty":
952
- emit(`~(${notes})`, false);
953
- break;
954
- case "missing":
955
- emit(`${STANZA_PLACEHOLDER}(${notes})`, true);
956
- pendingSpace = true;
957
- }
958
- canHold = true;
959
- }
960
- return out;
961
- }
962
- /** The `selectStanza` transform factory: rewrites the script to sing
963
- * stanza `stanza` (1-based; 1 is the script itself). Its syllables go on
964
- * the slots in order — missing ones become `STANZA_PLACEHOLDER`
965
- * syllables, extra ones are dropped (`stanzaWarnings` reports both) — and
966
- * the `(@stanza …)` statements are dropped. Everything that is not a
967
- * slot (statements, syllables without notes, marker-only groups) stays as
968
- * written. With `emptySlots: 'small'`, a slot the stanza leaves empty
969
- * while another stanza sings it gets small heads (`rendered` lists the
970
- * stanzas stacked with it: then a slot gets small heads when none of
971
- * them sings it while another stanza does). With `emptySlots:
972
- * 'partial'`, every slot some stanza sings and another does not gets
973
- * small heads, whatever is rendered. Stanza 1 with normal
974
- * empty slots returns the source unchanged. Throws a RangeError for a
975
- * stanza the script does not have. Register it first, so the other
976
- * transforms (the initial, the transpositions) see the stanza's text. */
977
- function selectStanza(stanza, options = {}) {
978
- return {
979
- name: "selectStanza",
980
- apply: (source) => stanzaSource(source, stanza, options)
981
- };
982
- }
983
- /** The script singing stanza `stanza` (see `selectStanza`); `transforms`
984
- * run after the stanza swap. A GuidoScript argument is taken by its
985
- * (already transformed) source. */
986
- function withStanza(script, stanza, options = {}) {
987
- return new GuidoScript(typeof script === "string" ? script : script.source, { transforms: [selectStanza(stanza, options), ...options.transforms ?? []] });
988
- }
989
- /** The stanza numbers a stack names: every stanza for `'all'`, the
990
- * listed ones otherwise. Throws a RangeError for an empty list or a
991
- * stanza the script does not have. */
992
- function stackedStanzaNumbers(script, stack, options = {}) {
993
- const count = stanzaCount(script, options);
994
- if (stack === "all") return Array.from({ length: count }, (_, k) => k + 1);
995
- if (stack.length === 0) throw new RangeError("No stanza to stack: the list is empty");
996
- for (const k of stack) checkStanzaNumber(k, count);
997
- return [...stack];
998
- }
999
- /** The scripts of stacked stanzas (issue #84): one per stanza of the
1000
- * stack, in its order, each singing its stanza on the shared notes (see
1001
- * `withStanza`; `transforms` run after the swap). Hand them to the layout
1002
- * together (`layoutScore`, `GuidoRender`, the Word export) for one text
1003
- * line per stanza under one staff. With `emptySlots: 'small'`, a slot
1004
- * gets small heads when no stacked stanza sings it while a stanza left
1005
- * out of the stack does, so every script carries the same notes. */
1006
- function stackStanzas(script, stack, options = {}) {
1007
- const rendered = stackedStanzaNumbers(script, stack, options);
1008
- return rendered.map((k) => withStanza(script, k, {
1009
- ...options,
1010
- rendered
1011
- }));
1012
- }
1013
- //#endregion
1014
- //#region src/exactTranspose.ts
1015
- /**
1016
- * Exact transposition (issue #70): moves the sounding pitches of a
1017
- * script and re-notates them under a target clef and key, so the result
1018
- * reads like a chant notated at the new pitch. The staff-degree shift
1019
- * (`transposeBy`) stays separate and ignores pitch meaning.
1020
- *
1021
- * A note's sounding pitch is its staff position + the clef in effect +
1022
- * the key in effect + any sign written in its group. A sign affects its
1023
- * whole group: every note of that pitch letter, in every octave. The
1024
- * transposition is two steps:
1025
- *
1026
- * 1. Move every pitch by a spelled interval (letter steps + semitones,
1027
- * so a major third up turns b♭ into d, not e♭♭).
1028
- * 2. Re-notate under the target clef and key: each note's staff position
1029
- * and glyph, plus the signs the target key doesn't cover. Added signs
1030
- * go before the note group, after its leading markers (the #49 rule).
1031
- *
1032
- * Keys are written with the classical key-signature layout
1033
- * (`KEY_SIGNATURES`). Results past the glyph range and missing glyph
1034
- * variants are errors, never silent clamps.
1035
- */
1036
- /** A transposed note past the end of the glyph range. Thrown as its own
1037
- * class so the octave search for a `final` can tell it apart. */
1038
- var TranspositionRangeError = class extends Error {
1039
- constructor(message) {
1040
- super(message);
1041
- this.name = "TranspositionRangeError";
1007
+ const listed = [];
1008
+ let atWordStart = true;
1009
+ for (const syl of all) if (roles.includes(syl.role)) {
1010
+ syl.wordStart = atWordStart;
1011
+ listed.push(syl);
1012
+ atWordStart = syl.wordEnd;
1013
+ } else if (syl.wordEnd) {
1014
+ if (listed.length > 0) listed[listed.length - 1].wordEnd = true;
1015
+ atWordStart = true;
1042
1016
  }
1017
+ return listed;
1018
+ }
1019
+ /** The text of the script to read: the sung words joined with single
1020
+ * spaces, with no markup, labels, signs or aids in them. Characters the
1021
+ * author escaped stay. */
1022
+ function chantText(script, options = {}) {
1023
+ const roles = ["sung"];
1024
+ if (options.labels) roles.push("label");
1025
+ if (options.aids) roles.push("aid");
1026
+ return scriptSyllables(script, { roles }).map((syl) => (syl.wordStart ? " " : "") + syl.text).join("").replace(/ +/g, " ").trim();
1027
+ }
1028
+ /** A text with nothing in it. */
1029
+ var NO_TEXT = {
1030
+ bare: "",
1031
+ source: "",
1032
+ runs: [],
1033
+ text: ""
1043
1034
  };
1044
- /** The key-signature glyphs per clef glyph (issue #70): flats in the
1045
- * order b e a d g c f, sharps in the order f c g d a e b, each at the
1046
- * highest octave of the shape that stays on the staff. A key of n signs
1047
- * is the first n glyphs of its row. */
1048
- var KEY_SIGNATURES = {
1049
- M: {
1050
- flats: "XBYVÍCS",
1051
- sharps: "ôþùßÑòÒ"
1052
- },
1053
- "<": {
1054
- flats: "XBYVÍCS",
1055
- sharps: "ôþùßÑòÒ"
1056
- },
1057
- ">": {
1058
- flats: "V$CNXBY",
1059
- sharps: "ÑòÒôþùß"
1060
- },
1061
- "#": {
1062
- flats: "NXBYVÍC",
1063
- sharps: "þÐßÑÎÒÏ"
1064
- },
1065
- "&": {
1066
- flats: "YVÍCSXA",
1067
- sharps: "òÒôþÐßÑ"
1068
- },
1069
- "@": {
1070
- flats: "CNXBYVÍ",
1071
- sharps: "ÐßÑòÒôþ"
1072
- },
1073
- "{": {
1074
- flats: "BYVÍCSX",
1075
- sharps: "ÒÏþÐÌÑÎ"
1076
- },
1077
- "}": {
1078
- flats: "ÍCSXAYa",
1079
- sharps: "ßÑòÒÏþÐ"
1080
- }
1081
- };
1082
- var FLAT_ORDER = "beadgcf";
1083
- var SHARP_ORDER = "fcgdaeb";
1084
- /** Pitch letters from c, so a diatonic step's letter is `step mod 7`. */
1085
- var LETTERS = "cdefgab";
1086
- var LETTER_SEMITONES = [
1087
- 0,
1088
- 2,
1089
- 4,
1090
- 5,
1091
- 7,
1092
- 9,
1093
- 11
1094
- ];
1095
- var mod7 = (n) => (n % 7 + 7) % 7;
1096
- function semitoneOf({ step, alter }) {
1097
- return Math.floor(step / 7) * 12 + LETTER_SEMITONES[mod7(step)] + alter;
1098
- }
1099
- function letterName(step) {
1100
- return LETTERS[mod7(step)];
1101
- }
1102
- /** A pitch moved by a spelled interval: the letter moves by the steps,
1103
- * the alteration absorbs whatever the semitones leave over. */
1104
- function movePitch(pitch, interval) {
1105
- const step = pitch.step + interval.steps;
1106
- const alter = semitoneOf(pitch) + interval.semitones - semitoneOf({
1107
- step,
1108
- alter: 0
1109
- });
1110
- if (Math.abs(alter) > 1) throw new Error(`Moving ${letterName(pitch.step)}${alterName(pitch.alter)} lands on a double accidental (${letterName(step)}, ${alter > 0 ? "+" : ""}${alter})`);
1111
- return {
1112
- step,
1113
- alter
1114
- };
1115
- }
1116
- function alterName(alter) {
1117
- return alter < 0 ? "♭" : alter > 0 ? "♯" : "";
1118
- }
1119
- function roleOfAlter(alter) {
1120
- return alter < 0 ? "modifyDown" : alter > 0 ? "modifyUp" : "modifyNatural";
1121
- }
1122
- function alterOfRole(role) {
1123
- return role === "modifyDown" ? -1 : role === "modifyUp" ? 1 : 0;
1124
- }
1125
- /** The staff position of a clef's own line and the step of its pitch. */
1126
- function clefAnchor(clef) {
1127
- const entry = CLEF_GLYPHS[clef];
1128
- const step = {
1129
- c: 28,
1130
- f: 24,
1131
- g: 32
1132
- }[entry.clef];
1035
+ /** A syllable's text fields, from its resolved text. */
1036
+ function textFields(piece) {
1037
+ const { text, source, runs, hyphen } = piece;
1133
1038
  return {
1134
- position: STAFF.indexOf("2") + 2 * (entry.line - 1),
1135
- step
1039
+ text,
1040
+ source,
1041
+ runs,
1042
+ ...hyphen ? { hyphen } : {}
1136
1043
  };
1137
1044
  }
1138
- function stepAt(position, clef) {
1139
- const anchor = clefAnchor(clef);
1140
- return anchor.step + position - anchor.position;
1141
- }
1142
- function positionOf(step, clef) {
1143
- const anchor = clefAnchor(clef);
1144
- return anchor.position + step - anchor.step;
1145
- }
1146
- /** The staff position and variant role of a pitched glyph (`'base'` for
1147
- * a base glyph), or undefined for a glyph without pitch. */
1148
- function glyphOf(ch) {
1149
- if (STAFF.includes(ch)) return {
1150
- position: STAFF.indexOf(ch),
1151
- role: "base"
1152
- };
1153
- const entry = baseOf(ch);
1154
- return entry ? {
1155
- position: STAFF.indexOf(entry.base),
1156
- role: entry.role
1157
- } : void 0;
1158
- }
1159
- /** Whether `ch` is in a pitch row. Read at call time: this module and
1160
- * the transforms module import each other. */
1161
- function isPitchChar(ch) {
1162
- return PITCH_ROWS.some((row) => row.includes(ch));
1163
- }
1164
- /** The glyph of `role` at a staff position. Throws past the glyph range
1165
- * and when the variant does not exist. */
1166
- function glyphAt(position, role, what) {
1167
- const base = STAFF[position];
1168
- if (base === void 0) throw new TranspositionRangeError(`${what} runs past the glyph range`);
1169
- const glyph = role === "base" ? base : variantOf(base, role);
1170
- if (glyph === void 0) throw new Error(`${what}: the glyph "${base}" has no ${role} variant`);
1171
- return glyph;
1172
- }
1173
- /** A key read from modifier glyphs under `clef`. Naturals carry no
1174
- * alteration, so they drop out. */
1175
- function readKey(glyphs, clef) {
1176
- const key = /* @__PURE__ */ new Map();
1177
- for (const ch of glyphs) {
1178
- if (!isModifierGlyph(ch)) continue;
1179
- const { base, role } = baseOf(ch);
1180
- const letter = mod7(stepAt(STAFF.indexOf(base), clef));
1181
- const alter = alterOfRole(role);
1182
- if (alter === 0) key.delete(letter);
1183
- else key.set(letter, alter);
1184
- }
1185
- return key;
1186
- }
1187
- /** A signed key count: −n is the first n flats, n the first n sharps. */
1188
- function countedKey(count) {
1189
- if (!Number.isInteger(count) || Math.abs(count) > 7) throw new Error(`A key has −7 to 7 signs, not ${count}`);
1190
- const order = count < 0 ? FLAT_ORDER : SHARP_ORDER;
1191
- const key = /* @__PURE__ */ new Map();
1192
- for (const name of order.slice(0, Math.abs(count))) key.set(LETTERS.indexOf(name), Math.sign(count));
1193
- return key;
1194
- }
1195
- /** A key moved by an interval. The key is a scale, not a set of
1196
- * pitches: every letter moves (d minor's natural e becomes g minor's
1197
- * e♭ a fourth up), and the moved key is whatever the scale alters. */
1198
- function moveKey(key, interval) {
1199
- const moved = /* @__PURE__ */ new Map();
1200
- for (let letter = 0; letter < 7; letter++) {
1201
- const pitch = movePitch({
1202
- step: letter,
1203
- alter: key.get(letter) ?? 0
1204
- }, interval);
1205
- if (pitch.alter !== 0) moved.set(mod7(pitch.step), pitch.alter);
1206
- }
1207
- return moved;
1208
- }
1209
- function sameKey(a, b) {
1210
- return a.size === b.size && [...a].every(([letter, alter]) => b.get(letter) === alter);
1211
- }
1212
- /** Whether two keys written as modifier glyphs under `clef` alter the
1213
- * same pitch letters the same way (glyph order and octave aside). */
1214
- function sameKeyGlyphs(a, b, clef) {
1215
- return sameKey(readKey(a, clef), readKey(b, clef));
1216
- }
1217
- /** A key written with the key-signature layout of `clef`: flats first,
1218
- * then sharps, each in the table's order. */
1219
- function writeKey(key, clef) {
1220
- const row = KEY_SIGNATURES[clef];
1221
- const glyphs = (order, alter, signs) => [...order].map((name, i) => key.get(LETTERS.indexOf(name)) === alter ? signs[i] : "").join("");
1222
- return glyphs(FLAT_ORDER, -1, row.flats) + glyphs(SHARP_ORDER, 1, row.sharps);
1223
- }
1224
- /** Parses an interval name: an optional sign, a quality (`P`, `M`, `m`,
1225
- * `A`, `d`) and a number (`P1`, `-P5`, `M3`, `A4`, `P8`, `M9`). */
1226
- function parseInterval(name) {
1227
- const match = name.trim().match(/^([+-]?)([PMmAd])(\d+)$/);
1228
- const number = match ? Number(match[3]) : 0;
1229
- if (!match || number < 1) throw new Error(`Unknown interval "${name}"`);
1230
- const [, sign, quality] = match;
1231
- const steps = number - 1;
1232
- const perfect = [
1233
- 0,
1234
- 3,
1235
- 4
1236
- ].includes(steps % 7);
1237
- if (!(perfect ? "PAd" : "MmAd").includes(quality)) throw new Error(`Unknown interval "${name}"`);
1238
- const base = Math.floor(steps / 7) * 12 + LETTER_SEMITONES[steps % 7];
1239
- const adjust = {
1240
- P: 0,
1241
- M: 0,
1242
- A: 1,
1243
- m: -1,
1244
- d: perfect ? -1 : -2
1245
- }[quality];
1246
- const direction = sign === "-" ? -1 : 1;
1247
- return {
1248
- steps: direction * steps,
1249
- semitones: direction * (base + adjust)
1250
- };
1251
- }
1252
- var GROUP = /((?:[^()\\]|\\.)*)\(((?:[^)\\]|\\.)*)\)/g;
1253
- function escapeNotes(notes) {
1254
- return notes.replace(/\\/g, "\\\\").replace(/[()]/g, (ch) => `\\${ch}`);
1255
- }
1256
- /** Re-notates one note group. `src*` are the clef and key in effect in
1257
- * the source, `tgt*` the ones in the result. Records the group's last
1258
- * note pitch (the candidate final) through `onNote`. */
1259
- function renotateGroup(notes, interval, srcClef, srcKey, tgtClef, tgtKey, onNote) {
1260
- const { leading, core, trailing } = splitNoteMarkers(notes);
1261
- const chars = [...core];
1262
- const groupSigns = /* @__PURE__ */ new Map();
1263
- for (const ch of chars) {
1264
- if (!isModifierGlyph(ch)) continue;
1265
- const glyph = glyphOf(ch);
1266
- const letter = mod7(stepAt(glyph.position, srcClef));
1267
- const alter = alterOfRole(glyph.role);
1268
- if (groupSigns.has(letter) && groupSigns.get(letter) !== alter) throw new Error(`The note group "${notes}" carries two different signs for ${LETTERS[letter]}`);
1269
- groupSigns.set(letter, alter);
1270
- }
1271
- const coveredLetters = /* @__PURE__ */ new Set();
1272
- const out = [];
1273
- const added = [];
1274
- const pending = [];
1275
- for (const ch of chars) {
1276
- const glyph = glyphOf(ch);
1277
- if (!glyph) {
1278
- if (isPitchChar(ch)) throw new Error(`The glyph "${ch}" has no glyph-family entry, so it cannot be transposed exactly`);
1279
- out.push(ch);
1280
- continue;
1281
- }
1282
- const step = stepAt(glyph.position, srcClef);
1283
- const letter = mod7(step);
1284
- const keyAlter = srcKey.get(letter) ?? 0;
1285
- if (isModifierGlyph(ch)) {
1286
- const alter = alterOfRole(glyph.role);
1287
- const moved = movePitch({
1288
- step,
1289
- alter
1290
- }, interval);
1291
- const tgtAlter = tgtKey.get(mod7(moved.step)) ?? 0;
1292
- if (moved.alter !== tgtAlter || alter === keyAlter) {
1293
- const position = positionOf(moved.step, tgtClef);
1294
- out.push(glyphAt(position, roleOfAlter(moved.alter), `The sign "${ch}"`));
1295
- coveredLetters.add(mod7(moved.step));
1296
- }
1045
+ /** A syllable's text fields, from text written on its own. */
1046
+ function syllableText(written) {
1047
+ return textFields(resolveSpans([written]).pieces[0]);
1048
+ }
1049
+ var LABEL_MARKS = ["liturgy", "rubric"];
1050
+ /** Whether a group carries pitch: anything but markers and spacing. */
1051
+ function hasPitch(notes) {
1052
+ return /[^-¨]/.test(splitNoteMarkers(notes).core);
1053
+ }
1054
+ /** What each syllable token is for. A held group takes its holder's role;
1055
+ * an empty slot stays `sung`, unless it stands in an `(@aid)` run. */
1056
+ function assignRoles(tokens) {
1057
+ let aid = 0;
1058
+ let holder = "sung";
1059
+ const markedBy = (tok, names) => tok.runs.every((run) => run.marks.some((mark) => names.includes(mark)));
1060
+ for (const tok of tokens) {
1061
+ if (tok.kind === "aid") aid = Math.max(0, aid + (tok.on ? 1 : -1));
1062
+ if (tok.kind !== "syllable") continue;
1063
+ if (tok.held) {
1064
+ tok.role = holder;
1297
1065
  continue;
1298
1066
  }
1299
- const pitch = {
1300
- step,
1301
- alter: groupSigns.get(letter) ?? keyAlter
1302
- };
1303
- const moved = movePitch(pitch, interval);
1304
- out.push(glyphAt(positionOf(moved.step, tgtClef), glyph.role, `The note "${ch}"`));
1305
- if (glyph.role === "smallPoint") continue;
1306
- onNote(pitch);
1307
- pending.push(moved);
1308
- }
1309
- for (const moved of pending) {
1310
- const letter = mod7(moved.step);
1311
- if (coveredLetters.has(letter) || moved.alter === (tgtKey.get(letter) ?? 0)) continue;
1312
- const sign = glyphAt(positionOf(moved.step, tgtClef), roleOfAlter(moved.alter), `The sign for ${letterName(moved.step)}${alterName(moved.alter)}`);
1313
- if (!added.includes(sign)) added.push(sign);
1067
+ if (tok.runs.length === 0) tok.role = !tok.empty && tok.notes === "" ? "sign" : aid > 0 ? "aid" : "sung";
1068
+ else if (tok.text === "" || markedBy(tok, ["plus"])) tok.role = "sign";
1069
+ else if (markedBy(tok, LABEL_MARKS) && !hasPitch(tok.notes)) tok.role = "label";
1070
+ else tok.role = aid > 0 ? "aid" : "sung";
1071
+ holder = tok.role;
1314
1072
  }
1315
- return leading + added.join("") + out.join("") + trailing;
1316
- }
1317
- /** One re-notation pass over the source. Returns the result and the
1318
- * source's final (the pitch of its last note). */
1319
- function renotate(source, plan) {
1320
- new GuidoScript(source).tokens;
1321
- const head = source.match(/^\s*\(([^)]*)\)/);
1322
- const opening = head && (!isStatementGroup(head[1]) || isC4ClefGroup(head[1])) ? head : null;
1323
- const openingClef = opening && isClefGlyph(opening[1].trimStart()[0] ?? "") ? opening[1].trimStart()[0] : void 0;
1324
- if (opening && openingClef === void 0 && opening[1].trim() !== "") throw new Error(`The opening group "(${opening[1]})" does not start with a clef glyph`);
1325
- if (plan.clef !== void 0 && !isClefGlyph(plan.clef)) throw new Error(`"${plan.clef}" is not a clef glyph`);
1326
- let srcClef = openingClef ?? "M";
1327
- let srcKey = readKey(opening && openingClef ? opening[1].trimStart().slice(1) : "", srcClef);
1328
- let tgtClef = plan.clef ?? srcClef;
1329
- let tgtKey = plan.key === void 0 ? moveKey(srcKey, plan.interval) : typeof plan.key === "number" ? countedKey(plan.key) : readKey(plan.key, tgtClef);
1330
- const openingKey = writeKey(tgtKey, tgtClef);
1331
- const openingGroup = opening || plan.clef !== void 0 || openingKey !== "" ? `(${tgtClef}${openingKey})` : "";
1332
- let final;
1333
- const offset = opening ? opening[0].length : 0;
1334
- return {
1335
- result: openingGroup + source.slice(offset).replace(GROUP, (_, text, rawNotes) => {
1336
- if (isStatementGroup(rawNotes)) {
1337
- const [, keyword, args = ""] = rawNotes.trim().match(/^@(\S*)(?: (.*))?$/) ?? [];
1338
- if (keyword === "clef") {
1339
- srcClef = args[0];
1340
- srcKey = readKey(args.slice(1), srcClef);
1341
- const moved = moveKey(srcKey, plan.interval);
1342
- if (plan.clef === void 0) {
1343
- tgtClef = srcClef;
1344
- tgtKey = moved;
1345
- return `${text}(@clef ${tgtClef}${writeKey(tgtKey, tgtClef)})`;
1346
- }
1347
- if (sameKey(moved, tgtKey)) return text;
1348
- tgtKey = moved;
1349
- const key = writeKey(tgtKey, tgtClef);
1350
- return `${text}(@key${key === "" ? "" : ` ${key}`})`;
1351
- }
1352
- if (keyword === "key") {
1353
- srcKey = readKey(args, srcClef);
1354
- tgtKey = moveKey(srcKey, plan.interval);
1355
- const key = writeKey(tgtKey, tgtClef);
1356
- return `${text}(@key${key === "" ? "" : ` ${key}`})`;
1357
- }
1358
- return `${text}(${rawNotes})`;
1359
- }
1360
- return `${text}(${escapeNotes(renotateGroup(unescape(rawNotes), plan.interval, srcClef, srcKey, tgtClef, tgtKey, (pitch) => {
1361
- final = pitch;
1362
- }))})`;
1363
- }),
1364
- final
1365
- };
1366
- }
1367
- /** The finals' pitch letter and alteration (`g`, `bb`, `b♭`, `f#`). */
1368
- function parseFinal(final) {
1369
- const match = final.trim().match(/^([a-gA-G])(b|♭|#|♯)?$/);
1370
- if (!match) throw new Error(`Unknown final "${final}"`);
1371
- const alter = match[2] === void 0 ? 0 : "b♭".includes(match[2]) ? -1 : 1;
1372
- return {
1373
- letter: LETTERS.indexOf(match[1].toLowerCase()),
1374
- alter
1375
- };
1376
- }
1377
- /**
1378
- * Transposes a script exactly: moves its sounding pitches and
1379
- * re-notates them under the target clef and key (see
1380
- * `TranspositionTarget`). Without a key, the key moves with the
1381
- * interval; without a clef, the clefs stay as written (mid-script
1382
- * `(@clef …)` included); `(@key …)` statements always move with the
1383
- * interval. A target clef re-notates the whole script in that clef and
1384
- * removes mid-script `(@clef …)` statements (one that changed the key
1385
- * leaves a `(@key …)` behind). With a `final`, the octave whose result
1386
- * fits the glyph range wins — the smaller move when several fit.
1387
- * Throws past the glyph range and on a missing glyph variant.
1388
- */
1389
- function transposeScript(source, target) {
1390
- if (target.interval !== void 0 && target.final !== void 0) throw new Error("A transposition target takes an interval or a final, not both");
1391
- const plan = (interval) => ({
1392
- interval,
1393
- clef: target.clef,
1394
- key: target.key
1395
- });
1396
- if (target.final === void 0) return renotate(source, plan(typeof target.interval === "string" ? parseInterval(target.interval) : target.interval ?? {
1397
- steps: 0,
1398
- semitones: 0
1399
- })).result;
1400
- const sourceFinal = renotate(source, { interval: {
1401
- steps: 0,
1402
- semitones: 0
1403
- } }).final;
1404
- if (sourceFinal === void 0) throw new Error("The script has no notes, so it has no final");
1405
- const wanted = parseFinal(target.final);
1406
- const up = mod7(wanted.letter - sourceFinal.step);
1407
- const candidates = [
1408
- -14,
1409
- -7,
1410
- 0,
1411
- 7,
1412
- 14
1413
- ].map((octave) => {
1414
- const semitones = semitoneOf({
1415
- step: sourceFinal.step + up + octave,
1416
- alter: wanted.alter
1417
- }) - semitoneOf(sourceFinal);
1418
- return {
1419
- steps: up + octave,
1420
- semitones
1421
- };
1422
- }).sort((a, b) => Math.abs(a.semitones) - Math.abs(b.semitones) || b.semitones - a.semitones);
1423
- let rangeError;
1424
- for (const interval of candidates) try {
1425
- return renotate(source, plan(interval)).result;
1426
- } catch (error) {
1427
- if (!(error instanceof TranspositionRangeError)) throw error;
1428
- rangeError ??= error;
1429
- }
1430
- throw rangeError;
1431
- }
1432
- /** The exact transposition as a script transform (see `transposeScript`). */
1433
- function transposeExact(target) {
1434
- return {
1435
- name: "transposeExact",
1436
- apply: (source) => transposeScript(source, target)
1437
- };
1438
- }
1439
- //#endregion
1440
- //#region src/guidoScriptTransforms.ts
1441
- /**
1442
- * Source-level transformations for GuidoScript: named rewrites applied
1443
- * to a script's raw source before parsing (see the `transforms` option
1444
- * on the GuidoScript constructor). Each one receives the source and
1445
- * returns the rewritten source — or the source unchanged when the
1446
- * feature does not apply. They compose in registration order, and the
1447
- * parsed script never sees which ones ran. New script-level features
1448
- * are added here, and only here: as entries of SCRIPT_TRANSFORMS, or —
1449
- * when the feature takes parameters — as factories returning a
1450
- * ScriptTransform (see `transposeBy`).
1451
- */
1452
- /** The first character unit of a text run: a backslash escape pair or a
1453
- * single character, skipping leading whitespace. Returns null when the
1454
- * run has no characters to mark. */
1455
- function firstCharUnit(text) {
1456
- const chars = [...text];
1457
- for (let i = 0; i < chars.length; i++) {
1458
- const ch = chars[i];
1459
- if (/\s/.test(ch)) continue;
1460
- return {
1461
- unit: ch === "\\" && chars[i + 1] !== void 0 ? ch + chars[i + 1] : ch,
1462
- index: i
1463
- };
1464
- }
1465
- return null;
1466
- }
1467
- /** The `startWithInitial` transform: finds the first syllable group with
1468
- * actual notes and text (the clef, no-notes groups, control statements,
1469
- * text-less groups and `~` empty slots don't count) and wraps the
1470
- * syllable's first character in the `*…*` initial marker. Already-marked
1471
- * text (leading `*`) is left alone. */
1472
- function startWithInitial(source) {
1473
- const clefMatch = source.match(/^\s*\(([^)]*)\)/);
1474
- const offset = clefMatch ? clefMatch[0].length : 0;
1475
- const rest = source.slice(offset);
1476
- for (const match of rest.matchAll(/((?:[^()\\]|\\.)*)\(((?:[^)\\]|\\.)*)\)/g)) {
1477
- const [, text, notes] = match;
1478
- if (unescape(notes).trim().length === 0) continue;
1479
- if (isStatementGroup(notes)) continue;
1480
- const unit = firstCharUnit(text);
1481
- if (!unit || text.trim() === "~") continue;
1482
- if (text.trimStart().startsWith("*")) return source;
1483
- const unitStart = offset + match.index + unit.index;
1484
- const unitEnd = unitStart + unit.unit.length;
1485
- return `${source.slice(0, unitStart)}*${source.slice(unitStart, unitEnd)}*${source.slice(unitEnd)}`;
1486
- }
1487
- return source;
1488
1073
  }
1489
- /**
1490
- * The built-in transformations, keyed by name; pass the ones a feature
1491
- * needs to the GuidoScript constructor.
1492
- */
1493
- var SCRIPT_TRANSFORMS = {
1494
- /** Wraps the first letter of the first syllable that has notes in
1495
- * `*…*`, the initial marker of the style marking system. */
1496
- startWithInitial: {
1497
- name: "startWithInitial",
1498
- apply: startWithInitial
1499
- } };
1500
- /** The pitch rows of the chant font: every character carrying pitch
1501
- * information, grouped into rows of neighbouring pitches from low to
1502
- * high. A transpose shift moves a character this many positions along
1503
- * its row; characters outside every row carry no pitch and stay put.
1504
- * Rows are searched in order, so a character found in several rows
1505
- * transposes within the first one. */
1506
- var PITCH_ROWS = [
1507
- "ðñ0123456789öüó",
1508
- "^]qwertzuiopõú",
1509
- "ÝÞQWERTZUIOPÕÚ",
1510
- "×sdfghjkléáû",
1511
- "ØÙDFGHJKLÉÁÛ",
1512
- "÷øaASÍYXCVBN$m",
1513
- "ÈÊËÌÎÏÐÑÒþßòôùý",
1514
- "“”•–—˜™š›œº»",
1515
- "®−§ÿ\"+!%/=()ÖÜÓ",
1516
- "Ÿ¡¢£[¥¦©ª«¬",
1517
- "~¯‚ƒ„…†‡ˆ‰Š‹Œ‘’",
1518
- "àâãäåæçèêëìîï",
1519
- "½°±²³´μ·¾¸¹"
1520
- ];
1521
- /** Maps one character to its pitch-shifted neighbour, or undefined when
1522
- * it is not a pitch character (and so stays unchanged). */
1523
- function shiftPitch(ch, shift, overflow) {
1524
- for (const row of PITCH_ROWS) {
1525
- const index = row.indexOf(ch);
1526
- if (index === -1) continue;
1527
- const target = index + shift;
1528
- if (target < 0 || target >= row.length) {
1529
- if (overflow === "null") return "\0";
1530
- if (overflow === "error") throw new Error(`Transposing "${ch}" by ${shift} runs past the glyph range`);
1531
- return row[Math.max(0, Math.min(row.length - 1, target))];
1532
- }
1533
- return row[target];
1534
- }
1074
+ /** Folds backslash escapes into the characters they stand for. Shared
1075
+ * with the transforms module (guidoScriptTransforms.ts). */
1076
+ function unescape(text) {
1077
+ return text.replace(/\\(.)/g, "$1");
1535
1078
  }
1536
- /** Transposes the pitch characters of one note group's content as
1537
- * written in the source (escapes included) — the staff-degree shift
1538
- * `transposeBy` applies to every group. Escape pairs stand for their
1539
- * underlying character (an escaped paren is a pitch glyph of the
1540
- * `®−§ÿ…` row), and a shifted result that is a control character of the
1541
- * group syntax is written escaped. A statement group's content (`@…`) is returned
1542
- * unchanged: its keyword letters are pitch glyphs, but no notes. */
1543
- function transposeNotes(notes, shift, options = {}) {
1544
- if (shift === 0 || isStatementGroup(notes)) return notes;
1545
- const overflow = options.overflow ?? "clamp";
1546
- let out = "";
1547
- for (let i = 0; i < notes.length; i++) {
1548
- const ch = notes[i];
1549
- const escaped = ch === "\\" && notes[i + 1] !== void 0;
1550
- const shifted = shiftPitch(escaped ? notes[i + 1] : ch, shift, overflow);
1551
- if (shifted === void 0) {
1552
- out += escaped ? ch + notes[i + 1] : ch;
1553
- if (escaped) i++;
1554
- continue;
1555
- }
1556
- out += "\\()".includes(shifted) ? `\\${shifted}` : shifted;
1557
- if (escaped) i++;
1558
- }
1559
- return out;
1560
- }
1561
- /** The `transposeBy` transform factory: shifts every pitch character of
1562
- * every notes group `shift` positions along its pitch row. The clef
1563
- * group and the syllable text are left alone — clef handling is a
1564
- * separate, future tool. */
1565
- function transposeBy(shift, options = {}) {
1566
- const overflow = options.overflow ?? "clamp";
1567
- const apply = (source) => {
1568
- if (shift === 0) return source;
1569
- const clefMatch = source.match(/^\s*\(([^)]*)\)/);
1570
- const offset = clefMatch ? clefMatch[0].length : 0;
1571
- return source.slice(0, offset) + source.slice(offset).replace(/((?:[^()\\]|\\.)*)\(((?:[^)\\]|\\.)*)\)/g, (_, text, notes) => `${text}(${transposeNotes(notes, shift, { overflow })})`);
1572
- };
1573
- return {
1574
- name: "transpose",
1575
- apply
1576
- };
1079
+ /** Turns literal parentheses and backslashes into their escape sequences. */
1080
+ function escape(text) {
1081
+ return text.replace(/\\/g, "\\\\").replace(/[()]/g, (ch) => `\\${ch}`);
1577
1082
  }
1578
1083
  //#endregion
1579
1084
  //#region src/guidoStyles.ts
@@ -1582,12 +1087,6 @@ function transposeBy(shift, options = {}) {
1582
1087
  * the special syllable decorations) kept in one constant registry, so a
1583
1088
  * new style is a data entry here rather than a renderer fork.
1584
1089
  */
1585
- /** The notation's pause-marker characters: they split off into their own
1586
- * runs in every style set — carrying the style set's dedicated
1587
- * `markerGlyphs` font when one is configured, the text font otherwise
1588
- * (Vesperale's text is Times New Roman already) — and always the
1589
- * notation-fixed `marker` kind. */
1590
- var MARKER_CHARS = /* @__PURE__ */ new Set(["*", "†"]);
1591
1090
  /** Text characters (* and †) rendered in Times New Roman. */
1592
1091
  var TIMES_MARKER_GLYPHS = {
1593
1092
  chars: MARKER_CHARS,
@@ -1625,33 +1124,33 @@ var STYLE_SETS = {
1625
1124
  weight: "700"
1626
1125
  }
1627
1126
  ],
1628
- decorations: {
1629
- __: {
1127
+ marks: {
1128
+ liturgy: {
1630
1129
  fontFamily: "'Liturgy', serif",
1631
1130
  weight: "700",
1632
1131
  color: "var(--red)"
1633
1132
  },
1634
- _: {
1133
+ rubric: {
1635
1134
  uppercase: true,
1636
1135
  scale: .7,
1637
1136
  color: "var(--red)"
1638
1137
  },
1639
- "*": {
1138
+ initial: {
1640
1139
  weight: "700",
1641
1140
  color: "var(--red)",
1642
1141
  initial: true
1643
- }
1644
- },
1645
- specialStarStyle: {
1646
- fontFamily: TIMES_MARKER_GLYPHS.fontFamily,
1647
- weight: "700",
1648
- scale: 1,
1649
- measureScale: .95,
1650
- raise: .1,
1651
- color: "var(--red)"
1142
+ },
1143
+ star: {
1144
+ fontFamily: TIMES_MARKER_GLYPHS.fontFamily,
1145
+ weight: "700",
1146
+ scale: 1,
1147
+ measureScale: .95,
1148
+ raise: .1,
1149
+ color: "var(--red)"
1150
+ },
1151
+ plus: LITURGY_PLUS_STYLE
1652
1152
  },
1653
- padding: 12,
1654
- scriptTransforms: [SCRIPT_TRANSFORMS.startWithInitial]
1153
+ padding: 12
1655
1154
  },
1656
1155
  /** Times New Roman text, strictly black and white. */
1657
1156
  Vesperale: {
@@ -1675,163 +1174,226 @@ var STYLE_SETS = {
1675
1174
  weight: "700"
1676
1175
  }
1677
1176
  ],
1678
- decorations: {
1679
- __: {
1177
+ marks: {
1178
+ liturgy: {
1680
1179
  fontFamily: "'Liturgy', serif",
1681
1180
  weight: "700"
1682
1181
  },
1683
- _: {
1182
+ rubric: {
1684
1183
  scale: .8,
1685
1184
  italic: true
1686
1185
  },
1687
- "*": {
1186
+ initial: {
1688
1187
  weight: "700",
1689
1188
  initial: true
1690
- }
1691
- },
1692
- specialStarStyle: {
1693
- fontFamily: TIMES_MARKER_GLYPHS.fontFamily,
1694
- weight: "700",
1695
- scale: 1,
1696
- measureScale: .95,
1697
- raise: .2
1189
+ },
1190
+ star: {
1191
+ fontFamily: TIMES_MARKER_GLYPHS.fontFamily,
1192
+ weight: "700",
1193
+ scale: 1,
1194
+ measureScale: .95,
1195
+ raise: .2
1196
+ },
1197
+ plus: LITURGY_PLUS_STYLE
1698
1198
  },
1699
- padding: 12,
1700
- scriptTransforms: []
1199
+ padding: 12
1701
1200
  }
1702
1201
  };
1703
1202
  var DEFAULT_STYLE_SET = "BNS";
1704
- /**
1705
- * Resolves a syllable's raw text into the runs it renders as: the whole-
1706
- * syllable `**` star renders as the bold ∗ operator, a `__…__` or `_…_`
1707
- * wrapper (the same characters on both ends, content between) picks up
1708
- * its decoration rule from the style set, and paired `*` markers wrap any
1709
- * part of the syllable — even the whole of it — with the initial rule
1710
- * (`*sam*ple` → "sam" in the initial style, "ple" normal; an unmatched
1711
- * `*` renders literally), the `bold` option forces weight 700 onto every
1712
- * run, and the marker characters (`*`, `†`) split off into runs of their
1713
- * own — with the style set's `markerGlyphs` font when one is configured,
1714
- * the text font otherwise (always the `marker` kind).
1715
- * Inside a Liturgy-font run, `+` gets its own weight-400 runs — the font
1716
- * is bold-looking by design, so the weight stays normal. The wrapper
1717
- * characters themselves are dropped. Each run also carries `kind`, the
1718
- * notation-fixed semantic of its markup (`liturgy`, `rubric`, `star`,
1719
- * `marker`, `plus`) — the vocabulary the marked-up text export and the
1720
- * renderer's run classes share, identical across style sets. `rawCase`
1721
- * skips the BNS rubric uppercasing: uppercasing is presentation, so the
1722
- * marked-up text export keeps the raw letter case (a consumer CSS applies
1723
- * text-transform instead).
1724
- */
1725
- function resolveSyllableParts(text, styleSet, bold, options = {}) {
1726
- if (text.length === 0) return [];
1727
- if (text === "**") return [{
1728
- text: "∗",
1729
- style: { ...styleSet.specialStarStyle },
1730
- kind: "star"
1731
- }];
1732
- let content = text;
1733
- let base = {};
1734
- let baseKind;
1735
- for (const wrapper of ["__", "_"]) {
1736
- const rule = styleSet.decorations[wrapper];
1737
- if (rule && text.length >= wrapper.length * 2 + 1 && text.startsWith(wrapper) && text.endsWith(wrapper)) {
1738
- content = text.slice(wrapper.length, -wrapper.length);
1739
- base = { ...rule };
1740
- baseKind = wrapper === "__" ? "liturgy" : "rubric";
1741
- break;
1742
- }
1743
- }
1744
- const initialRule = styleSet.decorations["*"];
1745
- const segmentSpecs = [];
1746
- let rest = content;
1747
- let plain = "";
1748
- for (let m = /\*([^*]+)\*/.exec(rest); m; m = /\*([^*]+)\*/.exec(rest)) {
1749
- plain += rest.slice(0, m.index);
1750
- if (plain) {
1751
- segmentSpecs.push({
1752
- text: plain,
1753
- marked: false
1754
- });
1755
- plain = "";
1203
+ /** The style sets `defineStyleSet` added. */
1204
+ var definedStyleSets = /* @__PURE__ */ new Map();
1205
+ /** The style set of that name, built-in or defined. */
1206
+ function styleSetOf(name) {
1207
+ return definedStyleSets.get(name) ?? STYLE_SETS[name];
1208
+ }
1209
+ /** Adds a style set under a name `style` can then give, without patching
1210
+ * the package. Returns it. */
1211
+ function defineStyleSet(name, definition) {
1212
+ const { extends: base = "BNS", ...own } = definition;
1213
+ const parent = styleSetOf(base);
1214
+ if (!parent) throw new Error(`Unknown style set: "${base}"`);
1215
+ const styleSet = {
1216
+ ...parent,
1217
+ ...own,
1218
+ marks: {
1219
+ ...parent.marks,
1220
+ ...own.marks
1221
+ },
1222
+ colors: {
1223
+ ...parent.colors,
1224
+ ...own.colors
1225
+ },
1226
+ fonts: {
1227
+ ...parent.fonts,
1228
+ ...own.fonts
1756
1229
  }
1757
- segmentSpecs.push({
1758
- text: m[1],
1759
- marked: true
1760
- });
1761
- rest = rest.slice(m.index + m[0].length);
1762
- }
1763
- plain += rest;
1764
- if (plain) segmentSpecs.push({
1765
- text: plain,
1766
- marked: false
1767
- });
1768
- const segments = segmentSpecs.map(({ text: segText, marked }) => ({
1769
- text: segText,
1770
- style: marked ? {
1771
- ...base,
1772
- ...initialRule,
1773
- initial: true
1774
- } : { ...base },
1775
- kind: baseKind
1776
- }));
1777
- const glyphs = styleSet.markerGlyphs;
1778
- const parts = [];
1779
- for (const segment of segments) {
1780
- if (segment.style.uppercase && !options.rawCase) segment.text = segment.text.toUpperCase();
1781
- if (bold) segment.style = {
1782
- ...segment.style,
1230
+ };
1231
+ definedStyleSets.set(name, styleSet);
1232
+ return styleSet;
1233
+ }
1234
+ /** The built-in colors `color:<name>` can name. */
1235
+ var PALETTE = { red: "var(--red)" };
1236
+ /** The built-in fonts `font:<name>` can name. */
1237
+ var FONTS = {
1238
+ liturgy: "'Liturgy', serif",
1239
+ times: "'Times New Roman', Times, serif"
1240
+ };
1241
+ /** How much smaller small capitals draw than the full capitals. */
1242
+ var SMALL_CAP_SCALE = .75;
1243
+ var KINDS = /* @__PURE__ */ new Set([
1244
+ "liturgy",
1245
+ "rubric",
1246
+ "star",
1247
+ "marker",
1248
+ "plus"
1249
+ ]);
1250
+ /** The run kind of a run's marks: the last of the notation's own. */
1251
+ function kindOf(marks) {
1252
+ return marks.filter((mark) => KINDS.has(mark)).pop();
1253
+ }
1254
+ /** The style `mark` leaves on `style`, or undefined when no such mark
1255
+ * exists. The primitives come first, so they mean the same in every style
1256
+ * set; a registered mark's `color` may name a palette color. */
1257
+ function withMark(style, mark, text, styleSet, extra) {
1258
+ const colorOf = (name) => styleSet.colors?.[name] ?? PALETTE[name];
1259
+ const at = mark.indexOf(":");
1260
+ const name = at < 0 ? mark : mark.slice(0, at);
1261
+ const argument = at < 0 ? "" : mark.slice(at + 1);
1262
+ const amount = Number(argument);
1263
+ switch (name) {
1264
+ case "plain": return {};
1265
+ case "red": return {
1266
+ ...style,
1267
+ color: PALETTE.red
1268
+ };
1269
+ case "b": return {
1270
+ ...style,
1783
1271
  weight: "700"
1784
1272
  };
1785
- const chars = [...segment.text];
1786
- const inLiturgy = segment.style.fontFamily?.includes("Liturgy") ?? false;
1787
- const runKind = (ch) => {
1788
- if (MARKER_CHARS.has(ch) || glyphs && glyphs.chars.has(ch)) return "marker";
1789
- if (inLiturgy && ch === "+") return "plus";
1790
- return "text";
1273
+ case "i": return {
1274
+ ...style,
1275
+ italic: true
1791
1276
  };
1792
- if (chars.every((ch) => runKind(ch) === "text")) {
1793
- parts.push({
1794
- text: segment.text,
1795
- style: { ...segment.style },
1796
- kind: segment.kind
1797
- });
1798
- continue;
1799
- }
1800
- let charRun = "";
1801
- let currentKind = null;
1802
- const pushRun = () => {
1803
- if (!charRun) return;
1804
- let runStyle = { ...segment.style };
1805
- let partKind = segment.kind;
1806
- if (currentKind === "marker") {
1807
- partKind = "marker";
1808
- if (glyphs && glyphs.chars.has(charRun[0])) runStyle = {
1809
- ...runStyle,
1810
- fontFamily: glyphs.fontFamily
1811
- };
1812
- } else if (currentKind === "plus") {
1813
- runStyle = {
1814
- ...runStyle,
1815
- ...LITURGY_PLUS_STYLE
1816
- };
1817
- partKind = "plus";
1818
- }
1819
- parts.push({
1820
- text: charRun,
1821
- style: runStyle,
1822
- kind: partKind
1823
- });
1824
- charRun = "";
1277
+ case "sc": return {
1278
+ ...style,
1279
+ smallCaps: true
1825
1280
  };
1826
- for (const ch of chars) {
1827
- const kind = runKind(ch);
1828
- if (kind !== currentKind) pushRun();
1829
- currentKind = kind;
1830
- charRun += ch;
1281
+ case "up": return {
1282
+ ...style,
1283
+ uppercase: true
1284
+ };
1285
+ case "color": {
1286
+ const color = colorOf(argument);
1287
+ return color ? {
1288
+ ...style,
1289
+ color
1290
+ } : void 0;
1291
+ }
1292
+ case "size": return amount > 0 ? {
1293
+ ...style,
1294
+ scale: amount,
1295
+ measureScale: void 0
1296
+ } : void 0;
1297
+ case "raise": return Number.isFinite(amount) && argument !== "" ? {
1298
+ ...style,
1299
+ raise: amount
1300
+ } : void 0;
1301
+ case "font": {
1302
+ const fontFamily = styleSet.fonts?.[argument] ?? FONTS[argument];
1303
+ return fontFamily ? {
1304
+ ...style,
1305
+ fontFamily
1306
+ } : void 0;
1831
1307
  }
1832
- pushRun();
1308
+ case "marker": return styleSet.markerGlyphs?.chars.has(text[0]) ? {
1309
+ ...style,
1310
+ fontFamily: styleSet.markerGlyphs.fontFamily
1311
+ } : style;
1833
1312
  }
1834
- return parts;
1313
+ const rule = extra?.[mark] ?? styleSet.marks[mark];
1314
+ if (!rule) return void 0;
1315
+ const color = rule.color && colorOf(rule.color);
1316
+ return {
1317
+ ...style,
1318
+ ...rule,
1319
+ ...color ? { color } : {}
1320
+ };
1321
+ }
1322
+ /** The look of a list of marks, later ones winning; a mark that does not
1323
+ * exist changes nothing (`unknownMarks` reports it). */
1324
+ function styleOf(text, marks, styleSet, extra) {
1325
+ return marks.reduce((style, mark) => withMark(style, mark, text, styleSet, extra) ?? style, {});
1326
+ }
1327
+ /** The look of comma-separated marks (`red,sc`), for a host styling prose
1328
+ * to match the score. */
1329
+ function resolveMarks(marks, styleSet, extra) {
1330
+ return styleOf("", marks.split(",").map((mark) => mark.trim()), styleSet, extra);
1331
+ }
1332
+ /** The marks of `marks` that neither the primitives, the style set nor
1333
+ * `extra` define. */
1334
+ function unknownMarks(marks, styleSet, extra) {
1335
+ return marks.filter((mark) => withMark({}, mark, "", styleSet, extra) === void 0);
1336
+ }
1337
+ /** A run's small-caps split: lowercase letters as small capitals, in runs
1338
+ * of their own, everything else at full size. */
1339
+ function splitSmallCaps(text) {
1340
+ const pieces = [];
1341
+ for (const ch of text) {
1342
+ const small = ch.toUpperCase() !== ch;
1343
+ const last = pieces[pieces.length - 1];
1344
+ if (last && last.small === small) last.text += ch;
1345
+ else pieces.push({
1346
+ text: ch,
1347
+ small
1348
+ });
1349
+ }
1350
+ return pieces;
1351
+ }
1352
+ /** Resolves parsed text runs (`SyllableToken.runs`) into how a style set
1353
+ * draws them: each run takes the style of its marks, the `bold` option
1354
+ * forces weight 700 onto every run, and `kind` names its notation-fixed
1355
+ * semantic (`liturgy`, `rubric`, `star`, `marker`, `plus`), the vocabulary
1356
+ * the marked-up text export and the renderer's run classes share. A
1357
+ * small-caps run splits into full and small parts. Text stays as written:
1358
+ * capitals are the part's display (`drawnText`). */
1359
+ function resolveTextRuns(runs, styleSet, bold, extra) {
1360
+ return runs.flatMap(({ text, marks }) => {
1361
+ const resolved = styleOf(text, marks, styleSet, extra);
1362
+ const style = bold ? {
1363
+ ...resolved,
1364
+ weight: "700"
1365
+ } : resolved;
1366
+ const kind = kindOf(marks);
1367
+ if (!style.smallCaps) return [{
1368
+ text,
1369
+ style,
1370
+ kind
1371
+ }];
1372
+ const full = {
1373
+ ...style,
1374
+ smallCaps: void 0
1375
+ };
1376
+ return splitSmallCaps(text).map((piece) => ({
1377
+ text: piece.text,
1378
+ kind,
1379
+ style: piece.small ? {
1380
+ ...full,
1381
+ smallCaps: true,
1382
+ uppercase: true,
1383
+ scale: (full.scale ?? 1) * SMALL_CAP_SCALE,
1384
+ measureScale: void 0
1385
+ } : full
1386
+ }));
1387
+ });
1388
+ }
1389
+ /** The characters a part draws, which measuring must see. */
1390
+ function drawnText(part) {
1391
+ return part.style.uppercase ? part.text.toUpperCase() : part.text;
1392
+ }
1393
+ /** Parses a syllable as written (`SyllableToken.source`) and resolves its
1394
+ * runs in one step (see `resolveSpans`, `resolveTextRuns`). */
1395
+ function resolveSyllableParts(written, styleSet, bold, extra) {
1396
+ return resolveTextRuns(resolveSpans([written]).pieces[0].runs, styleSet, bold, extra);
1835
1397
  }
1836
1398
  /** The canvas font shorthand for measuring a run at the text size. */
1837
1399
  function measurementFont(style, textPx, fallbackStack) {
@@ -1852,6 +1414,7 @@ function inlineStylesFor(style, textPx) {
1852
1414
  if (style.italic) styles["font-style"] = "italic";
1853
1415
  if (style.scale !== void 0) styles["font-size"] = `${textPx * style.scale}px`;
1854
1416
  if (style.color) styles["color"] = style.color;
1417
+ if (style.uppercase) styles["text-transform"] = "uppercase";
1855
1418
  if (style.raise) {
1856
1419
  styles["position"] = "relative";
1857
1420
  styles["top"] = `${-textPx * style.raise}px`;
@@ -1888,7 +1451,32 @@ function isRecitationGroup(notes) {
1888
1451
  */
1889
1452
  var NOTE_MODIFIERS = "÷øaASÍYXCVBN$mÈÊËÌÎÏÐÑÒþßòôùý“”•–—˜™š›œº»";
1890
1453
  var MODIFIER_CHARS = new Set(NOTE_MODIFIERS.split(""));
1454
+ /**
1455
+ * The length of what hangs at the start of a group's core: its leading
1456
+ * modifiers and bracketed accidentals (issue #95), which stand in the
1457
+ * junction whitespace before the group's first note.
1458
+ */
1459
+ function hangingLength(core) {
1460
+ let at = 0;
1461
+ for (;;) {
1462
+ const unit = MODIFIER_CHARS.has(core[at] ?? "") ? 1 : bracketedAccidentalLength(core, at);
1463
+ if (unit === 0) return at;
1464
+ at += unit;
1465
+ }
1466
+ }
1467
+ /** The index in `notes` right after its hanging run (leading markers
1468
+ * counted), or 0 when nothing hangs. */
1469
+ function hangEnd(notes) {
1470
+ const { leading, core } = splitNoteMarkers(notes);
1471
+ const hang = hangingLength(core);
1472
+ return hang === 0 ? 0 : leading.length + hang;
1473
+ }
1891
1474
  var NOTE_GROUP_SPLITTERS = ["-", "¨"];
1475
+ /** A junction `thirds` thirds of a dash wide: whole dashes, then one `¨`
1476
+ * per leftover third (`--¨¨` is 2⅔). */
1477
+ function junctionSpacer(thirds) {
1478
+ return "-".repeat(Math.floor(thirds / 3)) + "¨".repeat(thirds % 3);
1479
+ }
1892
1480
  /** The key written by a run of modifier glyphs, under `clef` (a clef
1893
1481
  * glyph; the standard g-clef when unknown — matching pitches by staff
1894
1482
  * position does not depend on it). A statement's key throws when two
@@ -1925,25 +1513,29 @@ function noteBaseOf(ch) {
1925
1513
  * signs stand before the note group, not before their notes: they go at
1926
1514
  * the start of the group's notes (after its leading markers), one per
1927
1515
  * 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
1516
+ * already marks with a modifier are left alone (a bracketed accidental
1517
+ * opening the group, issue #95, marks the note after it). The groups a
1518
+ * syllable holds (`held`, issue #83) are scanned too: a held run writes its signs
1930
1519
  * once, before its first group. Returns the rewritten group and the
1931
1520
  * indices of the inserted signs. Throws when a needed sign does not
1932
1521
  * exist.
1933
1522
  */
1934
1523
  function applyKeyChange(notes, staff, active, clef, held = []) {
1935
1524
  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;
1525
+ for (const group of [notes, ...held]) {
1526
+ const hang = hangEnd(group);
1527
+ for (let i = 0; i < group.length; i++) {
1528
+ const ch = group[i];
1529
+ const base = noteBaseOf(ch);
1530
+ const letter = base !== void 0 ? pitchLetterOf(base, clefOrDefault(clef)) : void 0;
1531
+ const want = letter !== void 0 ? active.get(letter) : void 0;
1532
+ const marked = i > 0 && (isModifierGlyph(group[i - 1]) || i === hang);
1533
+ if (letter !== void 0 && want !== staff.get(letter) && !marked) {
1534
+ const role = want ?? "modifyNatural";
1535
+ const sign = want ? variantOf(base, want) : modifyNatural(base);
1536
+ if (sign === void 0) throw new Error(`The note "${ch}" has no ${role} glyph for the key change`);
1537
+ if (!signs.includes(sign)) signs += sign;
1538
+ }
1947
1539
  }
1948
1540
  }
1949
1541
  const at = splitNoteMarkers(notes).leading.length;
@@ -1975,6 +1567,12 @@ function ink(text, font) {
1975
1567
  right: m.actualBoundingBoxRight
1976
1568
  };
1977
1569
  }
1570
+ var STAFF_FILLS = [
1571
+ "all-but-last",
1572
+ "none",
1573
+ "all",
1574
+ "longest"
1575
+ ];
1978
1576
  /** Each underlay's tokens, checked to share one melody. */
1979
1577
  function underlayTokens(source) {
1980
1578
  const list = typeof source === "string" || source instanceof GuidoScript ? [source] : source;
@@ -2020,10 +1618,34 @@ function silent(tok) {
2020
1618
  * fonts cannot be loaded.
2021
1619
  */
2022
1620
  async function layoutScore(source, options = {}) {
2023
- const { style: styleName = "BNS", bold = false, textPx = 18, notesPx = textPx * 2, maxWidthPx = Infinity } = options;
1621
+ const breakBefore = /* @__PURE__ */ new Set();
1622
+ const wraps = /* @__PURE__ */ new Set();
1623
+ for (;;) {
1624
+ const { result, splitRuns } = await layoutPass(source, options, breakBefore);
1625
+ const open = splitRuns.filter((r) => !wraps.has(r.run));
1626
+ if (open.length === 0) return result;
1627
+ const split = open.reduce((a, b) => b.run < a.run ? b : a);
1628
+ if (breakBefore.has(split.run) || split.atLineStart) {
1629
+ wraps.add(split.run);
1630
+ if (split.nested) breakBefore.add(split.run);
1631
+ else breakBefore.delete(split.run);
1632
+ } else breakBefore.add(split.run);
1633
+ }
1634
+ }
1635
+ /** One pass of `layoutScore`: `breakBefore` lists the `(@keep)` runs (by
1636
+ * position in the script) that open a fresh line; `splitRuns` reports the
1637
+ * ones that crossed a line break. */
1638
+ async function layoutPass(source, options, breakBefore) {
1639
+ const { style: styleName = "BNS", marks, bold = false, textPx = 18, notesPx = textPx * 2, maxWidthPx = Infinity, junctionDashes = 3, staffFill = "all-but-last", staffFillSnapPx = 0 } = options;
1640
+ if (!STAFF_FILLS.includes(staffFill)) throw new Error(`Unknown staffFill: "${staffFill}"`);
1641
+ if (!(staffFillSnapPx >= 0 && Number.isFinite(staffFillSnapPx))) throw new Error(`staffFillSnapPx must be zero or more: ${staffFillSnapPx}`);
1642
+ const junctionThirds = Math.round(junctionDashes * 3);
1643
+ if (!(junctionDashes >= 1 && Math.abs(junctionDashes - junctionThirds / 3) <= .01)) throw new Error(`junctionDashes must be at least 1, in steps of a third: ${junctionDashes}`);
1644
+ const fullJunction = junctionSpacer(junctionThirds);
1645
+ const reducedJunction = junctionSpacer(Math.max(3, junctionThirds - 3));
2024
1646
  const underlays = underlayTokens(source);
2025
1647
  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
- const styleSet = STYLE_SETS[styleName];
1648
+ const styleSet = styleSetOf(styleName);
2027
1649
  if (!styleSet) throw new Error(`Unknown style set: "${styleName}"`);
2028
1650
  for (const font of fontStringsToVerify(styleSet, textPx)) {
2029
1651
  try {
@@ -2034,10 +1656,23 @@ async function layoutScore(source, options = {}) {
2034
1656
  const notesFont = `400 ${notesPx}px ${styleSet.notesFontStack}`;
2035
1657
  const textStack = styleSet.textFontStack;
2036
1658
  const spaceFont = measurementFont({ weight: bold ? "700" : "400" }, textPx, textStack);
2037
- const resolveParts = (spanText) => resolveSyllableParts(spanText, styleSet, bold);
2038
- const measureParts = (parts) => parts.reduce((w, part) => w + measure(part.text, measurementFont(part.style, textPx, textStack)), 0);
1659
+ const resolveParts = (runs) => resolveTextRuns(runs, styleSet, bold, marks);
1660
+ const measureParts = (parts) => parts.reduce((w, part) => w + measure(drawnText(part), measurementFont(part.style, textPx, textStack)), 0);
2039
1661
  const dashNotesWidth = measure("-", notesFont);
2040
1662
  const dashTextWidth = measure("-", spaceFont);
1663
+ /** The hyphen after a syllable: plain, unless a `{…}` span runs on
1664
+ * across it, when it takes the span's look and that look's width. */
1665
+ const hyphenOf = (hyphenMarks) => {
1666
+ if (!hyphenMarks) return { width: dashTextWidth };
1667
+ const parts = resolveParts([{
1668
+ text: "-",
1669
+ marks: hyphenMarks
1670
+ }]);
1671
+ return {
1672
+ parts,
1673
+ width: measureParts(parts)
1674
+ };
1675
+ };
2041
1676
  let clefGlyph = script.clef?.[0];
2042
1677
  let keyGlyphs = [...(script.clef ?? "").slice(1)].filter(isModifierGlyph).join("");
2043
1678
  let clefGroup = script.clef;
@@ -2051,7 +1686,8 @@ async function layoutScore(source, options = {}) {
2051
1686
  lastTextSyl: syls.reduce((last, s, i) => silent(s) ? last : i, -1),
2052
1687
  cursor: 0,
2053
1688
  pending: [],
2054
- prevWordEnd: void 0
1689
+ prevWordEnd: void 0,
1690
+ hyphen: { width: dashTextWidth }
2055
1691
  };
2056
1692
  });
2057
1693
  const lines = [];
@@ -2079,6 +1715,7 @@ async function layoutScore(source, options = {}) {
2079
1715
  segments: texts[0].segments,
2080
1716
  textCursor: 0,
2081
1717
  notesEnd: 0,
1718
+ staffEnd: 0,
2082
1719
  lastWordEnd: null,
2083
1720
  texts
2084
1721
  };
@@ -2101,9 +1738,15 @@ async function layoutScore(source, options = {}) {
2101
1738
  const items = [];
2102
1739
  let sylIndex = 0;
2103
1740
  let runHead;
1741
+ let tightDepth = 0;
1742
+ let tightGroupPlaced = false;
2104
1743
  for (const tok of tokens) if (tok.kind !== "syllable") {
2105
1744
  items.push(tok);
2106
1745
  runHead = void 0;
1746
+ if (tok.kind === "tight" || tok.kind === "unit") {
1747
+ tightDepth = Math.max(0, tightDepth + (tok.on ? 1 : -1));
1748
+ if (tightDepth === 0) tightGroupPlaced = false;
1749
+ }
2107
1750
  } else {
2108
1751
  const item = {
2109
1752
  kind: "syl",
@@ -2114,8 +1757,10 @@ async function layoutScore(source, options = {}) {
2114
1757
  first: true,
2115
1758
  lastSeg: true,
2116
1759
  heldRun: [],
2117
- signedByRun: false
1760
+ signedByRun: false,
1761
+ tightJoin: tightGroupPlaced
2118
1762
  };
1763
+ if (tok.notes !== "") tightGroupPlaced = tightDepth > 0;
2119
1764
  if (allHeld(item.i) && runHead) {
2120
1765
  runHead.heldRun.push(tok.notes);
2121
1766
  item.signedByRun = true;
@@ -2124,7 +1769,8 @@ async function layoutScore(source, options = {}) {
2124
1769
  }
2125
1770
  const placedNotes = [];
2126
1771
  const findBreakCut = (notes, room, measureFromLineStart) => {
2127
- for (let c = notes.length - 1; c > 0; c--) {
1772
+ const first = hangEnd(notes);
1773
+ for (let c = notes.length - 1; c >= first && c > 0; c--) {
2128
1774
  if (!NOTE_GROUP_SPLITTERS.includes(notes[c])) continue;
2129
1775
  let end = c + 1;
2130
1776
  while (end < notes.length && MARKER_CHARS$1.has(notes[end])) end++;
@@ -2153,7 +1799,8 @@ async function layoutScore(source, options = {}) {
2153
1799
  first: false,
2154
1800
  lastSeg: true,
2155
1801
  heldRun: [],
2156
- signedByRun: false
1802
+ signedByRun: false,
1803
+ tightJoin: false
2157
1804
  });
2158
1805
  forceBreak = true;
2159
1806
  };
@@ -2161,7 +1808,7 @@ async function layoutScore(source, options = {}) {
2161
1808
  tracks.forEach((t, u) => {
2162
1809
  while (t.pending.length > 0) {
2163
1810
  const p = t.pending[0];
2164
- if (t.cursor > 0 && t.cursor + p.textWidth + (p.wordEnd ? 0 : dashTextWidth) > maxWidthPx) {
1811
+ if (t.cursor > 0 && t.cursor + p.textWidth + (p.wordEnd ? 0 : p.hyphen.width) > maxWidthPx) {
2165
1812
  startLine();
2166
1813
  continue;
2167
1814
  }
@@ -2188,11 +1835,20 @@ async function layoutScore(source, options = {}) {
2188
1835
  t.cursor += p.spaceWidth;
2189
1836
  }
2190
1837
  text.lastWordEnd = p.wordEnd;
1838
+ text.hyphen = p.hyphen;
1839
+ t.hyphen = p.hyphen;
2191
1840
  text.textCursor = t.cursor;
2192
1841
  }
2193
1842
  });
2194
1843
  };
2195
1844
  let forceBreak = false;
1845
+ let keepRuns = 0;
1846
+ const keepStack = [];
1847
+ const splitRuns = [];
1848
+ const closeKeepRun = () => {
1849
+ const run = keepStack.pop();
1850
+ if (run && lines.length - 1 > run.line) splitRuns.push(run);
1851
+ };
2196
1852
  let idx = 0;
2197
1853
  while (idx < items.length) {
2198
1854
  const item = items[idx];
@@ -2204,6 +1860,29 @@ async function layoutScore(source, options = {}) {
2204
1860
  idx++;
2205
1861
  continue;
2206
1862
  }
1863
+ if (item.kind === "tight" || item.kind === "aid") {
1864
+ idx++;
1865
+ continue;
1866
+ }
1867
+ if (item.kind === "keep" || item.kind === "unit") {
1868
+ if (!item.on) closeKeepRun();
1869
+ else {
1870
+ const hasContent = line.texts.some((x) => x.segments.length > 0) || tracks.some((t) => t.pending.length > 0);
1871
+ if (breakBefore.has(keepRuns) && hasContent) {
1872
+ flushPending(false);
1873
+ forceBreak = true;
1874
+ }
1875
+ if (keepStack.length > 0) keepStack[keepStack.length - 1].nested = true;
1876
+ keepStack.push({
1877
+ run: keepRuns++,
1878
+ line: forceBreak ? lines.length : lines.length - 1,
1879
+ atLineStart: !hasContent || forceBreak,
1880
+ nested: false
1881
+ });
1882
+ }
1883
+ idx++;
1884
+ continue;
1885
+ }
2207
1886
  if (item.kind === "clef" || item.kind === "key") {
2208
1887
  if (item.kind === "clef") clefGlyph = item.clef;
2209
1888
  keyGlyphs = item.key;
@@ -2214,7 +1893,7 @@ async function layoutScore(source, options = {}) {
2214
1893
  notesSoFar = line.clefPrefix;
2215
1894
  staffKey = activeKey;
2216
1895
  } else if (item.kind === "clef") {
2217
- const part = (lastGroupTrailingMarker ? "--" : "---") + clefGroup + "-";
1896
+ const part = (lastGroupTrailingMarker ? reducedJunction : fullJunction) + clefGroup + "-";
2218
1897
  if (measure(notesSoFar + part, notesFont) > maxWidthPx) forceBreak = true;
2219
1898
  else {
2220
1899
  line.notesParts.push(part);
@@ -2244,7 +1923,7 @@ async function layoutScore(source, options = {}) {
2244
1923
  const sung = tracks.map((t) => {
2245
1924
  const own = t.syls[i];
2246
1925
  const last = item.lastSeg && i >= t.lastTextSyl;
2247
- const sylParts = resolveParts(item.first ? own.text : "");
1926
+ const sylParts = resolveParts(item.first ? own.runs : []);
2248
1927
  return {
2249
1928
  t,
2250
1929
  own,
@@ -2266,13 +1945,14 @@ async function layoutScore(source, options = {}) {
2266
1945
  sylParts: s.sylParts,
2267
1946
  textWidth: s.textWidth,
2268
1947
  spaceWidth: s.spaceWidth,
2269
- wordEnd: s.own.wordEnd
1948
+ wordEnd: s.own.wordEnd,
1949
+ hyphen: hyphenOf(s.own.hyphen)
2270
1950
  });
2271
1951
  }
2272
1952
  idx++;
2273
1953
  continue;
2274
1954
  }
2275
- if (item.first && item.lastSeg && !syl.empty && syl.text.trim() === "" && splitNoteMarkers(item.notes).core === "") {
1955
+ if (item.first && item.lastSeg && !syl.empty && syl.runs.length === 0 && splitNoteMarkers(item.notes).core === "") {
2276
1956
  const last = notesSoFar[notesSoFar.length - 1];
2277
1957
  const sep = last && last !== "-" && !lastGroupTrailingMarker && !syl.notes.startsWith("-") ? "-" : "";
2278
1958
  line.notesParts.push(sep + syl.notes);
@@ -2298,7 +1978,7 @@ async function layoutScore(source, options = {}) {
2298
1978
  continue;
2299
1979
  }
2300
1980
  let parts = splitNoteMarkers(item.notes);
2301
- const joinOf = () => line.notesParts.length === 0 || afterInlineClef ? "" : held ? lastGroupTrailingMarker ? "--" : "-" : lastGroupTrailingMarker || MODIFIER_CHARS.has(parts.core[0]) ? "--" : "---";
1981
+ const joinOf = () => line.notesParts.length === 0 || afterInlineClef ? "" : held ? lastGroupTrailingMarker ? "--" : "-" : lastGroupTrailingMarker || item.tightJoin || hangingLength(parts.core) > 0 ? reducedJunction : fullJunction;
2302
1982
  let join = joinOf();
2303
1983
  if (line.notesParts.length > 0 && measure(notesSoFar + join + item.notes, notesFont) > maxWidthPx) {
2304
1984
  startLine();
@@ -2326,7 +2006,7 @@ async function layoutScore(source, options = {}) {
2326
2006
  }
2327
2007
  const voiced = item.first ? sung.filter((s) => !silent(s.own)) : sung;
2328
2008
  const runStart = placedNotes[i - 1] !== item.notes;
2329
- const specialFits = voiced.every((s) => s.t.cursor === 0 || s.t.cursor + s.pendingTotal + s.textWidth + (s.own.wordEnd ? 0 : dashTextWidth) <= maxWidthPx);
2009
+ const specialFits = voiced.every((s) => s.t.cursor === 0 || s.t.cursor + s.pendingTotal + s.textWidth + (s.own.wordEnd ? 0 : hyphenOf(s.own.hyphen).width) <= maxWidthPx);
2330
2010
  if (special && !runStart && line.notesParts.length > 0 && !specialFits) startLine();
2331
2011
  if (!item.first) {
2332
2012
  for (;;) {
@@ -2349,10 +2029,13 @@ async function layoutScore(source, options = {}) {
2349
2029
  continue;
2350
2030
  }
2351
2031
  let parts = splitNoteMarkers(item.notes);
2352
- let junctionPrefix = line.notesParts.length === 0 || afterInlineClef ? "" : prevRecited ? "" : lastGroupTrailingMarker || MODIFIER_CHARS.has(parts.core[0]) ? "--" : "---";
2032
+ let junctionPrefix = line.notesParts.length === 0 || afterInlineClef ? "" : lastGroupTrailingMarker || item.tightJoin || hangingLength(parts.core) > 0 ? reducedJunction : fullJunction;
2033
+ if (prevRecited) {
2034
+ const closing = /-*$/.exec(notesSoFar)[0].length;
2035
+ junctionPrefix = special && !runStart || closing > /^-*/.exec(junctionPrefix)[0].length ? "" : junctionPrefix.slice(closing);
2036
+ }
2353
2037
  const place = (padDashes = 0) => {
2354
- let mods = 0;
2355
- while (mods < parts.core.length && MODIFIER_CHARS.has(parts.core[mods])) mods++;
2038
+ let mods = hangingLength(parts.core);
2356
2039
  if (mods === parts.core.length) mods = 0;
2357
2040
  const anchorText = parts.core.slice(mods);
2358
2041
  const contentWidth = measure(anchorText, notesFont);
@@ -2370,7 +2053,7 @@ async function layoutScore(source, options = {}) {
2370
2053
  let placed = place();
2371
2054
  for (;;) {
2372
2055
  const notesOver = measure(notesSoFar + junctionPrefix + item.notes, notesFont) > maxWidthPx;
2373
- const textOver = voiced.some((s) => placed.textStartOf(s.textWidth) + s.textWidth + (s.own.wordEnd ? 0 : dashTextWidth) > maxWidthPx);
2056
+ const textOver = voiced.some((s) => placed.textStartOf(s.textWidth) + s.textWidth + (s.own.wordEnd ? 0 : hyphenOf(s.own.hyphen).width) > maxWidthPx);
2374
2057
  if (!notesOver && !textOver) break;
2375
2058
  if (notesOver) {
2376
2059
  const cut = findBreakCut(item.notes, maxWidthPx, (prefix) => measure(notesSoFar + junctionPrefix + prefix, notesFont));
@@ -2404,13 +2087,12 @@ async function layoutScore(source, options = {}) {
2404
2087
  const { t, textWidth } = s;
2405
2088
  const { contentWidth } = placed;
2406
2089
  const connectorDash = line.notesParts.length > 0 && !t.prevWordEnd && s.pendingTotal === 0;
2407
- const minStart = t.cursor + dashTextWidth;
2408
- const minTextStart = t.cursor + s.pendingTotal + (prevRecited && connectorDash ? dashTextWidth : 0);
2090
+ const minStart = t.cursor + t.hyphen.width;
2091
+ const minTextStart = t.cursor + s.pendingTotal + (prevRecited && connectorDash ? t.hyphen.width : 0);
2409
2092
  let textStart = placed.textStartOf(textWidth);
2410
2093
  let contentStart = placed.contentStart;
2411
2094
  let pads = 0;
2412
2095
  let tight = false;
2413
- let wantsBreak = false;
2414
2096
  if (!prevRecited && connectorDash && textStart < minStart && (textWidth > contentWidth || textStart < t.cursor)) {
2415
2097
  tight = true;
2416
2098
  textStart = t.cursor;
@@ -2422,8 +2104,7 @@ async function layoutScore(source, options = {}) {
2422
2104
  pads,
2423
2105
  tight,
2424
2106
  floor: t.cursor,
2425
- minStart,
2426
- wantsBreak
2107
+ minStart
2427
2108
  };
2428
2109
  }
2429
2110
  if (textStart < minTextStart) {
@@ -2437,7 +2118,6 @@ async function layoutScore(source, options = {}) {
2437
2118
  }
2438
2119
  textStart = padded.textStartOf(textWidth);
2439
2120
  contentStart = padded.contentStart;
2440
- wantsBreak = line.notesParts.length > 0 && measure(notesSoFar + junctionPrefix + "-".repeat(pads) + item.notes, notesFont) > maxWidthPx;
2441
2121
  }
2442
2122
  }
2443
2123
  return {
@@ -2446,8 +2126,7 @@ async function layoutScore(source, options = {}) {
2446
2126
  pads,
2447
2127
  tight,
2448
2128
  floor: minTextStart,
2449
- minStart,
2450
- wantsBreak
2129
+ minStart
2451
2130
  };
2452
2131
  };
2453
2132
  const hiddenSpecial = special && !runStart && line.notesParts.length > 0 && !afterInlineClef;
@@ -2463,8 +2142,7 @@ async function layoutScore(source, options = {}) {
2463
2142
  pads: 0,
2464
2143
  tight: line.notesParts.length > 0 && !s.t.prevWordEnd && s.pendingTotal === 0,
2465
2144
  floor: textStart,
2466
- minStart: textStart,
2467
- wantsBreak: false
2145
+ minStart: textStart
2468
2146
  };
2469
2147
  });
2470
2148
  const deficit = Math.max(...voiced.map((s, v) => placements[v].textStart + s.textWidth + s.spaceWidth)) - measure(notesSoFar, notesFont);
@@ -2474,28 +2152,33 @@ async function layoutScore(source, options = {}) {
2474
2152
  item.inserted = [];
2475
2153
  parts = splitNoteMarkers(item.notes);
2476
2154
  } else {
2477
- placements = voiced.map(decide);
2478
- if (placements.some((p) => p.wantsBreak)) {
2155
+ const settle = () => {
2156
+ placements = voiced.map(decide);
2157
+ padDashes = Math.max(0, ...placements.map((p) => p.pads));
2158
+ if (placements.some((p) => p.pads < padDashes)) {
2159
+ const padded = place(padDashes);
2160
+ placements = placements.map((p, v) => {
2161
+ if (p.pads === padDashes) return p;
2162
+ const textStart = Math.max(padded.textStartOf(voiced[v].textWidth), p.floor);
2163
+ return {
2164
+ ...p,
2165
+ textStart,
2166
+ contentStart: padded.contentStart,
2167
+ pads: padDashes,
2168
+ tight: p.tight && textStart < p.minStart
2169
+ };
2170
+ });
2171
+ }
2172
+ };
2173
+ settle();
2174
+ if (line.notesParts.length > 0 && (measure(notesSoFar + junctionPrefix + "-".repeat(padDashes) + item.notes, notesFont) > maxWidthPx || voiced.some((s, v) => {
2175
+ return Math.max(placements[v].textStart, s.t.cursor + s.pendingTotal) + s.textWidth + (s.own.wordEnd ? 0 : hyphenOf(s.own.hyphen).width) > maxWidthPx;
2176
+ }))) {
2479
2177
  startLine();
2480
2178
  junctionPrefix = "";
2481
2179
  parts = splitNoteMarkers(item.notes);
2482
2180
  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
- });
2181
+ settle();
2499
2182
  }
2500
2183
  }
2501
2184
  const notesStr = junctionPrefix + "-".repeat(padDashes) + item.notes;
@@ -2522,12 +2205,13 @@ async function layoutScore(source, options = {}) {
2522
2205
  textStartPx: textStart
2523
2206
  });
2524
2207
  else if (pendingTotal === 0 && p.tight) {} else if (pendingTotal === 0) {
2525
- const pad = Math.max(0, (spacerWidth - dashTextWidth) / 2);
2208
+ const pad = Math.max(0, (spacerWidth - t.hyphen.width) / 2);
2526
2209
  text.segments.push({
2527
2210
  kind: "connector",
2528
2211
  pad,
2529
2212
  gapWidth: spacerWidth,
2530
- dashWidth: dashTextWidth,
2213
+ dashWidth: t.hyphen.width,
2214
+ ...t.hyphen.parts ? { parts: t.hyphen.parts } : {},
2531
2215
  dashStartPx: t.cursor + pad,
2532
2216
  nextAnchorPx: textStart
2533
2217
  });
@@ -2573,6 +2257,8 @@ async function layoutScore(source, options = {}) {
2573
2257
  t.cursor = textStart + textWidth + spaceWidth;
2574
2258
  text.lastWordEnd = s.own.wordEnd;
2575
2259
  t.prevWordEnd = s.own.wordEnd;
2260
+ t.hyphen = hyphenOf(s.own.hyphen);
2261
+ text.hyphen = t.hyphen;
2576
2262
  });
2577
2263
  for (const s of sung) if (!voiced.includes(s)) keepWordState(s, fresh);
2578
2264
  notesSoFar += notesStr;
@@ -2586,6 +2272,7 @@ async function layoutScore(source, options = {}) {
2586
2272
  idx++;
2587
2273
  }
2588
2274
  flushPending(true);
2275
+ while (keepStack.length > 0) closeKeepRun();
2589
2276
  tracks.forEach((t, u) => {
2590
2277
  line.texts[u].textCursor = t.cursor;
2591
2278
  });
@@ -2594,11 +2281,13 @@ async function layoutScore(source, options = {}) {
2594
2281
  if (li === lines.length - 1) return;
2595
2282
  for (const text of l.texts) {
2596
2283
  if (text.lastWordEnd !== false) continue;
2597
- const pad = l.notesEnd > text.textCursor ? Math.max(0, (l.notesEnd - text.textCursor - dashTextWidth) / 2) : 0;
2284
+ const hyphen = text.hyphen ?? { width: dashTextWidth };
2285
+ const pad = l.notesEnd > text.textCursor ? Math.max(0, (l.notesEnd - text.textCursor - hyphen.width) / 2) : 0;
2598
2286
  text.segments.push({
2599
2287
  kind: "line-end-dash",
2600
2288
  pad,
2601
- dashWidth: dashTextWidth,
2289
+ dashWidth: hyphen.width,
2290
+ ...hyphen.parts ? { parts: hyphen.parts } : {},
2602
2291
  dashStartPx: text.textCursor + pad,
2603
2292
  trailEndPx: l.notesEnd,
2604
2293
  textEndPx: text.textCursor
@@ -2609,33 +2298,52 @@ async function layoutScore(source, options = {}) {
2609
2298
  l.textCursor = l.texts[0].textCursor;
2610
2299
  l.lastWordEnd = l.texts[0].lastWordEnd;
2611
2300
  }
2612
- const starTarget = maxWidthPx + (styleSet.padding ?? 0);
2301
+ const padding = styleSet.padding ?? 0;
2302
+ const starTarget = maxWidthPx + padding;
2613
2303
  const starWidth = measure("*", notesFont);
2304
+ const fill = staffFill === "all" && maxWidthPx === Infinity ? "longest" : staffFill;
2305
+ const fillsLast = fill === "all" || fill === "longest";
2306
+ const longest = Math.max(...lines.map((l) => Math.max(l.notesEnd, ...l.texts.map((t) => t.textCursor))));
2307
+ const fillTarget = fill === "none" || maxWidthPx === Infinity && !fillsLast ? null : fill === "longest" && maxWidthPx - longest > staffFillSnapPx ? longest : maxWidthPx;
2614
2308
  lines.forEach((l, li) => {
2615
- if (li === lines.length - 1) return;
2616
- if (maxWidthPx === Infinity) {
2617
- l.breakMarkerLeftPx = styleSet.padding ?? 0;
2309
+ const last = li === lines.length - 1;
2310
+ l.staffEnd = l.notesEnd;
2311
+ if (last && (!fillsLast || l.notesParts.length === 0)) return;
2312
+ if (fillTarget === null) {
2313
+ l.breakMarkerLeftPx = padding;
2618
2314
  return;
2619
2315
  }
2316
+ const staffEdge = fillTarget + padding;
2620
2317
  let lineEnd = measure(l.clefPrefix + l.notesParts.join(""), notesFont);
2621
- while (lineEnd + dashNotesWidth <= starTarget - starWidth && lineEnd + dashNotesWidth < maxWidthPx) {
2318
+ while (last ? lineEnd + dashNotesWidth <= staffEdge : lineEnd + dashNotesWidth <= staffEdge - starWidth && lineEnd + dashNotesWidth < fillTarget) {
2622
2319
  l.notesParts.push("-");
2623
2320
  lineEnd += dashNotesWidth;
2624
2321
  }
2625
- l.breakMarkerLeftPx = starTarget - lineEnd - starWidth;
2322
+ if (last) {
2323
+ const third = measure("¨", notesFont);
2324
+ while (lineEnd + third <= staffEdge) {
2325
+ l.notesParts.push("¨");
2326
+ lineEnd += third;
2327
+ }
2328
+ }
2329
+ l.staffEnd = lineEnd;
2330
+ if (!last) l.breakMarkerLeftPx = staffEdge - lineEnd - starWidth;
2626
2331
  });
2627
2332
  return {
2628
- lines,
2629
- clefPrefix: lines[0].clefPrefix,
2630
- styleSet,
2631
- styleName,
2632
- textPx,
2633
- notesPx,
2634
- bold,
2635
- maxWidthPx,
2636
- starTarget,
2637
- starWidth
2333
+ result: {
2334
+ lines,
2335
+ clefPrefix: lines[0].clefPrefix,
2336
+ styleSet,
2337
+ styleName,
2338
+ textPx,
2339
+ notesPx,
2340
+ bold,
2341
+ maxWidthPx,
2342
+ starTarget,
2343
+ starWidth
2344
+ },
2345
+ splitRuns
2638
2346
  };
2639
2347
  }
2640
2348
  //#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 };
2349
+ export { CLEF_GLYPHS as A, toConnectDown as B, scriptSyllables as C, resolveSpans as D, unescape as E, isModifierGlyph as F, variantOf as G, toSmallHead as H, modifyDown as I, modifyNatural as L, baseOf as M, gClefPitchOf as N, SCORE_MARKERS as O, isClefGlyph as P, modifyUp as R, runProperties as S, syllableText as T, toSmallPoint as U, toLonga as V, toVirga as W, GuidoScript as _, DEFAULT_STYLE_SET as a, isC4ClefGroup as b, defineStyleSet as c, measurementFont as d, resolveMarks as f, unknownMarks as g, styleSetOf as h, measure as i, STAFF as j, splitNoteMarkers as k, inlineStylesFor as l, resolveTextRuns as m, SPECIAL_NOTES as n, SMALL_CAP_SCALE as o, resolveSyllableParts as p, layoutScore as r, STYLE_SETS as s, NOTE_MODIFIERS as t, kindOf as u, chantText as v, statementSource as w, isStatementGroup as x, escape as y, toCephalicus as z };