guidex 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/CHANGELOG.md +215 -0
  2. package/README.md +62 -16
  3. package/dist/lib/app/App.d.ts +1 -0
  4. package/dist/lib/app/AretinoControls.d.ts +35 -0
  5. package/dist/lib/app/CaretBand.d.ts +28 -0
  6. package/dist/lib/app/Developers.d.ts +13 -0
  7. package/dist/lib/app/EditorContext.d.ts +15 -0
  8. package/dist/lib/app/EditorTextarea.d.ts +18 -1
  9. package/dist/lib/app/EditorToolbar.d.ts +13 -0
  10. package/dist/lib/app/ExportSettings.d.ts +20 -1
  11. package/dist/lib/app/Footer.d.ts +1 -0
  12. package/dist/lib/app/GlyphChooser.d.ts +31 -0
  13. package/dist/lib/app/Inspector.d.ts +26 -0
  14. package/dist/lib/app/LiveScore.d.ts +31 -0
  15. package/dist/lib/app/Opening.d.ts +3 -0
  16. package/dist/lib/app/Reference.d.ts +28 -0
  17. package/dist/lib/app/RenderSettings.d.ts +2 -1
  18. package/dist/lib/app/ScriptViews.d.ts +8 -0
  19. package/dist/lib/app/SectionSize.d.ts +33 -0
  20. package/dist/lib/app/StaffSettings.d.ts +4 -0
  21. package/dist/lib/app/StaffedGlyph.d.ts +8 -0
  22. package/dist/lib/app/Tabs.d.ts +15 -0
  23. package/dist/lib/app/TakeItOut.d.ts +1 -0
  24. package/dist/lib/app/ThemeSwitch.d.ts +1 -0
  25. package/dist/lib/app/TopBar.d.ts +6 -0
  26. package/dist/lib/app/WidthControls.d.ts +21 -0
  27. package/dist/lib/app/aretinoCaret.d.ts +47 -0
  28. package/dist/lib/app/aretinoSource.d.ts +46 -0
  29. package/dist/lib/app/caretSync.d.ts +48 -0
  30. package/dist/lib/app/chantLibrary.d.ts +8 -4
  31. package/dist/lib/app/editorSnapshot.d.ts +11 -0
  32. package/dist/lib/app/editorState.d.ts +38 -5
  33. package/dist/lib/app/expandLink.d.ts +19 -0
  34. package/dist/lib/app/glyphData.d.ts +37 -0
  35. package/dist/lib/app/inCode.d.ts +4 -0
  36. package/dist/lib/app/insertAtCaret.d.ts +12 -0
  37. package/dist/lib/app/learn/Learn.d.ts +1 -0
  38. package/dist/lib/app/learn/LessonCard.d.ts +12 -0
  39. package/dist/lib/app/learn/lessons.d.ts +64 -0
  40. package/dist/lib/app/learn/narrowing.d.ts +24 -0
  41. package/dist/lib/app/learn/progress.d.ts +14 -0
  42. package/dist/lib/app/pageEvents.d.ts +14 -0
  43. package/dist/lib/app/previewHighlight.d.ts +44 -0
  44. package/dist/lib/app/samples.d.ts +9 -1
  45. package/dist/lib/app/scriptParts.d.ts +31 -0
  46. package/dist/lib/app/shareLink.d.ts +12 -2
  47. package/dist/lib/app/showcases/Showcases.d.ts +17 -0
  48. package/dist/lib/app/wordCopy.d.ts +4 -0
  49. package/dist/lib/aretino/fromAretino.d.ts +99 -0
  50. package/dist/lib/aretino/index.d.ts +38 -0
  51. package/dist/lib/aretino/index.js +1870 -0
  52. package/dist/lib/aretino/toAretino.d.ts +27 -0
  53. package/dist/lib/chantLayout-BRQ6FYND.js +1345 -0
  54. package/dist/lib/chantLayout.d.ts +101 -6
  55. package/dist/lib/chantMarkup-DX4K86Rv.js +993 -0
  56. package/dist/lib/drawnStaff.d.ts +39 -5
  57. package/dist/lib/editorStorage.d.ts +48 -6
  58. package/dist/lib/embed/core.d.ts +15 -1
  59. package/dist/lib/embed/index.js +1 -1
  60. package/dist/lib/embed/manual.d.ts +5 -4
  61. package/dist/lib/embed/manual.js +6 -4
  62. package/dist/lib/fonts/guidohu-staffless.woff2 +0 -0
  63. package/dist/lib/fonts/guidohu.ttf +0 -0
  64. package/dist/lib/glyphFamilies.d.ts +5 -1
  65. package/dist/lib/guidoRender.d.ts +30 -1
  66. package/dist/lib/guidoScriptTransforms.d.ts +2 -2
  67. package/dist/lib/guidoStyles-CvnACCsk.js +1466 -0
  68. package/dist/lib/guidoStyles.d.ts +23 -2
  69. package/dist/lib/react/GuidexScore.d.ts +10 -2
  70. package/dist/lib/react/index.js +14 -4
  71. package/dist/lib/{scoreImage-B2SGdROL.js → scoreImage-CKsQxHg5.js} +282 -1026
  72. package/dist/lib/theme.d.ts +13 -0
  73. package/dist/lib/word/index.d.ts +1 -1
  74. package/dist/lib/word/index.js +1 -1
  75. package/dist/lib/{wordChecker-CjYl2yof.js → wordChecker-BN_9dKAx.js} +133 -20
  76. package/dist/lib/wordChecker.d.ts +18 -1
  77. package/dist/lib/wordExport.d.ts +51 -3
  78. package/dist-embed/demo.html +2 -2
  79. package/dist-embed/fonts/guidohu-staffless.woff2 +0 -0
  80. package/dist-embed/fonts/guidohu.ttf +0 -0
  81. package/dist-embed/guidex-embed.min.js +1 -1
  82. package/package.json +10 -1
  83. package/dist/lib/app/ControlsRow.d.ts +0 -1
  84. package/dist/lib/app/SettingsMenu.d.ts +0 -1
  85. package/dist/lib/app/SettingsPanel.d.ts +0 -1
  86. package/dist/lib/chantLayout-BrCQUOhp.js +0 -2616
