guidex 0.5.1 → 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 +200 -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-DUxsPIm0.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-DmjGFR7e.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-DGWAhg8Q.js +0 -2617
@@ -0,0 +1,993 @@
1
+ import { A as splitNoteMarkers, D as resolveSpans, E as unescape, G as toSmallHead, I as isClefGlyph, J as variantOf, L as isModifierGlyph, M as STAFF, N as baseOf, _ as GuidoScript, b as isC4ClefGroup, d as resolveMarks, g as unknownMarks, j as CLEF_GLYPHS, l as kindOf, m as styleSetOf, p as resolveTextRuns, w as statementSource, x as isStatementGroup, y as escape } from "./guidoStyles-CvnACCsk.js";
2
+ //#region src/stanzas.ts
3
+ /**
4
+ * Stanzas on one melody (issue #69): a hymn stores its melody once, as
5
+ * stanza 1's GuidoScript, and every further stanza as syllabified text
6
+ * whose syllables map one-to-one onto the melody's note groups — the
7
+ * slots.
8
+ *
9
+ * A slot is one note group: held groups and `~` empty slots included
10
+ * (issue #83), syllables without notes and marker-only groups not. The
11
+ * further stanzas ride the script as `(@stanza …)` statements at its end
12
+ * (`GuidoScript.stanzas`), or come from a `stanzas` option that replaces
13
+ * them. Stanza numbers and slot numbers are 1-based: stanza 1 is the
14
+ * script itself, and they are what the warnings report.
15
+ *
16
+ * Stanza text follows Aretino's lyric-line rules (see `parseStanza`).
17
+ * Rendering stanza k is a script rewrite (`selectStanza`, `withStanza`):
18
+ * its syllables are swapped onto the slots, the notes never change, so
19
+ * every emitter (DOM, image, Word) works on the result unchanged.
20
+ */
21
+ /** The syllable text that marks a slot a stanza is missing a syllable
22
+ * for: a rubric ellipsis, red in BNS, so the mismatch shows in the
23
+ * render (and in the Word export). */
24
+ var STANZA_PLACEHOLDER = "_…_";
25
+ /** The unescaped characters that end a syllable within a word: the
26
+ * hyphen, the mandatory hyphen and the soft hyphen. */
27
+ var SYLLABLE_BREAKS = "-=­";
28
+ /** The characters an escape takes out of the syllable formatting. */
29
+ var MARKUP_CHARS = "_*†∗{}";
30
+ /**
31
+ * Parses stanza text into its slot items, by Aretino's lyric-line rules:
32
+ *
33
+ * - whitespace separates words, `-` separates the syllables of a word
34
+ * (a soft hyphen U+00AD counts as `-`, and so does the mandatory
35
+ * hyphen `=` — the renderer has no hyphen it may not drop yet);
36
+ * - a lone `-` (or an empty syllable, `Al--le`) holds the slot for the
37
+ * syllable before it; that syllable's word end is its own (`Al- - le`
38
+ * is mid-word, `bunt - gen` ends the word);
39
+ * - a lone `~` is an empty slot; `~` inside a syllable is a
40
+ * non-breaking space;
41
+ * - a backslash makes the next character literal (`\-`, `\~`, `\=`,
42
+ * `\(`, `\\`), markup characters included (`\_`, `\*`).
43
+ *
44
+ * There are no `_` extenders: `_…_`, `__…__` and `*…*` stay the
45
+ * syllable formatting of the script notation.
46
+ */
47
+ function parseStanza(text) {
48
+ const words = [];
49
+ let word = null;
50
+ const chars = Array.from(text);
51
+ for (let i = 0; i < chars.length; i++) {
52
+ let ch = chars[i];
53
+ const escaped = ch === "\\" && i + 1 < chars.length;
54
+ if (escaped) ch = chars[++i];
55
+ if (!escaped && /\s/.test(ch)) {
56
+ word = null;
57
+ continue;
58
+ }
59
+ if (word === null) {
60
+ word = [];
61
+ words.push(word);
62
+ }
63
+ word.push({
64
+ ch,
65
+ escaped
66
+ });
67
+ }
68
+ const out = [];
69
+ for (const w of words) {
70
+ if (w.length === 1 && !w[0].escaped && w[0].ch === "~") {
71
+ out.push({ kind: "empty" });
72
+ continue;
73
+ }
74
+ const pieces = [""];
75
+ const written = [""];
76
+ for (const { ch, escaped } of w) {
77
+ if (!escaped && SYLLABLE_BREAKS.includes(ch)) {
78
+ pieces.push("");
79
+ written.push("");
80
+ continue;
81
+ }
82
+ const shown = !escaped && ch === "~" ? "\xA0" : ch;
83
+ pieces[pieces.length - 1] += shown;
84
+ written[written.length - 1] += escaped && MARKUP_CHARS.includes(ch) ? `\\${ch}` : escape(shown);
85
+ }
86
+ const last = pieces.length - 1;
87
+ for (const [p, piece] of pieces.entries()) {
88
+ if (piece === "") {
89
+ if (p < last) out.push({ kind: "hold" });
90
+ continue;
91
+ }
92
+ const source = written[p];
93
+ out.push({
94
+ kind: "syllable",
95
+ text: piece,
96
+ wordEnd: p === last,
97
+ ...source !== escape(piece) ? { source } : {}
98
+ });
99
+ }
100
+ }
101
+ return standaloneSpans(out);
102
+ }
103
+ /** Closes a `{…}` span at each stanza syllable and reopens it at the next,
104
+ * so a syllable stands on its own wherever a slice cuts the stanza. */
105
+ function standaloneSpans(items) {
106
+ const syllables = items.filter((item) => item.kind === "syllable");
107
+ const written = syllables.map((syl) => syl.source ?? escape(syl.text));
108
+ if (!written.some((text) => /[{}]/.test(text))) return items;
109
+ const { pieces } = resolveSpans(written);
110
+ for (const [i, syl] of syllables.entries()) syl.source = pieces[i].source;
111
+ return items;
112
+ }
113
+ /** Whether a token opens a slot: a sung syllable with notes that are not
114
+ * all markers. Labels and signs are never slots. */
115
+ function isSlot(tok) {
116
+ return tok.kind === "syllable" && tok.role !== "label" && tok.role !== "sign" && tok.notes !== "" && splitNoteMarkers(tok.notes).core !== "";
117
+ }
118
+ function parsed(script) {
119
+ return typeof script === "string" ? new GuidoScript(script) : script;
120
+ }
121
+ /** The number of slots (note groups that take a stanza syllable). */
122
+ function slotCount(script) {
123
+ return parsed(script).tokens.filter(isSlot).length;
124
+ }
125
+ /** The stanza texts of stanzas 2, 3, …: the `stanzas` option when
126
+ * given, the script's `(@stanza …)` statements otherwise. */
127
+ function stanzaTexts(script, options = {}) {
128
+ return options.stanzas ?? parsed(script).stanzas;
129
+ }
130
+ /** How many stanzas the script has, stanza 1 (the script) included. */
131
+ function stanzaCount(script, options = {}) {
132
+ return stanzaTexts(script, options).length + 1;
133
+ }
134
+ function sings(fill) {
135
+ return fill.kind === "syllable" || fill.kind === "hold";
136
+ }
137
+ /** Stanza 1's fills: the slot tokens themselves. */
138
+ function scriptFills(slots) {
139
+ return slots.map((tok) => tok.empty ? { kind: "empty" } : tok.held ? { kind: "hold" } : {
140
+ kind: "syllable",
141
+ text: tok.text,
142
+ source: tok.source,
143
+ wordEnd: tok.wordEnd
144
+ });
145
+ }
146
+ /** A stanza's syllables laid on `count` slots, with its mismatches. */
147
+ function alignStanza(text, count, stanza) {
148
+ const syllables = parseStanza(text);
149
+ const fills = [];
150
+ const warnings = [];
151
+ for (let i = 0; i < count; i++) {
152
+ const syl = syllables[i];
153
+ fills.push(syl ?? { kind: "missing" });
154
+ if (syl === void 0) warnings.push({
155
+ stanza,
156
+ slot: i + 1,
157
+ kind: "missing",
158
+ message: `Stanza ${stanza} has no syllable for slot ${i + 1} of ${count}`
159
+ });
160
+ }
161
+ for (const [i, syl] of syllables.slice(count).entries()) {
162
+ const shown = syl.kind === "syllable" ? syl.text : syl.kind === "hold" ? "-" : "~";
163
+ warnings.push({
164
+ stanza,
165
+ slot: count + i + 1,
166
+ kind: "extra",
167
+ text: shown,
168
+ message: `Stanza ${stanza} has an extra syllable "${shown}" past the last slot (${count})`
169
+ });
170
+ }
171
+ return {
172
+ fills,
173
+ warnings
174
+ };
175
+ }
176
+ /** Throws when `stanza` is not one of the script's stanzas. */
177
+ function checkStanzaNumber(stanza, count) {
178
+ if (!Number.isInteger(stanza) || stanza < 1 || stanza > count) throw new RangeError(`Stanza ${stanza} does not exist: the script has ${count} stanza${count === 1 ? "" : "s"}`);
179
+ }
180
+ /** The count mismatches of one stanza (`options.stanza`), or of every
181
+ * stanza when none is named. Stanza 1 is the script and never warns;
182
+ * an intentional `~` is a syllable like any other. */
183
+ function stanzaWarnings(script, options = {}) {
184
+ const texts = stanzaTexts(script, options);
185
+ const count = slotCount(script);
186
+ if (options.stanza !== void 0) {
187
+ checkStanzaNumber(options.stanza, texts.length + 1);
188
+ if (options.stanza === 1) return [];
189
+ return alignStanza(texts[options.stanza - 2], count, options.stanza).warnings;
190
+ }
191
+ return texts.flatMap((text, i) => alignStanza(text, count, i + 2).warnings);
192
+ }
193
+ /** Pads stanza text with `~` empty slots up to the script's slot count
194
+ * (unchanged when it already has enough syllables). */
195
+ function padStanza(script, text) {
196
+ const missing = slotCount(script) - parseStanza(text).length;
197
+ return missing > 0 ? `${text.trimEnd()}${" ~".repeat(missing)}` : text;
198
+ }
199
+ /** A note group with its plain heads, virgas and longas swapped for small
200
+ * heads (connectors, markers and signs stay). */
201
+ function smallHeads(notes) {
202
+ return Array.from(notes, (ch) => {
203
+ const small = toSmallHead(ch);
204
+ if (small !== void 0) return small;
205
+ const variant = baseOf(ch);
206
+ if (variant && (variant.role === "virga" || variant.role === "longa")) return toSmallHead(variant.base) ?? ch;
207
+ return ch;
208
+ }).join("");
209
+ }
210
+ /** A stanza syllable written in the script notation. */
211
+ function syllableSource({ text, source }) {
212
+ return source ?? (text === "~" ? "\\~" : escape(text));
213
+ }
214
+ /** Rewrites a script's source to sing stanza `stanza`. */
215
+ function stanzaSource(source, stanza, options) {
216
+ const script = new GuidoScript(source);
217
+ const texts = stanzaTexts(script, options);
218
+ checkStanzaNumber(stanza, texts.length + 1);
219
+ const rendered = options.rendered ?? [stanza];
220
+ for (const k of rendered) checkStanzaNumber(k, texts.length + 1);
221
+ const mode = options.emptySlots ?? "normal";
222
+ if (stanza === 1 && mode === "normal") return source;
223
+ const tokens = script.tokens;
224
+ const slotTokens = tokens.filter((t) => isSlot(t));
225
+ const allFills = [scriptFills(slotTokens), ...texts.map((text, i) => alignStanza(text, slotTokens.length, i + 2).fills)];
226
+ const fills = allFills[stanza - 1];
227
+ const cue = (slot) => mode === "partial" ? allFills.some((f) => sings(f[slot])) && !allFills.every((f) => sings(f[slot])) : mode === "small" && rendered.every((k) => !sings(allFills[k - 1][slot])) && allFills.some((f, j) => !rendered.includes(j + 1) && sings(f[slot]));
228
+ let out = script.clef !== void 0 ? `(${script.clef})` : "";
229
+ let first = true;
230
+ let pendingSpace = false;
231
+ let canHold = false;
232
+ const emit = (piece, space) => {
233
+ out += (space && !first ? " " : "") + piece;
234
+ first = false;
235
+ };
236
+ let slot = 0;
237
+ for (const tok of tokens) {
238
+ if (tok.kind !== "syllable") {
239
+ emit(statementSource(tok), pendingSpace);
240
+ pendingSpace = false;
241
+ continue;
242
+ }
243
+ if (!isSlot(tok)) {
244
+ if (tok.held) {
245
+ emit(`(${escape(tok.notes)})`, pendingSpace);
246
+ pendingSpace = false;
247
+ } else {
248
+ emit(`${tok.source}(${escape(tok.notes)})`, pendingSpace || tok.spaceBefore);
249
+ pendingSpace = tok.wordEnd;
250
+ canHold = tok.notes !== "";
251
+ }
252
+ continue;
253
+ }
254
+ const fill = fills[slot];
255
+ const notes = escape(cue(slot) ? smallHeads(tok.notes) : tok.notes);
256
+ slot++;
257
+ switch (fill.kind) {
258
+ case "syllable":
259
+ emit(`${syllableSource(fill)}(${notes})`, pendingSpace);
260
+ pendingSpace = fill.wordEnd;
261
+ break;
262
+ case "hold":
263
+ emit(`${canHold ? "" : "~"}(${notes})`, false);
264
+ break;
265
+ case "empty":
266
+ emit(`~(${notes})`, false);
267
+ break;
268
+ case "missing":
269
+ emit(`${STANZA_PLACEHOLDER}(${notes})`, true);
270
+ pendingSpace = true;
271
+ }
272
+ canHold = true;
273
+ }
274
+ return out;
275
+ }
276
+ /** The `selectStanza` transform factory: rewrites the script to sing
277
+ * stanza `stanza` (1-based; 1 is the script itself). Its syllables go on
278
+ * the slots in order — missing ones become `STANZA_PLACEHOLDER`
279
+ * syllables, extra ones are dropped (`stanzaWarnings` reports both) — and
280
+ * the `(@stanza …)` statements are dropped. Everything that is not a
281
+ * slot (statements, syllables without notes, marker-only groups) stays as
282
+ * written. With `emptySlots: 'small'`, a slot the stanza leaves empty
283
+ * while another stanza sings it gets small heads (`rendered` lists the
284
+ * stanzas stacked with it: then a slot gets small heads when none of
285
+ * them sings it while another stanza does). With `emptySlots:
286
+ * 'partial'`, every slot some stanza sings and another does not gets
287
+ * small heads, whatever is rendered. Stanza 1 with normal
288
+ * empty slots returns the source unchanged. Throws a RangeError for a
289
+ * stanza the script does not have. Register it first, so the other
290
+ * transforms (the initial, the transpositions) see the stanza's text. */
291
+ function selectStanza(stanza, options = {}) {
292
+ return {
293
+ name: "selectStanza",
294
+ apply: (source) => stanzaSource(source, stanza, options)
295
+ };
296
+ }
297
+ /** The script singing stanza `stanza` (see `selectStanza`); `transforms`
298
+ * run after the stanza swap. A GuidoScript argument is taken by its
299
+ * (already transformed) source. */
300
+ function withStanza(script, stanza, options = {}) {
301
+ const source = typeof script === "string" ? script : script.source;
302
+ return new GuidoScript(source, { transforms: [selectStanza(stanza, options), ...options.transforms ?? []] });
303
+ }
304
+ /** The stanza numbers a stack names: every stanza for `'all'`, the
305
+ * listed ones otherwise. Throws a RangeError for an empty list or a
306
+ * stanza the script does not have. */
307
+ function stackedStanzaNumbers(script, stack, options = {}) {
308
+ const count = stanzaCount(script, options);
309
+ if (stack === "all") return Array.from({ length: count }, (_, k) => k + 1);
310
+ if (stack.length === 0) throw new RangeError("No stanza to stack: the list is empty");
311
+ for (const k of stack) checkStanzaNumber(k, count);
312
+ return [...stack];
313
+ }
314
+ /** The scripts of stacked stanzas (issue #84): one per stanza of the
315
+ * stack, in its order, each singing its stanza on the shared notes (see
316
+ * `withStanza`; `transforms` run after the swap). Hand them to the layout
317
+ * together (`layoutScore`, `GuidoRender`, the Word export) for one text
318
+ * line per stanza under one staff. With `emptySlots: 'small'`, a slot
319
+ * gets small heads when no stacked stanza sings it while a stanza left
320
+ * out of the stack does, so every script carries the same notes. */
321
+ function stackStanzas(script, stack, options = {}) {
322
+ const rendered = stackedStanzaNumbers(script, stack, options);
323
+ return rendered.map((k) => withStanza(script, k, {
324
+ ...options,
325
+ rendered
326
+ }));
327
+ }
328
+ //#endregion
329
+ //#region src/exactTranspose.ts
330
+ /**
331
+ * Exact transposition (issue #70): moves the sounding pitches of a
332
+ * script and re-notates them under a target clef and key, so the result
333
+ * reads like a chant notated at the new pitch. The staff-degree shift
334
+ * (`transposeBy`) stays separate and ignores pitch meaning.
335
+ *
336
+ * A note's sounding pitch is its staff position + the clef in effect +
337
+ * the key in effect + any sign written in its group. A sign affects its
338
+ * whole group: every note of that pitch letter, in every octave. The
339
+ * transposition is two steps:
340
+ *
341
+ * 1. Move every pitch by a spelled interval (letter steps + semitones,
342
+ * so a major third up turns b♭ into d, not e♭♭).
343
+ * 2. Re-notate under the target clef and key: each note's staff position
344
+ * and glyph, plus the signs the target key doesn't cover. Added signs
345
+ * go before the note group, after its leading markers (the #49 rule).
346
+ *
347
+ * Keys are written with the classical key-signature layout
348
+ * (`KEY_SIGNATURES`). Results past the glyph range and missing glyph
349
+ * variants are errors, never silent clamps. Small points are the one
350
+ * exception: the font draws them in the spaces (and on a″), so one that
351
+ * lands on another line moves to a space (`smallPointAt`).
352
+ */
353
+ /** A transposed note past the end of the glyph range. Thrown as its own
354
+ * class so the octave search for a `final` can tell it apart. */
355
+ var TranspositionRangeError = class extends Error {
356
+ constructor(message) {
357
+ super(message);
358
+ this.name = "TranspositionRangeError";
359
+ }
360
+ };
361
+ /** The key-signature glyphs per clef glyph (issue #70): flats in the
362
+ * order b e a d g c f, sharps in the order f c g d a e b, each at the
363
+ * highest octave of the shape that stays on the staff. A key of n signs
364
+ * is the first n glyphs of its row. */
365
+ var KEY_SIGNATURES = {
366
+ M: {
367
+ flats: "XBYVÍCS",
368
+ sharps: "ôþùßÑòÒ"
369
+ },
370
+ "<": {
371
+ flats: "XBYVÍCS",
372
+ sharps: "ôþùßÑòÒ"
373
+ },
374
+ ">": {
375
+ flats: "V$CNXBY",
376
+ sharps: "ÑòÒôþùß"
377
+ },
378
+ "#": {
379
+ flats: "NXBYVÍC",
380
+ sharps: "þÐßÑÎÒÏ"
381
+ },
382
+ "&": {
383
+ flats: "YVÍCSXA",
384
+ sharps: "òÒôþÐßÑ"
385
+ },
386
+ "@": {
387
+ flats: "CNXBYVÍ",
388
+ sharps: "ÐßÑòÒôþ"
389
+ },
390
+ "{": {
391
+ flats: "BYVÍCSX",
392
+ sharps: "ÒÏþÐÌÑÎ"
393
+ },
394
+ "}": {
395
+ flats: "ÍCSXAYa",
396
+ sharps: "ßÑòÒÏþÐ"
397
+ }
398
+ };
399
+ var FLAT_ORDER = "beadgcf";
400
+ var SHARP_ORDER = "fcgdaeb";
401
+ /** Pitch letters from c, so a diatonic step's letter is `step mod 7`. */
402
+ var LETTERS = "cdefgab";
403
+ var LETTER_SEMITONES = [
404
+ 0,
405
+ 2,
406
+ 4,
407
+ 5,
408
+ 7,
409
+ 9,
410
+ 11
411
+ ];
412
+ var mod7 = (n) => (n % 7 + 7) % 7;
413
+ function semitoneOf({ step, alter }) {
414
+ return Math.floor(step / 7) * 12 + LETTER_SEMITONES[mod7(step)] + alter;
415
+ }
416
+ function letterName(step) {
417
+ return LETTERS[mod7(step)];
418
+ }
419
+ /** A pitch moved by a spelled interval: the letter moves by the steps,
420
+ * the alteration absorbs whatever the semitones leave over. */
421
+ function movePitch(pitch, interval) {
422
+ const step = pitch.step + interval.steps;
423
+ const alter = semitoneOf(pitch) + interval.semitones - semitoneOf({
424
+ step,
425
+ alter: 0
426
+ });
427
+ if (Math.abs(alter) > 1) throw new Error(`Moving ${letterName(pitch.step)}${alterName(pitch.alter)} lands on a double accidental (${letterName(step)}, ${alter > 0 ? "+" : ""}${alter})`);
428
+ return {
429
+ step,
430
+ alter
431
+ };
432
+ }
433
+ function alterName(alter) {
434
+ return alter < 0 ? "♭" : alter > 0 ? "♯" : "";
435
+ }
436
+ function roleOfAlter(alter) {
437
+ return alter < 0 ? "modifyDown" : alter > 0 ? "modifyUp" : "modifyNatural";
438
+ }
439
+ function alterOfRole(role) {
440
+ return role === "modifyDown" ? -1 : role === "modifyUp" ? 1 : 0;
441
+ }
442
+ /** The staff position of a clef's own line and the step of its pitch. */
443
+ function clefAnchor(clef) {
444
+ const entry = CLEF_GLYPHS[clef];
445
+ const step = {
446
+ c: 28,
447
+ f: 24,
448
+ g: 32
449
+ }[entry.clef];
450
+ return {
451
+ position: STAFF.indexOf("2") + 2 * (entry.line - 1),
452
+ step
453
+ };
454
+ }
455
+ function stepAt(position, clef) {
456
+ const anchor = clefAnchor(clef);
457
+ return anchor.step + position - anchor.position;
458
+ }
459
+ function positionOf(step, clef) {
460
+ const anchor = clefAnchor(clef);
461
+ return anchor.position + step - anchor.step;
462
+ }
463
+ /** The staff position and variant role of a pitched glyph (`'base'` for
464
+ * a base glyph), or undefined for a glyph without pitch. */
465
+ function glyphOf(ch) {
466
+ if (STAFF.includes(ch)) return {
467
+ position: STAFF.indexOf(ch),
468
+ role: "base"
469
+ };
470
+ const entry = baseOf(ch);
471
+ return entry ? {
472
+ position: STAFF.indexOf(entry.base),
473
+ role: entry.role
474
+ } : void 0;
475
+ }
476
+ /** Whether `ch` is in a pitch row. Read at call time: this module and
477
+ * the transforms module import each other. */
478
+ function isPitchChar(ch) {
479
+ return ch === "ÿ" || PITCH_ROWS.some((row) => row.includes(ch));
480
+ }
481
+ /** The glyph of `role` at a staff position. Throws past the glyph range
482
+ * and when the variant does not exist. */
483
+ function glyphAt(position, role, what) {
484
+ const base = STAFF[position];
485
+ if (base === void 0) throw new TranspositionRangeError(`${what} runs past the glyph range`);
486
+ const glyph = role === "base" ? base : variantOf(base, role);
487
+ if (glyph === void 0) throw new Error(`${what}: the glyph "${base}" has no ${role} variant`);
488
+ return glyph;
489
+ }
490
+ /** The small point for a dot that moved to `position`. The font draws
491
+ * them in the spaces (and on a″), so a dot that lands on another line goes
492
+ * to the space of the note it lengthens (`notePosition`, the last note
493
+ * before it in its group, moved): the note's own space, or the space above
494
+ * a note on a line.
495
+ * Without a note before it, the dot rounds up to the space above. The
496
+ * note's own space is what keeps a dot right when its source note sat on
497
+ * a line and borrowed the space above: one step up, the note lands in a
498
+ * space and the dot keeps that space. */
499
+ function smallPointAt(position, notePosition, what) {
500
+ const hasDot = (p) => {
501
+ const base = STAFF[p];
502
+ return base !== void 0 && variantOf(base, "smallPoint") !== void 0;
503
+ };
504
+ if (hasDot(position)) return glyphAt(position, "smallPoint", what);
505
+ if (notePosition !== void 0 && hasDot(notePosition)) return glyphAt(notePosition, "smallPoint", what);
506
+ return glyphAt((notePosition ?? position) + 1, "smallPoint", what);
507
+ }
508
+ /** A key read from modifier glyphs under `clef`. Naturals carry no
509
+ * alteration, so they drop out. */
510
+ function readKey(glyphs, clef) {
511
+ const key = /* @__PURE__ */ new Map();
512
+ for (const ch of glyphs) {
513
+ if (!isModifierGlyph(ch)) continue;
514
+ const { base, role } = baseOf(ch);
515
+ const letter = mod7(stepAt(STAFF.indexOf(base), clef));
516
+ const alter = alterOfRole(role);
517
+ if (alter === 0) key.delete(letter);
518
+ else key.set(letter, alter);
519
+ }
520
+ return key;
521
+ }
522
+ /** A signed key count: −n is the first n flats, n the first n sharps. */
523
+ function countedKey(count) {
524
+ if (!Number.isInteger(count) || Math.abs(count) > 7) throw new Error(`A key has −7 to 7 signs, not ${count}`);
525
+ const order = count < 0 ? FLAT_ORDER : SHARP_ORDER;
526
+ const key = /* @__PURE__ */ new Map();
527
+ for (const name of order.slice(0, Math.abs(count))) key.set(LETTERS.indexOf(name), Math.sign(count));
528
+ return key;
529
+ }
530
+ /** A key moved by an interval. The key is a scale, not a set of
531
+ * pitches: every letter moves (d minor's natural e becomes g minor's
532
+ * e♭ a fourth up), and the moved key is whatever the scale alters. */
533
+ function moveKey(key, interval) {
534
+ const moved = /* @__PURE__ */ new Map();
535
+ for (let letter = 0; letter < 7; letter++) {
536
+ const pitch = movePitch({
537
+ step: letter,
538
+ alter: key.get(letter) ?? 0
539
+ }, interval);
540
+ if (pitch.alter !== 0) moved.set(mod7(pitch.step), pitch.alter);
541
+ }
542
+ return moved;
543
+ }
544
+ function sameKey(a, b) {
545
+ return a.size === b.size && [...a].every(([letter, alter]) => b.get(letter) === alter);
546
+ }
547
+ /** Whether two keys written as modifier glyphs under `clef` alter the
548
+ * same pitch letters the same way (glyph order and octave aside). */
549
+ function sameKeyGlyphs(a, b, clef) {
550
+ return sameKey(readKey(a, clef), readKey(b, clef));
551
+ }
552
+ /** A key written with the key-signature layout of `clef`: flats first,
553
+ * then sharps, each in the table's order. */
554
+ function writeKey(key, clef) {
555
+ const row = KEY_SIGNATURES[clef];
556
+ const glyphs = (order, alter, signs) => [...order].map((name, i) => key.get(LETTERS.indexOf(name)) === alter ? signs[i] : "").join("");
557
+ return glyphs(FLAT_ORDER, -1, row.flats) + glyphs(SHARP_ORDER, 1, row.sharps);
558
+ }
559
+ /** Parses an interval name: an optional sign, a quality (`P`, `M`, `m`,
560
+ * `A`, `d`) and a number (`P1`, `-P5`, `M3`, `A4`, `P8`, `M9`). */
561
+ function parseInterval(name) {
562
+ const match = name.trim().match(/^([+-]?)([PMmAd])(\d+)$/);
563
+ const number = match ? Number(match[3]) : 0;
564
+ if (!match || number < 1) throw new Error(`Unknown interval "${name}"`);
565
+ const [, sign, quality] = match;
566
+ const steps = number - 1;
567
+ const perfect = [
568
+ 0,
569
+ 3,
570
+ 4
571
+ ].includes(steps % 7);
572
+ if (!(perfect ? "PAd" : "MmAd").includes(quality)) throw new Error(`Unknown interval "${name}"`);
573
+ const base = Math.floor(steps / 7) * 12 + LETTER_SEMITONES[steps % 7];
574
+ const adjust = {
575
+ P: 0,
576
+ M: 0,
577
+ A: 1,
578
+ m: -1,
579
+ d: perfect ? -1 : -2
580
+ }[quality];
581
+ const direction = sign === "-" ? -1 : 1;
582
+ return {
583
+ steps: direction * steps,
584
+ semitones: direction * (base + adjust)
585
+ };
586
+ }
587
+ var GROUP = /((?:[^()\\]|\\.)*)\(((?:[^)\\]|\\.)*)\)/g;
588
+ function escapeNotes(notes) {
589
+ return notes.replace(/\\/g, "\\\\").replace(/[()]/g, (ch) => `\\${ch}`);
590
+ }
591
+ /** Re-notates one note group. `src*` are the clef and key in effect in
592
+ * the source, `tgt*` the ones in the result. Records the group's last
593
+ * note pitch (the candidate final) through `onNote`. */
594
+ function renotateGroup(notes, interval, srcClef, srcKey, tgtClef, tgtKey, onNote) {
595
+ const { leading, core, trailing } = splitNoteMarkers(notes);
596
+ const chars = [...core];
597
+ const groupSigns = /* @__PURE__ */ new Map();
598
+ for (const ch of chars) {
599
+ if (!isModifierGlyph(ch)) continue;
600
+ const glyph = glyphOf(ch);
601
+ const letter = mod7(stepAt(glyph.position, srcClef));
602
+ const alter = alterOfRole(glyph.role);
603
+ if (groupSigns.has(letter) && groupSigns.get(letter) !== alter) throw new Error(`The note group "${notes}" carries two different signs for ${LETTERS[letter]}`);
604
+ groupSigns.set(letter, alter);
605
+ }
606
+ const coveredLetters = /* @__PURE__ */ new Set();
607
+ const out = [];
608
+ const added = [];
609
+ const pending = [];
610
+ let notePosition;
611
+ for (const ch of chars) {
612
+ const glyph = glyphOf(ch);
613
+ if (!glyph) {
614
+ if (isPitchChar(ch)) throw new Error(`The glyph "${ch}" has no glyph-family entry, so it cannot be transposed exactly`);
615
+ out.push(ch);
616
+ continue;
617
+ }
618
+ const step = stepAt(glyph.position, srcClef);
619
+ const letter = mod7(step);
620
+ const keyAlter = srcKey.get(letter) ?? 0;
621
+ if (isModifierGlyph(ch)) {
622
+ const alter = alterOfRole(glyph.role);
623
+ const moved = movePitch({
624
+ step,
625
+ alter
626
+ }, interval);
627
+ const tgtAlter = tgtKey.get(mod7(moved.step)) ?? 0;
628
+ if (moved.alter !== tgtAlter || alter === keyAlter) {
629
+ const position = positionOf(moved.step, tgtClef);
630
+ out.push(glyphAt(position, roleOfAlter(moved.alter), `The sign "${ch}"`));
631
+ coveredLetters.add(mod7(moved.step));
632
+ }
633
+ continue;
634
+ }
635
+ const pitch = {
636
+ step,
637
+ alter: groupSigns.get(letter) ?? keyAlter
638
+ };
639
+ const moved = movePitch(pitch, interval);
640
+ const position = positionOf(moved.step, tgtClef);
641
+ if (glyph.role === "smallPoint") {
642
+ out.push(smallPointAt(position, notePosition, `The small point "${ch}"`));
643
+ continue;
644
+ }
645
+ out.push(glyphAt(position, glyph.role, `The note "${ch}"`));
646
+ notePosition = position;
647
+ onNote(pitch);
648
+ pending.push(moved);
649
+ }
650
+ for (const moved of pending) {
651
+ const letter = mod7(moved.step);
652
+ if (coveredLetters.has(letter) || moved.alter === (tgtKey.get(letter) ?? 0)) continue;
653
+ const sign = glyphAt(positionOf(moved.step, tgtClef), roleOfAlter(moved.alter), `The sign for ${letterName(moved.step)}${alterName(moved.alter)}`);
654
+ if (!added.includes(sign)) added.push(sign);
655
+ }
656
+ return leading + added.join("") + out.join("") + trailing;
657
+ }
658
+ /** One re-notation pass over the source. Returns the result and the
659
+ * source's final (the pitch of its last note). */
660
+ function renotate(source, plan) {
661
+ new GuidoScript(source).tokens;
662
+ const head = source.match(/^\s*\(([^)]*)\)/);
663
+ const opening = head && (!isStatementGroup(head[1]) || isC4ClefGroup(head[1])) ? head : null;
664
+ const openingClef = opening && isClefGlyph(opening[1].trimStart()[0] ?? "") ? opening[1].trimStart()[0] : void 0;
665
+ if (opening && openingClef === void 0 && opening[1].trim() !== "") throw new Error(`The opening group "(${opening[1]})" does not start with a clef glyph`);
666
+ if (plan.clef !== void 0 && !isClefGlyph(plan.clef)) throw new Error(`"${plan.clef}" is not a clef glyph`);
667
+ let srcClef = openingClef ?? "M";
668
+ let srcKey = readKey(opening && openingClef ? opening[1].trimStart().slice(1) : "", srcClef);
669
+ let tgtClef = plan.clef ?? srcClef;
670
+ let tgtKey = plan.key === void 0 ? moveKey(srcKey, plan.interval) : typeof plan.key === "number" ? countedKey(plan.key) : readKey(plan.key, tgtClef);
671
+ const openingKey = writeKey(tgtKey, tgtClef);
672
+ const openingGroup = opening || plan.clef !== void 0 || openingKey !== "" ? `(${tgtClef}${openingKey})` : "";
673
+ let final;
674
+ const offset = opening ? opening[0].length : 0;
675
+ return {
676
+ result: openingGroup + source.slice(offset).replace(GROUP, (_, text, rawNotes) => {
677
+ if (isStatementGroup(rawNotes)) {
678
+ const [, keyword, args = ""] = rawNotes.trim().match(/^@(\S*)(?: (.*))?$/) ?? [];
679
+ if (keyword === "clef") {
680
+ srcClef = args[0];
681
+ srcKey = readKey(args.slice(1), srcClef);
682
+ const moved = moveKey(srcKey, plan.interval);
683
+ if (plan.clef === void 0) {
684
+ tgtClef = srcClef;
685
+ tgtKey = moved;
686
+ return `${text}(@clef ${tgtClef}${writeKey(tgtKey, tgtClef)})`;
687
+ }
688
+ if (sameKey(moved, tgtKey)) return text;
689
+ tgtKey = moved;
690
+ const key = writeKey(tgtKey, tgtClef);
691
+ return `${text}(@key${key === "" ? "" : ` ${key}`})`;
692
+ }
693
+ if (keyword === "key") {
694
+ srcKey = readKey(args, srcClef);
695
+ tgtKey = moveKey(srcKey, plan.interval);
696
+ const key = writeKey(tgtKey, tgtClef);
697
+ return `${text}(@key${key === "" ? "" : ` ${key}`})`;
698
+ }
699
+ return `${text}(${rawNotes})`;
700
+ }
701
+ return `${text}(${escapeNotes(renotateGroup(unescape(rawNotes), plan.interval, srcClef, srcKey, tgtClef, tgtKey, (pitch) => {
702
+ final = pitch;
703
+ }))})`;
704
+ }),
705
+ final
706
+ };
707
+ }
708
+ /** The finals' pitch letter and alteration (`g`, `bb`, `b♭`, `f#`). */
709
+ function parseFinal(final) {
710
+ const match = final.trim().match(/^([a-gA-G])(b|♭|#|♯)?$/);
711
+ if (!match) throw new Error(`Unknown final "${final}"`);
712
+ const alter = match[2] === void 0 ? 0 : "b♭".includes(match[2]) ? -1 : 1;
713
+ return {
714
+ letter: LETTERS.indexOf(match[1].toLowerCase()),
715
+ alter
716
+ };
717
+ }
718
+ /**
719
+ * Transposes a script exactly: moves its sounding pitches and
720
+ * re-notates them under the target clef and key (see
721
+ * `TranspositionTarget`). Without a key, the key moves with the
722
+ * interval; without a clef, the clefs stay as written (mid-script
723
+ * `(@clef …)` included); `(@key …)` statements always move with the
724
+ * interval. A target clef re-notates the whole script in that clef and
725
+ * removes mid-script `(@clef …)` statements (one that changed the key
726
+ * leaves a `(@key …)` behind). With a `final`, the octave whose result
727
+ * fits the glyph range wins — the smaller move when several fit.
728
+ * Throws past the glyph range and on a missing glyph variant.
729
+ */
730
+ function transposeScript(source, target) {
731
+ if (target.interval !== void 0 && target.final !== void 0) throw new Error("A transposition target takes an interval or a final, not both");
732
+ const plan = (interval) => ({
733
+ interval,
734
+ clef: target.clef,
735
+ key: target.key
736
+ });
737
+ if (target.final === void 0) return renotate(source, plan(typeof target.interval === "string" ? parseInterval(target.interval) : target.interval ?? {
738
+ steps: 0,
739
+ semitones: 0
740
+ })).result;
741
+ const sourceFinal = renotate(source, { interval: {
742
+ steps: 0,
743
+ semitones: 0
744
+ } }).final;
745
+ if (sourceFinal === void 0) throw new Error("The script has no notes, so it has no final");
746
+ const wanted = parseFinal(target.final);
747
+ const up = mod7(wanted.letter - sourceFinal.step);
748
+ const candidates = [
749
+ -14,
750
+ -7,
751
+ 0,
752
+ 7,
753
+ 14
754
+ ].map((octave) => {
755
+ const semitones = semitoneOf({
756
+ step: sourceFinal.step + up + octave,
757
+ alter: wanted.alter
758
+ }) - semitoneOf(sourceFinal);
759
+ return {
760
+ steps: up + octave,
761
+ semitones
762
+ };
763
+ }).sort((a, b) => Math.abs(a.semitones) - Math.abs(b.semitones) || b.semitones - a.semitones);
764
+ let rangeError;
765
+ for (const interval of candidates) try {
766
+ return renotate(source, plan(interval)).result;
767
+ } catch (error) {
768
+ if (!(error instanceof TranspositionRangeError)) throw error;
769
+ rangeError ??= error;
770
+ }
771
+ throw rangeError;
772
+ }
773
+ /** The exact transposition as a script transform (see `transposeScript`). */
774
+ function transposeExact(target) {
775
+ return {
776
+ name: "transposeExact",
777
+ apply: (source) => transposeScript(source, target)
778
+ };
779
+ }
780
+ //#endregion
781
+ //#region src/guidoScriptTransforms.ts
782
+ /**
783
+ * Source-level transformations for GuidoScript: named rewrites applied
784
+ * to a script's raw source before parsing (see the `transforms` option
785
+ * on the GuidoScript constructor). Each one receives the source and
786
+ * returns the rewritten source — or the source unchanged when the
787
+ * feature does not apply. They compose in registration order, and the
788
+ * parsed script never sees which ones ran. New script-level features
789
+ * are added here, and only here, as factories returning a ScriptTransform
790
+ * (see `transposeBy`).
791
+ */
792
+ /** The pitch rows of the chant font: every character carrying pitch
793
+ * information, grouped into rows of neighbouring pitches from low to
794
+ * high. A transpose shift moves a character this many positions along
795
+ * its row; characters outside every row carry no pitch and stay put.
796
+ * Rows are searched in order, so a character found in several rows
797
+ * transposes within the first one. */
798
+ var PITCH_ROWS = [
799
+ "ðñ0123456789öüó",
800
+ "^]qwertzuiopõú",
801
+ "ÝÞQWERTZUIOPÕÚ",
802
+ "Ô×sdfghjkléáû",
803
+ "ØÙDFGHJKLÉÁÛ",
804
+ "÷øaASÍYXCVBN$m",
805
+ "ÈÊËÌÎÏÐÑÒþßòôùý",
806
+ "“”•–—˜™š›œº»",
807
+ "®−§'\"+!%/=()ÖÜÓ",
808
+ "€ŽžŸ¡¢£[¥¦©ª«¬¤",
809
+ "~¯‚ƒ„…†‡ˆ‰Š‹Œ‘’",
810
+ "àâãäåæçèêëìîï",
811
+ "½°±²³´μ·¾¸¹"
812
+ ];
813
+ /** Maps one character to its pitch-shifted neighbour, or undefined when
814
+ * it is not a pitch character (and so stays unchanged). */
815
+ function shiftPitch(ch, shift, overflow) {
816
+ if (ch === "ÿ") ch = "'";
817
+ for (const row of PITCH_ROWS) {
818
+ const index = row.indexOf(ch);
819
+ if (index === -1) continue;
820
+ const target = index + shift;
821
+ if (target < 0 || target >= row.length) {
822
+ if (overflow === "null") return "\0";
823
+ if (overflow === "error") throw new Error(`Transposing "${ch}" by ${shift} runs past the glyph range`);
824
+ return row[Math.max(0, Math.min(row.length - 1, target))];
825
+ }
826
+ return row[target];
827
+ }
828
+ }
829
+ /** Transposes the pitch characters of one note group's content as
830
+ * written in the source (escapes included) — the staff-degree shift
831
+ * `transposeBy` applies to every group. Escape pairs stand for their
832
+ * underlying character (an escaped paren is a pitch glyph of the
833
+ * `®−§'…` row), and a shifted result that is a control character of the
834
+ * group syntax is written escaped. A statement group's content (`@…`) is returned
835
+ * unchanged: its keyword letters are pitch glyphs, but no notes. */
836
+ function transposeNotes(notes, shift, options = {}) {
837
+ if (shift === 0 || isStatementGroup(notes)) return notes;
838
+ const overflow = options.overflow ?? "clamp";
839
+ let out = "";
840
+ for (let i = 0; i < notes.length; i++) {
841
+ const ch = notes[i];
842
+ const escaped = ch === "\\" && notes[i + 1] !== void 0;
843
+ const shifted = shiftPitch(escaped ? notes[i + 1] : ch, shift, overflow);
844
+ if (shifted === void 0) {
845
+ out += escaped ? ch + notes[i + 1] : ch;
846
+ if (escaped) i++;
847
+ continue;
848
+ }
849
+ out += "\\()".includes(shifted) ? `\\${shifted}` : shifted;
850
+ if (escaped) i++;
851
+ }
852
+ return out;
853
+ }
854
+ /** The `transposeBy` transform factory: shifts every pitch character of
855
+ * every notes group `shift` positions along its pitch row. The clef
856
+ * group and the syllable text are left alone — clef handling is a
857
+ * separate, future tool. */
858
+ function transposeBy(shift, options = {}) {
859
+ const overflow = options.overflow ?? "clamp";
860
+ const apply = (source) => {
861
+ if (shift === 0) return source;
862
+ const clefMatch = source.match(/^\s*\(([^)]*)\)/);
863
+ const offset = clefMatch ? clefMatch[0].length : 0;
864
+ return source.slice(0, offset) + source.slice(offset).replace(/((?:[^()\\]|\\.)*)\(((?:[^)\\]|\\.)*)\)/g, (_, text, notes) => `${text}(${transposeNotes(notes, shift, { overflow })})`);
865
+ };
866
+ return {
867
+ name: "transpose",
868
+ apply
869
+ };
870
+ }
871
+ //#endregion
872
+ //#region src/chantMarkup.ts
873
+ /**
874
+ * The marked-up text of a chant script, for other applications: the parsed
875
+ * runs of the score, with what they mean and what they are for, and no
876
+ * style set in them. `chantRuns` gives the structured form; `chantHtml`
877
+ * serializes it as HTML spans a consumer styles with its own CSS
878
+ * (`chantTextStyle` gives a mark's look in a style set).
879
+ */
880
+ var ALL_ROLES = [
881
+ "sung",
882
+ "label",
883
+ "sign",
884
+ "aid"
885
+ ];
886
+ var chantRunOf = (run, role) => {
887
+ const kind = kindOf(run.marks);
888
+ return {
889
+ text: run.text,
890
+ ...kind ? { kind } : {},
891
+ ...run.marks.includes("initial") ? { initial: true } : {},
892
+ marks: run.marks,
893
+ role
894
+ };
895
+ };
896
+ var sameMarks = (a, b) => a.length === b.length && a.every((mark, i) => mark === b[i]);
897
+ function chantRuns(script, options = {}) {
898
+ const roles = options.roles ?? ALL_ROLES;
899
+ const words = new GuidoScript(script).words.map((word) => ({ syllables: word.syllables.filter((syl) => roles.includes(syl.role) && syl.runs.length > 0).map((syl) => ({ runs: syl.runs.map((run) => chantRunOf(run, syl.role)) })) })).filter((word) => word.syllables.length > 0);
900
+ if (options.merge !== "word") return words;
901
+ return words.flatMap((word) => {
902
+ const merged = [];
903
+ for (const run of word.syllables.flatMap((syl) => syl.runs)) {
904
+ const last = merged[merged.length - 1];
905
+ if (last && last.role === run.role && sameMarks(last.marks, run.marks)) last.text += run.text;
906
+ else merged.push({
907
+ ...run,
908
+ wordEnd: false
909
+ });
910
+ }
911
+ merged[merged.length - 1].wordEnd = true;
912
+ return merged;
913
+ });
914
+ }
915
+ /** The marked-up text as an HTML string: one span per marked run, classed
916
+ * with its kind, `initial` and any marks of its own, bare text otherwise.
917
+ * Syllables of a word concatenate and words join with single spaces —
918
+ * hyphenation is the consumer's job, and `chantRuns` has the syllable
919
+ * boundaries. Text is HTML-escaped. */
920
+ function chantHtml(script, options = {}) {
921
+ const run = (r) => runHtml(r, options.classPrefix ?? "");
922
+ return chantRuns(script, { roles: options.roles }).map((word) => word.syllables.map((syl) => syl.runs.map(run).join("")).join("")).join(" ");
923
+ }
924
+ /** The marks the notation names through `kind` and `initial`. */
925
+ var NOTATION_MARKS = /* @__PURE__ */ new Set([
926
+ "liturgy",
927
+ "rubric",
928
+ "star",
929
+ "marker",
930
+ "plus",
931
+ "initial"
932
+ ]);
933
+ var runHtml = (run, prefix) => {
934
+ const classes = [
935
+ ...run.kind ? [run.kind] : [],
936
+ ...run.initial ? ["initial"] : [],
937
+ ...run.marks.filter((mark) => !NOTATION_MARKS.has(mark)).map((mark) => mark.replace(/[^\w-]/g, "-"))
938
+ ].map((name) => prefix + name).join(" ");
939
+ return classes ? `<span class="${classes}">${escapeHtml(run.text)}</span>` : escapeHtml(run.text);
940
+ };
941
+ var escapeHtml = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
942
+ /** The resolved look of comma-separated marks (`red,sc`), for a host styling
943
+ * prose to match a score. */
944
+ function chantTextStyle(marks, options = {}) {
945
+ const styleName = options.style ?? "BNS";
946
+ const styleSet = styleSetOf(styleName);
947
+ if (!styleSet) throw new Error(`Unknown style set: "${styleName}"`);
948
+ return resolveMarks(marks, styleSet, options.marks);
949
+ }
950
+ /** Everything `liturgy.ttf` maps. */
951
+ var LITURGY_GLYPHS = /* @__PURE__ */ new Set([
952
+ "+",
953
+ ".",
954
+ "/",
955
+ "R",
956
+ "V"
957
+ ]);
958
+ /** What is wrong with the script's text markup: malformed `{…}` spans,
959
+ * unknown marks, and characters the Liturgy font does not have, each once
960
+ * per syllable. */
961
+ function markupWarnings(script, options = {}) {
962
+ const parsed = typeof script === "string" ? new GuidoScript(script) : script;
963
+ const styleSet = styleSetOf(options.style ?? "BNS");
964
+ if (!styleSet) return parsed.spanProblems;
965
+ const warnings = [...parsed.spanProblems];
966
+ const unknown = /* @__PURE__ */ new Set();
967
+ for (const tok of parsed.tokens) {
968
+ if (tok.kind !== "syllable") continue;
969
+ for (const mark of unknownMarks([...new Set(tok.runs.flatMap((run) => run.marks))], styleSet, options.marks)) {
970
+ if (unknown.has(mark)) continue;
971
+ unknown.add(mark);
972
+ warnings.push({
973
+ kind: "mark",
974
+ mark,
975
+ text: tok.source,
976
+ message: `Unknown mark "${mark}" (in "${tok.source}")`
977
+ });
978
+ }
979
+ const drawn = resolveTextRuns(tok.runs, styleSet, false, options.marks).filter((part) => part.style.fontFamily?.includes("Liturgy") && part.kind !== "marker").flatMap((part) => [...part.text]);
980
+ for (const char of new Set(drawn)) {
981
+ if (LITURGY_GLYPHS.has(char) || /\s/.test(char)) continue;
982
+ warnings.push({
983
+ kind: "glyph",
984
+ char,
985
+ text: tok.source,
986
+ message: `The Liturgy font has no "${char}" (in "${tok.source}"); it has only + . / R V`
987
+ });
988
+ }
989
+ }
990
+ return warnings;
991
+ }
992
+ //#endregion
993
+ export { stanzaCount as C, withStanza as E, stackedStanzaNumbers as S, stanzaWarnings as T, parseStanza as _, PITCH_ROWS as a, smallHeads as b, KEY_SIGNATURES as c, sameKeyGlyphs as d, transposeExact as f, padStanza as g, isSlot as h, markupWarnings as i, TranspositionRangeError as l, STANZA_PLACEHOLDER as m, chantRuns as n, transposeBy as o, transposeScript as p, chantTextStyle as r, transposeNotes as s, chantHtml as t, parseInterval as u, selectStanza as v, stanzaTexts as w, stackStanzas as x, slotCount as y };