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,1345 @@
1
+ import { A as splitNoteMarkers, I as isClefGlyph, J as variantOf, L as isModifierGlyph, N as baseOf, O as MARKER_CHARS, P as bracketedAccidentalLength, V as pitchLetterOf, W as toLonga, _ as GuidoScript, h as textFontStackOf, i as cleanFontName, m as styleSetOf, o as drawnText, p as resolveTextRuns, s as fontStringsToVerify, u as measurementFont, z as modifyNatural } from "./guidoStyles-CvnACCsk.js";
2
+ //#region src/recitationSegments.ts
3
+ /** The reciting pitch of a note group: one reciting glyph, or one plain
4
+ * note that has one, optionally after one accidental sign; null for any
5
+ * other group. */
6
+ function recitationPitch(notes) {
7
+ const sign = notes.length === 2 && isModifierGlyph(notes[0]) ? notes[0] : "";
8
+ const ch = notes.slice(sign.length);
9
+ if (ch.length !== 1) return null;
10
+ const family = baseOf(ch);
11
+ if (family?.role === "longa") return {
12
+ sign,
13
+ plain: family.base,
14
+ glyph: ch,
15
+ written: "glyph"
16
+ };
17
+ const glyph = toLonga(ch);
18
+ return glyph ? {
19
+ sign,
20
+ plain: ch,
21
+ glyph,
22
+ written: "plain"
23
+ } : null;
24
+ }
25
+ /** The notes a group renders with in a mode. */
26
+ function notesInMode(notes, mode) {
27
+ const pitch = recitationPitch(notes);
28
+ if (!pitch || mode === "written") return notes;
29
+ return pitch.sign + (mode === "recite" ? pitch.glyph : pitch.plain);
30
+ }
31
+ /** What a mode renders, in written terms: 'recite' or 'plain'. */
32
+ function shownAs(notes, mode) {
33
+ if (mode !== "written") return mode;
34
+ return recitationPitch(notes)?.written === "glyph" ? "recite" : "plain";
35
+ }
36
+ /** The decisions' view of a script: its syllables, and where a clef or key
37
+ * statement stands (a run never continues across one). */
38
+ function runSyllables(underlays) {
39
+ const syllables = [];
40
+ const pitchBreaks = /* @__PURE__ */ new Set();
41
+ (underlays[0] ?? []).forEach((tok, k) => {
42
+ if (tok.kind === "clef" || tok.kind === "key") pitchBreaks.add(syllables.length);
43
+ if (tok.kind !== "syllable") return;
44
+ const counted = underlays.some((u) => {
45
+ const own = u[k];
46
+ return own?.kind === "syllable" && !own.held && !own.empty;
47
+ });
48
+ syllables.push({
49
+ notes: tok.notes,
50
+ counted
51
+ });
52
+ });
53
+ return {
54
+ syllables,
55
+ pitchBreaks
56
+ };
57
+ }
58
+ /** Whether a syllable can join a recitation run under the options. */
59
+ function isMember(syl, options) {
60
+ const pitch = recitationPitch(syl.notes);
61
+ if (!pitch) return false;
62
+ return pitch.written === "glyph" || options.plainRunsToRecitation;
63
+ }
64
+ /** The run key of a member: its pitch, glyph and plain note alike. */
65
+ function runKey(notes) {
66
+ const pitch = recitationPitch(notes);
67
+ return pitch.sign + pitch.plain;
68
+ }
69
+ /**
70
+ * The mode each member is first laid out in: a recitation when its run in
71
+ * the script counts 3 or more syllables (so the line segments are counted
72
+ * with the recitation's widths), else as written (a run of 2 or fewer can
73
+ * only ever need its pair converted).
74
+ */
75
+ function trialModes(syllables, pitchBreaks, options) {
76
+ const modes = /* @__PURE__ */ new Map();
77
+ let k = 0;
78
+ while (k < syllables.length) {
79
+ if (!isMember(syllables[k], options)) {
80
+ k++;
81
+ continue;
82
+ }
83
+ const key = runKey(syllables[k].notes);
84
+ let end = k;
85
+ let count = 0;
86
+ while (end < syllables.length && isMember(syllables[end], options) && runKey(syllables[end].notes) === key && (end === k || !pitchBreaks.has(end))) {
87
+ if (syllables[end].counted) count++;
88
+ end++;
89
+ }
90
+ for (let j = k; j < end; j++) modes.set(j, count >= 3 ? "recite" : "written");
91
+ k = end;
92
+ }
93
+ return modes;
94
+ }
95
+ /** Whether a script has anything for the decisions to do. */
96
+ function hasCandidates(syllables, options) {
97
+ if (!options.twoSyllableRecitationsToPlain && !options.plainRunsToRecitation) return false;
98
+ return syllables.some((s) => isMember(s, options));
99
+ }
100
+ /** The line segments of a pass: consecutive members on the same line with
101
+ * the same placed pitch. */
102
+ function segmentsOf(syllables, placedNotes, sylLines, options) {
103
+ const segments = [];
104
+ let current;
105
+ let currentKey = "";
106
+ let currentLine = -1;
107
+ syllables.forEach((syl, k) => {
108
+ const placed = placedNotes[k];
109
+ const line = sylLines[k];
110
+ if (!(isMember(syl, options) && placed !== void 0 && line !== void 0 && recitationPitch(placed) !== null)) {
111
+ current = void 0;
112
+ return;
113
+ }
114
+ const key = runKey(placed);
115
+ if (!current || key !== currentKey || line !== currentLine) {
116
+ current = {
117
+ members: [],
118
+ count: 0
119
+ };
120
+ segments.push(current);
121
+ currentKey = key;
122
+ currentLine = line;
123
+ }
124
+ current.members.push(k);
125
+ if (syl.counted) current.count++;
126
+ });
127
+ return segments;
128
+ }
129
+ function initialState() {
130
+ return {
131
+ decided: /* @__PURE__ */ new Map(),
132
+ breakBefore: /* @__PURE__ */ new Set(),
133
+ pending: null
134
+ };
135
+ }
136
+ /** The mode each member renders with in the next pass. */
137
+ function passModes(trial, state) {
138
+ const modes = new Map(trial);
139
+ for (const [k, mode] of state.decided) modes.set(k, mode);
140
+ return modes;
141
+ }
142
+ /**
143
+ * One step of the decisions over a laid-out pass, from the left: checks the
144
+ * segment changed in the previous step, then decides segments in order while
145
+ * the pass already rendered them as decided, and stops at the first one
146
+ * whose decision changes what the pass rendered. Returns whether another
147
+ * pass is needed.
148
+ *
149
+ * Every pass lays the score out left to right, so a decision only moves
150
+ * what comes after it: the segments decided before it stay where they
151
+ * were. A segment is counted on the line the pass put it on, and a change
152
+ * keeps it there: one that opened its line still opens it (as plain notes
153
+ * it might fit the line before), and a member that no longer fits its line
154
+ * in the new form (a pair turned plain is wider than its recitation) opens
155
+ * the next one and is decided again there, the members before it keeping
156
+ * their written form.
157
+ */
158
+ function decideStep(syllables, placedNotes, sylLines, modes, state, options) {
159
+ if (state.pending) {
160
+ const { members, line } = state.pending;
161
+ state.pending = null;
162
+ const moved = members.findIndex((k) => sylLines[k] !== line);
163
+ if (moved >= 0) {
164
+ members.forEach((k, j) => {
165
+ if (j < moved) state.decided.set(k, "written");
166
+ else state.decided.delete(k);
167
+ });
168
+ state.breakBefore.add(members[moved]);
169
+ return true;
170
+ }
171
+ }
172
+ for (const segment of segmentsOf(syllables, placedNotes, sylLines, options)) {
173
+ if (segment.members.every((k) => state.decided.has(k))) continue;
174
+ const target = segment.count >= 3 ? "recite" : segment.count === 2 && options.twoSyllableRecitationsToPlain ? "plain" : "written";
175
+ const changes = segment.members.some((k) => {
176
+ const notes = syllables[k].notes;
177
+ return shownAs(notes, modes.get(k) ?? "written") !== shownAs(notes, target);
178
+ });
179
+ for (const k of segment.members) state.decided.set(k, target);
180
+ if (changes) {
181
+ const first = segment.members[0];
182
+ const line = sylLines[first];
183
+ if (first > 0 && (sylLines[first - 1] ?? -1) < line) state.breakBefore.add(first);
184
+ state.pending = {
185
+ members: segment.members,
186
+ line
187
+ };
188
+ return true;
189
+ }
190
+ }
191
+ return false;
192
+ }
193
+ //#endregion
194
+ //#region src/chantLayout.ts
195
+ /**
196
+ * Special reciting notes: when such a note stands alone in a note group it
197
+ * marks recited text. The glyph shows at a run's first syllable (the
198
+ * previous syllable has different notes) and at every line start; every
199
+ * other recited syllable contributes only the staff-line segments filling
200
+ * the space above its text, which flows tight after the previous text.
201
+ */
202
+ var SPECIAL_NOTES = "€ŽžŸ¡¢£[¥¦©ª«¬¤";
203
+ var SPECIAL_NOTE_CHARS = new Set(SPECIAL_NOTES.split(""));
204
+ /** Whether a note group is a recitation group: one special reciting note,
205
+ * optionally after one accidental sign (`¦`, `C¦`). */
206
+ function isRecitationGroup(notes) {
207
+ return notes.length === 1 && SPECIAL_NOTE_CHARS.has(notes) || notes.length === 2 && MODIFIER_CHARS.has(notes[0]) && SPECIAL_NOTE_CHARS.has(notes[1]);
208
+ }
209
+ /**
210
+ * Modifier glyphs: flats, sharps, and naturals. They carry pitch (and
211
+ * transpose with the melody) but modify the note that follows them, so
212
+ * they hang in the junction whitespace: the syllable text anchors on the
213
+ * note characters only, and a group starting with a modifier needs only
214
+ * two junction dashes — the glyph itself provides the third dash's
215
+ * separation.
216
+ */
217
+ var NOTE_MODIFIERS = "÷øaASÍYXCVBN$mÈÊËÌÎÏÐÑÒþßòôùý“”•–—˜™š›œº»";
218
+ var MODIFIER_CHARS = new Set(NOTE_MODIFIERS.split(""));
219
+ /**
220
+ * The length of what hangs at the start of a group's core: its leading
221
+ * modifiers and bracketed accidentals (issue #95), which stand in the
222
+ * junction whitespace before the group's first note.
223
+ */
224
+ function hangingLength(core) {
225
+ let at = 0;
226
+ for (;;) {
227
+ const unit = MODIFIER_CHARS.has(core[at] ?? "") ? 1 : bracketedAccidentalLength(core, at);
228
+ if (unit === 0) return at;
229
+ at += unit;
230
+ }
231
+ }
232
+ /** The index in `notes` right after its hanging run (leading markers
233
+ * counted), or 0 when nothing hangs. */
234
+ function hangEnd(notes) {
235
+ const { leading, core } = splitNoteMarkers(notes);
236
+ const hang = hangingLength(core);
237
+ return hang === 0 ? 0 : leading.length + hang;
238
+ }
239
+ var NOTE_GROUP_SPLITTERS = ["-", "¨"];
240
+ /** A junction `thirds` thirds of a dash wide: whole dashes, then one `¨`
241
+ * per leftover third (`--¨¨` is 2⅔). */
242
+ function junctionSpacer(thirds) {
243
+ return "-".repeat(Math.floor(thirds / 3)) + "¨".repeat(thirds % 3);
244
+ }
245
+ /** The key written by a run of modifier glyphs, under `clef` (a clef
246
+ * glyph; the standard g-clef when unknown — matching pitches by staff
247
+ * position does not depend on it). A statement's key throws when two
248
+ * glyphs alter the same pitch; the opening group's stays lenient (the
249
+ * later glyph wins), as it was never validated. */
250
+ function keyMapOf(key, clef, strict = true) {
251
+ const map = /* @__PURE__ */ new Map();
252
+ for (const ch of key) {
253
+ if (!isModifierGlyph(ch)) continue;
254
+ const letter = pitchLetterOf(ch, clefOrDefault(clef));
255
+ if (strict && map.has(letter)) throw new Error(`Key "${key}" alters the pitch ${letter} twice`);
256
+ map.set(letter, baseOf(ch).role);
257
+ }
258
+ return map;
259
+ }
260
+ function clefOrDefault(clef) {
261
+ return clef !== void 0 && isClefGlyph(clef) ? clef : "M";
262
+ }
263
+ /** The note glyphs a key alters: the base pitch glyphs and their shape
264
+ * variants. Accidentals and small points are not notes, and the score
265
+ * markers carry no pitch (several double as cephalicus glyphs). */
266
+ function noteBaseOf(ch) {
267
+ if (MARKER_CHARS.has(ch)) return void 0;
268
+ if (variantOf(ch, "smallHead") !== void 0) return ch;
269
+ const entry = baseOf(ch);
270
+ if (!entry || entry.role === "smallPoint" || isModifierGlyph(ch)) return void 0;
271
+ return entry.base;
272
+ }
273
+ /**
274
+ * Writes a mid-line key change into a note group (issue #49): every note
275
+ * whose pitch carries a different accidental under `active` than under
276
+ * `staff` (the key the line's staff shows) calls for the accidental
277
+ * sign — or the natural, when the pitch dropped out of the key. The
278
+ * signs stand before the note group, not before their notes: they go at
279
+ * the start of the group's notes (after its leading markers), one per
280
+ * affected pitch glyph, in order of first appearance. Notes the source
281
+ * already marks with a modifier are left alone (a bracketed accidental
282
+ * opening the group, issue #95, marks the note after it). The groups a
283
+ * syllable holds (`held`, issue #83) are scanned too: a held run writes its signs
284
+ * once, before its first group. Returns the rewritten group and the
285
+ * indices of the inserted signs. Throws when a needed sign does not
286
+ * exist.
287
+ */
288
+ function applyKeyChange(notes, staff, active, clef, held = []) {
289
+ let signs = "";
290
+ for (const group of [notes, ...held]) {
291
+ const hang = hangEnd(group);
292
+ for (let i = 0; i < group.length; i++) {
293
+ const ch = group[i];
294
+ const base = noteBaseOf(ch);
295
+ const letter = base !== void 0 ? pitchLetterOf(base, clefOrDefault(clef)) : void 0;
296
+ const want = letter !== void 0 ? active.get(letter) : void 0;
297
+ const marked = i > 0 && (isModifierGlyph(group[i - 1]) || i === hang);
298
+ if (letter !== void 0 && want !== staff.get(letter) && !marked) {
299
+ const role = want ?? "modifyNatural";
300
+ const sign = want ? variantOf(base, want) : modifyNatural(base);
301
+ if (sign === void 0) throw new Error(`The note "${ch}" has no ${role} glyph for the key change`);
302
+ if (!signs.includes(sign)) signs += sign;
303
+ }
304
+ }
305
+ }
306
+ const at = splitNoteMarkers(notes).leading.length;
307
+ return {
308
+ notes: notes.slice(0, at) + signs + notes.slice(at),
309
+ inserted: [...signs].map((_, k) => at + k)
310
+ };
311
+ }
312
+ /** A group with the given inserted signs removed again. */
313
+ function stripInserted(notes, inserted, from = 0) {
314
+ return [...notes].filter((_, i) => !inserted.includes(i + from)).join("");
315
+ }
316
+ var ctx = null;
317
+ /** Canvas text measurement, shared with the emitters (the Word export
318
+ * measures the spacer character's natural advance for the unit width). */
319
+ /**
320
+ * Whether a font family is available to this browser by name (installed,
321
+ * or loaded as a webfont). The browser silently falls back for a missing
322
+ * one, so this measures a test string in the family with each generic
323
+ * font behind it: when every width matches the generic alone, the family
324
+ * is missing. Undefined for a name that cannot be a font family.
325
+ */
326
+ function isFontAvailable(name) {
327
+ const family = cleanFontName(name);
328
+ if (!family) return void 0;
329
+ const sample = "mmmmmmmmmmlliWW@#ÁéőŰ";
330
+ return [
331
+ "monospace",
332
+ "serif",
333
+ "sans-serif"
334
+ ].some((generic) => measure(sample, `72px "${family}", ${generic}`) !== measure(sample, `72px ${generic}`));
335
+ }
336
+ function measure(text, font) {
337
+ if (!ctx) ctx = document.createElement("canvas").getContext("2d");
338
+ ctx.font = font;
339
+ return ctx.measureText(text).width;
340
+ }
341
+ /** Ink extents of the text relative to the glyph origin (negative left
342
+ * means the ink starts left of the origin). */
343
+ function ink(text, font) {
344
+ if (!ctx) ctx = document.createElement("canvas").getContext("2d");
345
+ ctx.font = font;
346
+ const m = ctx.measureText(text);
347
+ return {
348
+ left: m.actualBoundingBoxLeft,
349
+ right: m.actualBoundingBoxRight
350
+ };
351
+ }
352
+ var STAFF_FILLS = [
353
+ "all-but-last",
354
+ "none",
355
+ "all",
356
+ "longest"
357
+ ];
358
+ var CLEF_MARKS = ["glyph", "line"];
359
+ /** A bar closing a group: `,` `:` `;` (doubled or not), then any dashes or
360
+ * `¨`. The first group is the bar glyphs. */
361
+ var CLOSING_BAR = /([,:;]+)[-¨]*$/;
362
+ /** Settles a star under a bar once the text after it is placed (at
363
+ * `next`): a word space clear of the text on either side, under the bar
364
+ * where that leaves room, else pulled left of it; with no room for both
365
+ * spaces, centred between the two texts (never under the one before). */
366
+ function fitMark(mark, next) {
367
+ const w = mark.seg.textWidth;
368
+ const lo = mark.lo + mark.space;
369
+ const hi = next - mark.space - w;
370
+ let x = Math.max(mark.center - w / 2, lo);
371
+ if (x > hi) x = lo <= hi ? hi : Math.max(mark.lo, (mark.lo + next - w) / 2);
372
+ mark.seg.textStart = x;
373
+ }
374
+ /** Whether a syllable is the star sign, `**` */
375
+ var isStar = (syl) => syl.runs.length === 1 && syl.runs[0].marks.includes("star");
376
+ /** Each underlay's tokens, checked to share one melody. */
377
+ function underlayTokens(source) {
378
+ const list = typeof source === "string" || source instanceof GuidoScript ? [source] : source;
379
+ if (list.length === 0) throw new Error("Nothing to lay out: no script given");
380
+ const all = list.map((s) => (typeof s === "string" ? new GuidoScript(s) : s).tokens);
381
+ const [first] = all;
382
+ for (const [u, tokens] of all.entries()) if (!(tokens.length === first.length && tokens.every((tok, k) => {
383
+ const ref = first[k];
384
+ return tok.kind === ref.kind && (tok.kind !== "syllable" || tok.notes === ref.notes);
385
+ }))) throw new Error(`Stacked underlay ${u + 1} does not share the first one's notes`);
386
+ return all;
387
+ }
388
+ /** Whether an underlay's token sings no text of its own on its group: a
389
+ * held group or an empty slot. */
390
+ function silent(tok) {
391
+ return !!(tok.held || tok.empty);
392
+ }
393
+ /**
394
+ * Lays a GuidoScript score out: a notes line in the chant font, and a text
395
+ * line where each syllable is centered below its notes. The dashes of the
396
+ * chant font are pure whitespace: centering ignores them and happens under
397
+ * the non-whitespace note characters only. When a syllable's text would
398
+ * overlap the previous one, it starts right after it and the notes group is
399
+ * padded with extra dashes until it covers the text.
400
+ *
401
+ * Stacked stanzas (issue #84): given several underlays of one melody, every
402
+ * line pair gets one text line per underlay. Each text line keeps its own
403
+ * cursor and runs the placement rules on its own (tight pairs, connectors,
404
+ * hyphens, recitation flow); a group takes the most pad dashes any of them
405
+ * asks for, so the notes spacing serves every text line, and a line breaks
406
+ * wherever any of them has to. A group that every underlay holds joins its
407
+ * run with the held join; one that some underlay sings takes the normal
408
+ * junction.
409
+ *
410
+ * This is the shared layout pass behind every emitter: the DOM renderer
411
+ * turns the returned lines into (notes div, text paragraph) pairs, and the
412
+ * Word export turns them into fake-spaced Word HTML. Both consume the same
413
+ * line breaks, notes parts, and syllable anchor positions.
414
+ *
415
+ * Appearance comes from a named style set (see guidoStyles.ts): the layout
416
+ * options reference it by name, together with the bold option and the
417
+ * text/notes sizes. Throws when the style set is unknown or one of its
418
+ * fonts cannot be loaded.
419
+ */
420
+ async function layoutScore(source, options = {}) {
421
+ const recitation = {
422
+ twoSyllableRecitationsToPlain: options.twoSyllableRecitationsToPlain ?? true,
423
+ plainRunsToRecitation: options.plainRunsToRecitation ?? false
424
+ };
425
+ const { syllables, pitchBreaks } = runSyllables(underlayTokens(source));
426
+ if (!hasCandidates(syllables, recitation)) return (await layoutKept(source, options, NO_RECITATION)).result;
427
+ const trial = trialModes(syllables, pitchBreaks, recitation);
428
+ const state = initialState();
429
+ for (let step = 0;; step++) {
430
+ const modes = passModes(trial, state);
431
+ const pass = await layoutKept(source, options, {
432
+ notes: notesOverrides(syllables.map((s) => s.notes), modes),
433
+ breakBefore: state.breakBefore
434
+ });
435
+ if (step > 4 * syllables.length + 8 || !decideStep(syllables, pass.placedNotes, pass.sylLines, modes, state, recitation)) return pass.result;
436
+ }
437
+ }
438
+ /** The notes each syllable renders with under the recitation modes, where
439
+ * they differ from the written ones. */
440
+ function notesOverrides(written, modes) {
441
+ const notes = /* @__PURE__ */ new Map();
442
+ for (const [k, mode] of modes) {
443
+ const shown = notesInMode(written[k], mode);
444
+ if (shown !== written[k]) notes.set(k, shown);
445
+ }
446
+ return notes;
447
+ }
448
+ var NO_RECITATION = {
449
+ notes: /* @__PURE__ */ new Map(),
450
+ breakBefore: /* @__PURE__ */ new Set()
451
+ };
452
+ /** One layout with its `(@keep)` runs settled: a run is only known to fit
453
+ * once it is placed, pads and group splits included, so a run that ends up
454
+ * split is retried with a break before it. One wider than a fresh line
455
+ * stops counting: a flat run wraps where it stood, and a run with inner
456
+ * runs dissolves into them but keeps its break, so the boundary between
457
+ * pairs still wins over the one between verses. Runs number in opening
458
+ * order, so the lowest split is the leftmost and outermost. */
459
+ async function layoutKept(source, options, recitation) {
460
+ const breakBefore = /* @__PURE__ */ new Set();
461
+ const wraps = /* @__PURE__ */ new Set();
462
+ for (;;) {
463
+ const pass = await layoutPass(source, options, breakBefore, recitation);
464
+ const open = pass.splitRuns.filter((r) => !wraps.has(r.run));
465
+ if (open.length === 0) return pass;
466
+ const split = open.reduce((a, b) => b.run < a.run ? b : a);
467
+ if (breakBefore.has(split.run) || split.atLineStart) {
468
+ wraps.add(split.run);
469
+ if (split.nested) breakBefore.add(split.run);
470
+ else breakBefore.delete(split.run);
471
+ } else breakBefore.add(split.run);
472
+ }
473
+ }
474
+ /** One pass of `layoutScore`: `breakBefore` lists the `(@keep)` runs (by
475
+ * position in the script) that open a fresh line; `splitRuns` reports the
476
+ * ones that crossed a line break. `recitation` carries the recitation
477
+ * segments' forms and breaks (issue #21). */
478
+ async function layoutPass(source, options, breakBefore, recitation = NO_RECITATION) {
479
+ const { style: styleName = "BNS", marks, bold = false, textPx = 18, notesPx = textPx * 2, maxWidthPx: lineWidthPx = Infinity, junctionDashes = 3, staffFill = "all-but-last", staffFillSnapPx = 0, paddingPx, clefMark = "glyph", textFont, notesLetterSpacingPx = 0, starUnderBar = true, cutEmptySlots = true } = options;
480
+ if (!STAFF_FILLS.includes(staffFill)) throw new Error(`Unknown staffFill: "${staffFill}"`);
481
+ if (!(staffFillSnapPx >= 0 && Number.isFinite(staffFillSnapPx))) throw new Error(`staffFillSnapPx must be zero or more: ${staffFillSnapPx}`);
482
+ if (paddingPx !== void 0 && !(paddingPx >= 0 && Number.isFinite(paddingPx))) throw new Error(`paddingPx must be zero or more: ${paddingPx}`);
483
+ if (!CLEF_MARKS.includes(clefMark)) throw new Error(`Unknown clefMark: "${clefMark}"`);
484
+ const junctionThirds = Math.round(junctionDashes * 3);
485
+ if (!(junctionDashes >= 1 && Math.abs(junctionDashes - junctionThirds / 3) <= .01)) throw new Error(`junctionDashes must be at least 1, in steps of a third: ${junctionDashes}`);
486
+ const fullJunction = junctionSpacer(junctionThirds);
487
+ const reducedJunction = junctionSpacer(Math.max(3, junctionThirds - 3));
488
+ const underlays = underlayTokens(source);
489
+ 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];
490
+ const styleSet = styleSetOf(styleName);
491
+ if (!styleSet) throw new Error(`Unknown style set: "${styleName}"`);
492
+ const padding = paddingPx ?? styleSet.padding ?? 0;
493
+ const leftPaddingPx = clefMark === "line" ? padding : 0;
494
+ const lineStartCursor = leftPaddingPx > 0 ? -leftPaddingPx : 0;
495
+ const maxWidthPx = lineWidthPx === Infinity ? Infinity : Math.max(0, lineWidthPx - padding - leftPaddingPx);
496
+ for (const font of fontStringsToVerify(styleSet, textPx)) {
497
+ try {
498
+ await document.fonts.load(font);
499
+ } catch {}
500
+ if (!document.fonts.check(font)) throw new Error(`Font could not be loaded: ${font} (style "${styleName}")`);
501
+ }
502
+ const notesFont = `400 ${notesPx}px ${styleSet.notesFontStack}`;
503
+ const measureNotes = (text) => measure(text, notesFont) + notesLetterSpacingPx * text.length;
504
+ const textStack = textFontStackOf(styleSet, textFont);
505
+ const spaceFont = measurementFont({ weight: bold ? "700" : "400" }, textPx, textStack);
506
+ const resolveParts = (runs) => resolveTextRuns(runs, styleSet, bold, marks);
507
+ const measureParts = (parts) => parts.reduce((w, part) => w + measure(drawnText(part), measurementFont(part.style, textPx, textStack)), 0);
508
+ const dashNotesWidth = measureNotes("-");
509
+ const dashTextWidth = measure("-", spaceFont);
510
+ /** The hyphen after a syllable: plain, unless a `{…}` span runs on
511
+ * across it, when it takes the span's look and that look's width. */
512
+ const hyphenOf = (hyphenMarks) => {
513
+ if (!hyphenMarks) return { width: dashTextWidth };
514
+ const parts = resolveParts([{
515
+ text: "-",
516
+ marks: hyphenMarks
517
+ }]);
518
+ return {
519
+ parts,
520
+ width: measureParts(parts)
521
+ };
522
+ };
523
+ let clefGlyph = script.clef?.[0];
524
+ let keyGlyphs = [...(script.clef ?? "").slice(1)].filter(isModifierGlyph).join("");
525
+ let clefGroup = script.clef;
526
+ const shownOf = (group) => clefMark === "line" && group ? [...group].filter((ch) => !isClefGlyph(ch)).join("") : group ?? "";
527
+ const prefixOf = (group) => shownOf(group) ? `${shownOf(group)}-` : "";
528
+ const clefsAtStart = () => clefGlyph ? [{
529
+ at: 0,
530
+ clef: clefGlyph
531
+ }] : [];
532
+ const chars = (text) => [...text].length;
533
+ let activeKey = keyMapOf(keyGlyphs, clefGlyph, false);
534
+ let staffKey = activeKey;
535
+ const tracks = underlays.map((tokens) => {
536
+ const syls = tokens.filter((t) => t.kind === "syllable");
537
+ return {
538
+ syls,
539
+ lastTextSyl: syls.reduce((last, s, i) => silent(s) ? last : i, -1),
540
+ cursor: 0,
541
+ pending: [],
542
+ prevWordEnd: void 0,
543
+ hyphen: { width: dashTextWidth }
544
+ };
545
+ });
546
+ const lines = [];
547
+ let line;
548
+ let notesSoFar;
549
+ let lastGroupTrailingMarker;
550
+ let afterInlineClef = false;
551
+ let current;
552
+ let prevRecited = false;
553
+ const pushGroup = (syllable, part, notes) => {
554
+ const end = line.clefPrefix.length + line.notesParts.reduce((n, p) => n + p.length, 0) + part.length;
555
+ line.groups.push({
556
+ syllable,
557
+ from: end - notes.length,
558
+ to: end
559
+ });
560
+ line.notesParts.push(part);
561
+ for (const t of tracks) if (t.mark && line.texts.includes(t.mark.text)) t.mark.inline = true;
562
+ const bar = notes.match(CLOSING_BAR);
563
+ if (bar) {
564
+ const text = line.clefPrefix + line.notesParts.join("");
565
+ const at = text.length - bar[0].length;
566
+ const glyphs = bar[1];
567
+ const from = measureNotes(text.slice(0, at));
568
+ const { left, right } = ink(glyphs, notesFont);
569
+ lastBar = {
570
+ line,
571
+ center: from + (right - left) / 2
572
+ };
573
+ } else lastBar = null;
574
+ };
575
+ let lastBar = null;
576
+ const startLine = () => {
577
+ if (line) {
578
+ tracks.forEach((t, u) => {
579
+ line.texts[u].textCursor = t.cursor;
580
+ });
581
+ line.notesEnd = line.notesParts.length ? measureNotes(line.clefPrefix + line.notesParts.join("")) : 0;
582
+ }
583
+ const texts = tracks.map(() => ({
584
+ segments: [],
585
+ textCursor: 0,
586
+ lastWordEnd: null
587
+ }));
588
+ line = {
589
+ clefPrefix: prefixOf(clefGroup),
590
+ notesParts: [],
591
+ segments: texts[0].segments,
592
+ textCursor: 0,
593
+ notesEnd: 0,
594
+ staffEnd: 0,
595
+ lastWordEnd: null,
596
+ texts,
597
+ clefs: clefsAtStart(),
598
+ groups: []
599
+ };
600
+ lines.push(line);
601
+ notesSoFar = line.clefPrefix;
602
+ for (const t of tracks) {
603
+ t.cursor = lineStartCursor;
604
+ if (t.mark && !t.mark.inline) {
605
+ const segs = t.mark.text.segments;
606
+ segs.splice(segs.indexOf(t.mark.seg), 1);
607
+ t.carry = t.mark.seg;
608
+ }
609
+ t.mark = void 0;
610
+ }
611
+ lastGroupTrailingMarker = false;
612
+ prevRecited = false;
613
+ afterInlineClef = false;
614
+ staffKey = activeKey;
615
+ if (current && current.inserted.length > 0) {
616
+ current.notes = stripInserted(current.notes, current.inserted);
617
+ current.inserted = [];
618
+ if (current.first) placedNotes[current.i] = current.notes;
619
+ }
620
+ };
621
+ startLine();
622
+ const tokens = underlays[0];
623
+ const allHeld = (i) => tracks.every((t) => t.syls[i].held);
624
+ const items = [];
625
+ let sylIndex = 0;
626
+ let runHead;
627
+ let tightDepth = 0;
628
+ let tightGroupPlaced = false;
629
+ for (const tok of tokens) if (tok.kind !== "syllable") {
630
+ items.push(tok);
631
+ runHead = void 0;
632
+ if (tok.kind === "tight" || tok.kind === "unit") {
633
+ tightDepth = Math.max(0, tightDepth + (tok.on ? 1 : -1));
634
+ if (tightDepth === 0) tightGroupPlaced = false;
635
+ }
636
+ } else {
637
+ const i = sylIndex++;
638
+ const item = {
639
+ kind: "syl",
640
+ syl: tok,
641
+ i,
642
+ notes: recitation.notes.get(i) ?? tok.notes,
643
+ inserted: [],
644
+ first: true,
645
+ lastSeg: true,
646
+ heldRun: [],
647
+ signedByRun: false,
648
+ tightJoin: tightGroupPlaced
649
+ };
650
+ if (tok.notes !== "") tightGroupPlaced = tightDepth > 0;
651
+ if (allHeld(item.i) && runHead) {
652
+ runHead.heldRun.push(tok.notes);
653
+ item.signedByRun = true;
654
+ } else runHead = item;
655
+ items.push(item);
656
+ }
657
+ const placedNotes = [];
658
+ const findBreakCut = (notes, room, measureFromLineStart) => {
659
+ const first = hangEnd(notes);
660
+ for (let c = notes.length - 1; c >= first && c > 0; c--) {
661
+ if (!NOTE_GROUP_SPLITTERS.includes(notes[c])) continue;
662
+ let end = c + 1;
663
+ while (end < notes.length && MARKER_CHARS.has(notes[end])) end++;
664
+ if (end >= notes.length) continue;
665
+ if (measureFromLineStart(notes.slice(0, end)) <= room) return c;
666
+ }
667
+ return -1;
668
+ };
669
+ const applyBreakCut = (item, cut) => {
670
+ const notes = item.notes;
671
+ let restStart = cut + 1;
672
+ while (restStart < notes.length && MARKER_CHARS.has(notes[restStart])) restStart++;
673
+ item.notes = notes.slice(0, cut) + notes.slice(cut + 1, restStart);
674
+ const rest = stripInserted(notes.slice(restStart), item.inserted, restStart);
675
+ item.inserted = item.inserted.filter((at) => at < cut);
676
+ return rest;
677
+ };
678
+ const queueContinuation = (item, idx, rest) => {
679
+ item.lastSeg = false;
680
+ items.splice(idx + 1, 0, {
681
+ kind: "syl",
682
+ syl: item.syl,
683
+ i: item.i,
684
+ notes: rest,
685
+ inserted: [],
686
+ first: false,
687
+ lastSeg: true,
688
+ heldRun: [],
689
+ signedByRun: false,
690
+ tightJoin: false
691
+ });
692
+ forceBreak = true;
693
+ };
694
+ const flushPending = (trailing) => {
695
+ tracks.forEach((t, u) => {
696
+ while (t.pending.length > 0) {
697
+ const p = t.pending[0];
698
+ if (t.cursor > lineStartCursor && t.cursor + p.textWidth + (p.wordEnd ? 0 : p.hyphen.width) > maxWidthPx) {
699
+ startLine();
700
+ continue;
701
+ }
702
+ t.pending.shift();
703
+ const text = line.texts[u];
704
+ text.segments.push({
705
+ kind: "syl",
706
+ syllable: p.syllable,
707
+ parts: p.sylParts,
708
+ textStart: t.cursor,
709
+ textWidth: p.textWidth,
710
+ contentWidth: 0,
711
+ contentStart: 0,
712
+ extraDashes: 0,
713
+ tight: false,
714
+ noNotes: true,
715
+ ...trailing && t.pending.length === 0 ? { trailing: true } : {}
716
+ });
717
+ t.cursor += p.textWidth;
718
+ if (p.spaceWidth > 0) {
719
+ text.segments.push({
720
+ kind: "word-space",
721
+ width: p.spaceWidth
722
+ });
723
+ t.cursor += p.spaceWidth;
724
+ }
725
+ text.lastWordEnd = p.wordEnd;
726
+ text.hyphen = p.hyphen;
727
+ t.hyphen = p.hyphen;
728
+ text.textCursor = t.cursor;
729
+ }
730
+ });
731
+ };
732
+ let forceBreak = false;
733
+ let keepRuns = 0;
734
+ const keepStack = [];
735
+ const splitRuns = [];
736
+ const closeKeepRun = () => {
737
+ const run = keepStack.pop();
738
+ if (run && lines.length - 1 > run.line) splitRuns.push(run);
739
+ };
740
+ const sylLines = [];
741
+ let placedSyl = -1;
742
+ const notePlacedLine = () => {
743
+ if (placedSyl >= 0) sylLines[placedSyl] = lines.length - 1;
744
+ placedSyl = -1;
745
+ };
746
+ let idx = 0;
747
+ while (idx < items.length) {
748
+ notePlacedLine();
749
+ const item = items[idx];
750
+ const barBefore = lastBar;
751
+ lastBar = null;
752
+ if (item.kind === "break") {
753
+ if (line.texts.some((x) => x.segments.length > 0) || tracks.some((t) => t.pending.length > 0)) {
754
+ flushPending(false);
755
+ forceBreak = true;
756
+ }
757
+ idx++;
758
+ continue;
759
+ }
760
+ if (item.kind === "tight" || item.kind === "aid") {
761
+ idx++;
762
+ continue;
763
+ }
764
+ if (item.kind === "keep" || item.kind === "unit") {
765
+ if (!item.on) closeKeepRun();
766
+ else {
767
+ const hasContent = line.texts.some((x) => x.segments.length > 0) || tracks.some((t) => t.pending.length > 0);
768
+ if (breakBefore.has(keepRuns) && hasContent) {
769
+ flushPending(false);
770
+ forceBreak = true;
771
+ }
772
+ if (keepStack.length > 0) keepStack[keepStack.length - 1].nested = true;
773
+ keepStack.push({
774
+ run: keepRuns++,
775
+ line: forceBreak ? lines.length : lines.length - 1,
776
+ atLineStart: !hasContent || forceBreak,
777
+ nested: false
778
+ });
779
+ }
780
+ idx++;
781
+ continue;
782
+ }
783
+ if (item.kind === "clef" || item.kind === "key") {
784
+ if (item.kind === "clef") clefGlyph = item.clef;
785
+ keyGlyphs = item.key;
786
+ clefGroup = (clefGlyph ?? "") + keyGlyphs;
787
+ activeKey = keyMapOf(keyGlyphs, clefGlyph);
788
+ if (forceBreak) {} else if (line.notesParts.length === 0) {
789
+ line.clefPrefix = prefixOf(clefGroup);
790
+ line.clefs = clefsAtStart();
791
+ notesSoFar = line.clefPrefix;
792
+ staffKey = activeKey;
793
+ } else if (item.kind === "clef") {
794
+ const shown = shownOf(clefGroup);
795
+ const part = shown ? (lastGroupTrailingMarker ? reducedJunction : fullJunction) + shown + "-" : "";
796
+ if (part && measureNotes(notesSoFar + part) > maxWidthPx) forceBreak = true;
797
+ else {
798
+ if (clefGlyph) line.clefs.push({
799
+ at: chars(notesSoFar),
800
+ clef: clefGlyph
801
+ });
802
+ if (part) {
803
+ line.notesParts.push(part);
804
+ notesSoFar += part;
805
+ afterInlineClef = true;
806
+ lastGroupTrailingMarker = false;
807
+ prevRecited = false;
808
+ }
809
+ staffKey = activeKey;
810
+ }
811
+ }
812
+ idx++;
813
+ continue;
814
+ }
815
+ const syl = item.syl;
816
+ const i = item.i;
817
+ if (item.first) placedSyl = i;
818
+ if (item.first && recitation.breakBefore.has(i) && (line.texts.some((x) => x.segments.length > 0) || tracks.some((t) => t.pending.length > 0))) {
819
+ flushPending(false);
820
+ forceBreak = true;
821
+ }
822
+ if (forceBreak) {
823
+ startLine();
824
+ forceBreak = false;
825
+ }
826
+ current = item;
827
+ if (staffKey !== activeKey && !item.signedByRun) {
828
+ const changed = applyKeyChange(item.notes, staffKey, activeKey, clefGlyph, item.first ? item.heldRun : []);
829
+ item.notes = changed.notes;
830
+ item.inserted = changed.inserted;
831
+ }
832
+ if (item.first) placedNotes[i] = item.signedByRun && staffKey !== activeKey ? applyKeyChange(item.notes, staffKey, activeKey, clefGlyph).notes : item.notes;
833
+ const sung = tracks.map((t) => {
834
+ const own = t.syls[i];
835
+ const last = item.lastSeg && i >= t.lastTextSyl;
836
+ const sylParts = resolveParts(item.first ? own.runs : []);
837
+ return {
838
+ t,
839
+ own,
840
+ sylParts,
841
+ textWidth: measureParts(sylParts),
842
+ spaceWidth: !last && own.wordEnd ? measure(" ", spaceFont) : 0,
843
+ pendingTotal: t.pending.reduce((s, p) => s + p.textWidth + p.spaceWidth, 0)
844
+ };
845
+ });
846
+ const special = isRecitationGroup(item.notes);
847
+ if (syl.empty && item.notes.length === 0) {
848
+ idx++;
849
+ continue;
850
+ }
851
+ if (item.notes.length === 0) {
852
+ const underBar = starUnderBar && barBefore?.line === line ? barBefore : null;
853
+ for (const s of sung) {
854
+ if (s.own.empty) continue;
855
+ if (underBar && isStar(s.own)) {
856
+ const text = line.texts[tracks.indexOf(s.t)];
857
+ const before = text.segments.findLast((g) => g.kind === "syl");
858
+ const lo = before ? before.textStart + before.textWidth : lineStartCursor;
859
+ const seg = {
860
+ kind: "mark",
861
+ syllable: item.i,
862
+ parts: s.sylParts,
863
+ textStart: Math.max(underBar.center - s.textWidth / 2, s.t.cursor),
864
+ textWidth: s.textWidth,
865
+ flowPx: s.t.cursor
866
+ };
867
+ text.segments.push(seg);
868
+ s.t.mark = {
869
+ seg,
870
+ text,
871
+ lo,
872
+ space: Math.max(0, s.t.cursor - lo),
873
+ center: underBar.center
874
+ };
875
+ continue;
876
+ }
877
+ s.t.pending.push({
878
+ syllable: item.i,
879
+ sylParts: s.sylParts,
880
+ textWidth: s.textWidth,
881
+ spaceWidth: s.spaceWidth,
882
+ wordEnd: s.own.wordEnd,
883
+ hyphen: hyphenOf(s.own.hyphen)
884
+ });
885
+ }
886
+ idx++;
887
+ continue;
888
+ }
889
+ if (item.first && item.lastSeg && !syl.empty && syl.runs.length === 0 && splitNoteMarkers(item.notes).core === "") {
890
+ const last = notesSoFar[notesSoFar.length - 1];
891
+ const sep = last && last !== "-" && !lastGroupTrailingMarker && !syl.notes.startsWith("-") ? "-" : "";
892
+ pushGroup(item.i, sep + syl.notes, syl.notes);
893
+ notesSoFar += sep + syl.notes;
894
+ lastGroupTrailingMarker = true;
895
+ prevRecited = false;
896
+ for (const s of sung) s.t.prevWordEnd = s.own.wordEnd;
897
+ idx++;
898
+ continue;
899
+ }
900
+ const keepWordState = (s, fresh) => {
901
+ if (s.own.held) {
902
+ if (fresh) line.texts[tracks.indexOf(s.t)].lastWordEnd = true;
903
+ s.t.prevWordEnd = s.own.wordEnd;
904
+ } else if (s.t.prevWordEnd === void 0) s.t.prevWordEnd = true;
905
+ };
906
+ if (item.first && sung.every((s) => silent(s.own))) {
907
+ const held = allHeld(i);
908
+ const recitation = isRecitationGroup(item.notes);
909
+ if (held && recitation && placedNotes[i - 1] === placedNotes[i] && line.notesParts.length > 0 && !afterInlineClef) {
910
+ prevRecited = true;
911
+ idx++;
912
+ continue;
913
+ }
914
+ let parts = splitNoteMarkers(item.notes);
915
+ const joinOf = () => line.notesParts.length === 0 || afterInlineClef ? "" : held ? lastGroupTrailingMarker ? "--" : "-" : lastGroupTrailingMarker || item.tightJoin || hangingLength(parts.core) > 0 ? reducedJunction : fullJunction;
916
+ let join = joinOf();
917
+ if (line.notesParts.length > 0 && measureNotes(notesSoFar + join + item.notes) > maxWidthPx) {
918
+ const cut = !held && cutEmptySlots ? findBreakCut(item.notes, maxWidthPx, (prefix) => measureNotes(notesSoFar + join + prefix)) : -1;
919
+ if (cut >= 0 && cut + 1 < item.notes.length) {
920
+ const rest = applyBreakCut(item, cut);
921
+ queueContinuation(item, idx, rest);
922
+ parts = splitNoteMarkers(item.notes);
923
+ } else {
924
+ startLine();
925
+ join = joinOf();
926
+ }
927
+ }
928
+ const fresh = line.notesParts.length === 0;
929
+ if (fresh && measureNotes(notesSoFar + item.notes) > maxWidthPx) {
930
+ const cut = findBreakCut(item.notes, maxWidthPx, (prefix) => measureNotes(notesSoFar + prefix));
931
+ if (cut >= 0 && cut + 1 < item.notes.length) {
932
+ const rest = applyBreakCut(item, cut);
933
+ queueContinuation(item, idx, rest);
934
+ parts = splitNoteMarkers(item.notes);
935
+ }
936
+ }
937
+ if (tracks.some((t) => t.carry)) {
938
+ let mods = hangingLength(parts.core);
939
+ if (mods === parts.core.length) mods = 0;
940
+ const inkStart = measureNotes(notesSoFar + join + parts.leading + parts.core.slice(0, mods)) - ink(parts.core.slice(mods), notesFont).left;
941
+ tracks.forEach((t, u) => {
942
+ if (!t.carry) return;
943
+ line.texts[u].segments.push({
944
+ ...t.carry,
945
+ textStart: Math.max(lineStartCursor, inkStart),
946
+ flowPx: t.cursor
947
+ });
948
+ t.carry = void 0;
949
+ });
950
+ }
951
+ pushGroup(item.i, join + item.notes, item.notes);
952
+ notesSoFar += join + item.notes;
953
+ for (const s of sung) keepWordState(s, fresh);
954
+ afterInlineClef = false;
955
+ if (item.lastSeg) {
956
+ lastGroupTrailingMarker = parts.trailing.length > 0;
957
+ prevRecited = recitation;
958
+ }
959
+ idx++;
960
+ continue;
961
+ }
962
+ const voiced = item.first ? sung.filter((s) => !silent(s.own)) : sung;
963
+ const runStart = placedNotes[i - 1] !== item.notes;
964
+ const specialFits = voiced.every((s) => s.t.cursor === lineStartCursor || s.t.cursor + s.pendingTotal + s.textWidth + (s.own.wordEnd ? 0 : hyphenOf(s.own.hyphen).width) <= maxWidthPx);
965
+ if (special && !runStart && line.notesParts.length > 0 && !specialFits) startLine();
966
+ if (!item.first) {
967
+ for (;;) {
968
+ if (measureNotes(notesSoFar + item.notes) <= maxWidthPx) break;
969
+ const cut = findBreakCut(item.notes, maxWidthPx, (prefix) => measureNotes(notesSoFar + prefix));
970
+ if (cut < 0 || cut + 1 >= item.notes.length) break;
971
+ const rest = applyBreakCut(item, cut);
972
+ queueContinuation(item, idx, rest);
973
+ }
974
+ const parts = splitNoteMarkers(item.notes);
975
+ pushGroup(item.i, item.notes, item.notes);
976
+ notesSoFar += item.notes;
977
+ if (item.lastSeg) lastGroupTrailingMarker = parts.trailing.length > 0;
978
+ for (const [u, s] of sung.entries()) {
979
+ line.texts[u].lastWordEnd = true;
980
+ s.t.prevWordEnd = s.own.wordEnd;
981
+ }
982
+ if (!item.lastSeg) forceBreak = true;
983
+ idx++;
984
+ continue;
985
+ }
986
+ let parts = splitNoteMarkers(item.notes);
987
+ let junctionPrefix = line.notesParts.length === 0 || afterInlineClef ? "" : lastGroupTrailingMarker || item.tightJoin || hangingLength(parts.core) > 0 ? reducedJunction : fullJunction;
988
+ if (prevRecited) {
989
+ const closing = /-*$/.exec(notesSoFar)[0].length;
990
+ junctionPrefix = special && !runStart || closing > /^-*/.exec(junctionPrefix)[0].length ? "" : junctionPrefix.slice(closing);
991
+ }
992
+ const place = (padDashes = 0) => {
993
+ let mods = hangingLength(parts.core);
994
+ if (mods === parts.core.length) mods = 0;
995
+ const anchorText = parts.core.slice(mods);
996
+ const contentWidth = measureNotes(anchorText);
997
+ const contentStart = measureNotes(notesSoFar + junctionPrefix + "-".repeat(padDashes) + parts.leading + parts.core.slice(0, mods));
998
+ const inkRaw = ink(anchorText, notesFont);
999
+ if (anchorText.length > 1) inkRaw.right += notesLetterSpacingPx * (anchorText.length - 1);
1000
+ const inkStartOffset = -inkRaw.left;
1001
+ const inkCenterOffset = (inkRaw.right - inkRaw.left) / 2;
1002
+ const textStartOf = (textWidth) => contentWidth >= textWidth || special ? contentStart + inkStartOffset : contentStart + inkCenterOffset - textWidth / 2;
1003
+ return {
1004
+ contentWidth,
1005
+ contentStart,
1006
+ textStartOf
1007
+ };
1008
+ };
1009
+ let placed = place();
1010
+ const uncut = {
1011
+ notes: item.notes,
1012
+ inserted: item.inserted,
1013
+ lastSeg: item.lastSeg,
1014
+ forceBreak,
1015
+ items: items.length
1016
+ };
1017
+ const fit = () => {
1018
+ for (;;) {
1019
+ const notesOver = measureNotes(notesSoFar + junctionPrefix + item.notes) > maxWidthPx;
1020
+ const textOver = voiced.some((s) => placed.textStartOf(s.textWidth) + s.textWidth + (s.own.wordEnd ? 0 : hyphenOf(s.own.hyphen).width) > maxWidthPx);
1021
+ if (!notesOver && !textOver) break;
1022
+ if (notesOver) {
1023
+ const cut = findBreakCut(item.notes, maxWidthPx, (prefix) => measureNotes(notesSoFar + junctionPrefix + prefix));
1024
+ if (cut >= 0 && cut + 1 < item.notes.length) {
1025
+ const rest = applyBreakCut(item, cut);
1026
+ queueContinuation(item, idx, rest);
1027
+ parts = splitNoteMarkers(item.notes);
1028
+ placed = place();
1029
+ break;
1030
+ }
1031
+ }
1032
+ if (line.notesParts.length === 0 && tracks.every((t) => t.cursor === lineStartCursor)) {
1033
+ if (notesOver) {
1034
+ const cut = findBreakCut(item.notes, maxWidthPx, (prefix) => measureNotes(notesSoFar + prefix));
1035
+ if (cut >= 0 && cut + 1 < item.notes.length) {
1036
+ const rest = applyBreakCut(item, cut);
1037
+ item.notes = item.notes.slice(0, cut);
1038
+ queueContinuation(item, idx, rest);
1039
+ parts = splitNoteMarkers(item.notes);
1040
+ placed = place();
1041
+ }
1042
+ }
1043
+ break;
1044
+ }
1045
+ startLine();
1046
+ junctionPrefix = "";
1047
+ parts = splitNoteMarkers(item.notes);
1048
+ placed = place();
1049
+ }
1050
+ };
1051
+ fit();
1052
+ const decide = (s) => {
1053
+ const { t, textWidth } = s;
1054
+ const { contentWidth } = placed;
1055
+ const connectorDash = line.notesParts.length > 0 && !t.prevWordEnd && s.pendingTotal === 0;
1056
+ const minStart = t.cursor + t.hyphen.width;
1057
+ const minTextStart = t.cursor + s.pendingTotal + (prevRecited && connectorDash ? t.hyphen.width : 0);
1058
+ let textStart = placed.textStartOf(textWidth);
1059
+ let contentStart = placed.contentStart;
1060
+ let pads = 0;
1061
+ let tight = false;
1062
+ if (!prevRecited && connectorDash && textStart < minStart && (textWidth > contentWidth || textStart < t.cursor)) {
1063
+ tight = true;
1064
+ textStart = t.cursor;
1065
+ const idealContentStart = contentWidth >= textWidth ? textStart : textStart + (textWidth - contentWidth) / 2;
1066
+ if (idealContentStart > contentStart) pads = Math.round((idealContentStart - contentStart) / dashNotesWidth);
1067
+ return {
1068
+ textStart,
1069
+ contentStart,
1070
+ pads,
1071
+ tight,
1072
+ floor: t.cursor,
1073
+ minStart
1074
+ };
1075
+ }
1076
+ if (textStart < minTextStart) {
1077
+ const idealContentStart = contentWidth >= textWidth ? minTextStart : minTextStart + (textWidth - contentWidth) / 2;
1078
+ if (idealContentStart > contentStart) {
1079
+ pads = Math.max(0, Math.floor((idealContentStart - contentStart) / dashNotesWidth));
1080
+ let padded = place(pads);
1081
+ while (padded.textStartOf(textWidth) < minTextStart) {
1082
+ pads++;
1083
+ padded = place(pads);
1084
+ }
1085
+ textStart = padded.textStartOf(textWidth);
1086
+ contentStart = padded.contentStart;
1087
+ }
1088
+ }
1089
+ return {
1090
+ textStart,
1091
+ contentStart,
1092
+ pads,
1093
+ tight,
1094
+ floor: minTextStart,
1095
+ minStart
1096
+ };
1097
+ };
1098
+ const hiddenSpecial = special && !runStart && line.notesParts.length > 0 && !afterInlineClef;
1099
+ let placements;
1100
+ let padDashes = 0;
1101
+ if (hiddenSpecial) {
1102
+ junctionPrefix = "";
1103
+ placements = voiced.map((s) => {
1104
+ const textStart = s.t.cursor + s.pendingTotal;
1105
+ return {
1106
+ textStart,
1107
+ contentStart: placed.contentStart,
1108
+ pads: 0,
1109
+ tight: line.notesParts.length > 0 && !s.t.prevWordEnd && s.pendingTotal === 0,
1110
+ floor: textStart,
1111
+ minStart: textStart
1112
+ };
1113
+ });
1114
+ const deficit = Math.max(...voiced.map((s, v) => placements[v].textStart + s.textWidth + s.spaceWidth)) - measureNotes(notesSoFar);
1115
+ const room = maxWidthPx - measureNotes(notesSoFar + junctionPrefix);
1116
+ const fill = deficit > 0 ? Math.min(Math.ceil(deficit / dashNotesWidth), Math.max(0, Math.floor(room / dashNotesWidth))) : 0;
1117
+ item.notes = "-".repeat(fill);
1118
+ item.inserted = [];
1119
+ parts = splitNoteMarkers(item.notes);
1120
+ } else {
1121
+ const settle = () => {
1122
+ placements = voiced.map(decide);
1123
+ padDashes = Math.max(0, ...placements.map((p) => p.pads));
1124
+ if (placements.some((p) => p.pads < padDashes)) {
1125
+ const padded = place(padDashes);
1126
+ placements = placements.map((p, v) => {
1127
+ if (p.pads === padDashes) return p;
1128
+ const textStart = Math.max(padded.textStartOf(voiced[v].textWidth), p.floor);
1129
+ return {
1130
+ ...p,
1131
+ textStart,
1132
+ contentStart: padded.contentStart,
1133
+ pads: padDashes,
1134
+ tight: p.tight && textStart < p.minStart
1135
+ };
1136
+ });
1137
+ }
1138
+ };
1139
+ settle();
1140
+ if (line.notesParts.length > 0 && (measureNotes(notesSoFar + junctionPrefix + "-".repeat(padDashes) + item.notes) > maxWidthPx || voiced.some((s, v) => {
1141
+ return Math.max(placements[v].textStart, s.t.cursor + s.pendingTotal) + s.textWidth + (s.own.wordEnd ? 0 : hyphenOf(s.own.hyphen).width) > maxWidthPx;
1142
+ }))) {
1143
+ const recut = items.length > uncut.items;
1144
+ if (recut) {
1145
+ items.splice(idx + 1, items.length - uncut.items);
1146
+ item.notes = uncut.notes;
1147
+ item.inserted = uncut.inserted;
1148
+ item.lastSeg = uncut.lastSeg;
1149
+ forceBreak = uncut.forceBreak;
1150
+ }
1151
+ startLine();
1152
+ junctionPrefix = "";
1153
+ parts = splitNoteMarkers(item.notes);
1154
+ placed = place();
1155
+ if (recut) fit();
1156
+ settle();
1157
+ }
1158
+ }
1159
+ const notesStr = junctionPrefix + "-".repeat(padDashes) + item.notes;
1160
+ const fresh = line.notesParts.length === 0;
1161
+ tracks.forEach((t, u) => {
1162
+ const seg = t.carry;
1163
+ if (!seg) return;
1164
+ t.carry = void 0;
1165
+ const v = voiced.findIndex((s) => s.t === t);
1166
+ const textStart = v >= 0 && item.first ? Math.max(lineStartCursor, placements[v].textStart - voiced[v].pendingTotal - measure(" ", spaceFont) - seg.textWidth) : place(padDashes).textStartOf(0);
1167
+ line.texts[u].segments.push({
1168
+ ...seg,
1169
+ textStart,
1170
+ flowPx: t.cursor
1171
+ });
1172
+ });
1173
+ voiced.forEach((s, v) => {
1174
+ const { t, sylParts, textWidth, spaceWidth, pendingTotal } = s;
1175
+ const text = line.texts[tracks.indexOf(t)];
1176
+ const p = placements[v];
1177
+ let textStart = p.textStart;
1178
+ if (pendingTotal > 0 && textStart < t.cursor + pendingTotal) textStart = t.cursor + pendingTotal;
1179
+ const spacerWidth = Math.max(0, textStart - pendingTotal - t.cursor);
1180
+ if (fresh) text.segments.push({
1181
+ kind: "gap",
1182
+ role: "lead-in",
1183
+ width: spacerWidth,
1184
+ endPx: textStart - pendingTotal,
1185
+ textStartPx: textStart
1186
+ });
1187
+ else if (t.prevWordEnd) text.segments.push({
1188
+ kind: "gap",
1189
+ role: "word-gap",
1190
+ width: spacerWidth,
1191
+ endPx: textStart - pendingTotal,
1192
+ textStartPx: textStart
1193
+ });
1194
+ else if (pendingTotal === 0 && p.tight) {} else if (pendingTotal === 0) {
1195
+ const pad = Math.max(0, (spacerWidth - t.hyphen.width) / 2);
1196
+ text.segments.push({
1197
+ kind: "connector",
1198
+ pad,
1199
+ gapWidth: spacerWidth,
1200
+ dashWidth: t.hyphen.width,
1201
+ ...t.hyphen.parts ? { parts: t.hyphen.parts } : {},
1202
+ dashStartPx: t.cursor + pad,
1203
+ nextAnchorPx: textStart
1204
+ });
1205
+ }
1206
+ if (t.mark?.text === text) fitMark(t.mark, textStart - pendingTotal);
1207
+ t.mark = void 0;
1208
+ let pendingStart = textStart - pendingTotal;
1209
+ for (const pend of t.pending) {
1210
+ text.segments.push({
1211
+ kind: "syl",
1212
+ syllable: pend.syllable,
1213
+ parts: pend.sylParts,
1214
+ textStart: pendingStart,
1215
+ textWidth: pend.textWidth,
1216
+ contentWidth: 0,
1217
+ contentStart: 0,
1218
+ extraDashes: 0,
1219
+ tight: false,
1220
+ noNotes: true
1221
+ });
1222
+ pendingStart += pend.textWidth;
1223
+ if (pend.spaceWidth > 0) {
1224
+ text.segments.push({
1225
+ kind: "word-space",
1226
+ width: pend.spaceWidth
1227
+ });
1228
+ pendingStart += pend.spaceWidth;
1229
+ }
1230
+ }
1231
+ t.pending = [];
1232
+ text.segments.push({
1233
+ kind: "syl",
1234
+ syllable: item.i,
1235
+ parts: sylParts,
1236
+ textStart,
1237
+ textWidth,
1238
+ contentWidth: placed.contentWidth,
1239
+ contentStart: p.contentStart,
1240
+ extraDashes: padDashes,
1241
+ tight: p.tight,
1242
+ noNotes: false
1243
+ });
1244
+ if (spaceWidth > 0) text.segments.push({
1245
+ kind: "word-space",
1246
+ width: spaceWidth
1247
+ });
1248
+ t.cursor = textStart + textWidth + spaceWidth;
1249
+ text.lastWordEnd = s.own.wordEnd;
1250
+ t.prevWordEnd = s.own.wordEnd;
1251
+ t.hyphen = hyphenOf(s.own.hyphen);
1252
+ text.hyphen = t.hyphen;
1253
+ });
1254
+ for (const s of sung) if (!voiced.includes(s)) keepWordState(s, fresh);
1255
+ notesSoFar += notesStr;
1256
+ pushGroup(item.i, notesStr, item.notes);
1257
+ afterInlineClef = false;
1258
+ if (item.lastSeg) {
1259
+ lastGroupTrailingMarker = parts.trailing.length > 0;
1260
+ prevRecited = special;
1261
+ }
1262
+ if (!item.lastSeg) forceBreak = true;
1263
+ idx++;
1264
+ }
1265
+ notePlacedLine();
1266
+ flushPending(true);
1267
+ while (keepStack.length > 0) closeKeepRun();
1268
+ tracks.forEach((t, u) => {
1269
+ line.texts[u].textCursor = t.cursor;
1270
+ });
1271
+ line.notesEnd = line.notesParts.length ? measureNotes(line.clefPrefix + line.notesParts.join("")) : 0;
1272
+ lines.forEach((l, li) => {
1273
+ if (li === lines.length - 1) return;
1274
+ for (const text of l.texts) {
1275
+ if (text.lastWordEnd !== false) continue;
1276
+ const hyphen = text.hyphen ?? { width: dashTextWidth };
1277
+ const pad = l.notesEnd > text.textCursor ? Math.max(0, (l.notesEnd - text.textCursor - hyphen.width) / 2) : 0;
1278
+ text.segments.push({
1279
+ kind: "line-end-dash",
1280
+ pad,
1281
+ dashWidth: hyphen.width,
1282
+ ...hyphen.parts ? { parts: hyphen.parts } : {},
1283
+ dashStartPx: text.textCursor + pad,
1284
+ trailEndPx: l.notesEnd,
1285
+ textEndPx: text.textCursor
1286
+ });
1287
+ }
1288
+ });
1289
+ for (const l of lines) {
1290
+ l.textCursor = l.texts[0].textCursor;
1291
+ l.lastWordEnd = l.texts[0].lastWordEnd;
1292
+ }
1293
+ const starTarget = maxWidthPx + padding;
1294
+ const starWidth = measureNotes("*");
1295
+ const fill = staffFill === "all" && maxWidthPx === Infinity ? "longest" : staffFill;
1296
+ const fillsLast = fill === "all" || fill === "longest";
1297
+ const longest = Math.max(...lines.map((l) => Math.max(l.notesEnd, ...l.texts.map((t) => t.textCursor))));
1298
+ const fillTarget = fill === "none" || maxWidthPx === Infinity && !fillsLast ? null : fill === "longest" && maxWidthPx - longest > staffFillSnapPx ? longest : maxWidthPx;
1299
+ lines.forEach((l, li) => {
1300
+ const last = li === lines.length - 1;
1301
+ l.staffEnd = l.notesEnd;
1302
+ if (last && (!fillsLast || l.notesParts.length === 0)) return;
1303
+ if (fillTarget === null) {
1304
+ l.breakMarkerLeftPx = padding;
1305
+ return;
1306
+ }
1307
+ const staffEdge = fillTarget + padding;
1308
+ let lineEnd = measureNotes(l.clefPrefix + l.notesParts.join(""));
1309
+ while (last ? lineEnd + dashNotesWidth <= staffEdge : lineEnd + dashNotesWidth <= staffEdge - starWidth && lineEnd + dashNotesWidth < fillTarget) {
1310
+ l.notesParts.push("-");
1311
+ lineEnd += dashNotesWidth;
1312
+ }
1313
+ if (last) {
1314
+ const third = measureNotes("¨");
1315
+ while (lineEnd + third <= staffEdge) {
1316
+ l.notesParts.push("¨");
1317
+ lineEnd += third;
1318
+ }
1319
+ }
1320
+ l.staffEnd = lineEnd;
1321
+ if (!last) l.breakMarkerLeftPx = staffEdge - lineEnd - starWidth;
1322
+ });
1323
+ return {
1324
+ result: {
1325
+ lines,
1326
+ clefPrefix: lines[0].clefPrefix,
1327
+ styleSet,
1328
+ styleName,
1329
+ textPx,
1330
+ notesPx,
1331
+ bold,
1332
+ maxWidthPx,
1333
+ starTarget,
1334
+ starWidth,
1335
+ clefMark,
1336
+ leftPaddingPx,
1337
+ textFontStack: textStack
1338
+ },
1339
+ splitRuns,
1340
+ placedNotes,
1341
+ sylLines
1342
+ };
1343
+ }
1344
+ //#endregion
1345
+ export { measure as a, layoutScore as i, SPECIAL_NOTES as n, isFontAvailable as r, NOTE_MODIFIERS as t };