guidex 0.3.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +53 -3
  2. package/dist/lib/app/EditorContext.d.ts +6 -1
  3. package/dist/lib/app/ExactTransposeControls.d.ts +1 -0
  4. package/dist/lib/app/StanzaControls.d.ts +1 -0
  5. package/dist/lib/app/TransposeSettings.d.ts +1 -0
  6. package/dist/lib/app/editorState.d.ts +78 -6
  7. package/dist/lib/app/shareLink.d.ts +22 -0
  8. package/dist/lib/chantLayout-B0xiaMo9.js +2641 -0
  9. package/dist/lib/chantLayout.d.ts +41 -8
  10. package/dist/lib/composeScript.d.ts +71 -0
  11. package/dist/lib/editorStorage.d.ts +6 -0
  12. package/dist/lib/embed/core.d.ts +28 -2
  13. package/dist/lib/embed/index.js +1 -1
  14. package/dist/lib/embed/manual.d.ts +12 -3
  15. package/dist/lib/embed/manual.js +324 -276
  16. package/dist/lib/exactTranspose.d.ts +54 -0
  17. package/dist/lib/glyphFamilies.d.ts +22 -0
  18. package/dist/lib/guidoRender.d.ts +5 -3
  19. package/dist/lib/guidoScript.d.ts +92 -10
  20. package/dist/lib/guidoScriptTransforms.d.ts +19 -7
  21. package/dist/lib/noteGroups.d.ts +22 -0
  22. package/dist/lib/react/GuidexScore.d.ts +19 -1
  23. package/dist/lib/react/index.d.ts +2 -1
  24. package/dist/lib/react/index.js +23 -3
  25. package/dist/lib/{scoreImage-oVBasBX5.js → scoreImage-DSEupCru.js} +102 -51
  26. package/dist/lib/stanzas.d.ts +135 -0
  27. package/dist/lib/word/index.js +1 -1
  28. package/dist/lib/{wordChecker-C3nJrk_j.js → wordChecker-EQx8frRp.js} +97 -45
  29. package/dist/lib/wordClipboard.d.ts +3 -3
  30. package/dist/lib/wordExport.d.ts +9 -5
  31. package/dist-embed/guidex-embed.min.js +1 -1
  32. package/package.json +1 -1
  33. package/dist/lib/chantLayout-GAfg2iKS.js +0 -1042