@@ -0,0 +1,1466 @@
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
+ longa: "€",
7
+ smallHead: "~",
8
+ modifyUp: "È",
9
+ cephalicus: "®"
10
+ },
11
+ ñ: {
12
+ virga: "^",
13
+ longa: "Ž",
14
+ smallHead: "¯",
15
+ modifyUp: "Ê",
16
+ modifyDown: "÷",
17
+ cephalicus: "−",
18
+ connectOneDown: "Ý",
19
+ smallPoint: "`"
20
+ },
21
+ "0": {
22
+ virga: "]",
23
+ longa: "ž",
24
+ smallHead: "‚",
25
+ modifyUp: "Ë",
26
+ modifyDown: "ø",
27
+ modifyNatural: "“",
28
+ cephalicus: "§",
29
+ connectOneDown: "Þ",
30
+ connectTwoDown: "Ô"
31
+ },
32
+ "1": {
33
+ virga: "q",
34
+ longa: "Ÿ",
35
+ smallHead: "ƒ",
36
+ modifyUp: "Ì",
37
+ modifyDown: "a",
38
+ modifyNatural: "”",
39
+ cephalicus: "'",
40
+ connectOneDown: "Q",
41
+ connectTwoDown: "×",
42
+ connectThreeDown: "Ø",
43
+ smallPoint: "í"
44
+ },
45
+ "2": {
46
+ virga: "w",
47
+ longa: "¡",
48
+ smallHead: "„",
49
+ modifyUp: "Î",
50
+ modifyDown: "A",
51
+ modifyNatural: "•",
52
+ cephalicus: "\"",
53
+ connectOneDown: "W",
54
+ connectTwoDown: "s",
55
+ connectThreeDown: "Ù",
56
+ connectFourDown: "½"
57
+ },
58
+ "3": {
59
+ virga: "e",
60
+ longa: "¢",
61
+ smallHead: "…",
62
+ modifyUp: "Ï",
63
+ modifyDown: "S",
64
+ modifyNatural: "–",
65
+ cephalicus: "+",
66
+ connectOneDown: "E",
67
+ connectTwoDown: "d",
68
+ connectThreeDown: "D",
69
+ connectFourDown: "°",
70
+ smallPoint: "y"
71
+ },
72
+ "4": {
73
+ virga: "r",
74
+ longa: "£",
75
+ smallHead: "†",
76
+ modifyUp: "Ð",
77
+ modifyDown: "Í",
78
+ modifyNatural: "—",
79
+ cephalicus: "!",
80
+ connectOneDown: "R",
81
+ connectTwoDown: "f",
82
+ connectThreeDown: "F",
83
+ connectFourDown: "±"
84
+ },
85
+ "5": {
86
+ virga: "t",
87
+ longa: "[",
88
+ smallHead: "‡",
89
+ modifyUp: "Ñ",
90
+ modifyDown: "Y",
91
+ modifyNatural: "˜",
92
+ cephalicus: "%",
93
+ connectOneDown: "T",
94
+ connectTwoDown: "g",
95
+ connectThreeDown: "G",
96
+ connectFourDown: "²",
97
+ smallPoint: "x"
98
+ },
99
+ "6": {
100
+ virga: "z",
101
+ longa: "¥",
102
+ smallHead: "ˆ",
103
+ modifyUp: "Ò",
104
+ modifyDown: "X",
105
+ modifyNatural: "™",
106
+ cephalicus: "/",
107
+ connectOneDown: "Z",
108
+ connectTwoDown: "h",
109
+ connectThreeDown: "H",
110
+ connectFourDown: "³"
111
+ },
112
+ "7": {
113
+ virga: "u",
114
+ longa: "¦",
115
+ smallHead: "‰",
116
+ modifyUp: "þ",
117
+ modifyDown: "C",
118
+ modifyNatural: "š",
119
+ cephalicus: "=",
120
+ connectOneDown: "U",
121
+ connectTwoDown: "j",
122
+ connectThreeDown: "J",
123
+ connectFourDown: "´",
124
+ smallPoint: "c"
125
+ },
126
+ "8": {
127
+ virga: "i",
128
+ longa: "©",
129
+ smallHead: "Š",
130
+ modifyUp: "ß",
131
+ modifyDown: "V",
132
+ modifyNatural: "›",
133
+ cephalicus: "(",
134
+ connectOneDown: "I",
135
+ connectTwoDown: "k",
136
+ connectThreeDown: "K",
137
+ connectFourDown: "μ"
138
+ },
139
+ "9": {
140
+ virga: "o",
141
+ longa: "ª",
142
+ smallHead: "‹",
143
+ modifyUp: "ò",
144
+ modifyDown: "B",
145
+ modifyNatural: "œ",
146
+ cephalicus: ")",
147
+ connectOneDown: "O",
148
+ connectTwoDown: "l",
149
+ connectThreeDown: "L",
150
+ connectFourDown: "·",
151
+ smallPoint: "v"
152
+ },
153
+ ö: {
154
+ virga: "p",
155
+ longa: "«",
156
+ smallHead: "Œ",
157
+ modifyUp: "ô",
158
+ modifyDown: "N",
159
+ modifyNatural: "º",
160
+ cephalicus: "Ö",
161
+ connectOneDown: "P",
162
+ connectTwoDown: "é",
163
+ connectThreeDown: "É",
164
+ connectFourDown: "¾"
165
+ },
166
+ ü: {
167
+ virga: "õ",
168
+ longa: "¬",
169
+ smallHead: "‘",
170
+ modifyUp: "ù",
171
+ modifyDown: "$",
172
+ modifyNatural: "»",
173
+ cephalicus: "Ü",
174
+ connectOneDown: "Õ",
175
+ connectTwoDown: "á",
176
+ connectThreeDown: "Á",
177
+ connectFourDown: "¸",
178
+ smallPoint: "b"
179
+ },
180
+ ó: {
181
+ virga: "ú",
182
+ longa: "¤",
183
+ smallHead: "’",
184
+ modifyUp: "ý",
185
+ modifyDown: "m",
186
+ cephalicus: "Ó",
187
+ connectOneDown: "Ú",
188
+ connectTwoDown: "û",
189
+ connectThreeDown: "Û",
190
+ connectFourDown: "¹",
191
+ smallPoint: "n"
192
+ }
193
+ };
194
+ /** Base pitch glyph → its pitch name in the standard g-clef (the
195
+ * "pitch in standard g-clef" column of the notation table). The last
196
+ * row of that table has no base glyph, so it has no entry here. */
197
+ var G_CLEF_PITCHES = {
198
+ ð: "a",
199
+ ñ: "b",
200
+ "0": "c'",
201
+ "1": "d'",
202
+ "2": "e'",
203
+ "3": "f'",
204
+ "4": "g'",
205
+ "5": "a'",
206
+ "6": "b'",
207
+ "7": "c''",
208
+ "8": "d''",
209
+ "9": "e''",
210
+ ö: "f''",
211
+ ü: "g''",
212
+ ó: "a''"
213
+ };
214
+ /** The standard g-clef pitch name of a base glyph, or of the base of a
215
+ * variant glyph; undefined when the glyph has no pitch. */
216
+ function gClefPitchOf(ch) {
217
+ return G_CLEF_PITCHES[ch] ?? G_CLEF_PITCHES[baseOf(ch)?.base ?? ""];
218
+ }
219
+ /** Reverse lookup: variant glyph → its base glyph and role. Built once;
220
+ * the table has no glyph in two places, so each variant maps to one base. */
221
+ var BASES = /* @__PURE__ */ new Map();
222
+ for (const [base, family] of Object.entries(FAMILIES)) for (const role of Object.keys(family)) BASES.set(family[role], {
223
+ base,
224
+ role
225
+ });
226
+ for (const [alias, glyph] of Object.entries({ ÿ: "'" })) BASES.set(alias, BASES.get(glyph));
227
+ /** The variant of `ch` in `role`, or undefined when `ch` has none. */
228
+ function variantOf(ch, role) {
229
+ return FAMILIES[ch]?.[role];
230
+ }
231
+ /** The virga (the stemmed form) of a pitch glyph. */
232
+ function toVirga(ch) {
233
+ return variantOf(ch, "virga");
234
+ }
235
+ /** The longa (the double-length form) of a pitch glyph. */
236
+ function toLonga(ch) {
237
+ return variantOf(ch, "longa");
238
+ }
239
+ /** The small head of a pitch glyph. */
240
+ function toSmallHead(ch) {
241
+ return variantOf(ch, "smallHead");
242
+ }
243
+ /** The cephalicus of a pitch glyph. */
244
+ function toCephalicus(ch) {
245
+ return variantOf(ch, "cephalicus");
246
+ }
247
+ /** The connecting form that joins a pitch to the note `steps` rows below
248
+ * it (1 to 4). */
249
+ function toConnectDown(ch, steps) {
250
+ const role = [
251
+ "connectOneDown",
252
+ "connectTwoDown",
253
+ "connectThreeDown",
254
+ "connectFourDown"
255
+ ][steps - 1];
256
+ return variantOf(ch, role);
257
+ }
258
+ /** The small point (the dot that lengthens a note by half) of a pitch glyph. */
259
+ function toSmallPoint(ch) {
260
+ return variantOf(ch, "smallPoint");
261
+ }
262
+ /** The sharp (raised) form of a pitch glyph. */
263
+ function modifyUp(ch) {
264
+ return variantOf(ch, "modifyUp");
265
+ }
266
+ /** The flat (lowered) form of a pitch glyph. */
267
+ function modifyDown(ch) {
268
+ return variantOf(ch, "modifyDown");
269
+ }
270
+ /** The natural sign for a pitch glyph. */
271
+ function modifyNatural(ch) {
272
+ return variantOf(ch, "modifyNatural");
273
+ }
274
+ /** Reverse lookup: the base glyph and role of a variant glyph, or
275
+ * undefined when `ch` is not a variant. */
276
+ function baseOf(ch) {
277
+ const entry = BASES.get(ch);
278
+ return entry ? { ...entry } : void 0;
279
+ }
280
+ /** The modifier roles: the accidental signs a key is written with. */
281
+ var MODIFIER_ROLES = [
282
+ "modifyUp",
283
+ "modifyDown",
284
+ "modifyNatural"
285
+ ];
286
+ /** Whether `ch` is a modifier glyph (a sharp, flat or natural sign). */
287
+ function isModifierGlyph(ch) {
288
+ const role = BASES.get(ch)?.role;
289
+ return role !== void 0 && MODIFIER_ROLES.includes(role);
290
+ }
291
+ /** The bracket pairs that set a cautionary accidental off (issue #95). */
292
+ var ACCIDENTAL_BRACKETS = /* @__PURE__ */ new Map([
293
+ ["Â", "Ã"],
294
+ ["Ä", "Å"],
295
+ ["Æ", "Ç"]
296
+ ]);
297
+ /**
298
+ * The length of the bracketed accidental that opens `notes` at `from`:
299
+ * an opening bracket, one or more accidental signs, the matching closing
300
+ * bracket, and the `¨`/`-` spacing right after it (`ÄôŨ¨` in `ÄôŨ¨õ`).
301
+ * 0 when no such unit stands there.
302
+ */
303
+ function bracketedAccidentalLength(notes, from = 0) {
304
+ const close = ACCIDENTAL_BRACKETS.get(notes[from] ?? "");
305
+ if (close === void 0) return 0;
306
+ let at = from + 1;
307
+ while (at < notes.length && isModifierGlyph(notes[at])) at++;
308
+ if (at === from + 1 || notes[at] !== close) return 0;
309
+ at++;
310
+ while (notes[at] === "¨" || notes[at] === "-") at++;
311
+ return at - from;
312
+ }
313
+ /** The clef glyphs (issue #49) and the staff line each one sits on,
314
+ * counted from the bottom. The g-clef has two keybindings. */
315
+ var CLEF_GLYPHS = {
316
+ ">": {
317
+ clef: "c",
318
+ line: 1
319
+ },
320
+ "#": {
321
+ clef: "c",
322
+ line: 2
323
+ },
324
+ "&": {
325
+ clef: "c",
326
+ line: 3
327
+ },
328
+ "@": {
329
+ clef: "c",
330
+ line: 4
331
+ },
332
+ "{": {
333
+ clef: "f",
334
+ line: 3
335
+ },
336
+ "}": {
337
+ clef: "f",
338
+ line: 4
339
+ },
340
+ M: {
341
+ clef: "g",
342
+ line: 2
343
+ },
344
+ "<": {
345
+ clef: "g",
346
+ line: 2
347
+ }
348
+ };
349
+ /** Whether `ch` is a clef glyph. */
350
+ function isClefGlyph(ch) {
351
+ return Object.hasOwn(CLEF_GLYPHS, ch);
352
+ }
353
+ /** The base pitch glyphs from low to high, one per staff position
354
+ * (spelled out: `Object.keys` would list the digit keys first). The
355
+ * index is the staff position the exact transposition counts with. */
356
+ var STAFF = [..."ðñ0123456789öüó"];
357
+ var LETTERS = "abcdefg";
358
+ /** The pitch letter (`a`…`g`, octave dropped) of a pitch glyph — a base
359
+ * glyph or any of its variants — under `clef` (a clef glyph; default the
360
+ * standard g-clef). Undefined when the glyph has no pitch or the clef
361
+ * glyph is unknown. */
362
+ function pitchLetterOf(ch, clef = "M") {
363
+ const position = STAFF.indexOf(STAFF.includes(ch) ? ch : baseOf(ch)?.base ?? "");
364
+ const entry = CLEF_GLYPHS[clef];
365
+ if (position < 0 || !entry) return void 0;
366
+ const linePosition = STAFF.indexOf("2") + 2 * (entry.line - 1);
367
+ const shift = LETTERS.indexOf(entry.clef) - LETTERS.indexOf(gClefPitchOf(STAFF[linePosition])[0]);
368
+ return LETTERS[((LETTERS.indexOf(gClefPitchOf(STAFF[position])[0]) + shift) % 7 + 7) % 7];
369
+ }
370
+ //#endregion
371
+ //#region src/noteGroups.ts
372
+ /**
373
+ * Note-group anatomy shared by the layout pass and the exact
374
+ * transposition: the score markers and the split of a group into its
375
+ * leading markers, notes and trailing markers. Kept free of imports, so
376
+ * the transforms can use it without pulling in the style sets.
377
+ */
378
+ /**
379
+ * Score marker characters: they carry no pitch, and when they sit at the
380
+ * start or end of a note group (with the adjacent dash) they act as
381
+ * whitespace rather than note width.
382
+ */
383
+ var SCORE_MARKERS = ",.:?'\"+!%/=()ÖÜÓ;";
384
+ var MARKER_CHARS$1 = new Set(SCORE_MARKERS.split(""));
385
+ function splitNoteMarkers(notes) {
386
+ let start = 0;
387
+ while (start < notes.length && MARKER_CHARS$1.has(notes[start])) start++;
388
+ if (start > 0 && start < notes.length) start = notes[start] === "-" ? start + 1 : 0;
389
+ let end = notes.length;
390
+ while (end > start && MARKER_CHARS$1.has(notes[end - 1])) end--;
391
+ if (end < notes.length && end > start) end = notes[end - 1] === "-" ? end - 1 : notes.length;
392
+ return {
393
+ leading: notes.slice(0, start),
394
+ core: notes.slice(start, end),
395
+ trailing: notes.slice(end)
396
+ };
397
+ }
398
+ //#endregion
399
+ //#region src/textMarkup.ts
400
+ /** The pause-marker characters: they split off into runs of their own. */
401
+ var MARKER_CHARS = /* @__PURE__ */ new Set(["*", "†"]);
402
+ /** The marks that take an argument, written `size:0.8`. */
403
+ var MARK_ARGUMENTS = /* @__PURE__ */ new Set([
404
+ "color",
405
+ "size",
406
+ "raise",
407
+ "font"
408
+ ]);
409
+ /** Stand-ins for escaped markup characters, from the private use area:
410
+ * the matching below never mistakes them for markup. Only ever held by a
411
+ * masked string, inside the functions that work on one. */
412
+ var MASKED = {
413
+ _: "",
414
+ "*": "",
415
+ "†": "",
416
+ "∗": ""
417
+ };
418
+ var UNMASKED = new Map(Object.entries(MASKED).map(([ch, mask]) => [mask, ch]));
419
+ function maskEscapes(written) {
420
+ return written.replace(/\\(.)/gsu, (_, ch) => MASKED[ch] ?? ch);
421
+ }
422
+ function unmask(masked) {
423
+ return masked.replace(/[-]/g, (mask) => UNMASKED.get(mask));
424
+ }
425
+ /** The whole-syllable wrapper of masked text, the longer `__` first so
426
+ * `__V.__` never matches the `_` rubric rule: the same characters on both
427
+ * ends, content between. */
428
+ function wrapperOf(masked) {
429
+ return ["__", "_"].find((wrapper) => masked.length >= wrapper.length * 2 + 1 && masked.startsWith(wrapper) && masked.endsWith(wrapper));
430
+ }
431
+ /** The `*…*` initial pairs of masked text, as segments: only non-empty
432
+ * pairs count, so an unmatched (or doubled) star stays a character. */
433
+ function initialSegments(masked) {
434
+ const segments = [];
435
+ let rest = masked;
436
+ let plain = "";
437
+ for (let m = /\*([^*]+)\*/.exec(rest); m; m = /\*([^*]+)\*/.exec(rest)) {
438
+ plain += rest.slice(0, m.index);
439
+ if (plain) {
440
+ segments.push({
441
+ text: plain,
442
+ initial: false
443
+ });
444
+ plain = "";
445
+ }
446
+ segments.push({
447
+ text: m[1],
448
+ initial: true
449
+ });
450
+ rest = rest.slice(m.index + m[0].length);
451
+ }
452
+ plain += rest;
453
+ if (plain) segments.push({
454
+ text: plain,
455
+ initial: false
456
+ });
457
+ return segments;
458
+ }
459
+ /** Splits one segment's characters into its plain, marker and plus runs. */
460
+ function splitGlyphRuns(text, marks, liturgy) {
461
+ const glyphOf = (ch) => MARKER_CHARS.has(ch) ? "marker" : liturgy && ch === "+" ? "plus" : void 0;
462
+ const runs = [];
463
+ for (const ch of text) {
464
+ const glyph = glyphOf(ch);
465
+ const last = runs[runs.length - 1];
466
+ if (last && last.glyph === glyph) last.text += ch;
467
+ else runs.push({
468
+ text: ch,
469
+ glyph
470
+ });
471
+ }
472
+ return runs.map((run) => ({
473
+ text: run.text,
474
+ marks: run.glyph ? [...marks, run.glyph] : [...marks]
475
+ }));
476
+ }
477
+ /**
478
+ * Parses text with no `{…}` span in it into the runs it draws: the
479
+ * whole-syllable `**` star (drawn as ∗), a `__…__` or `_…_` wrapper around
480
+ * all of it, paired `*` markers around any part of it (`*sam*ple` → "sam"
481
+ * and "ple"), and the marker characters and a Liturgy run's `+` split off.
482
+ * The wrapper characters are dropped; escaped characters are literal.
483
+ */
484
+ function parseTextRuns(written) {
485
+ if (written.length === 0) return [];
486
+ const masked = maskEscapes(written);
487
+ if (masked === "**") return [{
488
+ text: "∗",
489
+ marks: ["star"]
490
+ }];
491
+ const wrapper = wrapperOf(masked);
492
+ const content = wrapper ? masked.slice(wrapper.length, -wrapper.length) : masked;
493
+ const base = wrapper ? [wrapper === "__" ? "liturgy" : "rubric"] : [];
494
+ return initialSegments(content).flatMap(({ text, initial }) => splitGlyphRuns(unmask(text), initial ? [...base, "initial"] : base, wrapper === "__"));
495
+ }
496
+ /** The text to read from text with no span in it: every unescaped markup
497
+ * character and sign gone, escapes folded. Empty for a sign alone. */
498
+ function plainText(written) {
499
+ return unmask(maskEscapes(written).replace(/[_*†∗]/g, ""));
500
+ }
501
+ /** The marks of a span's opening, read just past its `{`: comma-separated
502
+ * names, those of `MARK_ARGUMENTS` with a `:argument`, closed by a colon.
503
+ * Returns undefined when the text does not start with such a list. */
504
+ function spanHead(text) {
505
+ const marks = [];
506
+ let at = 0;
507
+ for (;;) {
508
+ const name = /^[A-Za-z][\w-]*/.exec(text.slice(at))?.[0];
509
+ if (!name) return void 0;
510
+ at += name.length;
511
+ if (text[at] === ":" && MARK_ARGUMENTS.has(name)) {
512
+ const argument = /^[^\s,:{}]+/.exec(text.slice(at + 1))?.[0];
513
+ if (!argument) return void 0;
514
+ marks.push(`${name}:${argument}`);
515
+ at += 1 + argument.length;
516
+ } else marks.push(name);
517
+ if (text[at] === ":") return {
518
+ marks,
519
+ length: at + 1
520
+ };
521
+ if (text[at] !== ",") return void 0;
522
+ at += 1;
523
+ }
524
+ }
525
+ /** Splits text into what stands between its braces, and its braces. */
526
+ function lexSpans(text) {
527
+ const lexemes = [];
528
+ let written = "";
529
+ const flush = () => {
530
+ if (written) lexemes.push({
531
+ type: "text",
532
+ written
533
+ });
534
+ written = "";
535
+ };
536
+ for (let i = 0; i < text.length; i++) {
537
+ const ch = text[i];
538
+ if (ch === "\\" && i + 1 < text.length) written += ch + text[++i];
539
+ else if (ch === "{") {
540
+ flush();
541
+ const head = spanHead(text.slice(i + 1));
542
+ lexemes.push({
543
+ type: "open",
544
+ marks: head?.marks
545
+ });
546
+ if (head) i += head.length;
547
+ } else if (ch === "}") {
548
+ flush();
549
+ lexemes.push({ type: "close" });
550
+ } else written += ch;
551
+ }
552
+ flush();
553
+ return lexemes;
554
+ }
555
+ /**
556
+ * Resolves the `{…}` spans of consecutive pieces of text, which may open in
557
+ * one piece and close in a later one. A malformed span, a span never closed
558
+ * and a stray `}` are reported in `problems`; their text stays, plain, and
559
+ * their braces go, so no punctuation prints.
560
+ */
561
+ function resolveSpans(pieces) {
562
+ const problems = [];
563
+ const lexed = pieces.map(lexSpans);
564
+ const opens = /* @__PURE__ */ new Map();
565
+ const stack = [];
566
+ const strays = /* @__PURE__ */ new Set();
567
+ for (const [p, lexemes] of lexed.entries()) for (const lexeme of lexemes) if (lexeme.type === "open") {
568
+ if (!lexeme.marks) problems.push({
569
+ kind: "span",
570
+ text: pieces[p].trim(),
571
+ message: `A "{" needs its marks and a colon, as in "{red:text}" (in "${pieces[p].trim()}")`
572
+ });
573
+ const span = { marks: lexeme.marks ?? [] };
574
+ opens.set(lexeme, span);
575
+ stack.push(span);
576
+ } else if (lexeme.type === "close" && !stack.pop()) {
577
+ strays.add(lexeme);
578
+ problems.push({
579
+ kind: "span",
580
+ text: pieces[p].trim(),
581
+ message: `A "}" closes nothing (in "${pieces[p].trim()}")`
582
+ });
583
+ }
584
+ for (const span of stack) {
585
+ if (span.marks.length > 0) problems.push({
586
+ kind: "span",
587
+ text: span.marks.join(","),
588
+ message: `The span "{${span.marks.join(",")}:" is never closed`
589
+ });
590
+ span.marks = [];
591
+ }
592
+ const open = [];
593
+ const resolved = [];
594
+ let lastVisible;
595
+ for (const [p, lexemes] of lexed.entries()) {
596
+ const crossesIn = open.length > 0;
597
+ const segments = [];
598
+ const piece = {
599
+ bare: "",
600
+ source: "",
601
+ runs: [],
602
+ text: ""
603
+ };
604
+ for (const lexeme of lexemes) if (lexeme.type === "open") open.push(opens.get(lexeme));
605
+ else if (lexeme.type === "close") {
606
+ if (!strays.has(lexeme)) open.pop();
607
+ } else segments.push({
608
+ marks: open.flatMap((span) => span.marks),
609
+ written: lexeme.written
610
+ });
611
+ piece.bare = segments.map((s) => s.written).join("");
612
+ const body = trimSegments(segments);
613
+ piece.runs = body.flatMap(({ marks, written }) => parseTextRuns(written).map((run) => ({
614
+ text: run.text,
615
+ marks: [...marks, ...run.marks]
616
+ })));
617
+ piece.text = body.map(({ written }) => plainText(written)).join("");
618
+ const dropped = lexemes.some((l) => strays.has(l) || l.type === "open" && opens.get(l).marks.length === 0);
619
+ const live = lexemes.some((l) => l.type === "open" || l.type === "close");
620
+ piece.source = crossesIn || open.length > 0 || dropped || live && piece.bare.trim() === "" ? body.map(({ marks, written }) => marks.length > 0 ? `{${marks.join(",")}:${written}}` : written).join("") : pieces[p].trim();
621
+ const visible = body.filter((s) => s.written.trim() !== "");
622
+ if (visible.length > 0) {
623
+ if (lastVisible) {
624
+ const next = new Set(visible[0].marks);
625
+ const shared = lastVisible.marks.filter((mark) => next.has(mark));
626
+ if (shared.length > 0) lastVisible.piece.hyphen = shared;
627
+ }
628
+ lastVisible = {
629
+ piece,
630
+ marks: visible[visible.length - 1].marks
631
+ };
632
+ }
633
+ resolved.push(piece);
634
+ }
635
+ return {
636
+ pieces: resolved,
637
+ problems
638
+ };
639
+ }
640
+ /** The segments with the piece's outer whitespace gone. */
641
+ function trimSegments(segments) {
642
+ const body = segments.map((s) => ({ ...s }));
643
+ const first = body[0];
644
+ const last = body[body.length - 1];
645
+ if (first) first.written = first.written.trimStart();
646
+ if (last) last.written = last.written.trimEnd();
647
+ return body.filter((s) => s.written !== "");
648
+ }
649
+ //#endregion
650
+ //#region src/guidoScript.ts
651
+ /**
652
+ * A Guido script: the compact chant notation where pitches, neume shapes,
653
+ * and rhythm are packed into short character sequences, e.g.
654
+ *
655
+ * (MX)Ki(3)rály(3)ként(5) tró(7i)nol(7-:) *() az(7i) Úr(5-/) mind(5)ö(4t)rök(3)re.(3-.)
656
+ *
657
+ * The first parenthesized group, when present, is the starting clef and
658
+ * note modifiers. After that the source alternates syllable-first:
659
+ *
660
+ * (clef) syllable(notes) syllable(notes) ...
661
+ *
662
+ * Word boundaries are carried by whitespace in the source: a syllable
663
+ * after which the source has a space ends a word.
664
+ *
665
+ * A note group with no text in front of it is held by the syllable
666
+ * before it (issue #83): `mé(3)(tT4R3E2)` sings `mé` on both groups. The
667
+ * held group stays a token of its own (`text: ''`, `held: true`), so
668
+ * every group is one slot and formatting still resolves on each
669
+ * syllable's own text. A syllable whose whole text is `~` is an empty
670
+ * slot (`empty: true`): notes, but no syllable — and so is a text-less
671
+ * group at the very start of the script.
672
+ *
673
+ * The parentheses and backslash are control characters, so literal ones
674
+ * in the syllable text are typed as backslash escapes: `\(`, `\)` and
675
+ * `\\` stand for `(`, `)` and `\`.
676
+ *
677
+ * Control statements are groups whose content is an `@`-keyword with
678
+ * optional arguments after one space: `(@break)` ends the current line
679
+ * pair at its position, `(@clef MX)` changes the clef (and key) inline,
680
+ * `(@key X)` replaces the key and `(@key)` clears it. `(@tight)` tightens
681
+ * the junctions up to `(@tight off)`, `(@keep)` keeps its run on one line
682
+ * up to `(@keep off)`, and `(@unit)` / `(@unit off)` do both. Statements are
683
+ * positional — the text run before one must be whitespace-only — and
684
+ * they are invisible to the sung-text accessors.
685
+ *
686
+ * `(@stanza …)` statements (issue #69) stand at the very end of the
687
+ * script, one per further stanza (2, 3, …) in order. Their text is
688
+ * syllabified stanza text (see `parseStanza` in stanzas.ts), kept raw —
689
+ * escapes included — and listed by `stanzas`; they are not tokens, so
690
+ * nothing that walks the tokens (the layout, the sung-text accessors)
691
+ * ever sees them.
692
+ *
693
+ * `@` is also the c4 clef glyph: an opening group of `@` and nothing but
694
+ * modifier glyphs (`(@)`, `(@X)`) is the opening clef, not a statement.
695
+ */
696
+ /** The run properties a run statement sets. */
697
+ function runProperties(kind) {
698
+ return kind === "unit" ? ["tight", "keep"] : [kind];
699
+ }
700
+ /** Whether a group's content is a control statement (`@`-keyword,
701
+ * trimmed). Shared with the transforms, which must leave statement
702
+ * groups alone — their keyword characters are pitch glyphs otherwise.
703
+ * A c4 clef group (`@` + modifier glyphs) counts too: the opening one is
704
+ * told apart by `isC4ClefGroup`, and mid-script it is an error. */
705
+ function isStatementGroup(content) {
706
+ return content.trim().startsWith("@");
707
+ }
708
+ /** Whether a group's content has the shape of a c4 clef group: `@`
709
+ * followed by nothing but modifier glyphs. Statement keywords never
710
+ * consist solely of modifier glyphs, so the two cannot collide. */
711
+ function isC4ClefGroup(content) {
712
+ const [at, ...key] = content;
713
+ return at === "@" && key.every(isModifierGlyph);
714
+ }
715
+ /** Whether the leading group is the opening clef: anything but a
716
+ * statement, and the c4 clef despite its `@`. */
717
+ function isOpeningClef(content) {
718
+ return !isStatementGroup(content) || isC4ClefGroup(content);
719
+ }
720
+ /** Parses a key argument: modifier glyphs only. */
721
+ function parseKey(glyphs, statement) {
722
+ for (const ch of glyphs) if (!isModifierGlyph(ch)) throw new Error(`"${ch}" is not a key modifier glyph in "${statement}"`);
723
+ return glyphs;
724
+ }
725
+ /** Parses one statement group's content into its token (without
726
+ * `spaceBefore`). Throws on an unknown keyword or a bad argument. */
727
+ function parseStatement(content) {
728
+ const statement = content.trim();
729
+ if (isC4ClefGroup(statement)) throw new Error(`a clef group is only allowed at the start; write "(@clef ${statement})" to change the clef`);
730
+ const [, keyword, args = ""] = statement.match(/^@(\S*)(?: (.*))?$/) ?? [];
731
+ switch (keyword) {
732
+ case "break":
733
+ if (args !== "") throw new Error(`"@break" takes no argument: "${statement}"`);
734
+ return { kind: "break" };
735
+ case "clef": {
736
+ const [clef, ...key] = args;
737
+ if (clef === void 0) throw new Error("\"@clef\" needs a clef group argument, e.g. \"(@clef MX)\"");
738
+ if (!isClefGlyph(clef)) throw new Error(`"${clef}" is not a clef glyph in "${statement}"`);
739
+ return {
740
+ kind: "clef",
741
+ clef,
742
+ key: parseKey(key.join(""), statement)
743
+ };
744
+ }
745
+ case "key": return {
746
+ kind: "key",
747
+ key: parseKey(args, statement)
748
+ };
749
+ case "tight":
750
+ case "keep":
751
+ case "unit":
752
+ case "aid":
753
+ if (args !== "" && args !== "off") throw new Error(`"@${keyword}" takes only "off": "${statement}"`);
754
+ return {
755
+ kind: keyword,
756
+ on: args === ""
757
+ };
758
+ default: throw new Error(`Unknown statement "${statement}"`);
759
+ }
760
+ }
761
+ /** A statement token written back as its group. */
762
+ function statementSource(tok) {
763
+ switch (tok.kind) {
764
+ case "break": return "(@break)";
765
+ case "clef": return `(@clef ${tok.clef}${tok.key})`;
766
+ case "key": return tok.key === "" ? "(@key)" : `(@key ${tok.key})`;
767
+ case "tight":
768
+ case "keep":
769
+ case "unit":
770
+ case "aid": return tok.on ? `(@${tok.kind})` : `(@${tok.kind} off)`;
771
+ }
772
+ }
773
+ /** The stanza text of a `(@stanza …)` statement's trimmed content, or
774
+ * undefined when the statement is something else. */
775
+ function stanzaStatementText(statement) {
776
+ const match = statement.match(/^@stanza(?:\s+([\s\S]*))?$/);
777
+ return match ? match[1] ?? "" : void 0;
778
+ }
779
+ var GuidoScript = class {
780
+ source;
781
+ constructor(source, options = {}) {
782
+ this.source = (options.transforms ?? []).reduce((script, transform) => transform.apply(script), source);
783
+ }
784
+ /** The starting clef and note modifiers, or undefined when absent.
785
+ * A leading statement group is not a clef. */
786
+ get clef() {
787
+ const match = this.normalized.match(/^\s*\(([^)]*)\)/);
788
+ if (!match || !isOpeningClef(match[1])) return void 0;
789
+ return match[1];
790
+ }
791
+ /** The script's tokens in source order: syllables interleaved with
792
+ * control statements. Throws on a malformed statement (syllable text
793
+ * attached to one, or an unknown `@` keyword). */
794
+ get tokens() {
795
+ return this.parse().tokens;
796
+ }
797
+ /** The raw text of the `(@stanza …)` statements at the end of the
798
+ * script — stanzas 2, 3, … in order, escapes kept (the stanza text
799
+ * grammar folds them). Throws like `tokens` on a malformed script,
800
+ * and when anything but another stanza follows a stanza statement. */
801
+ get stanzas() {
802
+ return this.parse().stanzas;
803
+ }
804
+ /** Where each token stands in the source, parallel to `tokens`:
805
+ * offsets of its text (past leading whitespace), of its group's
806
+ * content and just past its group's `)`. The walker
807
+ * (`scriptSyllables`) reads them. */
808
+ get tokenSpans() {
809
+ return this.parse().spans;
810
+ }
811
+ /** What is wrong with the script's `{…}` spans: such a span renders
812
+ * plainly instead of failing the score. */
813
+ get spanProblems() {
814
+ return this.parse().problems;
815
+ }
816
+ parse() {
817
+ const script = this.normalized;
818
+ const head = script.match(/^\s*\(([^)]*)\)/);
819
+ const skipped = head && isOpeningClef(head[1]) ? head[0].length : 0;
820
+ const matches = [...script.slice(skipped).matchAll(/((?:[^()\\]|\\.)*)\(((?:[^)\\]|\\.)*)\)/g)];
821
+ const resolved = resolveSpans(matches.map((match) => match[1]));
822
+ let prev;
823
+ const stanzas = [];
824
+ const tokens = [];
825
+ const spans = [];
826
+ for (const [m, match] of matches.entries()) {
827
+ const [, written, notes] = match;
828
+ const piece = resolved.pieces[m];
829
+ const text = piece.bare;
830
+ const at = skipped + match.index;
831
+ const notesStart = at + written.length + 1;
832
+ const span = {
833
+ start: at + (written.length - written.trimStart().length),
834
+ notesStart,
835
+ notesEnd: notesStart + notes.length,
836
+ end: notesStart + notes.length + 1
837
+ };
838
+ const stanza = isStatementGroup(notes) ? stanzaStatementText(notes.trim()) : void 0;
839
+ if (stanza !== void 0) {
840
+ if (text.trim() !== "") throw new Error(`statement must not carry syllable text: "${unescape(text.trim())}"`);
841
+ stanzas.push(stanza);
842
+ continue;
843
+ }
844
+ if (stanzas.length > 0) {
845
+ if (text.trim() === "" && notes === "") continue;
846
+ throw new Error("\"(@stanza …)\" statements must stand at the end of the script");
847
+ }
848
+ if (isStatementGroup(notes)) {
849
+ const statement = parseStatement(notes);
850
+ if (text.trim() !== "") throw new Error(`statement must not carry syllable text: "${unescape(text.trim())}"`);
851
+ tokens.push({
852
+ ...statement,
853
+ spaceBefore: /^\s/.test(text)
854
+ });
855
+ spans.push(span);
856
+ continue;
857
+ }
858
+ const raw = text.trim();
859
+ if (raw === "" && notes === "" && written.trim() !== "") continue;
860
+ const tok = {
861
+ kind: "syllable",
862
+ ...textFields(raw === "~" ? NO_TEXT : piece),
863
+ role: "sung",
864
+ notes: unescape(notes),
865
+ spaceBefore: /^\s/.test(text)
866
+ };
867
+ if (raw === "~" || raw === "" && prev === void 0 && tok.notes !== "") tok.empty = true;
868
+ else if (raw === "" && tok.notes !== "") {
869
+ 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`);
870
+ tok.held = true;
871
+ }
872
+ prev = tok;
873
+ tokens.push(tok);
874
+ spans.push(span);
875
+ }
876
+ let holder;
877
+ for (const [i, t] of tokens.entries()) {
878
+ if (t.kind !== "syllable") continue;
879
+ if (t.held) {
880
+ t.wordEnd = holder.wordEnd;
881
+ continue;
882
+ }
883
+ t.wordEnd = true;
884
+ let space = false;
885
+ for (let j = i + 1; j < tokens.length; j++) {
886
+ const tok = tokens[j];
887
+ if (tok.spaceBefore) space = true;
888
+ if (tok.kind === "syllable" && !tok.held && !tok.empty) {
889
+ t.wordEnd = space;
890
+ break;
891
+ }
892
+ }
893
+ holder = t;
894
+ }
895
+ assignRoles(tokens);
896
+ return {
897
+ tokens,
898
+ stanzas,
899
+ spans,
900
+ problems: resolved.problems
901
+ };
902
+ }
903
+ /** The script broken into syllables, each with its sung text and
904
+ * notes — the syllable tokens, statements filtered out. */
905
+ get syllables() {
906
+ return this.tokens.filter((t) => t.kind === "syllable").map(({ text, notes, wordEnd, held, empty }) => ({
907
+ text,
908
+ notes,
909
+ wordEnd,
910
+ ...held ? { held } : {},
911
+ ...empty ? { empty } : {}
912
+ }));
913
+ }
914
+ /**
915
+ * The source with the typing conveniences folded in, so the parser
916
+ * itself only ever sees complete scripts:
917
+ *
918
+ * - an unclosed parenthesis is closed at the end, so the notes typed
919
+ * so far already preview on the score;
920
+ * - a trailing syllable with no note group gets an empty one, so it
921
+ * renders like a `*()` syllable (text without notes width).
922
+ */
923
+ get normalized() {
924
+ let script = this.source;
925
+ if ((script.match(/(^|[^\\])\(/g) ?? []).length > (script.match(/(^|[^\\])\)/g) ?? []).length) script += ")";
926
+ if (!/(^|[^\\])\)$/.test(script)) script += "()";
927
+ return script;
928
+ }
929
+ /** The syllables grouped into the words of the text. Held groups and
930
+ * empty slots sing no syllable of their own, so they are left out. */
931
+ get words() {
932
+ const words = [];
933
+ let word;
934
+ for (const syl of this.tokens) {
935
+ if (syl.kind !== "syllable" || syl.held || syl.empty) continue;
936
+ word ??= {
937
+ text: "",
938
+ syllables: []
939
+ };
940
+ const { text, source, runs, role, notes } = syl;
941
+ word.syllables.push({
942
+ text,
943
+ source,
944
+ runs,
945
+ role,
946
+ notes
947
+ });
948
+ word.text = word.syllables.map((s) => s.text).join("");
949
+ if (syl.wordEnd) {
950
+ words.push(word);
951
+ word = void 0;
952
+ }
953
+ }
954
+ return words;
955
+ }
956
+ /** The script rebuilt from the parsed pieces — a round-trip of the
957
+ * source, statements and stanzas included. */
958
+ toString() {
959
+ const parts = this.tokens.map((tok, i) => {
960
+ const prefix = i > 0 && tok.spaceBefore ? " " : "";
961
+ return tok.kind === "syllable" ? `${prefix}${tok.empty ? "~" : tok.source}(${escape(tok.notes)})` : `${prefix}${statementSource(tok)}`;
962
+ });
963
+ const stanzas = this.stanzas.map((text) => `(@stanza ${text})`);
964
+ return `${this.clef !== void 0 ? `(${this.clef})` : ""}${parts.join("")}${stanzas.join("")}`;
965
+ }
966
+ };
967
+ /** The roles `scriptSyllables` lists by default: what is sung. */
968
+ var SUNG_ROLES = ["sung", "aid"];
969
+ /**
970
+ * The syllables of a script, in order: by default the sung ones, labels and
971
+ * signs left out (`roles` chooses others). Held groups ride on their
972
+ * syllable (`held`); `~` empty slots, statements and `(@stanza …)` are
973
+ * skipped. Word starts and ends are the listed syllables' own, so a word
974
+ * end on a left-out syllable lands on the one before it. Offsets index the
975
+ * script's source; index i is the "syllable i" of `composeScript`'s
976
+ * `from`/`to`.
977
+ */
978
+ function scriptSyllables(script, options = {}) {
979
+ const parsed = typeof script === "string" ? new GuidoScript(script) : script;
980
+ const roles = options.roles ?? SUNG_ROLES;
981
+ const tokens = parsed.tokens;
982
+ const spans = parsed.tokenSpans;
983
+ const all = [];
984
+ let holder;
985
+ for (const [i, tok] of tokens.entries()) {
986
+ if (tok.kind !== "syllable") continue;
987
+ if (tok.empty) {
988
+ holder = void 0;
989
+ continue;
990
+ }
991
+ if (tok.held) {
992
+ if (holder) {
993
+ holder.held.push(tok.notes);
994
+ holder.end = spans[i].end;
995
+ }
996
+ continue;
997
+ }
998
+ const span = spans[i];
999
+ holder = {
1000
+ text: tok.text,
1001
+ source: tok.source,
1002
+ role: tok.role,
1003
+ notes: tok.notes,
1004
+ held: [],
1005
+ wordStart: false,
1006
+ wordEnd: tok.wordEnd,
1007
+ start: span.start,
1008
+ notesStart: span.notesStart,
1009
+ notesEnd: span.notesEnd,
1010
+ end: span.end,
1011
+ token: i
1012
+ };
1013
+ all.push(holder);
1014
+ }
1015
+ const listed = [];
1016
+ let atWordStart = true;
1017
+ for (const syl of all) if (roles.includes(syl.role)) {
1018
+ syl.wordStart = atWordStart;
1019
+ listed.push(syl);
1020
+ atWordStart = syl.wordEnd;
1021
+ } else if (syl.wordEnd) {
1022
+ if (listed.length > 0) listed[listed.length - 1].wordEnd = true;
1023
+ atWordStart = true;
1024
+ }
1025
+ return listed;
1026
+ }
1027
+ /** The text of the script to read: the sung words joined with single
1028
+ * spaces, with no markup, labels, signs or aids in them. Characters the
1029
+ * author escaped stay. */
1030
+ function chantText(script, options = {}) {
1031
+ const roles = ["sung"];
1032
+ if (options.labels) roles.push("label");
1033
+ if (options.aids) roles.push("aid");
1034
+ return scriptSyllables(script, { roles }).map((syl) => (syl.wordStart ? " " : "") + syl.text).join("").replace(/ +/g, " ").trim();
1035
+ }
1036
+ /** A text with nothing in it. */
1037
+ var NO_TEXT = {
1038
+ bare: "",
1039
+ source: "",
1040
+ runs: [],
1041
+ text: ""
1042
+ };
1043
+ /** A syllable's text fields, from its resolved text. */
1044
+ function textFields(piece) {
1045
+ const { text, source, runs, hyphen } = piece;
1046
+ return {
1047
+ text,
1048
+ source,
1049
+ runs,
1050
+ ...hyphen ? { hyphen } : {}
1051
+ };
1052
+ }
1053
+ /** A syllable's text fields, from text written on its own. */
1054
+ function syllableText(written) {
1055
+ return textFields(resolveSpans([written]).pieces[0]);
1056
+ }
1057
+ var LABEL_MARKS = ["liturgy", "rubric"];
1058
+ /** Whether a group carries pitch: anything but markers and spacing. */
1059
+ function hasPitch(notes) {
1060
+ return /[^-¨]/.test(splitNoteMarkers(notes).core);
1061
+ }
1062
+ /** What each syllable token is for. A held group takes its holder's role;
1063
+ * an empty slot stays `sung`, unless it stands in an `(@aid)` run. */
1064
+ function assignRoles(tokens) {
1065
+ let aid = 0;
1066
+ let holder = "sung";
1067
+ const markedBy = (tok, names) => tok.runs.every((run) => run.marks.some((mark) => names.includes(mark)));
1068
+ for (const tok of tokens) {
1069
+ if (tok.kind === "aid") aid = Math.max(0, aid + (tok.on ? 1 : -1));
1070
+ if (tok.kind !== "syllable") continue;
1071
+ if (tok.held) {
1072
+ tok.role = holder;
1073
+ continue;
1074
+ }
1075
+ if (tok.runs.length === 0) tok.role = !tok.empty && tok.notes === "" ? "sign" : aid > 0 ? "aid" : "sung";
1076
+ else if (tok.text === "" || markedBy(tok, ["plus"])) tok.role = "sign";
1077
+ else if (markedBy(tok, LABEL_MARKS) && !hasPitch(tok.notes)) tok.role = "label";
1078
+ else tok.role = aid > 0 ? "aid" : "sung";
1079
+ holder = tok.role;
1080
+ }
1081
+ }
1082
+ /** Folds backslash escapes into the characters they stand for. Shared
1083
+ * with the transforms module (guidoScriptTransforms.ts). */
1084
+ function unescape(text) {
1085
+ return text.replace(/\\(.)/g, "$1");
1086
+ }
1087
+ /** Turns literal parentheses and backslashes into their escape sequences. */
1088
+ function escape(text) {
1089
+ return text.replace(/\\/g, "\\\\").replace(/[()]/g, (ch) => `\\${ch}`);
1090
+ }
1091
+ //#endregion
1092
+ //#region src/guidoStyles.ts
1093
+ /**
1094
+ * Style sets for the renderer: named appearance rules (fonts, colors, and
1095
+ * the special syllable decorations) kept in one constant registry, so a
1096
+ * new style is a data entry here rather than a renderer fork.
1097
+ */
1098
+ /** Text characters (* and †) rendered in Times New Roman. */
1099
+ var TIMES_MARKER_GLYPHS = {
1100
+ chars: MARKER_CHARS,
1101
+ fontFamily: "'Times New Roman', Times, serif"
1102
+ };
1103
+ /** How a `+` inside a Liturgy-font run is drawn: normal weight (the font
1104
+ * is bold-looking by design), sized to 70% and raised 20% of the text
1105
+ * size so it sits like a connecting sign between syllable parts. */
1106
+ var LITURGY_PLUS_STYLE = {
1107
+ weight: "400",
1108
+ scale: .7,
1109
+ raise: .2
1110
+ };
1111
+ var STYLE_SETS = {
1112
+ /** Book Antiqua text with red accents. */
1113
+ BNS: {
1114
+ textFontStack: "'Book Antiqua', Georgia, serif",
1115
+ notesFontStack: "'Guidohu'",
1116
+ markerGlyphs: TIMES_MARKER_GLYPHS,
1117
+ verifiedFonts: [
1118
+ {
1119
+ family: "'Book Antiqua'",
1120
+ weight: "400"
1121
+ },
1122
+ {
1123
+ family: "'Book Antiqua'",
1124
+ weight: "700"
1125
+ },
1126
+ {
1127
+ family: "'Guidohu'",
1128
+ weight: "400"
1129
+ },
1130
+ {
1131
+ family: "'Liturgy'",
1132
+ weight: "700"
1133
+ }
1134
+ ],
1135
+ marks: {
1136
+ liturgy: {
1137
+ fontFamily: "'Liturgy', serif",
1138
+ weight: "700",
1139
+ color: "var(--red)"
1140
+ },
1141
+ rubric: {
1142
+ uppercase: true,
1143
+ scale: .7,
1144
+ color: "var(--red)"
1145
+ },
1146
+ initial: {
1147
+ weight: "700",
1148
+ color: "var(--red)",
1149
+ initial: true
1150
+ },
1151
+ star: {
1152
+ fontFamily: TIMES_MARKER_GLYPHS.fontFamily,
1153
+ weight: "700",
1154
+ scale: 1,
1155
+ measureScale: .95,
1156
+ raise: .1,
1157
+ color: "var(--red)"
1158
+ },
1159
+ plus: LITURGY_PLUS_STYLE
1160
+ },
1161
+ padding: 12,
1162
+ clefLine: { color: "var(--red, #d40000)" }
1163
+ },
1164
+ /** Times New Roman text, strictly black and white. */
1165
+ Vesperale: {
1166
+ textFontStack: "'Times New Roman', Times, serif",
1167
+ notesFontStack: "'Guidohu'",
1168
+ verifiedFonts: [
1169
+ {
1170
+ family: "'Times New Roman', Times, serif",
1171
+ weight: "400"
1172
+ },
1173
+ {
1174
+ family: "'Times New Roman', Times, serif",
1175
+ weight: "700"
1176
+ },
1177
+ {
1178
+ family: "'Guidohu'",
1179
+ weight: "400"
1180
+ },
1181
+ {
1182
+ family: "'Liturgy'",
1183
+ weight: "700"
1184
+ }
1185
+ ],
1186
+ marks: {
1187
+ liturgy: {
1188
+ fontFamily: "'Liturgy', serif",
1189
+ weight: "700"
1190
+ },
1191
+ rubric: {
1192
+ scale: .8,
1193
+ italic: true
1194
+ },
1195
+ initial: {
1196
+ weight: "700",
1197
+ initial: true
1198
+ },
1199
+ star: {
1200
+ fontFamily: TIMES_MARKER_GLYPHS.fontFamily,
1201
+ weight: "700",
1202
+ scale: 1,
1203
+ measureScale: .95,
1204
+ raise: .2
1205
+ },
1206
+ plus: LITURGY_PLUS_STYLE
1207
+ },
1208
+ padding: 12,
1209
+ clefLine: { weight: 2.5 }
1210
+ }
1211
+ };
1212
+ var DEFAULT_STYLE_SET = "BNS";
1213
+ /** The style sets `defineStyleSet` added. */
1214
+ var definedStyleSets = /* @__PURE__ */ new Map();
1215
+ /** The style set of that name, built-in or defined. */
1216
+ function styleSetOf(name) {
1217
+ return definedStyleSets.get(name) ?? STYLE_SETS[name];
1218
+ }
1219
+ /** Adds a style set under a name `style` can then give, without patching
1220
+ * the package. Returns it. */
1221
+ function defineStyleSet(name, definition) {
1222
+ const { extends: base = "BNS", ...own } = definition;
1223
+ const parent = styleSetOf(base);
1224
+ if (!parent) throw new Error(`Unknown style set: "${base}"`);
1225
+ const styleSet = {
1226
+ ...parent,
1227
+ ...own,
1228
+ marks: {
1229
+ ...parent.marks,
1230
+ ...own.marks
1231
+ },
1232
+ colors: {
1233
+ ...parent.colors,
1234
+ ...own.colors
1235
+ },
1236
+ fonts: {
1237
+ ...parent.fonts,
1238
+ ...own.fonts
1239
+ }
1240
+ };
1241
+ definedStyleSets.set(name, styleSet);
1242
+ return styleSet;
1243
+ }
1244
+ /** The built-in colors `color:<name>` can name. */
1245
+ var PALETTE = { red: "var(--red)" };
1246
+ /** The CSS named colors, which `color:` takes as written (after the style
1247
+ * set's colors and the palette, so `red` stays the theme's red) */
1248
+ var CSS_COLOR_NAMES = new Set("aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkgrey darkkhaki darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray darkslategrey darkturquoise darkviolet deeppink deepskyblue dimgray dimgrey dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow grey honeydew hotpink indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgoldenrodyellow lightgray lightgreen lightgrey lightpink lightsalmon lightseagreen lightskyblue lightslategray lightslategrey lightsteelblue lightyellow lime limegreen linen magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell sienna silver skyblue slateblue slategray slategrey snow springgreen steelblue tan teal thistle tomato turquoise violet wheat white whitesmoke yellow yellowgreen".split(" "));
1249
+ /** A color written as CSS: a named color or a hex code (#rgb, #rgba,
1250
+ * #rrggbb, #rrggbbaa); anything else is no color */
1251
+ function cssColor(written) {
1252
+ const name = written.toLowerCase();
1253
+ if (CSS_COLOR_NAMES.has(name)) return name;
1254
+ return /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(written) ? written : void 0;
1255
+ }
1256
+ /** The built-in fonts `font:<name>` can name. */
1257
+ var FONTS = {
1258
+ liturgy: "'Liturgy', serif",
1259
+ times: "'Times New Roman', Times, serif"
1260
+ };
1261
+ /** How much smaller small capitals draw than the full capitals. */
1262
+ var SMALL_CAP_SCALE = .75;
1263
+ var KINDS = /* @__PURE__ */ new Set([
1264
+ "liturgy",
1265
+ "rubric",
1266
+ "star",
1267
+ "marker",
1268
+ "plus"
1269
+ ]);
1270
+ /** The run kind of a run's marks: the last of the notation's own. */
1271
+ function kindOf(marks) {
1272
+ return marks.filter((mark) => KINDS.has(mark)).pop();
1273
+ }
1274
+ /** The style `mark` leaves on `style`, or undefined when no such mark
1275
+ * exists. The primitives come first, so they mean the same in every style
1276
+ * set; a registered mark's `color` may name a palette color. */
1277
+ function withMark(style, mark, text, styleSet, extra) {
1278
+ const colorOf = (name) => styleSet.colors?.[name] ?? PALETTE[name] ?? cssColor(name);
1279
+ const at = mark.indexOf(":");
1280
+ const name = at < 0 ? mark : mark.slice(0, at);
1281
+ const argument = at < 0 ? "" : mark.slice(at + 1);
1282
+ const amount = Number(argument);
1283
+ switch (name) {
1284
+ case "plain": return {};
1285
+ case "red": return {
1286
+ ...style,
1287
+ color: PALETTE.red
1288
+ };
1289
+ case "b": return {
1290
+ ...style,
1291
+ weight: "700"
1292
+ };
1293
+ case "i": return {
1294
+ ...style,
1295
+ italic: true
1296
+ };
1297
+ case "sc": return {
1298
+ ...style,
1299
+ smallCaps: true
1300
+ };
1301
+ case "up": return {
1302
+ ...style,
1303
+ uppercase: true
1304
+ };
1305
+ case "u": return {
1306
+ ...style,
1307
+ underline: true
1308
+ };
1309
+ case "color": {
1310
+ const color = colorOf(argument);
1311
+ return color ? {
1312
+ ...style,
1313
+ color
1314
+ } : void 0;
1315
+ }
1316
+ case "size": return amount > 0 ? {
1317
+ ...style,
1318
+ scale: amount,
1319
+ measureScale: void 0
1320
+ } : void 0;
1321
+ case "raise": return Number.isFinite(amount) && argument !== "" ? {
1322
+ ...style,
1323
+ raise: amount
1324
+ } : void 0;
1325
+ case "font": {
1326
+ const fontFamily = styleSet.fonts?.[argument] ?? FONTS[argument];
1327
+ return fontFamily ? {
1328
+ ...style,
1329
+ fontFamily
1330
+ } : void 0;
1331
+ }
1332
+ case "marker": return styleSet.markerGlyphs?.chars.has(text[0]) ? {
1333
+ ...style,
1334
+ fontFamily: styleSet.markerGlyphs.fontFamily
1335
+ } : style;
1336
+ }
1337
+ const rule = extra?.[mark] ?? styleSet.marks[mark];
1338
+ if (!rule) return void 0;
1339
+ const color = rule.color && colorOf(rule.color);
1340
+ return {
1341
+ ...style,
1342
+ ...rule,
1343
+ ...color ? { color } : {}
1344
+ };
1345
+ }
1346
+ /** The look of a list of marks, later ones winning; a mark that does not
1347
+ * exist changes nothing (`unknownMarks` reports it). */
1348
+ function styleOf(text, marks, styleSet, extra) {
1349
+ return marks.reduce((style, mark) => withMark(style, mark, text, styleSet, extra) ?? style, {});
1350
+ }
1351
+ /** The look of comma-separated marks (`red,sc`), for a host styling prose
1352
+ * to match the score. */
1353
+ function resolveMarks(marks, styleSet, extra) {
1354
+ return styleOf("", marks.split(",").map((mark) => mark.trim()), styleSet, extra);
1355
+ }
1356
+ /** The marks of `marks` that neither the primitives, the style set nor
1357
+ * `extra` define. */
1358
+ function unknownMarks(marks, styleSet, extra) {
1359
+ return marks.filter((mark) => withMark({}, mark, "", styleSet, extra) === void 0);
1360
+ }
1361
+ /** A run's small-caps split: lowercase letters as small capitals, in runs
1362
+ * of their own, everything else at full size. */
1363
+ function splitSmallCaps(text) {
1364
+ const pieces = [];
1365
+ for (const ch of text) {
1366
+ const small = ch.toUpperCase() !== ch;
1367
+ const last = pieces[pieces.length - 1];
1368
+ if (last && last.small === small) last.text += ch;
1369
+ else pieces.push({
1370
+ text: ch,
1371
+ small
1372
+ });
1373
+ }
1374
+ return pieces;
1375
+ }
1376
+ /** Resolves parsed text runs (`SyllableToken.runs`) into how a style set
1377
+ * draws them: each run takes the style of its marks, the `bold` option
1378
+ * forces weight 700 onto every run, and `kind` names its notation-fixed
1379
+ * semantic (`liturgy`, `rubric`, `star`, `marker`, `plus`), the vocabulary
1380
+ * the marked-up text export and the renderer's run classes share. A
1381
+ * small-caps run splits into full and small parts. Text stays as written:
1382
+ * capitals are the part's display (`drawnText`). */
1383
+ function resolveTextRuns(runs, styleSet, bold, extra) {
1384
+ return runs.flatMap(({ text, marks }) => {
1385
+ const resolved = styleOf(text, marks, styleSet, extra);
1386
+ const style = bold ? {
1387
+ ...resolved,
1388
+ weight: "700"
1389
+ } : resolved;
1390
+ const kind = kindOf(marks);
1391
+ if (!style.smallCaps) return [{
1392
+ text,
1393
+ style,
1394
+ kind
1395
+ }];
1396
+ const full = {
1397
+ ...style,
1398
+ smallCaps: void 0
1399
+ };
1400
+ return splitSmallCaps(text).map((piece) => ({
1401
+ text: piece.text,
1402
+ kind,
1403
+ style: piece.small ? {
1404
+ ...full,
1405
+ smallCaps: true,
1406
+ uppercase: true,
1407
+ scale: (full.scale ?? 1) * SMALL_CAP_SCALE,
1408
+ measureScale: void 0
1409
+ } : full
1410
+ }));
1411
+ });
1412
+ }
1413
+ /** The characters a part draws, which measuring must see. */
1414
+ function drawnText(part) {
1415
+ return part.style.uppercase ? part.text.toUpperCase() : part.text;
1416
+ }
1417
+ /** Parses a syllable as written (`SyllableToken.source`) and resolves its
1418
+ * runs in one step (see `resolveSpans`, `resolveTextRuns`). */
1419
+ function resolveSyllableParts(written, styleSet, bold, extra) {
1420
+ return resolveTextRuns(resolveSpans([written]).pieces[0].runs, styleSet, bold, extra);
1421
+ }
1422
+ /** The canvas font shorthand for measuring a run at the text size. */
1423
+ /** A font family name as typed, or undefined when it cannot be one: empty,
1424
+ * too long, or with quotes or CSS punctuation in it. */
1425
+ function cleanFontName(name) {
1426
+ const trimmed = (name ?? "").trim().replace(/\s+/g, " ");
1427
+ return trimmed && trimmed.length <= 80 && !/["'`;{}<>\\]/.test(trimmed) ? trimmed : void 0;
1428
+ }
1429
+ /** The text font stack with `textFont` in front, the style set's own stack
1430
+ * after it as the fallback. */
1431
+ function textFontStackOf(styleSet, textFont) {
1432
+ const name = cleanFontName(textFont);
1433
+ return name ? `"${name}", ${styleSet.textFontStack}` : styleSet.textFontStack;
1434
+ }
1435
+ function measurementFont(style, textPx, fallbackStack) {
1436
+ return [
1437
+ style.italic ? "italic" : "normal",
1438
+ "normal",
1439
+ style.weight ?? "400",
1440
+ `${textPx * (style.measureScale ?? style.scale ?? 1)}px`,
1441
+ style.fontFamily ?? fallbackStack
1442
+ ].join(" ");
1443
+ }
1444
+ /** The inline CSS properties that draw a run, as dash-cased names for
1445
+ * CSSStyleDeclaration.setProperty. */
1446
+ function inlineStylesFor(style, textPx) {
1447
+ const styles = {};
1448
+ if (style.fontFamily) styles["font-family"] = style.fontFamily;
1449
+ if (style.weight) styles["font-weight"] = style.weight;
1450
+ if (style.italic) styles["font-style"] = "italic";
1451
+ if (style.scale !== void 0) styles["font-size"] = `${textPx * style.scale}px`;
1452
+ if (style.color) styles["color"] = style.color;
1453
+ if (style.uppercase) styles["text-transform"] = "uppercase";
1454
+ if (style.underline) styles["text-decoration"] = "underline";
1455
+ if (style.raise) {
1456
+ styles["position"] = "relative";
1457
+ styles["top"] = `${-textPx * style.raise}px`;
1458
+ }
1459
+ return styles;
1460
+ }
1461
+ /** The font strings render() must load and verify for a style set. */
1462
+ function fontStringsToVerify(styleSet, textPx) {
1463
+ return styleSet.verifiedFonts.map((f) => `${f.weight} ${textPx}px ${f.family}`);
1464
+ }
1465
+ //#endregion
1466
+ export { splitNoteMarkers as A, modifyUp as B, scriptSyllables as C, resolveSpans as D, unescape as E, gClefPitchOf as F, toSmallHead as G, toCephalicus as H, isClefGlyph as I, variantOf as J, toSmallPoint as K, isModifierGlyph as L, STAFF as M, baseOf as N, MARKER_CHARS$1 as O, bracketedAccidentalLength as P, modifyDown as R, runProperties as S, syllableText as T, toConnectDown as U, pitchLetterOf as V, toLonga as W, GuidoScript as _, defineStyleSet as a, isC4ClefGroup as b, inlineStylesFor as c, resolveMarks as d, resolveSyllableParts as f, unknownMarks as g, textFontStackOf as h, cleanFontName as i, CLEF_GLYPHS as j, SCORE_MARKERS as k, kindOf as l, styleSetOf as m, SMALL_CAP_SCALE as n, drawnText as o, resolveTextRuns as p, toVirga as q, STYLE_SETS as r, fontStringsToVerify as s, DEFAULT_STYLE_SET as t, measurementFont as u, chantText as v, statementSource as w, isStatementGroup as x, escape as y, modifyNatural as z };