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
@@ -1,2616 +0,0 @@
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 bracket pairs that set a cautionary accidental off (issue #95). */
284
- var ACCIDENTAL_BRACKETS = /* @__PURE__ */ new Map([
285
- ["Â", "Ã"],
286
- ["Ä", "Å"],
287
- ["Æ", "Ç"]
288
- ]);
289
- /**
290
- * The length of the bracketed accidental that opens `notes` at `from`:
291
- * an opening bracket, one or more accidental signs, the matching closing
292
- * bracket, and the `¨`/`-` spacing right after it (`ÄôŨ¨` in `ÄôŨ¨õ`).
293
- * 0 when no such unit stands there.
294
- */
295
- function bracketedAccidentalLength(notes, from = 0) {
296
- const close = ACCIDENTAL_BRACKETS.get(notes[from] ?? "");
297
- if (close === void 0) return 0;
298
- let at = from + 1;
299
- while (at < notes.length && isModifierGlyph(notes[at])) at++;
300
- if (at === from + 1 || notes[at] !== close) return 0;
301
- at++;
302
- while (notes[at] === "¨" || notes[at] === "-") at++;
303
- return at - from;
304
- }
305
- /** The clef glyphs (issue #49) and the staff line each one sits on,
306
- * counted from the bottom. The g-clef has two keybindings. */
307
- var CLEF_GLYPHS = {
308
- ">": {
309
- clef: "c",
310
- line: 1
311
- },
312
- "#": {
313
- clef: "c",
314
- line: 2
315
- },
316
- "&": {
317
- clef: "c",
318
- line: 3
319
- },
320
- "@": {
321
- clef: "c",
322
- line: 4
323
- },
324
- "{": {
325
- clef: "f",
326
- line: 3
327
- },
328
- "}": {
329
- clef: "f",
330
- line: 4
331
- },
332
- M: {
333
- clef: "g",
334
- line: 2
335
- },
336
- "<": {
337
- clef: "g",
338
- line: 2
339
- }
340
- };
341
- /** Whether `ch` is a clef glyph. */
342
- function isClefGlyph(ch) {
343
- return Object.hasOwn(CLEF_GLYPHS, ch);
344
- }
345
- /** The base pitch glyphs from low to high, one per staff position
346
- * (spelled out: `Object.keys` would list the digit keys first). The
347
- * index is the staff position the exact transposition counts with. */
348
- var STAFF = [..."ðñ0123456789öüó"];
349
- var LETTERS = "abcdefg";
350
- /** The pitch letter (`a`…`g`, octave dropped) of a pitch glyph — a base
351
- * glyph or any of its variants — under `clef` (a clef glyph; default the
352
- * standard g-clef). Undefined when the glyph has no pitch or the clef
353
- * glyph is unknown. */
354
- function pitchLetterOf(ch, clef = "M") {
355
- const position = STAFF.indexOf(STAFF.includes(ch) ? ch : baseOf(ch)?.base ?? "");
356
- const entry = CLEF_GLYPHS[clef];
357
- if (position < 0 || !entry) return void 0;
358
- const linePosition = STAFF.indexOf("2") + 2 * (entry.line - 1);
359
- const shift = LETTERS.indexOf(entry.clef) - LETTERS.indexOf(gClefPitchOf(STAFF[linePosition])[0]);
360
- return LETTERS[((LETTERS.indexOf(gClefPitchOf(STAFF[position])[0]) + shift) % 7 + 7) % 7];
361
- }
362
- //#endregion
363
- //#region src/noteGroups.ts
364
- /**
365
- * Note-group anatomy shared by the layout pass and the exact
366
- * transposition: the score markers and the split of a group into its
367
- * leading markers, notes and trailing markers. Kept free of imports, so
368
- * the transforms can use it without pulling in the style sets.
369
- */
370
- /**
371
- * Score marker characters: they carry no pitch, and when they sit at the
372
- * start or end of a note group (with the adjacent dash) they act as
373
- * whitespace rather than note width.
374
- */
375
- var SCORE_MARKERS = ",.:?'\"+!%/=()ÖÜÓ;";
376
- var MARKER_CHARS$1 = new Set(SCORE_MARKERS.split(""));
377
- function splitNoteMarkers(notes) {
378
- let start = 0;
379
- while (start < notes.length && MARKER_CHARS$1.has(notes[start])) start++;
380
- if (start > 0 && start < notes.length) start = notes[start] === "-" ? start + 1 : 0;
381
- let end = notes.length;
382
- while (end > start && MARKER_CHARS$1.has(notes[end - 1])) end--;
383
- if (end < notes.length && end > start) end = notes[end - 1] === "-" ? end - 1 : notes.length;
384
- return {
385
- leading: notes.slice(0, start),
386
- core: notes.slice(start, end),
387
- trailing: notes.slice(end)
388
- };
389
- }
390
- //#endregion
391
- //#region src/textMarkup.ts
392
- /** The pause-marker characters: they split off into runs of their own. */
393
- var MARKER_CHARS = /* @__PURE__ */ new Set(["*", "†"]);
394
- /** The marks that take an argument, written `size:0.8`. */
395
- var MARK_ARGUMENTS = /* @__PURE__ */ new Set([
396
- "color",
397
- "size",
398
- "raise",
399
- "font"
400
- ]);
401
- /** Stand-ins for escaped markup characters, from the private use area:
402
- * the matching below never mistakes them for markup. Only ever held by a
403
- * masked string, inside the functions that work on one. */
404
- var MASKED = {
405
- _: "",
406
- "*": "",
407
- "†": "",
408
- "∗": ""
409
- };
410
- var UNMASKED = new Map(Object.entries(MASKED).map(([ch, mask]) => [mask, ch]));
411
- function maskEscapes(written) {
412
- return written.replace(/\\(.)/gsu, (_, ch) => MASKED[ch] ?? ch);
413
- }
414
- function unmask(masked) {
415
- return masked.replace(/[-]/g, (mask) => UNMASKED.get(mask));
416
- }
417
- /** The whole-syllable wrapper of masked text, the longer `__` first so
418
- * `__V.__` never matches the `_` rubric rule: the same characters on both
419
- * ends, content between. */
420
- function wrapperOf(masked) {
421
- return ["__", "_"].find((wrapper) => masked.length >= wrapper.length * 2 + 1 && masked.startsWith(wrapper) && masked.endsWith(wrapper));
422
- }
423
- /** The `*…*` initial pairs of masked text, as segments: only non-empty
424
- * pairs count, so an unmatched (or doubled) star stays a character. */
425
- function initialSegments(masked) {
426
- const segments = [];
427
- let rest = masked;
428
- let plain = "";
429
- for (let m = /\*([^*]+)\*/.exec(rest); m; m = /\*([^*]+)\*/.exec(rest)) {
430
- plain += rest.slice(0, m.index);
431
- if (plain) {
432
- segments.push({
433
- text: plain,
434
- initial: false
435
- });
436
- plain = "";
437
- }
438
- segments.push({
439
- text: m[1],
440
- initial: true
441
- });
442
- rest = rest.slice(m.index + m[0].length);
443
- }
444
- plain += rest;
445
- if (plain) segments.push({
446
- text: plain,
447
- initial: false
448
- });
449
- return segments;
450
- }
451
- /** Splits one segment's characters into its plain, marker and plus runs. */
452
- function splitGlyphRuns(text, marks, liturgy) {
453
- const glyphOf = (ch) => MARKER_CHARS.has(ch) ? "marker" : liturgy && ch === "+" ? "plus" : void 0;
454
- const runs = [];
455
- for (const ch of text) {
456
- const glyph = glyphOf(ch);
457
- const last = runs[runs.length - 1];
458
- if (last && last.glyph === glyph) last.text += ch;
459
- else runs.push({
460
- text: ch,
461
- glyph
462
- });
463
- }
464
- return runs.map((run) => ({
465
- text: run.text,
466
- marks: run.glyph ? [...marks, run.glyph] : [...marks]
467
- }));
468
- }
469
- /**
470
- * Parses text with no `{…}` span in it into the runs it draws: the
471
- * whole-syllable `**` star (drawn as ∗), a `__…__` or `_…_` wrapper around
472
- * all of it, paired `*` markers around any part of it (`*sam*ple` → "sam"
473
- * and "ple"), and the marker characters and a Liturgy run's `+` split off.
474
- * The wrapper characters are dropped; escaped characters are literal.
475
- */
476
- function parseTextRuns(written) {
477
- if (written.length === 0) return [];
478
- const masked = maskEscapes(written);
479
- if (masked === "**") return [{
480
- text: "∗",
481
- marks: ["star"]
482
- }];
483
- const wrapper = wrapperOf(masked);
484
- const content = wrapper ? masked.slice(wrapper.length, -wrapper.length) : masked;
485
- const base = wrapper ? [wrapper === "__" ? "liturgy" : "rubric"] : [];
486
- return initialSegments(content).flatMap(({ text, initial }) => splitGlyphRuns(unmask(text), initial ? [...base, "initial"] : base, wrapper === "__"));
487
- }
488
- /** The text to read from text with no span in it: every unescaped markup
489
- * character and sign gone, escapes folded. Empty for a sign alone. */
490
- function plainText(written) {
491
- return unmask(maskEscapes(written).replace(/[_*†∗]/g, ""));
492
- }
493
- /** The marks of a span's opening, read just past its `{`: comma-separated
494
- * names, those of `MARK_ARGUMENTS` with a `:argument`, closed by a colon.
495
- * Returns undefined when the text does not start with such a list. */
496
- function spanHead(text) {
497
- const marks = [];
498
- let at = 0;
499
- for (;;) {
500
- const name = /^[A-Za-z][\w-]*/.exec(text.slice(at))?.[0];
501
- if (!name) return void 0;
502
- at += name.length;
503
- if (text[at] === ":" && MARK_ARGUMENTS.has(name)) {
504
- const argument = /^[^\s,:{}]+/.exec(text.slice(at + 1))?.[0];
505
- if (!argument) return void 0;
506
- marks.push(`${name}:${argument}`);
507
- at += 1 + argument.length;
508
- } else marks.push(name);
509
- if (text[at] === ":") return {
510
- marks,
511
- length: at + 1
512
- };
513
- if (text[at] !== ",") return void 0;
514
- at += 1;
515
- }
516
- }
517
- /** Splits text into what stands between its braces, and its braces. */
518
- function lexSpans(text) {
519
- const lexemes = [];
520
- let written = "";
521
- const flush = () => {
522
- if (written) lexemes.push({
523
- type: "text",
524
- written
525
- });
526
- written = "";
527
- };
528
- for (let i = 0; i < text.length; i++) {
529
- const ch = text[i];
530
- if (ch === "\\" && i + 1 < text.length) written += ch + text[++i];
531
- else if (ch === "{") {
532
- flush();
533
- const head = spanHead(text.slice(i + 1));
534
- lexemes.push({
535
- type: "open",
536
- marks: head?.marks
537
- });
538
- if (head) i += head.length;
539
- } else if (ch === "}") {
540
- flush();
541
- lexemes.push({ type: "close" });
542
- } else written += ch;
543
- }
544
- flush();
545
- return lexemes;
546
- }
547
- /**
548
- * Resolves the `{…}` spans of consecutive pieces of text, which may open in
549
- * one piece and close in a later one. A malformed span, a span never closed
550
- * and a stray `}` are reported in `problems`; their text stays, plain, and
551
- * their braces go, so no punctuation prints.
552
- */
553
- function resolveSpans(pieces) {
554
- const problems = [];
555
- const lexed = pieces.map(lexSpans);
556
- const opens = /* @__PURE__ */ new Map();
557
- const stack = [];
558
- const strays = /* @__PURE__ */ new Set();
559
- for (const [p, lexemes] of lexed.entries()) for (const lexeme of lexemes) if (lexeme.type === "open") {
560
- if (!lexeme.marks) problems.push({
561
- kind: "span",
562
- text: pieces[p].trim(),
563
- message: `A "{" needs its marks and a colon, as in "{red:text}" (in "${pieces[p].trim()}")`
564
- });
565
- const span = { marks: lexeme.marks ?? [] };
566
- opens.set(lexeme, span);
567
- stack.push(span);
568
- } else if (lexeme.type === "close" && !stack.pop()) {
569
- strays.add(lexeme);
570
- problems.push({
571
- kind: "span",
572
- text: pieces[p].trim(),
573
- message: `A "}" closes nothing (in "${pieces[p].trim()}")`
574
- });
575
- }
576
- for (const span of stack) {
577
- if (span.marks.length > 0) problems.push({
578
- kind: "span",
579
- text: span.marks.join(","),
580
- message: `The span "{${span.marks.join(",")}:" is never closed`
581
- });
582
- span.marks = [];
583
- }
584
- const open = [];
585
- const resolved = [];
586
- let lastVisible;
587
- for (const [p, lexemes] of lexed.entries()) {
588
- const crossesIn = open.length > 0;
589
- const segments = [];
590
- const piece = {
591
- bare: "",
592
- source: "",
593
- runs: [],
594
- text: ""
595
- };
596
- for (const lexeme of lexemes) if (lexeme.type === "open") open.push(opens.get(lexeme));
597
- else if (lexeme.type === "close") {
598
- if (!strays.has(lexeme)) open.pop();
599
- } else segments.push({
600
- marks: open.flatMap((span) => span.marks),
601
- written: lexeme.written
602
- });
603
- piece.bare = segments.map((s) => s.written).join("");
604
- const body = trimSegments(segments);
605
- piece.runs = body.flatMap(({ marks, written }) => parseTextRuns(written).map((run) => ({
606
- text: run.text,
607
- marks: [...marks, ...run.marks]
608
- })));
609
- piece.text = body.map(({ written }) => plainText(written)).join("");
610
- const dropped = lexemes.some((l) => strays.has(l) || l.type === "open" && opens.get(l).marks.length === 0);
611
- const live = lexemes.some((l) => l.type === "open" || l.type === "close");
612
- piece.source = crossesIn || open.length > 0 || dropped || live && piece.bare.trim() === "" ? body.map(({ marks, written }) => marks.length > 0 ? `{${marks.join(",")}:${written}}` : written).join("") : pieces[p].trim();
613
- const visible = body.filter((s) => s.written.trim() !== "");
614
- if (visible.length > 0) {
615
- if (lastVisible) {
616
- const next = new Set(visible[0].marks);
617
- const shared = lastVisible.marks.filter((mark) => next.has(mark));
618
- if (shared.length > 0) lastVisible.piece.hyphen = shared;
619
- }
620
- lastVisible = {
621
- piece,
622
- marks: visible[visible.length - 1].marks
623
- };
624
- }
625
- resolved.push(piece);
626
- }
627
- return {
628
- pieces: resolved,
629
- problems
630
- };
631
- }
632
- /** The segments with the piece's outer whitespace gone. */
633
- function trimSegments(segments) {
634
- const body = segments.map((s) => ({ ...s }));
635
- const first = body[0];
636
- const last = body[body.length - 1];
637
- if (first) first.written = first.written.trimStart();
638
- if (last) last.written = last.written.trimEnd();
639
- return body.filter((s) => s.written !== "");
640
- }
641
- //#endregion
642
- //#region src/guidoScript.ts
643
- /**
644
- * A Guido script: the compact chant notation where pitches, neume shapes,
645
- * and rhythm are packed into short character sequences, e.g.
646
- *
647
- * (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-.)
648
- *
649
- * The first parenthesized group, when present, is the starting clef and
650
- * note modifiers. After that the source alternates syllable-first:
651
- *
652
- * (clef) syllable(notes) syllable(notes) ...
653
- *
654
- * Word boundaries are carried by whitespace in the source: a syllable
655
- * after which the source has a space ends a word.
656
- *
657
- * A note group with no text in front of it is held by the syllable
658
- * before it (issue #83): `mé(3)(tT4R3E2)` sings `mé` on both groups. The
659
- * held group stays a token of its own (`text: ''`, `held: true`), so
660
- * every group is one slot and formatting still resolves on each
661
- * syllable's own text. A syllable whose whole text is `~` is an empty
662
- * slot (`empty: true`): notes, but no syllable — and so is a text-less
663
- * group at the very start of the script.
664
- *
665
- * The parentheses and backslash are control characters, so literal ones
666
- * in the syllable text are typed as backslash escapes: `\(`, `\)` and
667
- * `\\` stand for `(`, `)` and `\`.
668
- *
669
- * Control statements are groups whose content is an `@`-keyword with
670
- * optional arguments after one space: `(@break)` ends the current line
671
- * pair at its position, `(@clef MX)` changes the clef (and key) inline,
672
- * `(@key X)` replaces the key and `(@key)` clears it. `(@tight)` tightens
673
- * the junctions up to `(@tight off)`, `(@keep)` keeps its run on one line
674
- * up to `(@keep off)`, and `(@unit)` / `(@unit off)` do both. Statements are
675
- * positional — the text run before one must be whitespace-only — and
676
- * they are invisible to the sung-text accessors.
677
- *
678
- * `(@stanza …)` statements (issue #69) stand at the very end of the
679
- * script, one per further stanza (2, 3, …) in order. Their text is
680
- * syllabified stanza text (see `parseStanza` in stanzas.ts), kept raw —
681
- * escapes included — and listed by `stanzas`; they are not tokens, so
682
- * nothing that walks the tokens (the layout, the sung-text accessors)
683
- * ever sees them.
684
- *
685
- * `@` is also the c4 clef glyph: an opening group of `@` and nothing but
686
- * modifier glyphs (`(@)`, `(@X)`) is the opening clef, not a statement.
687
- */
688
- /** The run properties a run statement sets. */
689
- function runProperties(kind) {
690
- return kind === "unit" ? ["tight", "keep"] : [kind];
691
- }
692
- /** Whether a group's content is a control statement (`@`-keyword,
693
- * trimmed). Shared with the transforms, which must leave statement
694
- * groups alone — their keyword characters are pitch glyphs otherwise.
695
- * A c4 clef group (`@` + modifier glyphs) counts too: the opening one is
696
- * told apart by `isC4ClefGroup`, and mid-script it is an error. */
697
- function isStatementGroup(content) {
698
- return content.trim().startsWith("@");
699
- }
700
- /** Whether a group's content has the shape of a c4 clef group: `@`
701
- * followed by nothing but modifier glyphs. Statement keywords never
702
- * consist solely of modifier glyphs, so the two cannot collide. */
703
- function isC4ClefGroup(content) {
704
- const [at, ...key] = content;
705
- return at === "@" && key.every(isModifierGlyph);
706
- }
707
- /** Whether the leading group is the opening clef: anything but a
708
- * statement, and the c4 clef despite its `@`. */
709
- function isOpeningClef(content) {
710
- return !isStatementGroup(content) || isC4ClefGroup(content);
711
- }
712
- /** Parses a key argument: modifier glyphs only. */
713
- function parseKey(glyphs, statement) {
714
- for (const ch of glyphs) if (!isModifierGlyph(ch)) throw new Error(`"${ch}" is not a key modifier glyph in "${statement}"`);
715
- return glyphs;
716
- }
717
- /** Parses one statement group's content into its token (without
718
- * `spaceBefore`). Throws on an unknown keyword or a bad argument. */
719
- function parseStatement(content) {
720
- const statement = content.trim();
721
- if (isC4ClefGroup(statement)) throw new Error(`a clef group is only allowed at the start; write "(@clef ${statement})" to change the clef`);
722
- const [, keyword, args = ""] = statement.match(/^@(\S*)(?: (.*))?$/) ?? [];
723
- switch (keyword) {
724
- case "break":
725
- if (args !== "") throw new Error(`"@break" takes no argument: "${statement}"`);
726
- return { kind: "break" };
727
- case "clef": {
728
- const [clef, ...key] = args;
729
- if (clef === void 0) throw new Error("\"@clef\" needs a clef group argument, e.g. \"(@clef MX)\"");
730
- if (!isClefGlyph(clef)) throw new Error(`"${clef}" is not a clef glyph in "${statement}"`);
731
- return {
732
- kind: "clef",
733
- clef,
734
- key: parseKey(key.join(""), statement)
735
- };
736
- }
737
- case "key": return {
738
- kind: "key",
739
- key: parseKey(args, statement)
740
- };
741
- case "tight":
742
- case "keep":
743
- case "unit":
744
- case "aid":
745
- if (args !== "" && args !== "off") throw new Error(`"@${keyword}" takes only "off": "${statement}"`);
746
- return {
747
- kind: keyword,
748
- on: args === ""
749
- };
750
- default: throw new Error(`Unknown statement "${statement}"`);
751
- }
752
- }
753
- /** A statement token written back as its group. */
754
- function statementSource(tok) {
755
- switch (tok.kind) {
756
- case "break": return "(@break)";
757
- case "clef": return `(@clef ${tok.clef}${tok.key})`;
758
- case "key": return tok.key === "" ? "(@key)" : `(@key ${tok.key})`;
759
- case "tight":
760
- case "keep":
761
- case "unit":
762
- case "aid": return tok.on ? `(@${tok.kind})` : `(@${tok.kind} off)`;
763
- }
764
- }
765
- /** The stanza text of a `(@stanza …)` statement's trimmed content, or
766
- * undefined when the statement is something else. */
767
- function stanzaStatementText(statement) {
768
- const match = statement.match(/^@stanza(?:\s+([\s\S]*))?$/);
769
- return match ? match[1] ?? "" : void 0;
770
- }
771
- var GuidoScript = class {
772
- source;
773
- constructor(source, options = {}) {
774
- this.source = (options.transforms ?? []).reduce((script, transform) => transform.apply(script), source);
775
- }
776
- /** The starting clef and note modifiers, or undefined when absent.
777
- * A leading statement group is not a clef. */
778
- get clef() {
779
- const match = this.normalized.match(/^\s*\(([^)]*)\)/);
780
- if (!match || !isOpeningClef(match[1])) return void 0;
781
- return match[1];
782
- }
783
- /** The script's tokens in source order: syllables interleaved with
784
- * control statements. Throws on a malformed statement (syllable text
785
- * attached to one, or an unknown `@` keyword). */
786
- get tokens() {
787
- return this.parse().tokens;
788
- }
789
- /** The raw text of the `(@stanza …)` statements at the end of the
790
- * script — stanzas 2, 3, … in order, escapes kept (the stanza text
791
- * grammar folds them). Throws like `tokens` on a malformed script,
792
- * and when anything but another stanza follows a stanza statement. */
793
- get stanzas() {
794
- return this.parse().stanzas;
795
- }
796
- /** Where each token stands in the source, parallel to `tokens`:
797
- * offsets of its text (past leading whitespace), of its group's
798
- * content and just past its group's `)`. The walker
799
- * (`scriptSyllables`) reads them. */
800
- get tokenSpans() {
801
- return this.parse().spans;
802
- }
803
- /** What is wrong with the script's `{…}` spans: such a span renders
804
- * plainly instead of failing the score. */
805
- get spanProblems() {
806
- return this.parse().problems;
807
- }
808
- parse() {
809
- const script = this.normalized;
810
- const head = script.match(/^\s*\(([^)]*)\)/);
811
- const skipped = head && isOpeningClef(head[1]) ? head[0].length : 0;
812
- const matches = [...script.slice(skipped).matchAll(/((?:[^()\\]|\\.)*)\(((?:[^)\\]|\\.)*)\)/g)];
813
- const resolved = resolveSpans(matches.map((match) => match[1]));
814
- let prev;
815
- const stanzas = [];
816
- const tokens = [];
817
- const spans = [];
818
- for (const [m, match] of matches.entries()) {
819
- const [, written, notes] = match;
820
- const piece = resolved.pieces[m];
821
- const text = piece.bare;
822
- const at = skipped + match.index;
823
- const notesStart = at + written.length + 1;
824
- const span = {
825
- start: at + (written.length - written.trimStart().length),
826
- notesStart,
827
- notesEnd: notesStart + notes.length,
828
- end: notesStart + notes.length + 1
829
- };
830
- const stanza = isStatementGroup(notes) ? stanzaStatementText(notes.trim()) : void 0;
831
- if (stanza !== void 0) {
832
- if (text.trim() !== "") throw new Error(`statement must not carry syllable text: "${unescape(text.trim())}"`);
833
- stanzas.push(stanza);
834
- continue;
835
- }
836
- if (stanzas.length > 0) {
837
- if (text.trim() === "" && notes === "") continue;
838
- throw new Error("\"(@stanza …)\" statements must stand at the end of the script");
839
- }
840
- if (isStatementGroup(notes)) {
841
- const statement = parseStatement(notes);
842
- if (text.trim() !== "") throw new Error(`statement must not carry syllable text: "${unescape(text.trim())}"`);
843
- tokens.push({
844
- ...statement,
845
- spaceBefore: /^\s/.test(text)
846
- });
847
- spans.push(span);
848
- continue;
849
- }
850
- const raw = text.trim();
851
- if (raw === "" && notes === "" && written.trim() !== "") continue;
852
- const tok = {
853
- kind: "syllable",
854
- ...textFields(raw === "~" ? NO_TEXT : piece),
855
- role: "sung",
856
- notes: unescape(notes),
857
- spaceBefore: /^\s/.test(text)
858
- };
859
- if (raw === "~" || raw === "" && prev === void 0 && tok.notes !== "") tok.empty = true;
860
- else if (raw === "" && tok.notes !== "") {
861
- 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`);
862
- tok.held = true;
863
- }
864
- prev = tok;
865
- tokens.push(tok);
866
- spans.push(span);
867
- }
868
- let holder;
869
- for (const [i, t] of tokens.entries()) {
870
- if (t.kind !== "syllable") continue;
871
- if (t.held) {
872
- t.wordEnd = holder.wordEnd;
873
- continue;
874
- }
875
- t.wordEnd = true;
876
- let space = false;
877
- for (let j = i + 1; j < tokens.length; j++) {
878
- const tok = tokens[j];
879
- if (tok.spaceBefore) space = true;
880
- if (tok.kind === "syllable" && !tok.held && !tok.empty) {
881
- t.wordEnd = space;
882
- break;
883
- }
884
- }
885
- holder = t;
886
- }
887
- assignRoles(tokens);
888
- return {
889
- tokens,
890
- stanzas,
891
- spans,
892
- problems: resolved.problems
893
- };
894
- }
895
- /** The script broken into syllables, each with its sung text and
896
- * notes — the syllable tokens, statements filtered out. */
897
- get syllables() {
898
- return this.tokens.filter((t) => t.kind === "syllable").map(({ text, notes, wordEnd, held, empty }) => ({
899
- text,
900
- notes,
901
- wordEnd,
902
- ...held ? { held } : {},
903
- ...empty ? { empty } : {}
904
- }));
905
- }
906
- /**
907
- * The source with the typing conveniences folded in, so the parser
908
- * itself only ever sees complete scripts:
909
- *
910
- * - an unclosed parenthesis is closed at the end, so the notes typed
911
- * so far already preview on the score;
912
- * - a trailing syllable with no note group gets an empty one, so it
913
- * renders like a `*()` syllable (text without notes width).
914
- */
915
- get normalized() {
916
- let script = this.source;
917
- if ((script.match(/(^|[^\\])\(/g) ?? []).length > (script.match(/(^|[^\\])\)/g) ?? []).length) script += ")";
918
- if (!/(^|[^\\])\)$/.test(script)) script += "()";
919
- return script;
920
- }
921
- /** The syllables grouped into the words of the text. Held groups and
922
- * empty slots sing no syllable of their own, so they are left out. */
923
- get words() {
924
- const words = [];
925
- let word;
926
- for (const syl of this.tokens) {
927
- if (syl.kind !== "syllable" || syl.held || syl.empty) continue;
928
- word ??= {
929
- text: "",
930
- syllables: []
931
- };
932
- const { text, source, runs, role, notes } = syl;
933
- word.syllables.push({
934
- text,
935
- source,
936
- runs,
937
- role,
938
- notes
939
- });
940
- word.text = word.syllables.map((s) => s.text).join("");
941
- if (syl.wordEnd) {
942
- words.push(word);
943
- word = void 0;
944
- }
945
- }
946
- return words;
947
- }
948
- /** The script rebuilt from the parsed pieces — a round-trip of the
949
- * source, statements and stanzas included. */
950
- toString() {
951
- const parts = this.tokens.map((tok, i) => {
952
- const prefix = i > 0 && tok.spaceBefore ? " " : "";
953
- return tok.kind === "syllable" ? `${prefix}${tok.empty ? "~" : tok.source}(${escape(tok.notes)})` : `${prefix}${statementSource(tok)}`;
954
- });
955
- const stanzas = this.stanzas.map((text) => `(@stanza ${text})`);
956
- return `${this.clef !== void 0 ? `(${this.clef})` : ""}${parts.join("")}${stanzas.join("")}`;
957
- }
958
- };
959
- /** The roles `scriptSyllables` lists by default: what is sung. */
960
- var SUNG_ROLES = ["sung", "aid"];
961
- /**
962
- * The syllables of a script, in order: by default the sung ones, labels and
963
- * signs left out (`roles` chooses others). Held groups ride on their
964
- * syllable (`held`); `~` empty slots, statements and `(@stanza …)` are
965
- * skipped. Word starts and ends are the listed syllables' own, so a word
966
- * end on a left-out syllable lands on the one before it. Offsets index the
967
- * script's source; index i is the "syllable i" of `composeScript`'s
968
- * `from`/`to`.
969
- */
970
- function scriptSyllables(script, options = {}) {
971
- const parsed = typeof script === "string" ? new GuidoScript(script) : script;
972
- const roles = options.roles ?? SUNG_ROLES;
973
- const tokens = parsed.tokens;
974
- const spans = parsed.tokenSpans;
975
- const all = [];
976
- let holder;
977
- for (const [i, tok] of tokens.entries()) {
978
- if (tok.kind !== "syllable") continue;
979
- if (tok.empty) {
980
- holder = void 0;
981
- continue;
982
- }
983
- if (tok.held) {
984
- if (holder) {
985
- holder.held.push(tok.notes);
986
- holder.end = spans[i].end;
987
- }
988
- continue;
989
- }
990
- const span = spans[i];
991
- holder = {
992
- text: tok.text,
993
- source: tok.source,
994
- role: tok.role,
995
- notes: tok.notes,
996
- held: [],
997
- wordStart: false,
998
- wordEnd: tok.wordEnd,
999
- start: span.start,
1000
- notesStart: span.notesStart,
1001
- notesEnd: span.notesEnd,
1002
- end: span.end,
1003
- token: i
1004
- };
1005
- all.push(holder);
1006
- }
1007
- const listed = [];
1008
- let atWordStart = true;
1009
- for (const syl of all) if (roles.includes(syl.role)) {
1010
- syl.wordStart = atWordStart;
1011
- listed.push(syl);
1012
- atWordStart = syl.wordEnd;
1013
- } else if (syl.wordEnd) {
1014
- if (listed.length > 0) listed[listed.length - 1].wordEnd = true;
1015
- atWordStart = true;
1016
- }
1017
- return listed;
1018
- }
1019
- /** The text of the script to read: the sung words joined with single
1020
- * spaces, with no markup, labels, signs or aids in them. Characters the
1021
- * author escaped stay. */
1022
- function chantText(script, options = {}) {
1023
- const roles = ["sung"];
1024
- if (options.labels) roles.push("label");
1025
- if (options.aids) roles.push("aid");
1026
- return scriptSyllables(script, { roles }).map((syl) => (syl.wordStart ? " " : "") + syl.text).join("").replace(/ +/g, " ").trim();
1027
- }
1028
- /** A text with nothing in it. */
1029
- var NO_TEXT = {
1030
- bare: "",
1031
- source: "",
1032
- runs: [],
1033
- text: ""
1034
- };
1035
- /** A syllable's text fields, from its resolved text. */
1036
- function textFields(piece) {
1037
- const { text, source, runs, hyphen } = piece;
1038
- return {
1039
- text,
1040
- source,
1041
- runs,
1042
- ...hyphen ? { hyphen } : {}
1043
- };
1044
- }
1045
- /** A syllable's text fields, from text written on its own. */
1046
- function syllableText(written) {
1047
- return textFields(resolveSpans([written]).pieces[0]);
1048
- }
1049
- var LABEL_MARKS = ["liturgy", "rubric"];
1050
- /** Whether a group carries pitch: anything but markers and spacing. */
1051
- function hasPitch(notes) {
1052
- return /[^-¨]/.test(splitNoteMarkers(notes).core);
1053
- }
1054
- /** What each syllable token is for. A held group takes its holder's role;
1055
- * an empty slot stays `sung`, unless it stands in an `(@aid)` run. */
1056
- function assignRoles(tokens) {
1057
- let aid = 0;
1058
- let holder = "sung";
1059
- const markedBy = (tok, names) => tok.runs.every((run) => run.marks.some((mark) => names.includes(mark)));
1060
- for (const tok of tokens) {
1061
- if (tok.kind === "aid") aid = Math.max(0, aid + (tok.on ? 1 : -1));
1062
- if (tok.kind !== "syllable") continue;
1063
- if (tok.held) {
1064
- tok.role = holder;
1065
- continue;
1066
- }
1067
- if (tok.runs.length === 0) tok.role = !tok.empty && tok.notes === "" ? "sign" : aid > 0 ? "aid" : "sung";
1068
- else if (tok.text === "" || markedBy(tok, ["plus"])) tok.role = "sign";
1069
- else if (markedBy(tok, LABEL_MARKS) && !hasPitch(tok.notes)) tok.role = "label";
1070
- else tok.role = aid > 0 ? "aid" : "sung";
1071
- holder = tok.role;
1072
- }
1073
- }
1074
- /** Folds backslash escapes into the characters they stand for. Shared
1075
- * with the transforms module (guidoScriptTransforms.ts). */
1076
- function unescape(text) {
1077
- return text.replace(/\\(.)/g, "$1");
1078
- }
1079
- /** Turns literal parentheses and backslashes into their escape sequences. */
1080
- function escape(text) {
1081
- return text.replace(/\\/g, "\\\\").replace(/[()]/g, (ch) => `\\${ch}`);
1082
- }
1083
- //#endregion
1084
- //#region src/guidoStyles.ts
1085
- /**
1086
- * Style sets for the renderer: named appearance rules (fonts, colors, and
1087
- * the special syllable decorations) kept in one constant registry, so a
1088
- * new style is a data entry here rather than a renderer fork.
1089
- */
1090
- /** Text characters (* and †) rendered in Times New Roman. */
1091
- var TIMES_MARKER_GLYPHS = {
1092
- chars: MARKER_CHARS,
1093
- fontFamily: "'Times New Roman', Times, serif"
1094
- };
1095
- /** How a `+` inside a Liturgy-font run is drawn: normal weight (the font
1096
- * is bold-looking by design), sized to 70% and raised 20% of the text
1097
- * size so it sits like a connecting sign between syllable parts. */
1098
- var LITURGY_PLUS_STYLE = {
1099
- weight: "400",
1100
- scale: .7,
1101
- raise: .2
1102
- };
1103
- var STYLE_SETS = {
1104
- /** Book Antiqua text with red accents. */
1105
- BNS: {
1106
- textFontStack: "'Book Antiqua', Georgia, serif",
1107
- notesFontStack: "'Guidohu'",
1108
- markerGlyphs: TIMES_MARKER_GLYPHS,
1109
- verifiedFonts: [
1110
- {
1111
- family: "'Book Antiqua'",
1112
- weight: "400"
1113
- },
1114
- {
1115
- family: "'Book Antiqua'",
1116
- weight: "700"
1117
- },
1118
- {
1119
- family: "'Guidohu'",
1120
- weight: "400"
1121
- },
1122
- {
1123
- family: "'Liturgy'",
1124
- weight: "700"
1125
- }
1126
- ],
1127
- marks: {
1128
- liturgy: {
1129
- fontFamily: "'Liturgy', serif",
1130
- weight: "700",
1131
- color: "var(--red)"
1132
- },
1133
- rubric: {
1134
- uppercase: true,
1135
- scale: .7,
1136
- color: "var(--red)"
1137
- },
1138
- initial: {
1139
- weight: "700",
1140
- color: "var(--red)",
1141
- initial: true
1142
- },
1143
- star: {
1144
- fontFamily: TIMES_MARKER_GLYPHS.fontFamily,
1145
- weight: "700",
1146
- scale: 1,
1147
- measureScale: .95,
1148
- raise: .1,
1149
- color: "var(--red)"
1150
- },
1151
- plus: LITURGY_PLUS_STYLE
1152
- },
1153
- padding: 12
1154
- },
1155
- /** Times New Roman text, strictly black and white. */
1156
- Vesperale: {
1157
- textFontStack: "'Times New Roman', Times, serif",
1158
- notesFontStack: "'Guidohu'",
1159
- verifiedFonts: [
1160
- {
1161
- family: "'Times New Roman', Times, serif",
1162
- weight: "400"
1163
- },
1164
- {
1165
- family: "'Times New Roman', Times, serif",
1166
- weight: "700"
1167
- },
1168
- {
1169
- family: "'Guidohu'",
1170
- weight: "400"
1171
- },
1172
- {
1173
- family: "'Liturgy'",
1174
- weight: "700"
1175
- }
1176
- ],
1177
- marks: {
1178
- liturgy: {
1179
- fontFamily: "'Liturgy', serif",
1180
- weight: "700"
1181
- },
1182
- rubric: {
1183
- scale: .8,
1184
- italic: true
1185
- },
1186
- initial: {
1187
- weight: "700",
1188
- initial: true
1189
- },
1190
- star: {
1191
- fontFamily: TIMES_MARKER_GLYPHS.fontFamily,
1192
- weight: "700",
1193
- scale: 1,
1194
- measureScale: .95,
1195
- raise: .2
1196
- },
1197
- plus: LITURGY_PLUS_STYLE
1198
- },
1199
- padding: 12
1200
- }
1201
- };
1202
- var DEFAULT_STYLE_SET = "BNS";
1203
- /** The style sets `defineStyleSet` added. */
1204
- var definedStyleSets = /* @__PURE__ */ new Map();
1205
- /** The style set of that name, built-in or defined. */
1206
- function styleSetOf(name) {
1207
- return definedStyleSets.get(name) ?? STYLE_SETS[name];
1208
- }
1209
- /** Adds a style set under a name `style` can then give, without patching
1210
- * the package. Returns it. */
1211
- function defineStyleSet(name, definition) {
1212
- const { extends: base = "BNS", ...own } = definition;
1213
- const parent = styleSetOf(base);
1214
- if (!parent) throw new Error(`Unknown style set: "${base}"`);
1215
- const styleSet = {
1216
- ...parent,
1217
- ...own,
1218
- marks: {
1219
- ...parent.marks,
1220
- ...own.marks
1221
- },
1222
- colors: {
1223
- ...parent.colors,
1224
- ...own.colors
1225
- },
1226
- fonts: {
1227
- ...parent.fonts,
1228
- ...own.fonts
1229
- }
1230
- };
1231
- definedStyleSets.set(name, styleSet);
1232
- return styleSet;
1233
- }
1234
- /** The built-in colors `color:<name>` can name. */
1235
- var PALETTE = { red: "var(--red)" };
1236
- /** The built-in fonts `font:<name>` can name. */
1237
- var FONTS = {
1238
- liturgy: "'Liturgy', serif",
1239
- times: "'Times New Roman', Times, serif"
1240
- };
1241
- /** How much smaller small capitals draw than the full capitals. */
1242
- var SMALL_CAP_SCALE = .75;
1243
- var KINDS = /* @__PURE__ */ new Set([
1244
- "liturgy",
1245
- "rubric",
1246
- "star",
1247
- "marker",
1248
- "plus"
1249
- ]);
1250
- /** The run kind of a run's marks: the last of the notation's own. */
1251
- function kindOf(marks) {
1252
- return marks.filter((mark) => KINDS.has(mark)).pop();
1253
- }
1254
- /** The style `mark` leaves on `style`, or undefined when no such mark
1255
- * exists. The primitives come first, so they mean the same in every style
1256
- * set; a registered mark's `color` may name a palette color. */
1257
- function withMark(style, mark, text, styleSet, extra) {
1258
- const colorOf = (name) => styleSet.colors?.[name] ?? PALETTE[name];
1259
- const at = mark.indexOf(":");
1260
- const name = at < 0 ? mark : mark.slice(0, at);
1261
- const argument = at < 0 ? "" : mark.slice(at + 1);
1262
- const amount = Number(argument);
1263
- switch (name) {
1264
- case "plain": return {};
1265
- case "red": return {
1266
- ...style,
1267
- color: PALETTE.red
1268
- };
1269
- case "b": return {
1270
- ...style,
1271
- weight: "700"
1272
- };
1273
- case "i": return {
1274
- ...style,
1275
- italic: true
1276
- };
1277
- case "sc": return {
1278
- ...style,
1279
- smallCaps: true
1280
- };
1281
- case "up": return {
1282
- ...style,
1283
- uppercase: true
1284
- };
1285
- case "color": {
1286
- const color = colorOf(argument);
1287
- return color ? {
1288
- ...style,
1289
- color
1290
- } : void 0;
1291
- }
1292
- case "size": return amount > 0 ? {
1293
- ...style,
1294
- scale: amount,
1295
- measureScale: void 0
1296
- } : void 0;
1297
- case "raise": return Number.isFinite(amount) && argument !== "" ? {
1298
- ...style,
1299
- raise: amount
1300
- } : void 0;
1301
- case "font": {
1302
- const fontFamily = styleSet.fonts?.[argument] ?? FONTS[argument];
1303
- return fontFamily ? {
1304
- ...style,
1305
- fontFamily
1306
- } : void 0;
1307
- }
1308
- case "marker": return styleSet.markerGlyphs?.chars.has(text[0]) ? {
1309
- ...style,
1310
- fontFamily: styleSet.markerGlyphs.fontFamily
1311
- } : style;
1312
- }
1313
- const rule = extra?.[mark] ?? styleSet.marks[mark];
1314
- if (!rule) return void 0;
1315
- const color = rule.color && colorOf(rule.color);
1316
- return {
1317
- ...style,
1318
- ...rule,
1319
- ...color ? { color } : {}
1320
- };
1321
- }
1322
- /** The look of a list of marks, later ones winning; a mark that does not
1323
- * exist changes nothing (`unknownMarks` reports it). */
1324
- function styleOf(text, marks, styleSet, extra) {
1325
- return marks.reduce((style, mark) => withMark(style, mark, text, styleSet, extra) ?? style, {});
1326
- }
1327
- /** The look of comma-separated marks (`red,sc`), for a host styling prose
1328
- * to match the score. */
1329
- function resolveMarks(marks, styleSet, extra) {
1330
- return styleOf("", marks.split(",").map((mark) => mark.trim()), styleSet, extra);
1331
- }
1332
- /** The marks of `marks` that neither the primitives, the style set nor
1333
- * `extra` define. */
1334
- function unknownMarks(marks, styleSet, extra) {
1335
- return marks.filter((mark) => withMark({}, mark, "", styleSet, extra) === void 0);
1336
- }
1337
- /** A run's small-caps split: lowercase letters as small capitals, in runs
1338
- * of their own, everything else at full size. */
1339
- function splitSmallCaps(text) {
1340
- const pieces = [];
1341
- for (const ch of text) {
1342
- const small = ch.toUpperCase() !== ch;
1343
- const last = pieces[pieces.length - 1];
1344
- if (last && last.small === small) last.text += ch;
1345
- else pieces.push({
1346
- text: ch,
1347
- small
1348
- });
1349
- }
1350
- return pieces;
1351
- }
1352
- /** Resolves parsed text runs (`SyllableToken.runs`) into how a style set
1353
- * draws them: each run takes the style of its marks, the `bold` option
1354
- * forces weight 700 onto every run, and `kind` names its notation-fixed
1355
- * semantic (`liturgy`, `rubric`, `star`, `marker`, `plus`), the vocabulary
1356
- * the marked-up text export and the renderer's run classes share. A
1357
- * small-caps run splits into full and small parts. Text stays as written:
1358
- * capitals are the part's display (`drawnText`). */
1359
- function resolveTextRuns(runs, styleSet, bold, extra) {
1360
- return runs.flatMap(({ text, marks }) => {
1361
- const resolved = styleOf(text, marks, styleSet, extra);
1362
- const style = bold ? {
1363
- ...resolved,
1364
- weight: "700"
1365
- } : resolved;
1366
- const kind = kindOf(marks);
1367
- if (!style.smallCaps) return [{
1368
- text,
1369
- style,
1370
- kind
1371
- }];
1372
- const full = {
1373
- ...style,
1374
- smallCaps: void 0
1375
- };
1376
- return splitSmallCaps(text).map((piece) => ({
1377
- text: piece.text,
1378
- kind,
1379
- style: piece.small ? {
1380
- ...full,
1381
- smallCaps: true,
1382
- uppercase: true,
1383
- scale: (full.scale ?? 1) * SMALL_CAP_SCALE,
1384
- measureScale: void 0
1385
- } : full
1386
- }));
1387
- });
1388
- }
1389
- /** The characters a part draws, which measuring must see. */
1390
- function drawnText(part) {
1391
- return part.style.uppercase ? part.text.toUpperCase() : part.text;
1392
- }
1393
- /** Parses a syllable as written (`SyllableToken.source`) and resolves its
1394
- * runs in one step (see `resolveSpans`, `resolveTextRuns`). */
1395
- function resolveSyllableParts(written, styleSet, bold, extra) {
1396
- return resolveTextRuns(resolveSpans([written]).pieces[0].runs, styleSet, bold, extra);
1397
- }
1398
- /** The canvas font shorthand for measuring a run at the text size. */
1399
- function measurementFont(style, textPx, fallbackStack) {
1400
- return [
1401
- style.italic ? "italic" : "normal",
1402
- "normal",
1403
- style.weight ?? "400",
1404
- `${textPx * (style.measureScale ?? style.scale ?? 1)}px`,
1405
- style.fontFamily ?? fallbackStack
1406
- ].join(" ");
1407
- }
1408
- /** The inline CSS properties that draw a run, as dash-cased names for
1409
- * CSSStyleDeclaration.setProperty. */
1410
- function inlineStylesFor(style, textPx) {
1411
- const styles = {};
1412
- if (style.fontFamily) styles["font-family"] = style.fontFamily;
1413
- if (style.weight) styles["font-weight"] = style.weight;
1414
- if (style.italic) styles["font-style"] = "italic";
1415
- if (style.scale !== void 0) styles["font-size"] = `${textPx * style.scale}px`;
1416
- if (style.color) styles["color"] = style.color;
1417
- if (style.uppercase) styles["text-transform"] = "uppercase";
1418
- if (style.raise) {
1419
- styles["position"] = "relative";
1420
- styles["top"] = `${-textPx * style.raise}px`;
1421
- }
1422
- return styles;
1423
- }
1424
- /** The font strings render() must load and verify for a style set. */
1425
- function fontStringsToVerify(styleSet, textPx) {
1426
- return styleSet.verifiedFonts.map((f) => `${f.weight} ${textPx}px ${f.family}`);
1427
- }
1428
- //#endregion
1429
- //#region src/recitationSegments.ts
1430
- /** The reciting pitch of a note group: one reciting glyph, or one plain
1431
- * note that has one, optionally after one accidental sign; null for any
1432
- * other group. */
1433
- function recitationPitch(notes) {
1434
- const sign = notes.length === 2 && isModifierGlyph(notes[0]) ? notes[0] : "";
1435
- const ch = notes.slice(sign.length);
1436
- if (ch.length !== 1) return null;
1437
- const family = baseOf(ch);
1438
- if (family?.role === "longa") return {
1439
- sign,
1440
- plain: family.base,
1441
- glyph: ch,
1442
- written: "glyph"
1443
- };
1444
- const glyph = toLonga(ch);
1445
- return glyph ? {
1446
- sign,
1447
- plain: ch,
1448
- glyph,
1449
- written: "plain"
1450
- } : null;
1451
- }
1452
- /** The notes a group renders with in a mode. */
1453
- function notesInMode(notes, mode) {
1454
- const pitch = recitationPitch(notes);
1455
- if (!pitch || mode === "written") return notes;
1456
- return pitch.sign + (mode === "recite" ? pitch.glyph : pitch.plain);
1457
- }
1458
- /** What a mode renders, in written terms: 'recite' or 'plain'. */
1459
- function shownAs(notes, mode) {
1460
- if (mode !== "written") return mode;
1461
- return recitationPitch(notes)?.written === "glyph" ? "recite" : "plain";
1462
- }
1463
- /** The decisions' view of a script: its syllables, and where a clef or key
1464
- * statement stands (a run never continues across one). */
1465
- function runSyllables(underlays) {
1466
- const syllables = [];
1467
- const pitchBreaks = /* @__PURE__ */ new Set();
1468
- (underlays[0] ?? []).forEach((tok, k) => {
1469
- if (tok.kind === "clef" || tok.kind === "key") pitchBreaks.add(syllables.length);
1470
- if (tok.kind !== "syllable") return;
1471
- const counted = underlays.some((u) => {
1472
- const own = u[k];
1473
- return own?.kind === "syllable" && !own.held && !own.empty;
1474
- });
1475
- syllables.push({
1476
- notes: tok.notes,
1477
- counted
1478
- });
1479
- });
1480
- return {
1481
- syllables,
1482
- pitchBreaks
1483
- };
1484
- }
1485
- /** Whether a syllable can join a recitation run under the options. */
1486
- function isMember(syl, options) {
1487
- const pitch = recitationPitch(syl.notes);
1488
- if (!pitch) return false;
1489
- return pitch.written === "glyph" || options.plainRunsToRecitation;
1490
- }
1491
- /** The run key of a member: its pitch, glyph and plain note alike. */
1492
- function runKey(notes) {
1493
- const pitch = recitationPitch(notes);
1494
- return pitch.sign + pitch.plain;
1495
- }
1496
- /**
1497
- * The mode each member is first laid out in: a recitation when its run in
1498
- * the script counts 3 or more syllables (so the line segments are counted
1499
- * with the recitation's widths), else as written (a run of 2 or fewer can
1500
- * only ever need its pair converted).
1501
- */
1502
- function trialModes(syllables, pitchBreaks, options) {
1503
- const modes = /* @__PURE__ */ new Map();
1504
- let k = 0;
1505
- while (k < syllables.length) {
1506
- if (!isMember(syllables[k], options)) {
1507
- k++;
1508
- continue;
1509
- }
1510
- const key = runKey(syllables[k].notes);
1511
- let end = k;
1512
- let count = 0;
1513
- while (end < syllables.length && isMember(syllables[end], options) && runKey(syllables[end].notes) === key && (end === k || !pitchBreaks.has(end))) {
1514
- if (syllables[end].counted) count++;
1515
- end++;
1516
- }
1517
- for (let j = k; j < end; j++) modes.set(j, count >= 3 ? "recite" : "written");
1518
- k = end;
1519
- }
1520
- return modes;
1521
- }
1522
- /** Whether a script has anything for the decisions to do. */
1523
- function hasCandidates(syllables, options) {
1524
- if (!options.twoSyllableRecitationsToPlain && !options.plainRunsToRecitation) return false;
1525
- return syllables.some((s) => isMember(s, options));
1526
- }
1527
- /** The line segments of a pass: consecutive members on the same line with
1528
- * the same placed pitch. */
1529
- function segmentsOf(syllables, placedNotes, sylLines, options) {
1530
- const segments = [];
1531
- let current;
1532
- let currentKey = "";
1533
- let currentLine = -1;
1534
- syllables.forEach((syl, k) => {
1535
- const placed = placedNotes[k];
1536
- const line = sylLines[k];
1537
- if (!(isMember(syl, options) && placed !== void 0 && line !== void 0 && recitationPitch(placed) !== null)) {
1538
- current = void 0;
1539
- return;
1540
- }
1541
- const key = runKey(placed);
1542
- if (!current || key !== currentKey || line !== currentLine) {
1543
- current = {
1544
- members: [],
1545
- count: 0
1546
- };
1547
- segments.push(current);
1548
- currentKey = key;
1549
- currentLine = line;
1550
- }
1551
- current.members.push(k);
1552
- if (syl.counted) current.count++;
1553
- });
1554
- return segments;
1555
- }
1556
- function initialState() {
1557
- return {
1558
- decided: /* @__PURE__ */ new Map(),
1559
- breakBefore: /* @__PURE__ */ new Set(),
1560
- pending: null
1561
- };
1562
- }
1563
- /** The mode each member renders with in the next pass. */
1564
- function passModes(trial, state) {
1565
- const modes = new Map(trial);
1566
- for (const [k, mode] of state.decided) modes.set(k, mode);
1567
- return modes;
1568
- }
1569
- /**
1570
- * One step of the decisions over a laid-out pass, from the left: checks the
1571
- * segment changed in the previous step, then decides segments in order while
1572
- * the pass already rendered them as decided, and stops at the first one
1573
- * whose decision changes what the pass rendered. Returns whether another
1574
- * pass is needed.
1575
- *
1576
- * Every pass lays the score out left to right, so a decision only moves
1577
- * what comes after it: the segments decided before it stay where they
1578
- * were. A segment is counted on the line the pass put it on, and a change
1579
- * keeps it there: one that opened its line still opens it (as plain notes
1580
- * it might fit the line before), and a member that no longer fits its line
1581
- * in the new form (a pair turned plain is wider than its recitation) opens
1582
- * the next one and is decided again there, the members before it keeping
1583
- * their written form.
1584
- */
1585
- function decideStep(syllables, placedNotes, sylLines, modes, state, options) {
1586
- if (state.pending) {
1587
- const { members, line } = state.pending;
1588
- state.pending = null;
1589
- const moved = members.findIndex((k) => sylLines[k] !== line);
1590
- if (moved >= 0) {
1591
- members.forEach((k, j) => {
1592
- if (j < moved) state.decided.set(k, "written");
1593
- else state.decided.delete(k);
1594
- });
1595
- state.breakBefore.add(members[moved]);
1596
- return true;
1597
- }
1598
- }
1599
- for (const segment of segmentsOf(syllables, placedNotes, sylLines, options)) {
1600
- if (segment.members.every((k) => state.decided.has(k))) continue;
1601
- const target = segment.count >= 3 ? "recite" : segment.count === 2 && options.twoSyllableRecitationsToPlain ? "plain" : "written";
1602
- const changes = segment.members.some((k) => {
1603
- const notes = syllables[k].notes;
1604
- return shownAs(notes, modes.get(k) ?? "written") !== shownAs(notes, target);
1605
- });
1606
- for (const k of segment.members) state.decided.set(k, target);
1607
- if (changes) {
1608
- const first = segment.members[0];
1609
- const line = sylLines[first];
1610
- if (first > 0 && (sylLines[first - 1] ?? -1) < line) state.breakBefore.add(first);
1611
- state.pending = {
1612
- members: segment.members,
1613
- line
1614
- };
1615
- return true;
1616
- }
1617
- }
1618
- return false;
1619
- }
1620
- //#endregion
1621
- //#region src/chantLayout.ts
1622
- /**
1623
- * Special reciting notes: when such a note stands alone in a note group it
1624
- * marks recited text. The glyph shows at a run's first syllable (the
1625
- * previous syllable has different notes) and at every line start; every
1626
- * other recited syllable contributes only the staff-line segments filling
1627
- * the space above its text, which flows tight after the previous text.
1628
- */
1629
- var SPECIAL_NOTES = "Ÿ¡¢£[¥¦©ª«¬";
1630
- var SPECIAL_NOTE_CHARS = new Set(SPECIAL_NOTES.split(""));
1631
- /** Whether a note group is a recitation group: one special reciting note,
1632
- * optionally after one accidental sign (`¦`, `C¦`). */
1633
- function isRecitationGroup(notes) {
1634
- return notes.length === 1 && SPECIAL_NOTE_CHARS.has(notes) || notes.length === 2 && MODIFIER_CHARS.has(notes[0]) && SPECIAL_NOTE_CHARS.has(notes[1]);
1635
- }
1636
- /**
1637
- * Modifier glyphs: flats, sharps, and naturals. They carry pitch (and
1638
- * transpose with the melody) but modify the note that follows them, so
1639
- * they hang in the junction whitespace: the syllable text anchors on the
1640
- * note characters only, and a group starting with a modifier needs only
1641
- * two junction dashes — the glyph itself provides the third dash's
1642
- * separation.
1643
- */
1644
- var NOTE_MODIFIERS = "÷øaASÍYXCVBN$mÈÊËÌÎÏÐÑÒþßòôùý“”•–—˜™š›œº»";
1645
- var MODIFIER_CHARS = new Set(NOTE_MODIFIERS.split(""));
1646
- /**
1647
- * The length of what hangs at the start of a group's core: its leading
1648
- * modifiers and bracketed accidentals (issue #95), which stand in the
1649
- * junction whitespace before the group's first note.
1650
- */
1651
- function hangingLength(core) {
1652
- let at = 0;
1653
- for (;;) {
1654
- const unit = MODIFIER_CHARS.has(core[at] ?? "") ? 1 : bracketedAccidentalLength(core, at);
1655
- if (unit === 0) return at;
1656
- at += unit;
1657
- }
1658
- }
1659
- /** The index in `notes` right after its hanging run (leading markers
1660
- * counted), or 0 when nothing hangs. */
1661
- function hangEnd(notes) {
1662
- const { leading, core } = splitNoteMarkers(notes);
1663
- const hang = hangingLength(core);
1664
- return hang === 0 ? 0 : leading.length + hang;
1665
- }
1666
- var NOTE_GROUP_SPLITTERS = ["-", "¨"];
1667
- /** A junction `thirds` thirds of a dash wide: whole dashes, then one `¨`
1668
- * per leftover third (`--¨¨` is 2⅔). */
1669
- function junctionSpacer(thirds) {
1670
- return "-".repeat(Math.floor(thirds / 3)) + "¨".repeat(thirds % 3);
1671
- }
1672
- /** The key written by a run of modifier glyphs, under `clef` (a clef
1673
- * glyph; the standard g-clef when unknown — matching pitches by staff
1674
- * position does not depend on it). A statement's key throws when two
1675
- * glyphs alter the same pitch; the opening group's stays lenient (the
1676
- * later glyph wins), as it was never validated. */
1677
- function keyMapOf(key, clef, strict = true) {
1678
- const map = /* @__PURE__ */ new Map();
1679
- for (const ch of key) {
1680
- if (!isModifierGlyph(ch)) continue;
1681
- const letter = pitchLetterOf(ch, clefOrDefault(clef));
1682
- if (strict && map.has(letter)) throw new Error(`Key "${key}" alters the pitch ${letter} twice`);
1683
- map.set(letter, baseOf(ch).role);
1684
- }
1685
- return map;
1686
- }
1687
- function clefOrDefault(clef) {
1688
- return clef !== void 0 && isClefGlyph(clef) ? clef : "M";
1689
- }
1690
- /** The note glyphs a key alters: the base pitch glyphs and their shape
1691
- * variants. Accidentals and small points are not notes, and the score
1692
- * markers carry no pitch (several double as cephalicus glyphs). */
1693
- function noteBaseOf(ch) {
1694
- if (MARKER_CHARS$1.has(ch)) return void 0;
1695
- if (variantOf(ch, "smallHead") !== void 0) return ch;
1696
- const entry = baseOf(ch);
1697
- if (!entry || entry.role === "smallPoint" || isModifierGlyph(ch)) return void 0;
1698
- return entry.base;
1699
- }
1700
- /**
1701
- * Writes a mid-line key change into a note group (issue #49): every note
1702
- * whose pitch carries a different accidental under `active` than under
1703
- * `staff` (the key the line's staff shows) calls for the accidental
1704
- * sign — or the natural, when the pitch dropped out of the key. The
1705
- * signs stand before the note group, not before their notes: they go at
1706
- * the start of the group's notes (after its leading markers), one per
1707
- * affected pitch glyph, in order of first appearance. Notes the source
1708
- * already marks with a modifier are left alone (a bracketed accidental
1709
- * opening the group, issue #95, marks the note after it). The groups a
1710
- * syllable holds (`held`, issue #83) are scanned too: a held run writes its signs
1711
- * once, before its first group. Returns the rewritten group and the
1712
- * indices of the inserted signs. Throws when a needed sign does not
1713
- * exist.
1714
- */
1715
- function applyKeyChange(notes, staff, active, clef, held = []) {
1716
- let signs = "";
1717
- for (const group of [notes, ...held]) {
1718
- const hang = hangEnd(group);
1719
- for (let i = 0; i < group.length; i++) {
1720
- const ch = group[i];
1721
- const base = noteBaseOf(ch);
1722
- const letter = base !== void 0 ? pitchLetterOf(base, clefOrDefault(clef)) : void 0;
1723
- const want = letter !== void 0 ? active.get(letter) : void 0;
1724
- const marked = i > 0 && (isModifierGlyph(group[i - 1]) || i === hang);
1725
- if (letter !== void 0 && want !== staff.get(letter) && !marked) {
1726
- const role = want ?? "modifyNatural";
1727
- const sign = want ? variantOf(base, want) : modifyNatural(base);
1728
- if (sign === void 0) throw new Error(`The note "${ch}" has no ${role} glyph for the key change`);
1729
- if (!signs.includes(sign)) signs += sign;
1730
- }
1731
- }
1732
- }
1733
- const at = splitNoteMarkers(notes).leading.length;
1734
- return {
1735
- notes: notes.slice(0, at) + signs + notes.slice(at),
1736
- inserted: [...signs].map((_, k) => at + k)
1737
- };
1738
- }
1739
- /** A group with the given inserted signs removed again. */
1740
- function stripInserted(notes, inserted, from = 0) {
1741
- return [...notes].filter((_, i) => !inserted.includes(i + from)).join("");
1742
- }
1743
- var ctx = null;
1744
- /** Canvas text measurement, shared with the emitters (the Word export
1745
- * measures the spacer character's natural advance for the unit width). */
1746
- function measure(text, font) {
1747
- if (!ctx) ctx = document.createElement("canvas").getContext("2d");
1748
- ctx.font = font;
1749
- return ctx.measureText(text).width;
1750
- }
1751
- /** Ink extents of the text relative to the glyph origin (negative left
1752
- * means the ink starts left of the origin). */
1753
- function ink(text, font) {
1754
- if (!ctx) ctx = document.createElement("canvas").getContext("2d");
1755
- ctx.font = font;
1756
- const m = ctx.measureText(text);
1757
- return {
1758
- left: m.actualBoundingBoxLeft,
1759
- right: m.actualBoundingBoxRight
1760
- };
1761
- }
1762
- var STAFF_FILLS = [
1763
- "all-but-last",
1764
- "none",
1765
- "all",
1766
- "longest"
1767
- ];
1768
- /** Each underlay's tokens, checked to share one melody. */
1769
- function underlayTokens(source) {
1770
- const list = typeof source === "string" || source instanceof GuidoScript ? [source] : source;
1771
- if (list.length === 0) throw new Error("Nothing to lay out: no script given");
1772
- const all = list.map((s) => (typeof s === "string" ? new GuidoScript(s) : s).tokens);
1773
- const [first] = all;
1774
- for (const [u, tokens] of all.entries()) if (!(tokens.length === first.length && tokens.every((tok, k) => {
1775
- const ref = first[k];
1776
- return tok.kind === ref.kind && (tok.kind !== "syllable" || tok.notes === ref.notes);
1777
- }))) throw new Error(`Stacked underlay ${u + 1} does not share the first one's notes`);
1778
- return all;
1779
- }
1780
- /** Whether an underlay's token sings no text of its own on its group: a
1781
- * held group or an empty slot. */
1782
- function silent(tok) {
1783
- return !!(tok.held || tok.empty);
1784
- }
1785
- /**
1786
- * Lays a GuidoScript score out: a notes line in the chant font, and a text
1787
- * line where each syllable is centered below its notes. The dashes of the
1788
- * chant font are pure whitespace: centering ignores them and happens under
1789
- * the non-whitespace note characters only. When a syllable's text would
1790
- * overlap the previous one, it starts right after it and the notes group is
1791
- * padded with extra dashes until it covers the text.
1792
- *
1793
- * Stacked stanzas (issue #84): given several underlays of one melody, every
1794
- * line pair gets one text line per underlay. Each text line keeps its own
1795
- * cursor and runs the placement rules on its own (tight pairs, connectors,
1796
- * hyphens, recitation flow); a group takes the most pad dashes any of them
1797
- * asks for, so the notes spacing serves every text line, and a line breaks
1798
- * wherever any of them has to. A group that every underlay holds joins its
1799
- * run with the held join; one that some underlay sings takes the normal
1800
- * junction.
1801
- *
1802
- * This is the shared layout pass behind every emitter: the DOM renderer
1803
- * turns the returned lines into (notes div, text paragraph) pairs, and the
1804
- * Word export turns them into fake-spaced Word HTML. Both consume the same
1805
- * line breaks, notes parts, and syllable anchor positions.
1806
- *
1807
- * Appearance comes from a named style set (see guidoStyles.ts): the layout
1808
- * options reference it by name, together with the bold option and the
1809
- * text/notes sizes. Throws when the style set is unknown or one of its
1810
- * fonts cannot be loaded.
1811
- */
1812
- async function layoutScore(source, options = {}) {
1813
- const recitation = {
1814
- twoSyllableRecitationsToPlain: options.twoSyllableRecitationsToPlain ?? true,
1815
- plainRunsToRecitation: options.plainRunsToRecitation ?? false
1816
- };
1817
- const { syllables, pitchBreaks } = runSyllables(underlayTokens(source));
1818
- if (!hasCandidates(syllables, recitation)) return (await layoutKept(source, options, NO_RECITATION)).result;
1819
- const trial = trialModes(syllables, pitchBreaks, recitation);
1820
- const state = initialState();
1821
- for (let step = 0;; step++) {
1822
- const modes = passModes(trial, state);
1823
- const pass = await layoutKept(source, options, {
1824
- notes: notesOverrides(syllables.map((s) => s.notes), modes),
1825
- breakBefore: state.breakBefore
1826
- });
1827
- if (step > 4 * syllables.length + 8 || !decideStep(syllables, pass.placedNotes, pass.sylLines, modes, state, recitation)) return pass.result;
1828
- }
1829
- }
1830
- /** The notes each syllable renders with under the recitation modes, where
1831
- * they differ from the written ones. */
1832
- function notesOverrides(written, modes) {
1833
- const notes = /* @__PURE__ */ new Map();
1834
- for (const [k, mode] of modes) {
1835
- const shown = notesInMode(written[k], mode);
1836
- if (shown !== written[k]) notes.set(k, shown);
1837
- }
1838
- return notes;
1839
- }
1840
- var NO_RECITATION = {
1841
- notes: /* @__PURE__ */ new Map(),
1842
- breakBefore: /* @__PURE__ */ new Set()
1843
- };
1844
- /** One layout with its `(@keep)` runs settled: a run is only known to fit
1845
- * once it is placed, pads and group splits included, so a run that ends up
1846
- * split is retried with a break before it. One wider than a fresh line
1847
- * stops counting: a flat run wraps where it stood, and a run with inner
1848
- * runs dissolves into them but keeps its break, so the boundary between
1849
- * pairs still wins over the one between verses. Runs number in opening
1850
- * order, so the lowest split is the leftmost and outermost. */
1851
- async function layoutKept(source, options, recitation) {
1852
- const breakBefore = /* @__PURE__ */ new Set();
1853
- const wraps = /* @__PURE__ */ new Set();
1854
- for (;;) {
1855
- const pass = await layoutPass(source, options, breakBefore, recitation);
1856
- const open = pass.splitRuns.filter((r) => !wraps.has(r.run));
1857
- if (open.length === 0) return pass;
1858
- const split = open.reduce((a, b) => b.run < a.run ? b : a);
1859
- if (breakBefore.has(split.run) || split.atLineStart) {
1860
- wraps.add(split.run);
1861
- if (split.nested) breakBefore.add(split.run);
1862
- else breakBefore.delete(split.run);
1863
- } else breakBefore.add(split.run);
1864
- }
1865
- }
1866
- /** One pass of `layoutScore`: `breakBefore` lists the `(@keep)` runs (by
1867
- * position in the script) that open a fresh line; `splitRuns` reports the
1868
- * ones that crossed a line break. `recitation` carries the recitation
1869
- * segments' forms and breaks (issue #21). */
1870
- async function layoutPass(source, options, breakBefore, recitation = NO_RECITATION) {
1871
- const { style: styleName = "BNS", marks, bold = false, textPx = 18, notesPx = textPx * 2, maxWidthPx = Infinity, junctionDashes = 3, staffFill = "all-but-last", staffFillSnapPx = 0 } = options;
1872
- if (!STAFF_FILLS.includes(staffFill)) throw new Error(`Unknown staffFill: "${staffFill}"`);
1873
- if (!(staffFillSnapPx >= 0 && Number.isFinite(staffFillSnapPx))) throw new Error(`staffFillSnapPx must be zero or more: ${staffFillSnapPx}`);
1874
- const junctionThirds = Math.round(junctionDashes * 3);
1875
- if (!(junctionDashes >= 1 && Math.abs(junctionDashes - junctionThirds / 3) <= .01)) throw new Error(`junctionDashes must be at least 1, in steps of a third: ${junctionDashes}`);
1876
- const fullJunction = junctionSpacer(junctionThirds);
1877
- const reducedJunction = junctionSpacer(Math.max(3, junctionThirds - 3));
1878
- const underlays = underlayTokens(source);
1879
- 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];
1880
- const styleSet = styleSetOf(styleName);
1881
- if (!styleSet) throw new Error(`Unknown style set: "${styleName}"`);
1882
- for (const font of fontStringsToVerify(styleSet, textPx)) {
1883
- try {
1884
- await document.fonts.load(font);
1885
- } catch {}
1886
- if (!document.fonts.check(font)) throw new Error(`Font could not be loaded: ${font} (style "${styleName}")`);
1887
- }
1888
- const notesFont = `400 ${notesPx}px ${styleSet.notesFontStack}`;
1889
- const textStack = styleSet.textFontStack;
1890
- const spaceFont = measurementFont({ weight: bold ? "700" : "400" }, textPx, textStack);
1891
- const resolveParts = (runs) => resolveTextRuns(runs, styleSet, bold, marks);
1892
- const measureParts = (parts) => parts.reduce((w, part) => w + measure(drawnText(part), measurementFont(part.style, textPx, textStack)), 0);
1893
- const dashNotesWidth = measure("-", notesFont);
1894
- const dashTextWidth = measure("-", spaceFont);
1895
- /** The hyphen after a syllable: plain, unless a `{…}` span runs on
1896
- * across it, when it takes the span's look and that look's width. */
1897
- const hyphenOf = (hyphenMarks) => {
1898
- if (!hyphenMarks) return { width: dashTextWidth };
1899
- const parts = resolveParts([{
1900
- text: "-",
1901
- marks: hyphenMarks
1902
- }]);
1903
- return {
1904
- parts,
1905
- width: measureParts(parts)
1906
- };
1907
- };
1908
- let clefGlyph = script.clef?.[0];
1909
- let keyGlyphs = [...(script.clef ?? "").slice(1)].filter(isModifierGlyph).join("");
1910
- let clefGroup = script.clef;
1911
- const prefixOf = (group) => group ? `${group}-` : "";
1912
- let activeKey = keyMapOf(keyGlyphs, clefGlyph, false);
1913
- let staffKey = activeKey;
1914
- const tracks = underlays.map((tokens) => {
1915
- const syls = tokens.filter((t) => t.kind === "syllable");
1916
- return {
1917
- syls,
1918
- lastTextSyl: syls.reduce((last, s, i) => silent(s) ? last : i, -1),
1919
- cursor: 0,
1920
- pending: [],
1921
- prevWordEnd: void 0,
1922
- hyphen: { width: dashTextWidth }
1923
- };
1924
- });
1925
- const lines = [];
1926
- let line;
1927
- let notesSoFar;
1928
- let lastGroupTrailingMarker;
1929
- let afterInlineClef = false;
1930
- let current;
1931
- let prevRecited = false;
1932
- const startLine = () => {
1933
- if (line) {
1934
- tracks.forEach((t, u) => {
1935
- line.texts[u].textCursor = t.cursor;
1936
- });
1937
- line.notesEnd = line.notesParts.length ? measure(line.clefPrefix + line.notesParts.join(""), notesFont) : 0;
1938
- }
1939
- const texts = tracks.map(() => ({
1940
- segments: [],
1941
- textCursor: 0,
1942
- lastWordEnd: null
1943
- }));
1944
- line = {
1945
- clefPrefix: prefixOf(clefGroup),
1946
- notesParts: [],
1947
- segments: texts[0].segments,
1948
- textCursor: 0,
1949
- notesEnd: 0,
1950
- staffEnd: 0,
1951
- lastWordEnd: null,
1952
- texts
1953
- };
1954
- lines.push(line);
1955
- notesSoFar = line.clefPrefix;
1956
- for (const t of tracks) t.cursor = 0;
1957
- lastGroupTrailingMarker = false;
1958
- prevRecited = false;
1959
- afterInlineClef = false;
1960
- staffKey = activeKey;
1961
- if (current && current.inserted.length > 0) {
1962
- current.notes = stripInserted(current.notes, current.inserted);
1963
- current.inserted = [];
1964
- if (current.first) placedNotes[current.i] = current.notes;
1965
- }
1966
- };
1967
- startLine();
1968
- const tokens = underlays[0];
1969
- const allHeld = (i) => tracks.every((t) => t.syls[i].held);
1970
- const items = [];
1971
- let sylIndex = 0;
1972
- let runHead;
1973
- let tightDepth = 0;
1974
- let tightGroupPlaced = false;
1975
- for (const tok of tokens) if (tok.kind !== "syllable") {
1976
- items.push(tok);
1977
- runHead = void 0;
1978
- if (tok.kind === "tight" || tok.kind === "unit") {
1979
- tightDepth = Math.max(0, tightDepth + (tok.on ? 1 : -1));
1980
- if (tightDepth === 0) tightGroupPlaced = false;
1981
- }
1982
- } else {
1983
- const i = sylIndex++;
1984
- const item = {
1985
- kind: "syl",
1986
- syl: tok,
1987
- i,
1988
- notes: recitation.notes.get(i) ?? tok.notes,
1989
- inserted: [],
1990
- first: true,
1991
- lastSeg: true,
1992
- heldRun: [],
1993
- signedByRun: false,
1994
- tightJoin: tightGroupPlaced
1995
- };
1996
- if (tok.notes !== "") tightGroupPlaced = tightDepth > 0;
1997
- if (allHeld(item.i) && runHead) {
1998
- runHead.heldRun.push(tok.notes);
1999
- item.signedByRun = true;
2000
- } else runHead = item;
2001
- items.push(item);
2002
- }
2003
- const placedNotes = [];
2004
- const findBreakCut = (notes, room, measureFromLineStart) => {
2005
- const first = hangEnd(notes);
2006
- for (let c = notes.length - 1; c >= first && c > 0; c--) {
2007
- if (!NOTE_GROUP_SPLITTERS.includes(notes[c])) continue;
2008
- let end = c + 1;
2009
- while (end < notes.length && MARKER_CHARS$1.has(notes[end])) end++;
2010
- if (end >= notes.length) continue;
2011
- if (measureFromLineStart(notes.slice(0, end)) <= room) return c;
2012
- }
2013
- return -1;
2014
- };
2015
- const applyBreakCut = (item, cut) => {
2016
- const notes = item.notes;
2017
- let restStart = cut + 1;
2018
- while (restStart < notes.length && MARKER_CHARS$1.has(notes[restStart])) restStart++;
2019
- item.notes = notes.slice(0, cut) + notes.slice(cut + 1, restStart);
2020
- const rest = stripInserted(notes.slice(restStart), item.inserted, restStart);
2021
- item.inserted = item.inserted.filter((at) => at < cut);
2022
- return rest;
2023
- };
2024
- const queueContinuation = (item, idx, rest) => {
2025
- item.lastSeg = false;
2026
- items.splice(idx + 1, 0, {
2027
- kind: "syl",
2028
- syl: item.syl,
2029
- i: item.i,
2030
- notes: rest,
2031
- inserted: [],
2032
- first: false,
2033
- lastSeg: true,
2034
- heldRun: [],
2035
- signedByRun: false,
2036
- tightJoin: false
2037
- });
2038
- forceBreak = true;
2039
- };
2040
- const flushPending = (trailing) => {
2041
- tracks.forEach((t, u) => {
2042
- while (t.pending.length > 0) {
2043
- const p = t.pending[0];
2044
- if (t.cursor > 0 && t.cursor + p.textWidth + (p.wordEnd ? 0 : p.hyphen.width) > maxWidthPx) {
2045
- startLine();
2046
- continue;
2047
- }
2048
- t.pending.shift();
2049
- const text = line.texts[u];
2050
- text.segments.push({
2051
- kind: "syl",
2052
- parts: p.sylParts,
2053
- textStart: t.cursor,
2054
- textWidth: p.textWidth,
2055
- contentWidth: 0,
2056
- contentStart: 0,
2057
- extraDashes: 0,
2058
- tight: false,
2059
- noNotes: true,
2060
- ...trailing && t.pending.length === 0 ? { trailing: true } : {}
2061
- });
2062
- t.cursor += p.textWidth;
2063
- if (p.spaceWidth > 0) {
2064
- text.segments.push({
2065
- kind: "word-space",
2066
- width: p.spaceWidth
2067
- });
2068
- t.cursor += p.spaceWidth;
2069
- }
2070
- text.lastWordEnd = p.wordEnd;
2071
- text.hyphen = p.hyphen;
2072
- t.hyphen = p.hyphen;
2073
- text.textCursor = t.cursor;
2074
- }
2075
- });
2076
- };
2077
- let forceBreak = false;
2078
- let keepRuns = 0;
2079
- const keepStack = [];
2080
- const splitRuns = [];
2081
- const closeKeepRun = () => {
2082
- const run = keepStack.pop();
2083
- if (run && lines.length - 1 > run.line) splitRuns.push(run);
2084
- };
2085
- const sylLines = [];
2086
- let placedSyl = -1;
2087
- const notePlacedLine = () => {
2088
- if (placedSyl >= 0) sylLines[placedSyl] = lines.length - 1;
2089
- placedSyl = -1;
2090
- };
2091
- let idx = 0;
2092
- while (idx < items.length) {
2093
- notePlacedLine();
2094
- const item = items[idx];
2095
- if (item.kind === "break") {
2096
- if (line.texts.some((x) => x.segments.length > 0) || tracks.some((t) => t.pending.length > 0)) {
2097
- flushPending(false);
2098
- forceBreak = true;
2099
- }
2100
- idx++;
2101
- continue;
2102
- }
2103
- if (item.kind === "tight" || item.kind === "aid") {
2104
- idx++;
2105
- continue;
2106
- }
2107
- if (item.kind === "keep" || item.kind === "unit") {
2108
- if (!item.on) closeKeepRun();
2109
- else {
2110
- const hasContent = line.texts.some((x) => x.segments.length > 0) || tracks.some((t) => t.pending.length > 0);
2111
- if (breakBefore.has(keepRuns) && hasContent) {
2112
- flushPending(false);
2113
- forceBreak = true;
2114
- }
2115
- if (keepStack.length > 0) keepStack[keepStack.length - 1].nested = true;
2116
- keepStack.push({
2117
- run: keepRuns++,
2118
- line: forceBreak ? lines.length : lines.length - 1,
2119
- atLineStart: !hasContent || forceBreak,
2120
- nested: false
2121
- });
2122
- }
2123
- idx++;
2124
- continue;
2125
- }
2126
- if (item.kind === "clef" || item.kind === "key") {
2127
- if (item.kind === "clef") clefGlyph = item.clef;
2128
- keyGlyphs = item.key;
2129
- clefGroup = (clefGlyph ?? "") + keyGlyphs;
2130
- activeKey = keyMapOf(keyGlyphs, clefGlyph);
2131
- if (forceBreak) {} else if (line.notesParts.length === 0) {
2132
- line.clefPrefix = prefixOf(clefGroup);
2133
- notesSoFar = line.clefPrefix;
2134
- staffKey = activeKey;
2135
- } else if (item.kind === "clef") {
2136
- const part = (lastGroupTrailingMarker ? reducedJunction : fullJunction) + clefGroup + "-";
2137
- if (measure(notesSoFar + part, notesFont) > maxWidthPx) forceBreak = true;
2138
- else {
2139
- line.notesParts.push(part);
2140
- notesSoFar += part;
2141
- staffKey = activeKey;
2142
- afterInlineClef = true;
2143
- lastGroupTrailingMarker = false;
2144
- prevRecited = false;
2145
- }
2146
- }
2147
- idx++;
2148
- continue;
2149
- }
2150
- const syl = item.syl;
2151
- const i = item.i;
2152
- if (item.first) placedSyl = i;
2153
- if (item.first && recitation.breakBefore.has(i) && (line.texts.some((x) => x.segments.length > 0) || tracks.some((t) => t.pending.length > 0))) {
2154
- flushPending(false);
2155
- forceBreak = true;
2156
- }
2157
- if (forceBreak) {
2158
- startLine();
2159
- forceBreak = false;
2160
- }
2161
- current = item;
2162
- if (staffKey !== activeKey && !item.signedByRun) {
2163
- const changed = applyKeyChange(item.notes, staffKey, activeKey, clefGlyph, item.first ? item.heldRun : []);
2164
- item.notes = changed.notes;
2165
- item.inserted = changed.inserted;
2166
- }
2167
- if (item.first) placedNotes[i] = item.signedByRun && staffKey !== activeKey ? applyKeyChange(item.notes, staffKey, activeKey, clefGlyph).notes : item.notes;
2168
- const sung = tracks.map((t) => {
2169
- const own = t.syls[i];
2170
- const last = item.lastSeg && i >= t.lastTextSyl;
2171
- const sylParts = resolveParts(item.first ? own.runs : []);
2172
- return {
2173
- t,
2174
- own,
2175
- sylParts,
2176
- textWidth: measureParts(sylParts),
2177
- spaceWidth: !last && own.wordEnd ? measure(" ", spaceFont) : 0,
2178
- pendingTotal: t.pending.reduce((s, p) => s + p.textWidth + p.spaceWidth, 0)
2179
- };
2180
- });
2181
- const special = isRecitationGroup(item.notes);
2182
- if (syl.empty && item.notes.length === 0) {
2183
- idx++;
2184
- continue;
2185
- }
2186
- if (item.notes.length === 0) {
2187
- for (const s of sung) {
2188
- if (s.own.empty) continue;
2189
- s.t.pending.push({
2190
- sylParts: s.sylParts,
2191
- textWidth: s.textWidth,
2192
- spaceWidth: s.spaceWidth,
2193
- wordEnd: s.own.wordEnd,
2194
- hyphen: hyphenOf(s.own.hyphen)
2195
- });
2196
- }
2197
- idx++;
2198
- continue;
2199
- }
2200
- if (item.first && item.lastSeg && !syl.empty && syl.runs.length === 0 && splitNoteMarkers(item.notes).core === "") {
2201
- const last = notesSoFar[notesSoFar.length - 1];
2202
- const sep = last && last !== "-" && !lastGroupTrailingMarker && !syl.notes.startsWith("-") ? "-" : "";
2203
- line.notesParts.push(sep + syl.notes);
2204
- notesSoFar += sep + syl.notes;
2205
- lastGroupTrailingMarker = true;
2206
- prevRecited = false;
2207
- for (const s of sung) s.t.prevWordEnd = s.own.wordEnd;
2208
- idx++;
2209
- continue;
2210
- }
2211
- const keepWordState = (s, fresh) => {
2212
- if (s.own.held) {
2213
- if (fresh) line.texts[tracks.indexOf(s.t)].lastWordEnd = true;
2214
- s.t.prevWordEnd = s.own.wordEnd;
2215
- } else if (s.t.prevWordEnd === void 0) s.t.prevWordEnd = true;
2216
- };
2217
- if (item.first && sung.every((s) => silent(s.own))) {
2218
- const held = allHeld(i);
2219
- const recitation = isRecitationGroup(item.notes);
2220
- if (held && recitation && placedNotes[i - 1] === placedNotes[i] && line.notesParts.length > 0 && !afterInlineClef) {
2221
- prevRecited = true;
2222
- idx++;
2223
- continue;
2224
- }
2225
- let parts = splitNoteMarkers(item.notes);
2226
- const joinOf = () => line.notesParts.length === 0 || afterInlineClef ? "" : held ? lastGroupTrailingMarker ? "--" : "-" : lastGroupTrailingMarker || item.tightJoin || hangingLength(parts.core) > 0 ? reducedJunction : fullJunction;
2227
- let join = joinOf();
2228
- if (line.notesParts.length > 0 && measure(notesSoFar + join + item.notes, notesFont) > maxWidthPx) {
2229
- startLine();
2230
- join = joinOf();
2231
- }
2232
- const fresh = line.notesParts.length === 0;
2233
- if (fresh && measure(notesSoFar + item.notes, notesFont) > maxWidthPx) {
2234
- const cut = findBreakCut(item.notes, maxWidthPx, (prefix) => measure(notesSoFar + prefix, notesFont));
2235
- if (cut >= 0 && cut + 1 < item.notes.length) {
2236
- const rest = applyBreakCut(item, cut);
2237
- queueContinuation(item, idx, rest);
2238
- parts = splitNoteMarkers(item.notes);
2239
- }
2240
- }
2241
- line.notesParts.push(join + item.notes);
2242
- notesSoFar += join + item.notes;
2243
- for (const s of sung) keepWordState(s, fresh);
2244
- afterInlineClef = false;
2245
- if (item.lastSeg) {
2246
- lastGroupTrailingMarker = parts.trailing.length > 0;
2247
- prevRecited = recitation;
2248
- }
2249
- idx++;
2250
- continue;
2251
- }
2252
- const voiced = item.first ? sung.filter((s) => !silent(s.own)) : sung;
2253
- const runStart = placedNotes[i - 1] !== item.notes;
2254
- const specialFits = voiced.every((s) => s.t.cursor === 0 || s.t.cursor + s.pendingTotal + s.textWidth + (s.own.wordEnd ? 0 : hyphenOf(s.own.hyphen).width) <= maxWidthPx);
2255
- if (special && !runStart && line.notesParts.length > 0 && !specialFits) startLine();
2256
- if (!item.first) {
2257
- for (;;) {
2258
- if (measure(notesSoFar + item.notes, notesFont) <= maxWidthPx) break;
2259
- const cut = findBreakCut(item.notes, maxWidthPx, (prefix) => measure(notesSoFar + prefix, notesFont));
2260
- if (cut < 0 || cut + 1 >= item.notes.length) break;
2261
- const rest = applyBreakCut(item, cut);
2262
- queueContinuation(item, idx, rest);
2263
- }
2264
- const parts = splitNoteMarkers(item.notes);
2265
- line.notesParts.push(item.notes);
2266
- notesSoFar += item.notes;
2267
- if (item.lastSeg) lastGroupTrailingMarker = parts.trailing.length > 0;
2268
- for (const [u, s] of sung.entries()) {
2269
- line.texts[u].lastWordEnd = true;
2270
- s.t.prevWordEnd = s.own.wordEnd;
2271
- }
2272
- if (!item.lastSeg) forceBreak = true;
2273
- idx++;
2274
- continue;
2275
- }
2276
- let parts = splitNoteMarkers(item.notes);
2277
- let junctionPrefix = line.notesParts.length === 0 || afterInlineClef ? "" : lastGroupTrailingMarker || item.tightJoin || hangingLength(parts.core) > 0 ? reducedJunction : fullJunction;
2278
- if (prevRecited) {
2279
- const closing = /-*$/.exec(notesSoFar)[0].length;
2280
- junctionPrefix = special && !runStart || closing > /^-*/.exec(junctionPrefix)[0].length ? "" : junctionPrefix.slice(closing);
2281
- }
2282
- const place = (padDashes = 0) => {
2283
- let mods = hangingLength(parts.core);
2284
- if (mods === parts.core.length) mods = 0;
2285
- const anchorText = parts.core.slice(mods);
2286
- const contentWidth = measure(anchorText, notesFont);
2287
- const contentStart = measure(notesSoFar + junctionPrefix + "-".repeat(padDashes) + parts.leading + parts.core.slice(0, mods), notesFont);
2288
- const inkRaw = ink(anchorText, notesFont);
2289
- const inkStartOffset = -inkRaw.left;
2290
- const inkCenterOffset = (inkRaw.right - inkRaw.left) / 2;
2291
- const textStartOf = (textWidth) => contentWidth >= textWidth || special ? contentStart + inkStartOffset : contentStart + inkCenterOffset - textWidth / 2;
2292
- return {
2293
- contentWidth,
2294
- contentStart,
2295
- textStartOf
2296
- };
2297
- };
2298
- let placed = place();
2299
- const uncut = {
2300
- notes: item.notes,
2301
- inserted: item.inserted,
2302
- lastSeg: item.lastSeg,
2303
- forceBreak,
2304
- items: items.length
2305
- };
2306
- const fit = () => {
2307
- for (;;) {
2308
- const notesOver = measure(notesSoFar + junctionPrefix + item.notes, notesFont) > maxWidthPx;
2309
- const textOver = voiced.some((s) => placed.textStartOf(s.textWidth) + s.textWidth + (s.own.wordEnd ? 0 : hyphenOf(s.own.hyphen).width) > maxWidthPx);
2310
- if (!notesOver && !textOver) break;
2311
- if (notesOver) {
2312
- const cut = findBreakCut(item.notes, maxWidthPx, (prefix) => measure(notesSoFar + junctionPrefix + prefix, notesFont));
2313
- if (cut >= 0 && cut + 1 < item.notes.length) {
2314
- const rest = applyBreakCut(item, cut);
2315
- queueContinuation(item, idx, rest);
2316
- parts = splitNoteMarkers(item.notes);
2317
- placed = place();
2318
- break;
2319
- }
2320
- }
2321
- if (line.notesParts.length === 0 && tracks.every((t) => t.cursor === 0)) {
2322
- if (notesOver) {
2323
- const cut = findBreakCut(item.notes, maxWidthPx, (prefix) => measure(notesSoFar + prefix, notesFont));
2324
- if (cut >= 0 && cut + 1 < item.notes.length) {
2325
- const rest = applyBreakCut(item, cut);
2326
- item.notes = item.notes.slice(0, cut);
2327
- queueContinuation(item, idx, rest);
2328
- parts = splitNoteMarkers(item.notes);
2329
- placed = place();
2330
- }
2331
- }
2332
- break;
2333
- }
2334
- startLine();
2335
- junctionPrefix = "";
2336
- parts = splitNoteMarkers(item.notes);
2337
- placed = place();
2338
- }
2339
- };
2340
- fit();
2341
- const decide = (s) => {
2342
- const { t, textWidth } = s;
2343
- const { contentWidth } = placed;
2344
- const connectorDash = line.notesParts.length > 0 && !t.prevWordEnd && s.pendingTotal === 0;
2345
- const minStart = t.cursor + t.hyphen.width;
2346
- const minTextStart = t.cursor + s.pendingTotal + (prevRecited && connectorDash ? t.hyphen.width : 0);
2347
- let textStart = placed.textStartOf(textWidth);
2348
- let contentStart = placed.contentStart;
2349
- let pads = 0;
2350
- let tight = false;
2351
- if (!prevRecited && connectorDash && textStart < minStart && (textWidth > contentWidth || textStart < t.cursor)) {
2352
- tight = true;
2353
- textStart = t.cursor;
2354
- const idealContentStart = contentWidth >= textWidth ? textStart : textStart + (textWidth - contentWidth) / 2;
2355
- if (idealContentStart > contentStart) pads = Math.round((idealContentStart - contentStart) / dashNotesWidth);
2356
- return {
2357
- textStart,
2358
- contentStart,
2359
- pads,
2360
- tight,
2361
- floor: t.cursor,
2362
- minStart
2363
- };
2364
- }
2365
- if (textStart < minTextStart) {
2366
- const idealContentStart = contentWidth >= textWidth ? minTextStart : minTextStart + (textWidth - contentWidth) / 2;
2367
- if (idealContentStart > contentStart) {
2368
- pads = Math.max(0, Math.floor((idealContentStart - contentStart) / dashNotesWidth));
2369
- let padded = place(pads);
2370
- while (padded.textStartOf(textWidth) < minTextStart) {
2371
- pads++;
2372
- padded = place(pads);
2373
- }
2374
- textStart = padded.textStartOf(textWidth);
2375
- contentStart = padded.contentStart;
2376
- }
2377
- }
2378
- return {
2379
- textStart,
2380
- contentStart,
2381
- pads,
2382
- tight,
2383
- floor: minTextStart,
2384
- minStart
2385
- };
2386
- };
2387
- const hiddenSpecial = special && !runStart && line.notesParts.length > 0 && !afterInlineClef;
2388
- let placements;
2389
- let padDashes = 0;
2390
- if (hiddenSpecial) {
2391
- junctionPrefix = "";
2392
- placements = voiced.map((s) => {
2393
- const textStart = s.t.cursor + s.pendingTotal;
2394
- return {
2395
- textStart,
2396
- contentStart: placed.contentStart,
2397
- pads: 0,
2398
- tight: line.notesParts.length > 0 && !s.t.prevWordEnd && s.pendingTotal === 0,
2399
- floor: textStart,
2400
- minStart: textStart
2401
- };
2402
- });
2403
- const deficit = Math.max(...voiced.map((s, v) => placements[v].textStart + s.textWidth + s.spaceWidth)) - measure(notesSoFar, notesFont);
2404
- const room = maxWidthPx - measure(notesSoFar + junctionPrefix, notesFont);
2405
- const fill = deficit > 0 ? Math.min(Math.ceil(deficit / dashNotesWidth), Math.max(0, Math.floor(room / dashNotesWidth))) : 0;
2406
- item.notes = "-".repeat(fill);
2407
- item.inserted = [];
2408
- parts = splitNoteMarkers(item.notes);
2409
- } else {
2410
- const settle = () => {
2411
- placements = voiced.map(decide);
2412
- padDashes = Math.max(0, ...placements.map((p) => p.pads));
2413
- if (placements.some((p) => p.pads < padDashes)) {
2414
- const padded = place(padDashes);
2415
- placements = placements.map((p, v) => {
2416
- if (p.pads === padDashes) return p;
2417
- const textStart = Math.max(padded.textStartOf(voiced[v].textWidth), p.floor);
2418
- return {
2419
- ...p,
2420
- textStart,
2421
- contentStart: padded.contentStart,
2422
- pads: padDashes,
2423
- tight: p.tight && textStart < p.minStart
2424
- };
2425
- });
2426
- }
2427
- };
2428
- settle();
2429
- if (line.notesParts.length > 0 && (measure(notesSoFar + junctionPrefix + "-".repeat(padDashes) + item.notes, notesFont) > maxWidthPx || voiced.some((s, v) => {
2430
- return Math.max(placements[v].textStart, s.t.cursor + s.pendingTotal) + s.textWidth + (s.own.wordEnd ? 0 : hyphenOf(s.own.hyphen).width) > maxWidthPx;
2431
- }))) {
2432
- const recut = items.length > uncut.items;
2433
- if (recut) {
2434
- items.splice(idx + 1, items.length - uncut.items);
2435
- item.notes = uncut.notes;
2436
- item.inserted = uncut.inserted;
2437
- item.lastSeg = uncut.lastSeg;
2438
- forceBreak = uncut.forceBreak;
2439
- }
2440
- startLine();
2441
- junctionPrefix = "";
2442
- parts = splitNoteMarkers(item.notes);
2443
- placed = place();
2444
- if (recut) fit();
2445
- settle();
2446
- }
2447
- }
2448
- const notesStr = junctionPrefix + "-".repeat(padDashes) + item.notes;
2449
- const fresh = line.notesParts.length === 0;
2450
- voiced.forEach((s, v) => {
2451
- const { t, sylParts, textWidth, spaceWidth, pendingTotal } = s;
2452
- const text = line.texts[tracks.indexOf(t)];
2453
- const p = placements[v];
2454
- let textStart = p.textStart;
2455
- if (pendingTotal > 0 && textStart < t.cursor + pendingTotal) textStart = t.cursor + pendingTotal;
2456
- const spacerWidth = Math.max(0, textStart - pendingTotal - t.cursor);
2457
- if (fresh) text.segments.push({
2458
- kind: "gap",
2459
- role: "lead-in",
2460
- width: spacerWidth,
2461
- endPx: textStart - pendingTotal,
2462
- textStartPx: textStart
2463
- });
2464
- else if (t.prevWordEnd) text.segments.push({
2465
- kind: "gap",
2466
- role: "word-gap",
2467
- width: spacerWidth,
2468
- endPx: textStart - pendingTotal,
2469
- textStartPx: textStart
2470
- });
2471
- else if (pendingTotal === 0 && p.tight) {} else if (pendingTotal === 0) {
2472
- const pad = Math.max(0, (spacerWidth - t.hyphen.width) / 2);
2473
- text.segments.push({
2474
- kind: "connector",
2475
- pad,
2476
- gapWidth: spacerWidth,
2477
- dashWidth: t.hyphen.width,
2478
- ...t.hyphen.parts ? { parts: t.hyphen.parts } : {},
2479
- dashStartPx: t.cursor + pad,
2480
- nextAnchorPx: textStart
2481
- });
2482
- }
2483
- let pendingStart = textStart - pendingTotal;
2484
- for (const pend of t.pending) {
2485
- text.segments.push({
2486
- kind: "syl",
2487
- parts: pend.sylParts,
2488
- textStart: pendingStart,
2489
- textWidth: pend.textWidth,
2490
- contentWidth: 0,
2491
- contentStart: 0,
2492
- extraDashes: 0,
2493
- tight: false,
2494
- noNotes: true
2495
- });
2496
- pendingStart += pend.textWidth;
2497
- if (pend.spaceWidth > 0) {
2498
- text.segments.push({
2499
- kind: "word-space",
2500
- width: pend.spaceWidth
2501
- });
2502
- pendingStart += pend.spaceWidth;
2503
- }
2504
- }
2505
- t.pending = [];
2506
- text.segments.push({
2507
- kind: "syl",
2508
- parts: sylParts,
2509
- textStart,
2510
- textWidth,
2511
- contentWidth: placed.contentWidth,
2512
- contentStart: p.contentStart,
2513
- extraDashes: padDashes,
2514
- tight: p.tight,
2515
- noNotes: false
2516
- });
2517
- if (spaceWidth > 0) text.segments.push({
2518
- kind: "word-space",
2519
- width: spaceWidth
2520
- });
2521
- t.cursor = textStart + textWidth + spaceWidth;
2522
- text.lastWordEnd = s.own.wordEnd;
2523
- t.prevWordEnd = s.own.wordEnd;
2524
- t.hyphen = hyphenOf(s.own.hyphen);
2525
- text.hyphen = t.hyphen;
2526
- });
2527
- for (const s of sung) if (!voiced.includes(s)) keepWordState(s, fresh);
2528
- notesSoFar += notesStr;
2529
- line.notesParts.push(notesStr);
2530
- afterInlineClef = false;
2531
- if (item.lastSeg) {
2532
- lastGroupTrailingMarker = parts.trailing.length > 0;
2533
- prevRecited = special;
2534
- }
2535
- if (!item.lastSeg) forceBreak = true;
2536
- idx++;
2537
- }
2538
- notePlacedLine();
2539
- flushPending(true);
2540
- while (keepStack.length > 0) closeKeepRun();
2541
- tracks.forEach((t, u) => {
2542
- line.texts[u].textCursor = t.cursor;
2543
- });
2544
- line.notesEnd = line.notesParts.length ? measure(line.clefPrefix + line.notesParts.join(""), notesFont) : 0;
2545
- lines.forEach((l, li) => {
2546
- if (li === lines.length - 1) return;
2547
- for (const text of l.texts) {
2548
- if (text.lastWordEnd !== false) continue;
2549
- const hyphen = text.hyphen ?? { width: dashTextWidth };
2550
- const pad = l.notesEnd > text.textCursor ? Math.max(0, (l.notesEnd - text.textCursor - hyphen.width) / 2) : 0;
2551
- text.segments.push({
2552
- kind: "line-end-dash",
2553
- pad,
2554
- dashWidth: hyphen.width,
2555
- ...hyphen.parts ? { parts: hyphen.parts } : {},
2556
- dashStartPx: text.textCursor + pad,
2557
- trailEndPx: l.notesEnd,
2558
- textEndPx: text.textCursor
2559
- });
2560
- }
2561
- });
2562
- for (const l of lines) {
2563
- l.textCursor = l.texts[0].textCursor;
2564
- l.lastWordEnd = l.texts[0].lastWordEnd;
2565
- }
2566
- const padding = styleSet.padding ?? 0;
2567
- const starTarget = maxWidthPx + padding;
2568
- const starWidth = measure("*", notesFont);
2569
- const fill = staffFill === "all" && maxWidthPx === Infinity ? "longest" : staffFill;
2570
- const fillsLast = fill === "all" || fill === "longest";
2571
- const longest = Math.max(...lines.map((l) => Math.max(l.notesEnd, ...l.texts.map((t) => t.textCursor))));
2572
- const fillTarget = fill === "none" || maxWidthPx === Infinity && !fillsLast ? null : fill === "longest" && maxWidthPx - longest > staffFillSnapPx ? longest : maxWidthPx;
2573
- lines.forEach((l, li) => {
2574
- const last = li === lines.length - 1;
2575
- l.staffEnd = l.notesEnd;
2576
- if (last && (!fillsLast || l.notesParts.length === 0)) return;
2577
- if (fillTarget === null) {
2578
- l.breakMarkerLeftPx = padding;
2579
- return;
2580
- }
2581
- const staffEdge = fillTarget + padding;
2582
- let lineEnd = measure(l.clefPrefix + l.notesParts.join(""), notesFont);
2583
- while (last ? lineEnd + dashNotesWidth <= staffEdge : lineEnd + dashNotesWidth <= staffEdge - starWidth && lineEnd + dashNotesWidth < fillTarget) {
2584
- l.notesParts.push("-");
2585
- lineEnd += dashNotesWidth;
2586
- }
2587
- if (last) {
2588
- const third = measure("¨", notesFont);
2589
- while (lineEnd + third <= staffEdge) {
2590
- l.notesParts.push("¨");
2591
- lineEnd += third;
2592
- }
2593
- }
2594
- l.staffEnd = lineEnd;
2595
- if (!last) l.breakMarkerLeftPx = staffEdge - lineEnd - starWidth;
2596
- });
2597
- return {
2598
- result: {
2599
- lines,
2600
- clefPrefix: lines[0].clefPrefix,
2601
- styleSet,
2602
- styleName,
2603
- textPx,
2604
- notesPx,
2605
- bold,
2606
- maxWidthPx,
2607
- starTarget,
2608
- starWidth
2609
- },
2610
- splitRuns,
2611
- placedNotes,
2612
- sylLines
2613
- };
2614
- }
2615
- //#endregion
2616
- export { CLEF_GLYPHS as A, toCephalicus as B, scriptSyllables as C, resolveSpans as D, unescape as E, isModifierGlyph as F, toVirga as G, toLonga as H, modifyDown as I, variantOf as K, modifyNatural as L, baseOf as M, gClefPitchOf as N, SCORE_MARKERS as O, isClefGlyph as P, modifyUp as R, runProperties as S, syllableText as T, toSmallHead as U, toConnectDown as V, toSmallPoint as W, GuidoScript as _, DEFAULT_STYLE_SET as a, isC4ClefGroup as b, defineStyleSet as c, measurementFont as d, resolveMarks as f, unknownMarks as g, styleSetOf as h, measure as i, STAFF as j, splitNoteMarkers as k, inlineStylesFor as l, resolveTextRuns as m, SPECIAL_NOTES as n, SMALL_CAP_SCALE as o, resolveSyllableParts as p, layoutScore as r, STYLE_SETS as s, NOTE_MODIFIERS as t, kindOf as u, chantText as v, statementSource as w, isStatementGroup as x, escape as y, pitchLetterOf as z };