@@ -0,0 +1,2641 @@
1
+ //#region src/glyphFamilies.ts
2
+ /** Base pitch glyph → its variants. Keys are the note glyphs of the
3
+ * first column of `PITCH_ROWS`' notation table. */
4
+ var FAMILIES = {
5
+ ð: {
6
+ smallHead: "~",
7
+ modifyUp: "È",
8
+ cephalicus: "®"
9
+ },
10
+ ñ: {
11
+ virga: "^",
12
+ smallHead: "¯",
13
+ modifyUp: "Ê",
14
+ modifyDown: "÷",
15
+ cephalicus: "−",
16
+ connectOneDown: "Ý"
17
+ },
18
+ "0": {
19
+ virga: "]",
20
+ smallHead: "‚",
21
+ modifyUp: "Ë",
22
+ modifyDown: "ø",
23
+ modifyNatural: "“",
24
+ cephalicus: "§",
25
+ connectOneDown: "Þ"
26
+ },
27
+ "1": {
28
+ virga: "q",
29
+ longa: "Ÿ",
30
+ smallHead: "ƒ",
31
+ modifyUp: "Ì",
32
+ modifyDown: "a",
33
+ modifyNatural: "”",
34
+ cephalicus: "ÿ",
35
+ connectOneDown: "Q",
36
+ connectTwoDown: "×",
37
+ connectThreeDown: "Ø",
38
+ smallPoint: "í"
39
+ },
40
+ "2": {
41
+ virga: "w",
42
+ longa: "¡",
43
+ smallHead: "„",
44
+ modifyUp: "Î",
45
+ modifyDown: "A",
46
+ modifyNatural: "•",
47
+ cephalicus: "\"",
48
+ connectOneDown: "W",
49
+ connectTwoDown: "s",
50
+ connectThreeDown: "Ù",
51
+ connectFourDown: "½"
52
+ },
53
+ "3": {
54
+ virga: "e",
55
+ longa: "¢",
56
+ smallHead: "…",
57
+ modifyUp: "Ï",
58
+ modifyDown: "S",
59
+ modifyNatural: "–",
60
+ cephalicus: "+",
61
+ connectOneDown: "E",
62
+ connectTwoDown: "d",
63
+ connectThreeDown: "D",
64
+ connectFourDown: "°",
65
+ smallPoint: "y"
66
+ },
67
+ "4": {
68
+ virga: "r",
69
+ longa: "£",
70
+ smallHead: "†",
71
+ modifyUp: "Ð",
72
+ modifyDown: "Í",
73
+ modifyNatural: "—",
74
+ cephalicus: "!",
75
+ connectOneDown: "R",
76
+ connectTwoDown: "f",
77
+ connectThreeDown: "F",
78
+ connectFourDown: "±"
79
+ },
80
+ "5": {
81
+ virga: "t",
82
+ longa: "[",
83
+ smallHead: "‡",
84
+ modifyUp: "Ñ",
85
+ modifyDown: "Y",
86
+ modifyNatural: "˜",
87
+ cephalicus: "%",
88
+ connectOneDown: "T",
89
+ connectTwoDown: "g",
90
+ connectThreeDown: "G",
91
+ connectFourDown: "²",
92
+ smallPoint: "x"
93
+ },
94
+ "6": {
95
+ virga: "z",
96
+ longa: "¥",
97
+ smallHead: "ˆ",
98
+ modifyUp: "Ò",
99
+ modifyDown: "X",
100
+ modifyNatural: "™",
101
+ cephalicus: "/",
102
+ connectOneDown: "Z",
103
+ connectTwoDown: "h",
104
+ connectThreeDown: "H",
105
+ connectFourDown: "³"
106
+ },
107
+ "7": {
108
+ virga: "u",
109
+ longa: "¦",
110
+ smallHead: "‰",
111
+ modifyUp: "þ",
112
+ modifyDown: "C",
113
+ modifyNatural: "š",
114
+ cephalicus: "=",
115
+ connectOneDown: "U",
116
+ connectTwoDown: "j",
117
+ connectThreeDown: "J",
118
+ connectFourDown: "´",
119
+ smallPoint: "c"
120
+ },
121
+ "8": {
122
+ virga: "i",
123
+ longa: "©",
124
+ smallHead: "Š",
125
+ modifyUp: "ß",
126
+ modifyDown: "V",
127
+ modifyNatural: "›",
128
+ cephalicus: "(",
129
+ connectOneDown: "I",
130
+ connectTwoDown: "k",
131
+ connectThreeDown: "K",
132
+ connectFourDown: "μ"
133
+ },
134
+ "9": {
135
+ virga: "o",
136
+ longa: "ª",
137
+ smallHead: "‹",
138
+ modifyUp: "ò",
139
+ modifyDown: "B",
140
+ modifyNatural: "œ",
141
+ cephalicus: ")",
142
+ connectOneDown: "O",
143
+ connectTwoDown: "l",
144
+ connectThreeDown: "L",
145
+ connectFourDown: "·",
146
+ smallPoint: "v"
147
+ },
148
+ ö: {
149
+ virga: "p",
150
+ longa: "«",
151
+ smallHead: "Œ",
152
+ modifyUp: "ô",
153
+ modifyDown: "N",
154
+ modifyNatural: "º",
155
+ cephalicus: "Ö",
156
+ connectOneDown: "P",
157
+ connectTwoDown: "é",
158
+ connectThreeDown: "É",
159
+ connectFourDown: "¾"
160
+ },
161
+ ü: {
162
+ virga: "õ",
163
+ longa: "¬",
164
+ smallHead: "‘",
165
+ modifyUp: "ù",
166
+ modifyDown: "$",
167
+ modifyNatural: "»",
168
+ cephalicus: "Ü",
169
+ connectOneDown: "Õ",
170
+ connectTwoDown: "á",
171
+ connectThreeDown: "Á",
172
+ connectFourDown: "¸",
173
+ smallPoint: "b"
174
+ },
175
+ ó: {
176
+ virga: "ú",
177
+ smallHead: "’",
178
+ modifyUp: "ý",
179
+ modifyDown: "m",
180
+ cephalicus: "Ó",
181
+ connectOneDown: "Ú",
182
+ connectTwoDown: "û",
183
+ connectThreeDown: "Û",
184
+ connectFourDown: "¹"
185
+ }
186
+ };
187
+ /** Base pitch glyph → its pitch name in the standard g-clef (the
188
+ * "pitch in standard g-clef" column of the notation table). The last
189
+ * row of that table has no base glyph, so it has no entry here. */
190
+ var G_CLEF_PITCHES = {
191
+ ð: "a",
192
+ ñ: "b",
193
+ "0": "c'",
194
+ "1": "d'",
195
+ "2": "e'",
196
+ "3": "f'",
197
+ "4": "g'",
198
+ "5": "a'",
199
+ "6": "b'",
200
+ "7": "c''",
201
+ "8": "d''",
202
+ "9": "e''",
203
+ ö: "f''",
204
+ ü: "g''",
205
+ ó: "a''"
206
+ };
207
+ /** The standard g-clef pitch name of a base glyph, or of the base of a
208
+ * variant glyph; undefined when the glyph has no pitch. */
209
+ function gClefPitchOf(ch) {
210
+ return G_CLEF_PITCHES[ch] ?? G_CLEF_PITCHES[baseOf(ch)?.base ?? ""];
211
+ }
212
+ /** Reverse lookup: variant glyph → its base glyph and role. Built once;
213
+ * the table has no glyph in two places, so each variant maps to one base. */
214
+ var BASES = /* @__PURE__ */ new Map();
215
+ for (const [base, family] of Object.entries(FAMILIES)) for (const role of Object.keys(family)) BASES.set(family[role], {
216
+ base,
217
+ role
218
+ });
219
+ /** The variant of `ch` in `role`, or undefined when `ch` has none. */
220
+ function variantOf(ch, role) {
221
+ return FAMILIES[ch]?.[role];
222
+ }
223
+ /** The virga (the stemmed form) of a pitch glyph. */
224
+ function toVirga(ch) {
225
+ return variantOf(ch, "virga");
226
+ }
227
+ /** The longa (the double-length form) of a pitch glyph. */
228
+ function toLonga(ch) {
229
+ return variantOf(ch, "longa");
230
+ }
231
+ /** The small head of a pitch glyph. */
232
+ function toSmallHead(ch) {
233
+ return variantOf(ch, "smallHead");
234
+ }
235
+ /** The cephalicus of a pitch glyph. */
236
+ function toCephalicus(ch) {
237
+ return variantOf(ch, "cephalicus");
238
+ }
239
+ /** The connecting form that joins a pitch to the note `steps` rows below
240
+ * it (1 to 4). */
241
+ function toConnectDown(ch, steps) {
242
+ const role = [
243
+ "connectOneDown",
244
+ "connectTwoDown",
245
+ "connectThreeDown",
246
+ "connectFourDown"
247
+ ][steps - 1];
248
+ return variantOf(ch, role);
249
+ }
250
+ /** The small point (the dot that lengthens a note by half) of a pitch glyph. */
251
+ function toSmallPoint(ch) {
252
+ return variantOf(ch, "smallPoint");
253
+ }
254
+ /** The sharp (raised) form of a pitch glyph. */
255
+ function modifyUp(ch) {
256
+ return variantOf(ch, "modifyUp");
257
+ }
258
+ /** The flat (lowered) form of a pitch glyph. */
259
+ function modifyDown(ch) {
260
+ return variantOf(ch, "modifyDown");
261
+ }
262
+ /** The natural sign for a pitch glyph. */
263
+ function modifyNatural(ch) {
264
+ return variantOf(ch, "modifyNatural");
265
+ }
266
+ /** Reverse lookup: the base glyph and role of a variant glyph, or
267
+ * undefined when `ch` is not a variant. */
268
+ function baseOf(ch) {
269
+ const entry = BASES.get(ch);
270
+ return entry ? { ...entry } : void 0;
271
+ }
272
+ /** The modifier roles: the accidental signs a key is written with. */
273
+ var MODIFIER_ROLES = [
274
+ "modifyUp",
275
+ "modifyDown",
276
+ "modifyNatural"
277
+ ];
278
+ /** Whether `ch` is a modifier glyph (a sharp, flat or natural sign). */
279
+ function isModifierGlyph(ch) {
280
+ const role = BASES.get(ch)?.role;
281
+ return role !== void 0 && MODIFIER_ROLES.includes(role);
282
+ }
283
+ /** The clef glyphs (issue #49) and the staff line each one sits on,
284
+ * counted from the bottom. The g-clef has two keybindings. */
285
+ var CLEF_GLYPHS = {
286
+ ">": {
287
+ clef: "c",
288
+ line: 1
289
+ },
290
+ "#": {
291
+ clef: "c",
292
+ line: 2
293
+ },
294
+ "&": {
295
+ clef: "c",
296
+ line: 3
297
+ },
298
+ "@": {
299
+ clef: "c",
300
+ line: 4
301
+ },
302
+ "{": {
303
+ clef: "f",
304
+ line: 3
305
+ },
306
+ "}": {
307
+ clef: "f",
308
+ line: 4
309
+ },
310
+ M: {
311
+ clef: "g",
312
+ line: 2
313
+ },
314
+ "<": {
315
+ clef: "g",
316
+ line: 2
317
+ }
318
+ };
319
+ /** Whether `ch` is a clef glyph. */
320
+ function isClefGlyph(ch) {
321
+ return Object.hasOwn(CLEF_GLYPHS, ch);
322
+ }
323
+ /** The base pitch glyphs from low to high, one per staff position
324
+ * (spelled out: `Object.keys` would list the digit keys first). The
325
+ * index is the staff position the exact transposition counts with. */
326
+ var STAFF = [..."ðñ0123456789öüó"];
327
+ var LETTERS$1 = "abcdefg";
328
+ /** The pitch letter (`a`…`g`, octave dropped) of a pitch glyph — a base
329
+ * glyph or any of its variants — under `clef` (a clef glyph; default the
330
+ * standard g-clef). Undefined when the glyph has no pitch or the clef
331
+ * glyph is unknown. */
332
+ function pitchLetterOf(ch, clef = "M") {
333
+ const position = STAFF.indexOf(STAFF.includes(ch) ? ch : baseOf(ch)?.base ?? "");
334
+ const entry = CLEF_GLYPHS[clef];
335
+ if (position < 0 || !entry) return void 0;
336
+ 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];
339
+ }
340
+ //#endregion
341
+ //#region src/guidoScript.ts
342
+ /**
343
+ * A Guido script: the compact chant notation where pitches, neume shapes,
344
+ * and rhythm are packed into short character sequences, e.g.
345
+ *
346
+ * (MX)Ki(3)rály(3)ként(5) tró(7i)nol(7-:) *() az(7i) Úr(5-/) mind(5)ö(4t)rök(3)ké.(3-.)
347
+ *
348
+ * The first parenthesized group, when present, is the starting clef and
349
+ * note modifiers. After that the source alternates syllable-first:
350
+ *
351
+ * (clef) syllable(notes) syllable(notes) ...
352
+ *
353
+ * Word boundaries are carried by whitespace in the source: a syllable
354
+ * after which the source has a space ends a word.
355
+ *
356
+ * A note group with no text in front of it is held by the syllable
357
+ * before it (issue #83): `mé(3)(tT4R3E2)` sings `mé` on both groups. The
358
+ * held group stays a token of its own (`text: ''`, `held: true`), so
359
+ * every group is one slot and formatting still resolves on each
360
+ * syllable's own text. A syllable whose whole text is `~` is an empty
361
+ * slot (`empty: true`): notes, but no syllable — and so is a text-less
362
+ * group at the very start of the script.
363
+ *
364
+ * The parentheses and backslash are control characters, so literal ones
365
+ * in the syllable text are typed as backslash escapes: `\(`, `\)` and
366
+ * `\\` stand for `(`, `)` and `\`.
367
+ *
368
+ * Control statements are groups whose content is an `@`-keyword with
369
+ * optional arguments after one space: `(@break)` ends the current line
370
+ * pair at its position, `(@clef MX)` changes the clef (and key) inline,
371
+ * `(@key X)` replaces the key and `(@key)` clears it. Statements are
372
+ * positional — the text run before one must be whitespace-only — and
373
+ * they are invisible to the sung-text accessors.
374
+ *
375
+ * `(@stanza …)` statements (issue #69) stand at the very end of the
376
+ * script, one per further stanza (2, 3, …) in order. Their text is
377
+ * syllabified stanza text (see `parseStanza` in stanzas.ts), kept raw —
378
+ * escapes included — and listed by `stanzas`; they are not tokens, so
379
+ * nothing that walks the tokens (the layout, the sung-text accessors)
380
+ * ever sees them.
381
+ *
382
+ * `@` is also the c4 clef glyph: an opening group of `@` and nothing but
383
+ * modifier glyphs (`(@)`, `(@X)`) is the opening clef, not a statement.
384
+ */
385
+ /** Whether a group's content is a control statement (`@`-keyword,
386
+ * trimmed). Shared with the transforms, which must leave statement
387
+ * groups alone — their keyword characters are pitch glyphs otherwise.
388
+ * A c4 clef group (`@` + modifier glyphs) counts too: the opening one is
389
+ * told apart by `isC4ClefGroup`, and mid-script it is an error. */
390
+ function isStatementGroup(content) {
391
+ return content.trim().startsWith("@");
392
+ }
393
+ /** Whether a group's content has the shape of a c4 clef group: `@`
394
+ * followed by nothing but modifier glyphs. Statement keywords never
395
+ * consist solely of modifier glyphs, so the two cannot collide. */
396
+ function isC4ClefGroup(content) {
397
+ const [at, ...key] = content;
398
+ return at === "@" && key.every(isModifierGlyph);
399
+ }
400
+ /** Whether the leading group is the opening clef: anything but a
401
+ * statement, and the c4 clef despite its `@`. */
402
+ function isOpeningClef(content) {
403
+ return !isStatementGroup(content) || isC4ClefGroup(content);
404
+ }
405
+ /** Parses a key argument: modifier glyphs only. */
406
+ function parseKey(glyphs, statement) {
407
+ for (const ch of glyphs) if (!isModifierGlyph(ch)) throw new Error(`"${ch}" is not a key modifier glyph in "${statement}"`);
408
+ return glyphs;
409
+ }
410
+ /** Parses one statement group's content into its token (without
411
+ * `spaceBefore`). Throws on an unknown keyword or a bad argument. */
412
+ function parseStatement(content) {
413
+ const statement = content.trim();
414
+ if (isC4ClefGroup(statement)) throw new Error(`a clef group is only allowed at the start; write "(@clef ${statement})" to change the clef`);
415
+ const [, keyword, args = ""] = statement.match(/^@(\S*)(?: (.*))?$/) ?? [];
416
+ switch (keyword) {
417
+ case "break":
418
+ if (args !== "") throw new Error(`"@break" takes no argument: "${statement}"`);
419
+ return { kind: "break" };
420
+ case "clef": {
421
+ const [clef, ...key] = args;
422
+ if (clef === void 0) throw new Error("\"@clef\" needs a clef group argument, e.g. \"(@clef MX)\"");
423
+ if (!isClefGlyph(clef)) throw new Error(`"${clef}" is not a clef glyph in "${statement}"`);
424
+ return {
425
+ kind: "clef",
426
+ clef,
427
+ key: parseKey(key.join(""), statement)
428
+ };
429
+ }
430
+ case "key": return {
431
+ kind: "key",
432
+ key: parseKey(args, statement)
433
+ };
434
+ default: throw new Error(`Unknown statement "${statement}"`);
435
+ }
436
+ }
437
+ /** A statement token written back as its group. */
438
+ function statementSource(tok) {
439
+ switch (tok.kind) {
440
+ case "break": return "(@break)";
441
+ case "clef": return `(@clef ${tok.clef}${tok.key})`;
442
+ case "key": return tok.key === "" ? "(@key)" : `(@key ${tok.key})`;
443
+ }
444
+ }
445
+ /** The stanza text of a `(@stanza …)` statement's trimmed content, or
446
+ * undefined when the statement is something else. */
447
+ function stanzaStatementText(statement) {
448
+ const match = statement.match(/^@stanza(?:\s+([\s\S]*))?$/);
449
+ return match ? match[1] ?? "" : void 0;
450
+ }
451
+ var GuidoScript = class {
452
+ source;
453
+ constructor(source, options = {}) {
454
+ this.source = (options.transforms ?? []).reduce((script, transform) => transform.apply(script), source);
455
+ }
456
+ /** The starting clef and note modifiers, or undefined when absent.
457
+ * A leading statement group is not a clef. */
458
+ get clef() {
459
+ const match = this.normalized.match(/^\s*\(([^)]*)\)/);
460
+ if (!match || !isOpeningClef(match[1])) return void 0;
461
+ return match[1];
462
+ }
463
+ /** The script's tokens in source order: syllables interleaved with
464
+ * control statements. Throws on a malformed statement (syllable text
465
+ * attached to one, or an unknown `@` keyword). */
466
+ get tokens() {
467
+ return this.parse().tokens;
468
+ }
469
+ /** The raw text of the `(@stanza …)` statements at the end of the
470
+ * script — stanzas 2, 3, … in order, escapes kept (the stanza text
471
+ * grammar folds them). Throws like `tokens` on a malformed script,
472
+ * and when anything but another stanza follows a stanza statement. */
473
+ get stanzas() {
474
+ return this.parse().stanzas;
475
+ }
476
+ /** Where each token stands in the source, parallel to `tokens`:
477
+ * offsets of its text (past leading whitespace), of its group's
478
+ * content and just past its group's `)`. The walker
479
+ * (`scriptSyllables`) reads them. */
480
+ get tokenSpans() {
481
+ return this.parse().spans;
482
+ }
483
+ parse() {
484
+ const script = this.normalized;
485
+ const head = script.match(/^\s*\(([^)]*)\)/);
486
+ const skipped = head && isOpeningClef(head[1]) ? head[0].length : 0;
487
+ const matches = [...script.slice(skipped).matchAll(/((?:[^()\\]|\\.)*)\(((?:[^)\\]|\\.)*)\)/g)];
488
+ let prev;
489
+ const stanzas = [];
490
+ const tokens = [];
491
+ const spans = [];
492
+ for (const match of matches) {
493
+ const [, text, notes] = match;
494
+ const at = skipped + match.index;
495
+ const notesStart = at + text.length + 1;
496
+ const span = {
497
+ start: at + (text.length - text.trimStart().length),
498
+ notesStart,
499
+ notesEnd: notesStart + notes.length,
500
+ end: notesStart + notes.length + 1
501
+ };
502
+ const stanza = isStatementGroup(notes) ? stanzaStatementText(notes.trim()) : void 0;
503
+ if (stanza !== void 0) {
504
+ if (text.trim() !== "") throw new Error(`statement must not carry syllable text: "${unescape(text.trim())}"`);
505
+ stanzas.push(stanza);
506
+ continue;
507
+ }
508
+ if (stanzas.length > 0) {
509
+ if (text.trim() === "" && notes === "") continue;
510
+ throw new Error("\"(@stanza …)\" statements must stand at the end of the script");
511
+ }
512
+ if (isStatementGroup(notes)) {
513
+ const statement = parseStatement(notes);
514
+ if (text.trim() !== "") throw new Error(`statement must not carry syllable text: "${unescape(text.trim())}"`);
515
+ tokens.push({
516
+ ...statement,
517
+ spaceBefore: /^\s/.test(text)
518
+ });
519
+ spans.push(span);
520
+ continue;
521
+ }
522
+ const raw = text.trim();
523
+ const tok = {
524
+ kind: "syllable",
525
+ text: raw === "~" ? "" : unescape(raw),
526
+ notes: unescape(notes),
527
+ spaceBefore: /^\s/.test(text)
528
+ };
529
+ if (raw === "~" || raw === "" && prev === void 0 && tok.notes !== "") tok.empty = true;
530
+ else if (raw === "" && tok.notes !== "") {
531
+ if (prev.notes === "") throw new Error(`the group "(${tok.notes})" has no syllable to hold it: "${prev.text}" has no notes; write "~(${tok.notes})" for an empty slot`);
532
+ tok.held = true;
533
+ }
534
+ prev = tok;
535
+ tokens.push(tok);
536
+ spans.push(span);
537
+ }
538
+ let holder;
539
+ for (const [i, t] of tokens.entries()) {
540
+ if (t.kind !== "syllable") continue;
541
+ if (t.held) {
542
+ t.wordEnd = holder.wordEnd;
543
+ continue;
544
+ }
545
+ t.wordEnd = true;
546
+ let space = false;
547
+ for (let j = i + 1; j < tokens.length; j++) {
548
+ const tok = tokens[j];
549
+ if (tok.spaceBefore) space = true;
550
+ if (tok.kind === "syllable" && !tok.held && !tok.empty) {
551
+ t.wordEnd = space;
552
+ break;
553
+ }
554
+ }
555
+ holder = t;
556
+ }
557
+ return {
558
+ tokens,
559
+ stanzas,
560
+ spans
561
+ };
562
+ }
563
+ /** The script broken into syllables, each with its sung text and
564
+ * notes — the syllable tokens, statements filtered out. */
565
+ get syllables() {
566
+ return this.tokens.filter((t) => t.kind === "syllable").map(({ text, notes, wordEnd, held, empty }) => ({
567
+ text,
568
+ notes,
569
+ wordEnd,
570
+ ...held ? { held } : {},
571
+ ...empty ? { empty } : {}
572
+ }));
573
+ }
574
+ /**
575
+ * The source with the typing conveniences folded in, so the parser
576
+ * itself only ever sees complete scripts:
577
+ *
578
+ * - an unclosed parenthesis is closed at the end, so the notes typed
579
+ * so far already preview on the score;
580
+ * - a trailing syllable with no note group gets an empty one, so it
581
+ * renders like a `*()` syllable (text without notes width).
582
+ */
583
+ get normalized() {
584
+ let script = this.source;
585
+ if ((script.match(/(^|[^\\])\(/g) ?? []).length > (script.match(/(^|[^\\])\)/g) ?? []).length) script += ")";
586
+ if (!/(^|[^\\])\)$/.test(script)) script += "()";
587
+ return script;
588
+ }
589
+ /** The syllables grouped into the words of the text. Held groups and
590
+ * empty slots sing no syllable of their own, so they are left out. */
591
+ get words() {
592
+ const words = [];
593
+ let word;
594
+ for (const syl of this.syllables) {
595
+ if (syl.held || syl.empty) continue;
596
+ word ??= {
597
+ text: "",
598
+ syllables: []
599
+ };
600
+ word.syllables.push({
601
+ text: syl.text,
602
+ notes: syl.notes
603
+ });
604
+ word.text = word.syllables.map((s) => s.text).join("");
605
+ if (syl.wordEnd) {
606
+ words.push(word);
607
+ word = void 0;
608
+ }
609
+ }
610
+ return words;
611
+ }
612
+ /** The script rebuilt from the parsed pieces — a round-trip of the
613
+ * source, statements and stanzas included. */
614
+ toString() {
615
+ const parts = this.tokens.map((tok, i) => {
616
+ 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)}`;
618
+ });
619
+ const stanzas = this.stanzas.map((text) => `(@stanza ${text})`);
620
+ return `${this.clef !== void 0 ? `(${this.clef})` : ""}${parts.join("")}${stanzas.join("")}`;
621
+ }
622
+ };
623
+ /**
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`.
630
+ */
631
+ function scriptSyllables(script) {
632
+ const parsed = typeof script === "string" ? new GuidoScript(script) : script;
633
+ const tokens = parsed.tokens;
634
+ const spans = parsed.tokenSpans;
635
+ const out = [];
636
+ let prevWordEnd = true;
637
+ let holder;
638
+ for (const [i, tok] of tokens.entries()) {
639
+ if (tok.kind !== "syllable") continue;
640
+ if (tok.empty) {
641
+ holder = void 0;
642
+ continue;
643
+ }
644
+ if (tok.held) {
645
+ if (holder) {
646
+ holder.held.push(tok.notes);
647
+ holder.end = spans[i].end;
648
+ }
649
+ continue;
650
+ }
651
+ const span = spans[i];
652
+ holder = {
653
+ text: tok.text,
654
+ notes: tok.notes,
655
+ held: [],
656
+ wordStart: prevWordEnd,
657
+ wordEnd: tok.wordEnd,
658
+ start: span.start,
659
+ notesStart: span.notesStart,
660
+ notesEnd: span.notesEnd,
661
+ end: span.end,
662
+ token: i
663
+ };
664
+ out.push(holder);
665
+ prevWordEnd = tok.wordEnd;
666
+ }
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";
1042
+ }
1043
+ };
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];
1133
+ return {
1134
+ position: STAFF.indexOf("2") + 2 * (entry.line - 1),
1135
+ step
1136
+ };
1137
+ }
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
+ }
1297
+ continue;
1298
+ }
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);
1314
+ }
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
+ }
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
+ }
1535
+ }
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
+ };
1577
+ }
1578
+ //#endregion
1579
+ //#region src/guidoStyles.ts
1580
+ /**
1581
+ * Style sets for the renderer: named appearance rules (fonts, colors, and
1582
+ * the special syllable decorations) kept in one constant registry, so a
1583
+ * new style is a data entry here rather than a renderer fork.
1584
+ */
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
+ /** Text characters (* and †) rendered in Times New Roman. */
1592
+ var TIMES_MARKER_GLYPHS = {
1593
+ chars: MARKER_CHARS,
1594
+ fontFamily: "'Times New Roman', Times, serif"
1595
+ };
1596
+ /** How a `+` inside a Liturgy-font run is drawn: normal weight (the font
1597
+ * is bold-looking by design), sized to 70% and raised 20% of the text
1598
+ * size so it sits like a connecting sign between syllable parts. */
1599
+ var LITURGY_PLUS_STYLE = {
1600
+ weight: "400",
1601
+ scale: .7,
1602
+ raise: .2
1603
+ };
1604
+ var STYLE_SETS = {
1605
+ /** Book Antiqua text with red accents. */
1606
+ BNS: {
1607
+ textFontStack: "'Book Antiqua', Georgia, serif",
1608
+ notesFontStack: "'Guidohu'",
1609
+ markerGlyphs: TIMES_MARKER_GLYPHS,
1610
+ verifiedFonts: [
1611
+ {
1612
+ family: "'Book Antiqua'",
1613
+ weight: "400"
1614
+ },
1615
+ {
1616
+ family: "'Book Antiqua'",
1617
+ weight: "700"
1618
+ },
1619
+ {
1620
+ family: "'Guidohu'",
1621
+ weight: "400"
1622
+ },
1623
+ {
1624
+ family: "'Liturgy'",
1625
+ weight: "700"
1626
+ }
1627
+ ],
1628
+ decorations: {
1629
+ __: {
1630
+ fontFamily: "'Liturgy', serif",
1631
+ weight: "700",
1632
+ color: "var(--red)"
1633
+ },
1634
+ _: {
1635
+ uppercase: true,
1636
+ scale: .7,
1637
+ color: "var(--red)"
1638
+ },
1639
+ "*": {
1640
+ weight: "700",
1641
+ color: "var(--red)",
1642
+ 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)"
1652
+ },
1653
+ padding: 12,
1654
+ scriptTransforms: [SCRIPT_TRANSFORMS.startWithInitial]
1655
+ },
1656
+ /** Times New Roman text, strictly black and white. */
1657
+ Vesperale: {
1658
+ textFontStack: "'Times New Roman', Times, serif",
1659
+ notesFontStack: "'Guidohu'",
1660
+ verifiedFonts: [
1661
+ {
1662
+ family: "'Times New Roman', Times, serif",
1663
+ weight: "400"
1664
+ },
1665
+ {
1666
+ family: "'Times New Roman', Times, serif",
1667
+ weight: "700"
1668
+ },
1669
+ {
1670
+ family: "'Guidohu'",
1671
+ weight: "400"
1672
+ },
1673
+ {
1674
+ family: "'Liturgy'",
1675
+ weight: "700"
1676
+ }
1677
+ ],
1678
+ decorations: {
1679
+ __: {
1680
+ fontFamily: "'Liturgy', serif",
1681
+ weight: "700"
1682
+ },
1683
+ _: {
1684
+ scale: .8,
1685
+ italic: true
1686
+ },
1687
+ "*": {
1688
+ weight: "700",
1689
+ initial: true
1690
+ }
1691
+ },
1692
+ specialStarStyle: {
1693
+ fontFamily: TIMES_MARKER_GLYPHS.fontFamily,
1694
+ weight: "700",
1695
+ scale: 1,
1696
+ measureScale: .95,
1697
+ raise: .2
1698
+ },
1699
+ padding: 12,
1700
+ scriptTransforms: []
1701
+ }
1702
+ };
1703
+ 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 = "";
1756
+ }
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,
1783
+ weight: "700"
1784
+ };
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";
1791
+ };
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 = "";
1825
+ };
1826
+ for (const ch of chars) {
1827
+ const kind = runKind(ch);
1828
+ if (kind !== currentKind) pushRun();
1829
+ currentKind = kind;
1830
+ charRun += ch;
1831
+ }
1832
+ pushRun();
1833
+ }
1834
+ return parts;
1835
+ }
1836
+ /** The canvas font shorthand for measuring a run at the text size. */
1837
+ function measurementFont(style, textPx, fallbackStack) {
1838
+ return [
1839
+ style.italic ? "italic" : "normal",
1840
+ "normal",
1841
+ style.weight ?? "400",
1842
+ `${textPx * (style.measureScale ?? style.scale ?? 1)}px`,
1843
+ style.fontFamily ?? fallbackStack
1844
+ ].join(" ");
1845
+ }
1846
+ /** The inline CSS properties that draw a run, as dash-cased names for
1847
+ * CSSStyleDeclaration.setProperty. */
1848
+ function inlineStylesFor(style, textPx) {
1849
+ const styles = {};
1850
+ if (style.fontFamily) styles["font-family"] = style.fontFamily;
1851
+ if (style.weight) styles["font-weight"] = style.weight;
1852
+ if (style.italic) styles["font-style"] = "italic";
1853
+ if (style.scale !== void 0) styles["font-size"] = `${textPx * style.scale}px`;
1854
+ if (style.color) styles["color"] = style.color;
1855
+ if (style.raise) {
1856
+ styles["position"] = "relative";
1857
+ styles["top"] = `${-textPx * style.raise}px`;
1858
+ }
1859
+ return styles;
1860
+ }
1861
+ /** The font strings render() must load and verify for a style set. */
1862
+ function fontStringsToVerify(styleSet, textPx) {
1863
+ return styleSet.verifiedFonts.map((f) => `${f.weight} ${textPx}px ${f.family}`);
1864
+ }
1865
+ //#endregion
1866
+ //#region src/chantLayout.ts
1867
+ /**
1868
+ * Special reciting notes: when such a note stands alone in a note group it
1869
+ * marks recited text. The glyph shows at a run's first syllable (the
1870
+ * previous syllable has different notes) and at every line start; every
1871
+ * other recited syllable contributes only the staff-line segments filling
1872
+ * the space above its text, which flows tight after the previous text.
1873
+ */
1874
+ var SPECIAL_NOTES = "Ÿ¡¢£[¥¦©ª«¬";
1875
+ var SPECIAL_NOTE_CHARS = new Set(SPECIAL_NOTES.split(""));
1876
+ /** Whether a note group is a recitation group: one special reciting note,
1877
+ * optionally after one accidental sign (`¦`, `C¦`). */
1878
+ function isRecitationGroup(notes) {
1879
+ return notes.length === 1 && SPECIAL_NOTE_CHARS.has(notes) || notes.length === 2 && MODIFIER_CHARS.has(notes[0]) && SPECIAL_NOTE_CHARS.has(notes[1]);
1880
+ }
1881
+ /**
1882
+ * Modifier glyphs: flats, sharps, and naturals. They carry pitch (and
1883
+ * transpose with the melody) but modify the note that follows them, so
1884
+ * they hang in the junction whitespace: the syllable text anchors on the
1885
+ * note characters only, and a group starting with a modifier needs only
1886
+ * two junction dashes — the glyph itself provides the third dash's
1887
+ * separation.
1888
+ */
1889
+ var NOTE_MODIFIERS = "÷øaASÍYXCVBN$mÈÊËÌÎÏÐÑÒþßòôùý“”•–—˜™š›œº»";
1890
+ var MODIFIER_CHARS = new Set(NOTE_MODIFIERS.split(""));
1891
+ var NOTE_GROUP_SPLITTERS = ["-", "¨"];
1892
+ /** The key written by a run of modifier glyphs, under `clef` (a clef
1893
+ * glyph; the standard g-clef when unknown — matching pitches by staff
1894
+ * position does not depend on it). A statement's key throws when two
1895
+ * glyphs alter the same pitch; the opening group's stays lenient (the
1896
+ * later glyph wins), as it was never validated. */
1897
+ function keyMapOf(key, clef, strict = true) {
1898
+ const map = /* @__PURE__ */ new Map();
1899
+ for (const ch of key) {
1900
+ if (!isModifierGlyph(ch)) continue;
1901
+ const letter = pitchLetterOf(ch, clefOrDefault(clef));
1902
+ if (strict && map.has(letter)) throw new Error(`Key "${key}" alters the pitch ${letter} twice`);
1903
+ map.set(letter, baseOf(ch).role);
1904
+ }
1905
+ return map;
1906
+ }
1907
+ function clefOrDefault(clef) {
1908
+ return clef !== void 0 && isClefGlyph(clef) ? clef : "M";
1909
+ }
1910
+ /** The note glyphs a key alters: the base pitch glyphs and their shape
1911
+ * variants. Accidentals and small points are not notes, and the score
1912
+ * markers carry no pitch (several double as cephalicus glyphs). */
1913
+ function noteBaseOf(ch) {
1914
+ if (MARKER_CHARS$1.has(ch)) return void 0;
1915
+ if (variantOf(ch, "smallHead") !== void 0) return ch;
1916
+ const entry = baseOf(ch);
1917
+ if (!entry || entry.role === "smallPoint" || isModifierGlyph(ch)) return void 0;
1918
+ return entry.base;
1919
+ }
1920
+ /**
1921
+ * Writes a mid-line key change into a note group (issue #49): every note
1922
+ * whose pitch carries a different accidental under `active` than under
1923
+ * `staff` (the key the line's staff shows) calls for the accidental
1924
+ * sign — or the natural, when the pitch dropped out of the key. The
1925
+ * signs stand before the note group, not before their notes: they go at
1926
+ * the start of the group's notes (after its leading markers), one per
1927
+ * 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
1930
+ * once, before its first group. Returns the rewritten group and the
1931
+ * indices of the inserted signs. Throws when a needed sign does not
1932
+ * exist.
1933
+ */
1934
+ function applyKeyChange(notes, staff, active, clef, held = []) {
1935
+ 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;
1947
+ }
1948
+ }
1949
+ const at = splitNoteMarkers(notes).leading.length;
1950
+ return {
1951
+ notes: notes.slice(0, at) + signs + notes.slice(at),
1952
+ inserted: [...signs].map((_, k) => at + k)
1953
+ };
1954
+ }
1955
+ /** A group with the given inserted signs removed again. */
1956
+ function stripInserted(notes, inserted, from = 0) {
1957
+ return [...notes].filter((_, i) => !inserted.includes(i + from)).join("");
1958
+ }
1959
+ var ctx = null;
1960
+ /** Canvas text measurement, shared with the emitters (the Word export
1961
+ * measures the spacer character's natural advance for the unit width). */
1962
+ function measure(text, font) {
1963
+ if (!ctx) ctx = document.createElement("canvas").getContext("2d");
1964
+ ctx.font = font;
1965
+ return ctx.measureText(text).width;
1966
+ }
1967
+ /** Ink extents of the text relative to the glyph origin (negative left
1968
+ * means the ink starts left of the origin). */
1969
+ function ink(text, font) {
1970
+ if (!ctx) ctx = document.createElement("canvas").getContext("2d");
1971
+ ctx.font = font;
1972
+ const m = ctx.measureText(text);
1973
+ return {
1974
+ left: m.actualBoundingBoxLeft,
1975
+ right: m.actualBoundingBoxRight
1976
+ };
1977
+ }
1978
+ /** Each underlay's tokens, checked to share one melody. */
1979
+ function underlayTokens(source) {
1980
+ const list = typeof source === "string" || source instanceof GuidoScript ? [source] : source;
1981
+ if (list.length === 0) throw new Error("Nothing to lay out: no script given");
1982
+ const all = list.map((s) => (typeof s === "string" ? new GuidoScript(s) : s).tokens);
1983
+ const [first] = all;
1984
+ for (const [u, tokens] of all.entries()) if (!(tokens.length === first.length && tokens.every((tok, k) => {
1985
+ const ref = first[k];
1986
+ return tok.kind === ref.kind && (tok.kind !== "syllable" || tok.notes === ref.notes);
1987
+ }))) throw new Error(`Stacked underlay ${u + 1} does not share the first one's notes`);
1988
+ return all;
1989
+ }
1990
+ /** Whether an underlay's token sings no text of its own on its group: a
1991
+ * held group or an empty slot. */
1992
+ function silent(tok) {
1993
+ return !!(tok.held || tok.empty);
1994
+ }
1995
+ /**
1996
+ * Lays a GuidoScript score out: a notes line in the chant font, and a text
1997
+ * line where each syllable is centered below its notes. The dashes of the
1998
+ * chant font are pure whitespace: centering ignores them and happens under
1999
+ * the non-whitespace note characters only. When a syllable's text would
2000
+ * overlap the previous one, it starts right after it and the notes group is
2001
+ * padded with extra dashes until it covers the text.
2002
+ *
2003
+ * Stacked stanzas (issue #84): given several underlays of one melody, every
2004
+ * line pair gets one text line per underlay. Each text line keeps its own
2005
+ * cursor and runs the placement rules on its own (tight pairs, connectors,
2006
+ * hyphens, recitation flow); a group takes the most pad dashes any of them
2007
+ * asks for, so the notes spacing serves every text line, and a line breaks
2008
+ * wherever any of them has to. A group that every underlay holds joins its
2009
+ * run with the held join; one that some underlay sings takes the normal
2010
+ * junction.
2011
+ *
2012
+ * This is the shared layout pass behind every emitter: the DOM renderer
2013
+ * turns the returned lines into (notes div, text paragraph) pairs, and the
2014
+ * Word export turns them into fake-spaced Word HTML. Both consume the same
2015
+ * line breaks, notes parts, and syllable anchor positions.
2016
+ *
2017
+ * Appearance comes from a named style set (see guidoStyles.ts): the layout
2018
+ * options reference it by name, together with the bold option and the
2019
+ * text/notes sizes. Throws when the style set is unknown or one of its
2020
+ * fonts cannot be loaded.
2021
+ */
2022
+ async function layoutScore(source, options = {}) {
2023
+ const { style: styleName = "BNS", bold = false, textPx = 18, notesPx = textPx * 2, maxWidthPx = Infinity } = options;
2024
+ const underlays = underlayTokens(source);
2025
+ 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];
2027
+ if (!styleSet) throw new Error(`Unknown style set: "${styleName}"`);
2028
+ for (const font of fontStringsToVerify(styleSet, textPx)) {
2029
+ try {
2030
+ await document.fonts.load(font);
2031
+ } catch {}
2032
+ if (!document.fonts.check(font)) throw new Error(`Font could not be loaded: ${font} (style "${styleName}")`);
2033
+ }
2034
+ const notesFont = `400 ${notesPx}px ${styleSet.notesFontStack}`;
2035
+ const textStack = styleSet.textFontStack;
2036
+ 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);
2039
+ const dashNotesWidth = measure("-", notesFont);
2040
+ const dashTextWidth = measure("-", spaceFont);
2041
+ let clefGlyph = script.clef?.[0];
2042
+ let keyGlyphs = [...(script.clef ?? "").slice(1)].filter(isModifierGlyph).join("");
2043
+ let clefGroup = script.clef;
2044
+ const prefixOf = (group) => group ? `${group}-` : "";
2045
+ let activeKey = keyMapOf(keyGlyphs, clefGlyph, false);
2046
+ let staffKey = activeKey;
2047
+ const tracks = underlays.map((tokens) => {
2048
+ const syls = tokens.filter((t) => t.kind === "syllable");
2049
+ return {
2050
+ syls,
2051
+ lastTextSyl: syls.reduce((last, s, i) => silent(s) ? last : i, -1),
2052
+ cursor: 0,
2053
+ pending: [],
2054
+ prevWordEnd: void 0
2055
+ };
2056
+ });
2057
+ const lines = [];
2058
+ let line;
2059
+ let notesSoFar;
2060
+ let lastGroupTrailingMarker;
2061
+ let afterInlineClef = false;
2062
+ let current;
2063
+ let prevRecited = false;
2064
+ const startLine = () => {
2065
+ if (line) {
2066
+ tracks.forEach((t, u) => {
2067
+ line.texts[u].textCursor = t.cursor;
2068
+ });
2069
+ line.notesEnd = line.notesParts.length ? measure(line.clefPrefix + line.notesParts.join(""), notesFont) : 0;
2070
+ }
2071
+ const texts = tracks.map(() => ({
2072
+ segments: [],
2073
+ textCursor: 0,
2074
+ lastWordEnd: null
2075
+ }));
2076
+ line = {
2077
+ clefPrefix: prefixOf(clefGroup),
2078
+ notesParts: [],
2079
+ segments: texts[0].segments,
2080
+ textCursor: 0,
2081
+ notesEnd: 0,
2082
+ lastWordEnd: null,
2083
+ texts
2084
+ };
2085
+ lines.push(line);
2086
+ notesSoFar = line.clefPrefix;
2087
+ for (const t of tracks) t.cursor = 0;
2088
+ lastGroupTrailingMarker = false;
2089
+ prevRecited = false;
2090
+ afterInlineClef = false;
2091
+ staffKey = activeKey;
2092
+ if (current && current.inserted.length > 0) {
2093
+ current.notes = stripInserted(current.notes, current.inserted);
2094
+ current.inserted = [];
2095
+ if (current.first) placedNotes[current.i] = current.notes;
2096
+ }
2097
+ };
2098
+ startLine();
2099
+ const tokens = underlays[0];
2100
+ const allHeld = (i) => tracks.every((t) => t.syls[i].held);
2101
+ const items = [];
2102
+ let sylIndex = 0;
2103
+ let runHead;
2104
+ for (const tok of tokens) if (tok.kind !== "syllable") {
2105
+ items.push(tok);
2106
+ runHead = void 0;
2107
+ } else {
2108
+ const item = {
2109
+ kind: "syl",
2110
+ syl: tok,
2111
+ i: sylIndex++,
2112
+ notes: tok.notes,
2113
+ inserted: [],
2114
+ first: true,
2115
+ lastSeg: true,
2116
+ heldRun: [],
2117
+ signedByRun: false
2118
+ };
2119
+ if (allHeld(item.i) && runHead) {
2120
+ runHead.heldRun.push(tok.notes);
2121
+ item.signedByRun = true;
2122
+ } else runHead = item;
2123
+ items.push(item);
2124
+ }
2125
+ const placedNotes = [];
2126
+ const findBreakCut = (notes, room, measureFromLineStart) => {
2127
+ for (let c = notes.length - 1; c > 0; c--) {
2128
+ if (!NOTE_GROUP_SPLITTERS.includes(notes[c])) continue;
2129
+ let end = c + 1;
2130
+ while (end < notes.length && MARKER_CHARS$1.has(notes[end])) end++;
2131
+ if (end >= notes.length) continue;
2132
+ if (measureFromLineStart(notes.slice(0, end)) <= room) return c;
2133
+ }
2134
+ return -1;
2135
+ };
2136
+ const applyBreakCut = (item, cut) => {
2137
+ const notes = item.notes;
2138
+ let restStart = cut + 1;
2139
+ while (restStart < notes.length && MARKER_CHARS$1.has(notes[restStart])) restStart++;
2140
+ item.notes = notes.slice(0, cut) + notes.slice(cut + 1, restStart);
2141
+ const rest = stripInserted(notes.slice(restStart), item.inserted, restStart);
2142
+ item.inserted = item.inserted.filter((at) => at < cut);
2143
+ return rest;
2144
+ };
2145
+ const queueContinuation = (item, idx, rest) => {
2146
+ item.lastSeg = false;
2147
+ items.splice(idx + 1, 0, {
2148
+ kind: "syl",
2149
+ syl: item.syl,
2150
+ i: item.i,
2151
+ notes: rest,
2152
+ inserted: [],
2153
+ first: false,
2154
+ lastSeg: true,
2155
+ heldRun: [],
2156
+ signedByRun: false
2157
+ });
2158
+ forceBreak = true;
2159
+ };
2160
+ const flushPending = (trailing) => {
2161
+ tracks.forEach((t, u) => {
2162
+ while (t.pending.length > 0) {
2163
+ const p = t.pending[0];
2164
+ if (t.cursor > 0 && t.cursor + p.textWidth + (p.wordEnd ? 0 : dashTextWidth) > maxWidthPx) {
2165
+ startLine();
2166
+ continue;
2167
+ }
2168
+ t.pending.shift();
2169
+ const text = line.texts[u];
2170
+ text.segments.push({
2171
+ kind: "syl",
2172
+ parts: p.sylParts,
2173
+ textStart: t.cursor,
2174
+ textWidth: p.textWidth,
2175
+ contentWidth: 0,
2176
+ contentStart: 0,
2177
+ extraDashes: 0,
2178
+ tight: false,
2179
+ noNotes: true,
2180
+ ...trailing && t.pending.length === 0 ? { trailing: true } : {}
2181
+ });
2182
+ t.cursor += p.textWidth;
2183
+ if (p.spaceWidth > 0) {
2184
+ text.segments.push({
2185
+ kind: "word-space",
2186
+ width: p.spaceWidth
2187
+ });
2188
+ t.cursor += p.spaceWidth;
2189
+ }
2190
+ text.lastWordEnd = p.wordEnd;
2191
+ text.textCursor = t.cursor;
2192
+ }
2193
+ });
2194
+ };
2195
+ let forceBreak = false;
2196
+ let idx = 0;
2197
+ while (idx < items.length) {
2198
+ const item = items[idx];
2199
+ if (item.kind === "break") {
2200
+ if (line.texts.some((x) => x.segments.length > 0) || tracks.some((t) => t.pending.length > 0)) {
2201
+ flushPending(false);
2202
+ forceBreak = true;
2203
+ }
2204
+ idx++;
2205
+ continue;
2206
+ }
2207
+ if (item.kind === "clef" || item.kind === "key") {
2208
+ if (item.kind === "clef") clefGlyph = item.clef;
2209
+ keyGlyphs = item.key;
2210
+ clefGroup = (clefGlyph ?? "") + keyGlyphs;
2211
+ activeKey = keyMapOf(keyGlyphs, clefGlyph);
2212
+ if (forceBreak) {} else if (line.notesParts.length === 0) {
2213
+ line.clefPrefix = prefixOf(clefGroup);
2214
+ notesSoFar = line.clefPrefix;
2215
+ staffKey = activeKey;
2216
+ } else if (item.kind === "clef") {
2217
+ const part = (lastGroupTrailingMarker ? "--" : "---") + clefGroup + "-";
2218
+ if (measure(notesSoFar + part, notesFont) > maxWidthPx) forceBreak = true;
2219
+ else {
2220
+ line.notesParts.push(part);
2221
+ notesSoFar += part;
2222
+ staffKey = activeKey;
2223
+ afterInlineClef = true;
2224
+ lastGroupTrailingMarker = false;
2225
+ prevRecited = false;
2226
+ }
2227
+ }
2228
+ idx++;
2229
+ continue;
2230
+ }
2231
+ const syl = item.syl;
2232
+ const i = item.i;
2233
+ if (forceBreak) {
2234
+ startLine();
2235
+ forceBreak = false;
2236
+ }
2237
+ current = item;
2238
+ if (staffKey !== activeKey && !item.signedByRun) {
2239
+ const changed = applyKeyChange(item.notes, staffKey, activeKey, clefGlyph, item.first ? item.heldRun : []);
2240
+ item.notes = changed.notes;
2241
+ item.inserted = changed.inserted;
2242
+ }
2243
+ if (item.first) placedNotes[i] = item.signedByRun && staffKey !== activeKey ? applyKeyChange(item.notes, staffKey, activeKey, clefGlyph).notes : item.notes;
2244
+ const sung = tracks.map((t) => {
2245
+ const own = t.syls[i];
2246
+ const last = item.lastSeg && i >= t.lastTextSyl;
2247
+ const sylParts = resolveParts(item.first ? own.text : "");
2248
+ return {
2249
+ t,
2250
+ own,
2251
+ sylParts,
2252
+ textWidth: measureParts(sylParts),
2253
+ spaceWidth: !last && own.wordEnd ? measure(" ", spaceFont) : 0,
2254
+ pendingTotal: t.pending.reduce((s, p) => s + p.textWidth + p.spaceWidth, 0)
2255
+ };
2256
+ });
2257
+ const special = isRecitationGroup(item.notes);
2258
+ if (syl.empty && item.notes.length === 0) {
2259
+ idx++;
2260
+ continue;
2261
+ }
2262
+ if (item.notes.length === 0) {
2263
+ for (const s of sung) {
2264
+ if (s.own.empty) continue;
2265
+ s.t.pending.push({
2266
+ sylParts: s.sylParts,
2267
+ textWidth: s.textWidth,
2268
+ spaceWidth: s.spaceWidth,
2269
+ wordEnd: s.own.wordEnd
2270
+ });
2271
+ }
2272
+ idx++;
2273
+ continue;
2274
+ }
2275
+ if (item.first && item.lastSeg && !syl.empty && syl.text.trim() === "" && splitNoteMarkers(item.notes).core === "") {
2276
+ const last = notesSoFar[notesSoFar.length - 1];
2277
+ const sep = last && last !== "-" && !lastGroupTrailingMarker && !syl.notes.startsWith("-") ? "-" : "";
2278
+ line.notesParts.push(sep + syl.notes);
2279
+ notesSoFar += sep + syl.notes;
2280
+ lastGroupTrailingMarker = true;
2281
+ prevRecited = false;
2282
+ for (const s of sung) s.t.prevWordEnd = s.own.wordEnd;
2283
+ idx++;
2284
+ continue;
2285
+ }
2286
+ const keepWordState = (s, fresh) => {
2287
+ if (s.own.held) {
2288
+ if (fresh) line.texts[tracks.indexOf(s.t)].lastWordEnd = true;
2289
+ s.t.prevWordEnd = s.own.wordEnd;
2290
+ } else if (s.t.prevWordEnd === void 0) s.t.prevWordEnd = true;
2291
+ };
2292
+ if (item.first && sung.every((s) => silent(s.own))) {
2293
+ const held = allHeld(i);
2294
+ const recitation = isRecitationGroup(item.notes);
2295
+ if (held && recitation && placedNotes[i - 1] === placedNotes[i] && line.notesParts.length > 0 && !afterInlineClef) {
2296
+ prevRecited = true;
2297
+ idx++;
2298
+ continue;
2299
+ }
2300
+ let parts = splitNoteMarkers(item.notes);
2301
+ const joinOf = () => line.notesParts.length === 0 || afterInlineClef ? "" : held ? lastGroupTrailingMarker ? "--" : "-" : lastGroupTrailingMarker || MODIFIER_CHARS.has(parts.core[0]) ? "--" : "---";
2302
+ let join = joinOf();
2303
+ if (line.notesParts.length > 0 && measure(notesSoFar + join + item.notes, notesFont) > maxWidthPx) {
2304
+ startLine();
2305
+ join = joinOf();
2306
+ }
2307
+ const fresh = line.notesParts.length === 0;
2308
+ if (fresh && measure(notesSoFar + item.notes, notesFont) > maxWidthPx) {
2309
+ const cut = findBreakCut(item.notes, maxWidthPx, (prefix) => measure(notesSoFar + prefix, notesFont));
2310
+ if (cut >= 0 && cut + 1 < item.notes.length) {
2311
+ const rest = applyBreakCut(item, cut);
2312
+ queueContinuation(item, idx, rest);
2313
+ parts = splitNoteMarkers(item.notes);
2314
+ }
2315
+ }
2316
+ line.notesParts.push(join + item.notes);
2317
+ notesSoFar += join + item.notes;
2318
+ for (const s of sung) keepWordState(s, fresh);
2319
+ afterInlineClef = false;
2320
+ if (item.lastSeg) {
2321
+ lastGroupTrailingMarker = parts.trailing.length > 0;
2322
+ prevRecited = recitation;
2323
+ }
2324
+ idx++;
2325
+ continue;
2326
+ }
2327
+ const voiced = item.first ? sung.filter((s) => !silent(s.own)) : sung;
2328
+ 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);
2330
+ if (special && !runStart && line.notesParts.length > 0 && !specialFits) startLine();
2331
+ if (!item.first) {
2332
+ for (;;) {
2333
+ if (measure(notesSoFar + item.notes, notesFont) <= maxWidthPx) break;
2334
+ const cut = findBreakCut(item.notes, maxWidthPx, (prefix) => measure(notesSoFar + prefix, notesFont));
2335
+ if (cut < 0 || cut + 1 >= item.notes.length) break;
2336
+ const rest = applyBreakCut(item, cut);
2337
+ queueContinuation(item, idx, rest);
2338
+ }
2339
+ const parts = splitNoteMarkers(item.notes);
2340
+ line.notesParts.push(item.notes);
2341
+ notesSoFar += item.notes;
2342
+ if (item.lastSeg) lastGroupTrailingMarker = parts.trailing.length > 0;
2343
+ for (const [u, s] of sung.entries()) {
2344
+ line.texts[u].lastWordEnd = true;
2345
+ s.t.prevWordEnd = s.own.wordEnd;
2346
+ }
2347
+ if (!item.lastSeg) forceBreak = true;
2348
+ idx++;
2349
+ continue;
2350
+ }
2351
+ let parts = splitNoteMarkers(item.notes);
2352
+ let junctionPrefix = line.notesParts.length === 0 || afterInlineClef ? "" : prevRecited ? "" : lastGroupTrailingMarker || MODIFIER_CHARS.has(parts.core[0]) ? "--" : "---";
2353
+ const place = (padDashes = 0) => {
2354
+ let mods = 0;
2355
+ while (mods < parts.core.length && MODIFIER_CHARS.has(parts.core[mods])) mods++;
2356
+ if (mods === parts.core.length) mods = 0;
2357
+ const anchorText = parts.core.slice(mods);
2358
+ const contentWidth = measure(anchorText, notesFont);
2359
+ const contentStart = measure(notesSoFar + junctionPrefix + "-".repeat(padDashes) + parts.leading + parts.core.slice(0, mods), notesFont);
2360
+ const inkRaw = ink(anchorText, notesFont);
2361
+ const inkStartOffset = -inkRaw.left;
2362
+ const inkCenterOffset = (inkRaw.right - inkRaw.left) / 2;
2363
+ const textStartOf = (textWidth) => contentWidth >= textWidth || special ? contentStart + inkStartOffset : contentStart + inkCenterOffset - textWidth / 2;
2364
+ return {
2365
+ contentWidth,
2366
+ contentStart,
2367
+ textStartOf
2368
+ };
2369
+ };
2370
+ let placed = place();
2371
+ for (;;) {
2372
+ 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);
2374
+ if (!notesOver && !textOver) break;
2375
+ if (notesOver) {
2376
+ const cut = findBreakCut(item.notes, maxWidthPx, (prefix) => measure(notesSoFar + junctionPrefix + prefix, notesFont));
2377
+ if (cut >= 0 && cut + 1 < item.notes.length) {
2378
+ const rest = applyBreakCut(item, cut);
2379
+ queueContinuation(item, idx, rest);
2380
+ parts = splitNoteMarkers(item.notes);
2381
+ placed = place();
2382
+ break;
2383
+ }
2384
+ }
2385
+ if (line.notesParts.length === 0 && tracks.every((t) => t.cursor === 0)) {
2386
+ if (notesOver) {
2387
+ const cut = findBreakCut(item.notes, maxWidthPx, (prefix) => measure(notesSoFar + prefix, notesFont));
2388
+ if (cut >= 0 && cut + 1 < item.notes.length) {
2389
+ const rest = applyBreakCut(item, cut);
2390
+ item.notes = item.notes.slice(0, cut);
2391
+ queueContinuation(item, idx, rest);
2392
+ parts = splitNoteMarkers(item.notes);
2393
+ placed = place();
2394
+ }
2395
+ }
2396
+ break;
2397
+ }
2398
+ startLine();
2399
+ junctionPrefix = "";
2400
+ parts = splitNoteMarkers(item.notes);
2401
+ placed = place();
2402
+ }
2403
+ const decide = (s) => {
2404
+ const { t, textWidth } = s;
2405
+ const { contentWidth } = placed;
2406
+ 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);
2409
+ let textStart = placed.textStartOf(textWidth);
2410
+ let contentStart = placed.contentStart;
2411
+ let pads = 0;
2412
+ let tight = false;
2413
+ let wantsBreak = false;
2414
+ if (!prevRecited && connectorDash && textStart < minStart && (textWidth > contentWidth || textStart < t.cursor)) {
2415
+ tight = true;
2416
+ textStart = t.cursor;
2417
+ const idealContentStart = contentWidth >= textWidth ? textStart : textStart + (textWidth - contentWidth) / 2;
2418
+ if (idealContentStart > contentStart) pads = Math.round((idealContentStart - contentStart) / dashNotesWidth);
2419
+ return {
2420
+ textStart,
2421
+ contentStart,
2422
+ pads,
2423
+ tight,
2424
+ floor: t.cursor,
2425
+ minStart,
2426
+ wantsBreak
2427
+ };
2428
+ }
2429
+ if (textStart < minTextStart) {
2430
+ const idealContentStart = contentWidth >= textWidth ? minTextStart : minTextStart + (textWidth - contentWidth) / 2;
2431
+ if (idealContentStart > contentStart) {
2432
+ pads = Math.max(0, Math.floor((idealContentStart - contentStart) / dashNotesWidth));
2433
+ let padded = place(pads);
2434
+ while (padded.textStartOf(textWidth) < minTextStart) {
2435
+ pads++;
2436
+ padded = place(pads);
2437
+ }
2438
+ textStart = padded.textStartOf(textWidth);
2439
+ contentStart = padded.contentStart;
2440
+ wantsBreak = line.notesParts.length > 0 && measure(notesSoFar + junctionPrefix + "-".repeat(pads) + item.notes, notesFont) > maxWidthPx;
2441
+ }
2442
+ }
2443
+ return {
2444
+ textStart,
2445
+ contentStart,
2446
+ pads,
2447
+ tight,
2448
+ floor: minTextStart,
2449
+ minStart,
2450
+ wantsBreak
2451
+ };
2452
+ };
2453
+ const hiddenSpecial = special && !runStart && line.notesParts.length > 0 && !afterInlineClef;
2454
+ let placements;
2455
+ let padDashes = 0;
2456
+ if (hiddenSpecial) {
2457
+ junctionPrefix = "";
2458
+ placements = voiced.map((s) => {
2459
+ const textStart = s.t.cursor + s.pendingTotal;
2460
+ return {
2461
+ textStart,
2462
+ contentStart: placed.contentStart,
2463
+ pads: 0,
2464
+ tight: line.notesParts.length > 0 && !s.t.prevWordEnd && s.pendingTotal === 0,
2465
+ floor: textStart,
2466
+ minStart: textStart,
2467
+ wantsBreak: false
2468
+ };
2469
+ });
2470
+ const deficit = Math.max(...voiced.map((s, v) => placements[v].textStart + s.textWidth + s.spaceWidth)) - measure(notesSoFar, notesFont);
2471
+ const room = maxWidthPx - measure(notesSoFar + junctionPrefix, notesFont);
2472
+ const fill = deficit > 0 ? Math.min(Math.ceil(deficit / dashNotesWidth), Math.max(0, Math.floor(room / dashNotesWidth))) : 0;
2473
+ item.notes = "-".repeat(fill);
2474
+ item.inserted = [];
2475
+ parts = splitNoteMarkers(item.notes);
2476
+ } else {
2477
+ placements = voiced.map(decide);
2478
+ if (placements.some((p) => p.wantsBreak)) {
2479
+ startLine();
2480
+ junctionPrefix = "";
2481
+ parts = splitNoteMarkers(item.notes);
2482
+ 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
+ });
2499
+ }
2500
+ }
2501
+ const notesStr = junctionPrefix + "-".repeat(padDashes) + item.notes;
2502
+ const fresh = line.notesParts.length === 0;
2503
+ voiced.forEach((s, v) => {
2504
+ const { t, sylParts, textWidth, spaceWidth, pendingTotal } = s;
2505
+ const text = line.texts[tracks.indexOf(t)];
2506
+ const p = placements[v];
2507
+ let textStart = p.textStart;
2508
+ if (pendingTotal > 0 && textStart < t.cursor + pendingTotal) textStart = t.cursor + pendingTotal;
2509
+ const spacerWidth = Math.max(0, textStart - pendingTotal - t.cursor);
2510
+ if (fresh) text.segments.push({
2511
+ kind: "gap",
2512
+ role: "lead-in",
2513
+ width: spacerWidth,
2514
+ endPx: textStart - pendingTotal,
2515
+ textStartPx: textStart
2516
+ });
2517
+ else if (t.prevWordEnd) text.segments.push({
2518
+ kind: "gap",
2519
+ role: "word-gap",
2520
+ width: spacerWidth,
2521
+ endPx: textStart - pendingTotal,
2522
+ textStartPx: textStart
2523
+ });
2524
+ else if (pendingTotal === 0 && p.tight) {} else if (pendingTotal === 0) {
2525
+ const pad = Math.max(0, (spacerWidth - dashTextWidth) / 2);
2526
+ text.segments.push({
2527
+ kind: "connector",
2528
+ pad,
2529
+ gapWidth: spacerWidth,
2530
+ dashWidth: dashTextWidth,
2531
+ dashStartPx: t.cursor + pad,
2532
+ nextAnchorPx: textStart
2533
+ });
2534
+ }
2535
+ let pendingStart = textStart - pendingTotal;
2536
+ for (const pend of t.pending) {
2537
+ text.segments.push({
2538
+ kind: "syl",
2539
+ parts: pend.sylParts,
2540
+ textStart: pendingStart,
2541
+ textWidth: pend.textWidth,
2542
+ contentWidth: 0,
2543
+ contentStart: 0,
2544
+ extraDashes: 0,
2545
+ tight: false,
2546
+ noNotes: true
2547
+ });
2548
+ pendingStart += pend.textWidth;
2549
+ if (pend.spaceWidth > 0) {
2550
+ text.segments.push({
2551
+ kind: "word-space",
2552
+ width: pend.spaceWidth
2553
+ });
2554
+ pendingStart += pend.spaceWidth;
2555
+ }
2556
+ }
2557
+ t.pending = [];
2558
+ text.segments.push({
2559
+ kind: "syl",
2560
+ parts: sylParts,
2561
+ textStart,
2562
+ textWidth,
2563
+ contentWidth: placed.contentWidth,
2564
+ contentStart: p.contentStart,
2565
+ extraDashes: padDashes,
2566
+ tight: p.tight,
2567
+ noNotes: false
2568
+ });
2569
+ if (spaceWidth > 0) text.segments.push({
2570
+ kind: "word-space",
2571
+ width: spaceWidth
2572
+ });
2573
+ t.cursor = textStart + textWidth + spaceWidth;
2574
+ text.lastWordEnd = s.own.wordEnd;
2575
+ t.prevWordEnd = s.own.wordEnd;
2576
+ });
2577
+ for (const s of sung) if (!voiced.includes(s)) keepWordState(s, fresh);
2578
+ notesSoFar += notesStr;
2579
+ line.notesParts.push(notesStr);
2580
+ afterInlineClef = false;
2581
+ if (item.lastSeg) {
2582
+ lastGroupTrailingMarker = parts.trailing.length > 0;
2583
+ prevRecited = special;
2584
+ }
2585
+ if (!item.lastSeg) forceBreak = true;
2586
+ idx++;
2587
+ }
2588
+ flushPending(true);
2589
+ tracks.forEach((t, u) => {
2590
+ line.texts[u].textCursor = t.cursor;
2591
+ });
2592
+ line.notesEnd = line.notesParts.length ? measure(line.clefPrefix + line.notesParts.join(""), notesFont) : 0;
2593
+ lines.forEach((l, li) => {
2594
+ if (li === lines.length - 1) return;
2595
+ for (const text of l.texts) {
2596
+ if (text.lastWordEnd !== false) continue;
2597
+ const pad = l.notesEnd > text.textCursor ? Math.max(0, (l.notesEnd - text.textCursor - dashTextWidth) / 2) : 0;
2598
+ text.segments.push({
2599
+ kind: "line-end-dash",
2600
+ pad,
2601
+ dashWidth: dashTextWidth,
2602
+ dashStartPx: text.textCursor + pad,
2603
+ trailEndPx: l.notesEnd,
2604
+ textEndPx: text.textCursor
2605
+ });
2606
+ }
2607
+ });
2608
+ for (const l of lines) {
2609
+ l.textCursor = l.texts[0].textCursor;
2610
+ l.lastWordEnd = l.texts[0].lastWordEnd;
2611
+ }
2612
+ const starTarget = maxWidthPx + (styleSet.padding ?? 0);
2613
+ const starWidth = measure("*", notesFont);
2614
+ lines.forEach((l, li) => {
2615
+ if (li === lines.length - 1) return;
2616
+ if (maxWidthPx === Infinity) {
2617
+ l.breakMarkerLeftPx = styleSet.padding ?? 0;
2618
+ return;
2619
+ }
2620
+ let lineEnd = measure(l.clefPrefix + l.notesParts.join(""), notesFont);
2621
+ while (lineEnd + dashNotesWidth <= starTarget - starWidth && lineEnd + dashNotesWidth < maxWidthPx) {
2622
+ l.notesParts.push("-");
2623
+ lineEnd += dashNotesWidth;
2624
+ }
2625
+ l.breakMarkerLeftPx = starTarget - lineEnd - starWidth;
2626
+ });
2627
+ return {
2628
+ lines,
2629
+ clefPrefix: lines[0].clefPrefix,
2630
+ styleSet,
2631
+ styleName,
2632
+ textPx,
2633
+ notesPx,
2634
+ bold,
2635
+ maxWidthPx,
2636
+ starTarget,
2637
+ starWidth
2638
+ };
2639
+ }
2640
+ //#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 };