guidex 0.3.1 → 0.3.3

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 (35) hide show
  1. package/README.md +81 -4
  2. package/dist/lib/app/EditorContext.d.ts +6 -1
  3. package/dist/lib/app/ExactTransposeControls.d.ts +1 -0
  4. package/dist/lib/app/StanzaControls.d.ts +1 -0
  5. package/dist/lib/app/TransposeSettings.d.ts +1 -0
  6. package/dist/lib/app/editorState.d.ts +81 -6
  7. package/dist/lib/app/shareLink.d.ts +22 -0
  8. package/dist/lib/chantLayout-CVVuJUJl.js +2778 -0
  9. package/dist/lib/chantLayout.d.ts +48 -8
  10. package/dist/lib/composeScript.d.ts +71 -0
  11. package/dist/lib/editorStorage.d.ts +11 -0
  12. package/dist/lib/embed/core.d.ts +34 -3
  13. package/dist/lib/embed/index.js +1 -1
  14. package/dist/lib/embed/manual.d.ts +12 -3
  15. package/dist/lib/embed/manual.js +348 -276
  16. package/dist/lib/exactTranspose.d.ts +54 -0
  17. package/dist/lib/glyphFamilies.d.ts +29 -0
  18. package/dist/lib/guidex.css +29 -2
  19. package/dist/lib/guidoRender.d.ts +7 -3
  20. package/dist/lib/guidoScript.d.ts +109 -10
  21. package/dist/lib/guidoScriptTransforms.d.ts +19 -7
  22. package/dist/lib/noteGroups.d.ts +22 -0
  23. package/dist/lib/react/GuidexScore.d.ts +21 -1
  24. package/dist/lib/react/index.d.ts +2 -1
  25. package/dist/lib/react/index.js +25 -3
  26. package/dist/lib/{scoreImage-oVBasBX5.js → scoreImage-lvOrTbG-.js} +111 -53
  27. package/dist/lib/stanzas.d.ts +135 -0
  28. package/dist/lib/word/index.js +1 -1
  29. package/dist/lib/{wordChecker-C3nJrk_j.js → wordChecker-DG09l_ol.js} +99 -46
  30. package/dist/lib/wordClipboard.d.ts +3 -3
  31. package/dist/lib/wordExport.d.ts +11 -5
  32. package/dist-embed/guidex-embed.min.css +1 -1
  33. package/dist-embed/guidex-embed.min.js +1 -1
  34. package/package.json +1 -1
  35. package/dist/lib/chantLayout-GAfg2iKS.js +0 -1042
@@ -1,4 +1,4 @@
1
- import { c as inlineStylesFor, d as transposeBy, f as GuidoScript, i as layoutScore, s as STYLE_SETS } from "./chantLayout-GAfg2iKS.js";
1
+ import { A as stanzaWarnings, C as selectStanza, D as stackedStanzaNumbers, E as stackStanzas, P as GuidoScript, d as transposeBy, o as STYLE_SETS, r as layoutScore, s as inlineStylesFor } from "./chantLayout-CVVuJUJl.js";
2
2
  //#region src/guidoRender.ts
3
3
  /**
4
4
  * Renders a GuidoScript into a tidy score: a notes line in the chant font,
@@ -9,12 +9,15 @@ import { c as inlineStylesFor, d as transposeBy, f as GuidoScript, i as layoutSc
9
9
  * `render` turns the laid-out lines into (notes `.guido` div, text `<p>`)
10
10
  * pairs — px-measured inline-block spacer spans fake the horizontal gaps.
11
11
  * The Word export (wordExport.ts) consumes the same layout with a
12
- * character-based spacer mechanism instead.
12
+ * character-based spacer mechanism instead. Given several underlays of
13
+ * one melody (stacked stanzas, issue #84 — see `stackStanzas`), every
14
+ * notes line is followed by one text `<p>` per underlay.
13
15
  */
14
16
  var GuidoRender = class GuidoRender {
15
17
  script;
16
18
  constructor(source) {
17
- this.script = typeof source === "string" ? new GuidoScript(source) : source;
19
+ const parse = (s) => typeof s === "string" ? new GuidoScript(s) : s;
20
+ this.script = typeof source === "string" || source instanceof GuidoScript ? parse(source) : source.map(parse);
18
21
  }
19
22
  /**
20
23
  * Renders the score into `container` as (notes line, text line) pairs.
@@ -25,22 +28,22 @@ var GuidoRender = class GuidoRender {
25
28
  */
26
29
  async render(container, options = {}) {
27
30
  const { debug = false } = options;
28
- const { lines, clefPrefix, styleSet, styleName, textPx, notesPx, bold, starTarget, starWidth } = await layoutScore(this.script, options);
31
+ const { lines, styleSet, styleName, textPx, notesPx, bold, starTarget, starWidth } = await layoutScore(this.script, options);
29
32
  container.style.fontSize = `${textPx}px`;
30
33
  container.style.fontFamily = styleSet.textFontStack;
31
34
  container.dataset.style = styleName;
32
- container.replaceChildren(...lines.flatMap((l) => [GuidoRender.notesLine(l, clefPrefix, notesPx, starTarget, starWidth, debug), GuidoRender.textLine(l, textPx, bold, debug)]));
35
+ container.replaceChildren(...lines.flatMap((l) => [GuidoRender.notesLine(l, notesPx, starTarget, starWidth, debug), ...l.texts.map((text) => GuidoRender.textLine(text, textPx, bold, debug))]));
33
36
  }
34
37
  /** Builds a line's notes div: the chant font text plus, on broken
35
38
  * lines, the break marker `*` as an inline span (so it shares the
36
39
  * text's baseline) shifted right so its right edge lands on the
37
40
  * padding-extended max-width position. position: relative keeps the
38
41
  * shift out of the flow measurements. */
39
- static notesLine(line, clefPrefix, notesPx, starTarget, starWidth, debug) {
42
+ static notesLine(line, notesPx, starTarget, starWidth, debug) {
40
43
  const notesEl = document.createElement("div");
41
44
  notesEl.className = "guido";
42
45
  notesEl.style.fontSize = `${notesPx}px`;
43
- notesEl.textContent = clefPrefix + line.notesParts.join("");
46
+ notesEl.textContent = line.clefPrefix + line.notesParts.join("");
44
47
  if (line.breakMarkerLeftPx !== void 0) {
45
48
  const star = document.createElement("span");
46
49
  star.className = "guido-break";
@@ -155,7 +158,7 @@ var GuidoRender = class GuidoRender {
155
158
  //#region src/embed/core.ts
156
159
  var version = {
157
160
  name: "guidex",
158
- version: "0.3.1",
161
+ version: "0.3.3",
159
162
  description: "Guidex — render plainchant scores from a compact GuidoScript notation, as a web app and an embeddable runtime",
160
163
  type: "module",
161
164
  workspaces: ["examples/*"],
@@ -236,7 +239,12 @@ var DEFAULTS = {
236
239
  style: "BNS",
237
240
  bold: false,
238
241
  textPx: 18,
242
+ junctionDashes: 3,
239
243
  transpose: 0,
244
+ stanza: 1,
245
+ stack: void 0,
246
+ emptySlots: "normal",
247
+ stanzas: void 0,
240
248
  debug: false
241
249
  };
242
250
  var globalOptions = {};
@@ -265,7 +273,7 @@ function number(value) {
265
273
  function parseMaxWidth(value, fallback) {
266
274
  if (/^auto$/i.test(value.trim())) return "auto";
267
275
  const n = Number(value);
268
- if (Number.isFinite(n) && n > 0) return n;
276
+ if (n > 0) return n;
269
277
  console.warn(`[guidex] ignoring invalid data-max-width "${value}"`);
270
278
  return fallback;
271
279
  }
@@ -273,6 +281,19 @@ function parseMaxWidth(value, fallback) {
273
281
  * callers): element data attributes win over these, these win over
274
282
  * `init` site-wide defaults. */
275
283
  var overrides = /* @__PURE__ */ new WeakMap();
284
+ function emptySlotsValue(value) {
285
+ if (value === void 0) return void 0;
286
+ if (value === "normal" || value === "small" || value === "partial") return value;
287
+ console.warn(`[guidex] ignoring invalid data-empty-slots "${value}"`);
288
+ }
289
+ /** `data-stack`: `all`, or a comma-separated list of stanza numbers. */
290
+ function stackValue(value) {
291
+ if (value === void 0) return void 0;
292
+ if (/^\s*all\s*$/i.test(value)) return "all";
293
+ const list = value.split(",").map((n) => Number(n.trim()));
294
+ if (value.trim() !== "" && list.every((n) => Number.isInteger(n) && n > 0)) return list;
295
+ console.warn(`[guidex] ignoring invalid data-stack "${value}"`);
296
+ }
276
297
  /** Element data attributes (or unset) over `renderScore` overrides over
277
298
  * init options over defaults. */
278
299
  function readOptions(el) {
@@ -283,7 +304,12 @@ function readOptions(el) {
283
304
  style: ds.style ?? local.style ?? globalOptions.style ?? DEFAULTS.style,
284
305
  bold: flag(ds.bold) ?? local.bold ?? globalOptions.bold ?? DEFAULTS.bold,
285
306
  textPx: number(ds.textPx) ?? local.textPx ?? globalOptions.textPx ?? DEFAULTS.textPx,
307
+ junctionDashes: number(ds.junctionDashes) ?? local.junctionDashes ?? globalOptions.junctionDashes ?? DEFAULTS.junctionDashes,
286
308
  transpose: number(ds.transpose) ?? local.transpose ?? globalOptions.transpose ?? DEFAULTS.transpose,
309
+ stanza: number(ds.stanza) ?? local.stanza ?? globalOptions.stanza ?? DEFAULTS.stanza,
310
+ stack: stackValue(ds.stack) ?? local.stack ?? globalOptions.stack ?? DEFAULTS.stack,
311
+ emptySlots: emptySlotsValue(ds.emptySlots) ?? local.emptySlots ?? globalOptions.emptySlots ?? DEFAULTS.emptySlots,
312
+ stanzas: local.stanzas ?? DEFAULTS.stanzas,
287
313
  debug: flag(ds.debug) ?? local.debug ?? globalOptions.debug ?? DEFAULTS.debug
288
314
  };
289
315
  }
@@ -291,7 +317,9 @@ function readOptions(el) {
291
317
  * line-box width the rendered score actually has to fit. Falls back to
292
318
  * the parent for inline targets; zero means no layout (hidden). */
293
319
  function contentWidthPx(el) {
294
- return el.querySelector(":scope > .guidex-render")?.clientWidth || el.clientWidth || el.parentElement?.clientWidth || 0;
320
+ const wrapper = el.querySelector(":scope > .guidex-render");
321
+ wrapper?.removeAttribute("data-fixed-width");
322
+ return wrapper?.clientWidth || el.clientWidth || el.parentElement?.clientWidth || 0;
295
323
  }
296
324
  /** The line-breaking budget in pixels for this render. Fixed values pass
297
325
  * through; 'auto' fits the element's content box, shrunk by the style
@@ -328,49 +356,95 @@ function renderError(wrapper, message) {
328
356
  const note = document.createElement("p");
329
357
  note.className = "guidex-error";
330
358
  note.textContent = message;
359
+ wrapper.removeAttribute("data-fixed-width");
331
360
  wrapper.replaceChildren(note);
332
361
  }
333
- /** The transforms a score renders with: the style set's defaults (BNS
334
- * marks the first initial) plus the user-requested transpose. An unknown
335
- * style name yields no defaults here — the render itself reports it. */
336
- function scriptTransforms(style, transpose) {
337
- const transforms = [...STYLE_SETS[style]?.scriptTransforms ?? []];
338
- if (transpose !== 0) transforms.push(transposeBy(transpose));
362
+ /** The transforms a score renders with after the stanza swap: the style
363
+ * set's defaults (BNS marks the first initial), then the user-requested
364
+ * transpose. An unknown style name yields no defaults here — the render
365
+ * itself reports it. */
366
+ function scriptTransforms(options) {
367
+ const transforms = [...STYLE_SETS[options.style]?.scriptTransforms ?? []];
368
+ if (options.transpose !== 0) transforms.push(transposeBy(options.transpose));
339
369
  return transforms;
340
370
  }
341
- /** Renders one target element. The score is built into a detached
342
- * scratch wrapper and swapped into the live one only when this run is
343
- * still the latest — a stale render that finished late leaves no
344
- * footprint. */
345
- async function renderElement(el) {
346
- const run = (runs.get(el) ?? 0) + 1;
347
- runs.set(el, run);
348
- const options = readOptions(el);
349
- const source = extractSource(el);
350
- sources.set(el, source);
371
+ /** The scripts a score renders: the stacked stanzas when a stack is set
372
+ * (one text line each), otherwise the one stanza — the stanza swap runs
373
+ * first, so the other transforms see the stanza's text. Returns the
374
+ * rendered stanzas' count mismatches with them. */
375
+ function renderedScripts(source, options) {
376
+ const transforms = scriptTransforms(options);
377
+ const { stanzas, emptySlots } = options;
378
+ if (options.stack !== void 0) {
379
+ const rendered = stackedStanzaNumbers(source, options.stack, { stanzas });
380
+ return {
381
+ scripts: stackStanzas(source, rendered, {
382
+ stanzas,
383
+ emptySlots,
384
+ transforms
385
+ }),
386
+ warnings: rendered.flatMap((stanza) => stanzaWarnings(source, {
387
+ stanzas,
388
+ stanza
389
+ }))
390
+ };
391
+ }
392
+ if (options.stanza !== 1 || emptySlots !== "normal") transforms.unshift(selectStanza(options.stanza, {
393
+ stanzas,
394
+ emptySlots
395
+ }));
396
+ return {
397
+ scripts: [new GuidoScript(source, { transforms })],
398
+ warnings: stanzaWarnings(source, {
399
+ stanzas,
400
+ stanza: options.stanza
401
+ })
402
+ };
403
+ }
404
+ /** Builds the score into a detached scratch wrapper and swaps it into
405
+ * the live one only when this run is still the latest — a stale render
406
+ * that finished late leaves no footprint. A failure (a script or stanza
407
+ * error, an unloadable font) replaces the score with an error note.
408
+ * Resolves with the rendered stanza's warnings, also logged. */
409
+ async function drawScore(el, run, source, options, widthPx) {
351
410
  const wrapper = scoreWrapper(el);
352
- const widthPx = resolveWidthPx(el, options.maxWidth, options.style);
353
- lastWidths.set(el, widthPx);
354
411
  const scratch = document.createElement("div");
355
- const script = new GuidoScript(source, { transforms: scriptTransforms(options.style, options.transpose) });
356
412
  try {
357
- await new GuidoRender(script).render(scratch, {
413
+ const { scripts, warnings } = renderedScripts(source, options);
414
+ await new GuidoRender(scripts).render(scratch, {
358
415
  style: options.style,
359
416
  bold: options.bold,
360
417
  textPx: options.textPx,
418
+ junctionDashes: options.junctionDashes,
361
419
  debug: options.debug,
362
420
  maxWidthPx: widthPx
363
421
  });
364
- if (runs.get(el) !== run) return;
422
+ if (runs.get(el) !== run) return { warnings };
423
+ for (const warning of warnings) console.warn(`[guidex] ${warning.message}`);
365
424
  wrapper.replaceChildren(...scratch.childNodes);
366
425
  wrapper.style.cssText = scratch.style.cssText;
367
426
  if (scratch.dataset.style) wrapper.dataset.style = scratch.dataset.style;
427
+ wrapper.toggleAttribute("data-fixed-width", typeof options.maxWidth === "number");
428
+ return { warnings };
368
429
  } catch (e) {
369
- if (runs.get(el) !== run) return;
430
+ if (runs.get(el) !== run) return { warnings: [] };
370
431
  console.error("[guidex]", e);
371
432
  renderError(wrapper, e instanceof Error ? e.message : String(e));
433
+ return { warnings: [] };
372
434
  }
373
435
  }
436
+ /** Renders one target element from its source and resolved options. */
437
+ async function renderElement(el) {
438
+ const run = (runs.get(el) ?? 0) + 1;
439
+ runs.set(el, run);
440
+ const options = readOptions(el);
441
+ const source = extractSource(el);
442
+ sources.set(el, source);
443
+ scoreWrapper(el);
444
+ const widthPx = resolveWidthPx(el, options.maxWidth, options.style);
445
+ lastWidths.set(el, widthPx);
446
+ await drawScore(el, run, source, options, widthPx);
447
+ }
374
448
  /** Sets up one resize listener per target element, on first render.
375
449
  * Only a changed line-breaking budget (width) triggers a re-render. */
376
450
  var detachFns = /* @__PURE__ */ new WeakMap();
@@ -413,36 +487,20 @@ function dispose(el) {
413
487
  * element's own text content is replaced by the rendered score and
414
488
  * re-rendered on resize. Call again with a new source to update.
415
489
  * Options set here override `init` defaults; data attributes on the
416
- * element still win. Resolves when the score has finished rendering. */
490
+ * element still win. `stanzas` replaces the script's `(@stanza …)`
491
+ * statements. Resolves when the score has finished rendering, with the
492
+ * rendered stanza's count mismatches. */
417
493
  async function renderScore(el, source, options = {}) {
418
494
  overrides.set(el, options);
419
495
  const run = (runs.get(el) ?? 0) + 1;
420
496
  runs.set(el, run);
421
497
  sources.set(el, source);
422
498
  const resolved = readOptions(el);
423
- const wrapper = scoreWrapper(el);
499
+ scoreWrapper(el);
424
500
  const widthPx = resolveWidthPx(el, resolved.maxWidth, resolved.style);
425
501
  lastWidths.set(el, widthPx);
426
502
  attachResizeListener(el);
427
- const scratch = document.createElement("div");
428
- const script = new GuidoScript(source, { transforms: scriptTransforms(resolved.style, resolved.transpose) });
429
- try {
430
- await new GuidoRender(script).render(scratch, {
431
- style: resolved.style,
432
- bold: resolved.bold,
433
- textPx: resolved.textPx,
434
- debug: resolved.debug,
435
- maxWidthPx: widthPx
436
- });
437
- if (runs.get(el) !== run) return;
438
- wrapper.replaceChildren(...scratch.childNodes);
439
- wrapper.style.cssText = scratch.style.cssText;
440
- if (scratch.dataset.style) wrapper.dataset.style = scratch.dataset.style;
441
- } catch (e) {
442
- if (runs.get(el) !== run) return;
443
- console.error("[guidex]", e);
444
- renderError(wrapper, e instanceof Error ? e.message : String(e));
445
- }
503
+ return drawScore(el, run, source, resolved, widthPx);
446
504
  }
447
505
  /** Renders every target under `root` (default: the whole document).
448
506
  * Already-rendered targets re-render from their cached source, so a
@@ -0,0 +1,135 @@
1
+ import { GuidoScript, ScriptToken } from './guidoScript';
2
+ import { ScriptTransform } from './guidoScriptTransforms';
3
+ /** One item of a parsed stanza: a sung syllable (with its word end), a
4
+ * hold (a lone `-`: the previous syllable goes on over this slot), or an
5
+ * empty slot (a lone `~`: the stanza sings nothing here). */
6
+ export type StanzaSyllable = {
7
+ kind: 'syllable';
8
+ text: string;
9
+ wordEnd: boolean;
10
+ } | {
11
+ kind: 'hold';
12
+ } | {
13
+ kind: 'empty';
14
+ };
15
+ /** How the slots not every stanza sings are drawn (a hold counts as
16
+ * singing, a missing syllable does not):
17
+ *
18
+ * - `'normal'`: with the notes as written;
19
+ * - `'small'`: with small heads (cue notes) where the rendered stanza
20
+ * leaves the slot empty while another stanza sings it — stacked (issue
21
+ * #84), where no rendered stanza sings it while a stanza left out does;
22
+ * - `'partial'`: with small heads wherever some stanza of the script
23
+ * sings the slot and another does not, whatever is rendered — normal
24
+ * heads only where every stanza sings it. The same notes come out for
25
+ * any stanza or stack.
26
+ *
27
+ * A slot no stanza sings keeps normal heads in every mode. */
28
+ export type EmptySlots = 'normal' | 'small' | 'partial';
29
+ /** The stanzas stacked under one staff (issue #84): every stanza, or the
30
+ * listed ones (1-based) in the given order. */
31
+ export type StanzaStack = 'all' | number[];
32
+ /** A count mismatch of one stanza: a slot it has no syllable for, or a
33
+ * syllable past the last slot (with its text; `-` for a hold, `~` for an
34
+ * empty slot). Stanza and slot are 1-based. */
35
+ export interface StanzaWarning {
36
+ stanza: number;
37
+ slot: number;
38
+ kind: 'missing' | 'extra';
39
+ text?: string;
40
+ message: string;
41
+ }
42
+ export interface StanzaOptions {
43
+ /** Stanzas 2, 3, … as stanza text; replaces the script's own
44
+ * `(@stanza …)` statements when given. */
45
+ stanzas?: string[];
46
+ }
47
+ /** The options of one stanza swap (`selectStanza`, `withStanza`). */
48
+ export interface SelectStanzaOptions extends StanzaOptions {
49
+ emptySlots?: EmptySlots;
50
+ /** The stanzas rendered together with this one (stacked under one
51
+ * staff, issue #84; default: this one alone), for the small-heads
52
+ * rule. */
53
+ rendered?: number[];
54
+ }
55
+ /** The syllable text that marks a slot a stanza is missing a syllable
56
+ * for: a rubric ellipsis, red in BNS, so the mismatch shows in the
57
+ * render (and in the Word export). */
58
+ export declare const STANZA_PLACEHOLDER = "_\u2026_";
59
+ /**
60
+ * Parses stanza text into its slot items, by Aretino's lyric-line rules:
61
+ *
62
+ * - whitespace separates words, `-` separates the syllables of a word
63
+ * (a soft hyphen U+00AD counts as `-`, and so does the mandatory
64
+ * hyphen `=` — the renderer has no hyphen it may not drop yet);
65
+ * - a lone `-` (or an empty syllable, `Al--le`) holds the slot for the
66
+ * syllable before it; that syllable's word end is its own (`Al- - le`
67
+ * is mid-word, `bunt - gen` ends the word);
68
+ * - a lone `~` is an empty slot; `~` inside a syllable is a
69
+ * non-breaking space;
70
+ * - a backslash makes the next character literal (`\-`, `\~`, `\=`,
71
+ * `\(`, `\\`).
72
+ *
73
+ * There are no `_` extenders: `_…_`, `__…__` and `*…*` stay the
74
+ * syllable formatting of the script notation.
75
+ */
76
+ export declare function parseStanza(text: string): StanzaSyllable[];
77
+ /** Whether a token opens a slot: a syllable with notes that are not all
78
+ * markers. */
79
+ export declare function isSlot(tok: ScriptToken): boolean;
80
+ /** The number of slots (note groups that take a stanza syllable). */
81
+ export declare function slotCount(script: GuidoScript | string): number;
82
+ /** The stanza texts of stanzas 2, 3, …: the `stanzas` option when
83
+ * given, the script's `(@stanza …)` statements otherwise. */
84
+ export declare function stanzaTexts(script: GuidoScript | string, options?: StanzaOptions): string[];
85
+ /** How many stanzas the script has, stanza 1 (the script) included. */
86
+ export declare function stanzaCount(script: GuidoScript | string, options?: StanzaOptions): number;
87
+ /** The count mismatches of one stanza (`options.stanza`), or of every
88
+ * stanza when none is named. Stanza 1 is the script and never warns;
89
+ * an intentional `~` is a syllable like any other. */
90
+ export declare function stanzaWarnings(script: GuidoScript | string, options?: StanzaOptions & {
91
+ stanza?: number;
92
+ }): StanzaWarning[];
93
+ /** Pads stanza text with `~` empty slots up to the script's slot count
94
+ * (unchanged when it already has enough syllables). */
95
+ export declare function padStanza(script: GuidoScript | string, text: string): string;
96
+ /** A note group with its plain heads, virgas and longas swapped for small
97
+ * heads (connectors, markers and signs stay). */
98
+ export declare function smallHeads(notes: string): string;
99
+ /** The `selectStanza` transform factory: rewrites the script to sing
100
+ * stanza `stanza` (1-based; 1 is the script itself). Its syllables go on
101
+ * the slots in order — missing ones become `STANZA_PLACEHOLDER`
102
+ * syllables, extra ones are dropped (`stanzaWarnings` reports both) — and
103
+ * the `(@stanza …)` statements are dropped. Everything that is not a
104
+ * slot (statements, syllables without notes, marker-only groups) stays as
105
+ * written. With `emptySlots: 'small'`, a slot the stanza leaves empty
106
+ * while another stanza sings it gets small heads (`rendered` lists the
107
+ * stanzas stacked with it: then a slot gets small heads when none of
108
+ * them sings it while another stanza does). With `emptySlots:
109
+ * 'partial'`, every slot some stanza sings and another does not gets
110
+ * small heads, whatever is rendered. Stanza 1 with normal
111
+ * empty slots returns the source unchanged. Throws a RangeError for a
112
+ * stanza the script does not have. Register it first, so the other
113
+ * transforms (the initial, the transpositions) see the stanza's text. */
114
+ export declare function selectStanza(stanza: number, options?: SelectStanzaOptions): ScriptTransform;
115
+ /** The script singing stanza `stanza` (see `selectStanza`); `transforms`
116
+ * run after the stanza swap. A GuidoScript argument is taken by its
117
+ * (already transformed) source. */
118
+ export declare function withStanza(script: GuidoScript | string, stanza: number, options?: SelectStanzaOptions & {
119
+ transforms?: ScriptTransform[];
120
+ }): GuidoScript;
121
+ /** The stanza numbers a stack names: every stanza for `'all'`, the
122
+ * listed ones otherwise. Throws a RangeError for an empty list or a
123
+ * stanza the script does not have. */
124
+ export declare function stackedStanzaNumbers(script: GuidoScript | string, stack: StanzaStack, options?: StanzaOptions): number[];
125
+ /** The scripts of stacked stanzas (issue #84): one per stanza of the
126
+ * stack, in its order, each singing its stanza on the shared notes (see
127
+ * `withStanza`; `transforms` run after the swap). Hand them to the layout
128
+ * together (`layoutScore`, `GuidoRender`, the Word export) for one text
129
+ * line per stanza under one staff. With `emptySlots: 'small'`, a slot
130
+ * gets small heads when no stacked stanza sings it while a stanza left
131
+ * out of the stack does, so every script carries the same notes. */
132
+ export declare function stackStanzas(script: GuidoScript | string, stack: StanzaStack, options?: StanzaOptions & {
133
+ emptySlots?: EmptySlots;
134
+ transforms?: ScriptTransform[];
135
+ }): GuidoScript[];
@@ -1,2 +1,2 @@
1
- import { a as DEFAULT_TAB_INTERVAL_PT, c as toWordHtml, i as DEFAULT_SPACER, l as toWordText, n as copyWordHtml, o as SpacerMeter, r as copyWordPlainText, s as layoutForWord, t as checkWordHtml, u as wordLayoutText } from "../wordChecker-C3nJrk_j.js";
1
+ import { a as DEFAULT_TAB_INTERVAL_PT, c as toWordHtml, i as DEFAULT_SPACER, l as toWordText, n as copyWordHtml, o as SpacerMeter, r as copyWordPlainText, s as layoutForWord, t as checkWordHtml, u as wordLayoutText } from "../wordChecker-DG09l_ol.js";
2
2
  export { DEFAULT_SPACER, DEFAULT_TAB_INTERVAL_PT, SpacerMeter, checkWordHtml, copyWordHtml, copyWordPlainText, layoutForWord, toWordHtml, toWordText, wordLayoutText };
@@ -1,5 +1,49 @@
1
- import { a as measure, i as layoutScore, l as measurementFont, n as SCORE_MARKERS, r as SPECIAL_NOTES, t as NOTE_MODIFIERS } from "./chantLayout-GAfg2iKS.js";
1
+ import { M as SCORE_MARKERS, V as CLEF_GLYPHS, c as measurementFont, i as measure, n as SPECIAL_NOTES, r as layoutScore, t as NOTE_MODIFIERS } from "./chantLayout-CVVuJUJl.js";
2
2
  //#region src/wordExport.ts
3
+ /**
4
+ * Word-compatible export: turns the shared layout (chantLayout.ts) into
5
+ * Word-flavoured HTML that pastes into Microsoft Word as alternating
6
+ * `BNS-nota` / `BNS-textus` paragraphs with the notes over their
7
+ * syllables.
8
+ *
9
+ * Word cannot consume the DOM renderer's positioned spacer spans, so every
10
+ * horizontal gap — lead-in, word gaps, syllable junctions alike — is faked
11
+ * by ONE spacer mechanism: a run of `unit × count` spacer characters. Two
12
+ * independent configuration axes tune it: the spacer character (tab, en,
13
+ * em, nbsp, simple space, or custom) and its width (tab-interval for tabs;
14
+ * scale, absolute width, or condensed/expanded letter-spacing for space
15
+ * characters — the latter stays tunable inside Word after pasting).
16
+ *
17
+ * The accounting is self-correcting: the export tracks the emitted position
18
+ * along the line and computes each gap as
19
+ * `count = max(0, round((next ideal anchor − emitted position) ÷ unit))` —
20
+ * never `round(gap ÷ unit)` per gap. An overshoot in one gap is absorbed by
21
+ * the next (possibly to zero), so every syllable anchor lands within ½ unit
22
+ * of its ideal and error never accumulates. Tab stops in Word are absolute
23
+ * positions, so the tab strategy snaps the emitted position onto the
24
+ * interval grid — the absolute-grid version of the same guarantee.
25
+ *
26
+ * Two error sources remain by nature and are named as such: quantization
27
+ * (≤ ½ unit per anchor, bounded, non-accumulating) and Word's font metrics
28
+ * differing from our canvas measurements — the latter is what width tuning
29
+ * and the checker's gap census (wordChecker.ts) address.
30
+ *
31
+ * The layout can run at the preview's px sizes (textPx/notesPx/maxWidthPx)
32
+ * or at the destination document's true Word sizes (textPt/notesPt/
33
+ * maxWidthPt, which take precedence — px = pt × 4/3). Destination sizing
34
+ * is what a real round-trip wants: Word renders the pasted styles at the
35
+ * destination's own pt sizes regardless of the web preview, so laying out
36
+ * at those same sizes makes the width tuning converge on the true grid
37
+ * (a tab unit of 0.5 mm really is 0.5 mm) and the line breaks match the
38
+ * destination column rather than the preview.
39
+ *
40
+ * The default spacer is a no-break space at its natural advance: the
41
+ * natural advance is proportional to the font size — size-invariant under
42
+ * Word's rendering — and plain characters survive any paste path (no
43
+ * mso machinery to lose). Tabs tune to an absolute interval grid; plain
44
+ * spaces (mso-spacerun:yes) are the fragile choice, kept for parity with
45
+ * the old workflow.
46
+ */
3
47
  var PT_PER_PX = .75;
4
48
  var PX_PER_PT = 4 / 3;
5
49
  /** Exact line heights in the target document: 1.2 × the font size, the
@@ -225,9 +269,10 @@ function walkTextLine(line, meter, pieces) {
225
269
  return out;
226
270
  }
227
271
  /** The notes line's raw Guido text: the renderer's own notes model is
228
- * already the Word representation. */
229
- function notesText(layout, line) {
230
- return layout.clefPrefix + line.notesParts.join("");
272
+ * already the Word representation. Each line opens with the clef and key
273
+ * in effect at its start. */
274
+ function notesText(line) {
275
+ return line.clefPrefix + line.notesParts.join("");
231
276
  }
232
277
  /** Spaces faking one tab's width for browser display; Word reads the
233
278
  * mso-tab-count, not the padding. */
@@ -257,7 +302,8 @@ function resolveSizing(options) {
257
302
  bold: options.bold,
258
303
  textPx: textPt !== void 0 ? textPt * PX_PER_PT : options.textPx,
259
304
  notesPx: notesPt !== void 0 ? notesPt * PX_PER_PT : options.notesPx,
260
- maxWidthPx: options.maxWidthPt !== void 0 ? options.maxWidthPt * PX_PER_PT : options.maxWidthPx
305
+ maxWidthPx: options.maxWidthPt !== void 0 ? options.maxWidthPt * PX_PER_PT : options.maxWidthPx,
306
+ junctionDashes: options.junctionDashes
261
307
  };
262
308
  }
263
309
  /**
@@ -301,8 +347,8 @@ async function toWordHtml(source, options = {}) {
301
347
  for (const line of layout.lines) {
302
348
  const markerStop = line.breakMarkerLeftPx !== void 0 && layout.maxWidthPx === Infinity ? ` style="tab-stops:right ${fmtPt((line.notesEnd + line.breakMarkerLeftPx + layout.starWidth) * PT_PER_PX)}pt"` : "";
303
349
  const marker = line.breakMarkerLeftPx !== void 0 ? `<span style="mso-tab-count:1">${" ".repeat(Math.max(1, Math.round((line.breakMarkerLeftPx + layout.starWidth) / spacePx)))}</span>*` : "";
304
- paragraphs.push(`<p class="${notaClass}"${markerStop}><span style="letter-spacing:-.1pt">${escapeHtml(notesText(layout, line))}</span>${marker}</p>`);
305
- paragraphs.push(`<p class="${textusClass}">` + walkTextLine(line, meter, {
350
+ paragraphs.push(`<p class="${notaClass}"${markerStop}><span style="letter-spacing:-.1pt">${escapeHtml(notesText(line))}</span>${marker}</p>`);
351
+ for (const text of line.texts) paragraphs.push(`<p class="${textusClass}">` + walkTextLine(text, meter, {
306
352
  spacer: spacerHtml,
307
353
  dash: () => "-",
308
354
  syl: (seg) => sylHtml(seg, layout.textPx)
@@ -401,45 +447,50 @@ async function layoutForWord(source, options = {}) {
401
447
  const notesPt = layout.notesPx * PT_PER_PX;
402
448
  const textPt = layout.textPx * PT_PER_PX;
403
449
  const finite = layout.maxWidthPx !== Infinity;
450
+ const textPieces = (line) => {
451
+ const text = [];
452
+ let emitted = 0;
453
+ const spacerTo = (targetPx) => {
454
+ const { count, emittedPx } = meter.advance(targetPx, emitted);
455
+ emitted = emittedPx;
456
+ if (count > 0) text.push({
457
+ type: "spacer",
458
+ count,
459
+ endPt: emitted * PT_PER_PX
460
+ });
461
+ };
462
+ for (const seg of line.segments) switch (seg.kind) {
463
+ case "gap":
464
+ spacerTo(seg.endPx);
465
+ break;
466
+ case "connector":
467
+ case "line-end-dash":
468
+ spacerTo(seg.dashStartPx);
469
+ text.push({ type: "dash" });
470
+ emitted += seg.dashWidth;
471
+ spacerTo(seg.kind === "connector" ? seg.nextAnchorPx : seg.trailEndPx);
472
+ break;
473
+ case "syl":
474
+ for (const part of seg.parts) for (const run of wordRuns(part, layout.textPx)) text.push({
475
+ type: "run",
476
+ run
477
+ });
478
+ emitted += seg.textWidth;
479
+ break;
480
+ case "word-space":
481
+ text.push({ type: "space" });
482
+ emitted += seg.width;
483
+ }
484
+ return text;
485
+ };
404
486
  return {
405
487
  lines: layout.lines.map((line) => {
406
- const text = [];
407
- let emitted = 0;
408
- const spacerTo = (targetPx) => {
409
- const { count, emittedPx } = meter.advance(targetPx, emitted);
410
- emitted = emittedPx;
411
- if (count > 0) text.push({
412
- type: "spacer",
413
- count,
414
- endPt: emitted * PT_PER_PX
415
- });
416
- };
417
- for (const seg of line.segments) switch (seg.kind) {
418
- case "gap":
419
- spacerTo(seg.endPx);
420
- break;
421
- case "connector":
422
- case "line-end-dash":
423
- spacerTo(seg.dashStartPx);
424
- text.push({ type: "dash" });
425
- emitted += seg.dashWidth;
426
- spacerTo(seg.kind === "connector" ? seg.nextAnchorPx : seg.trailEndPx);
427
- break;
428
- case "syl":
429
- for (const part of seg.parts) for (const run of wordRuns(part, layout.textPx)) text.push({
430
- type: "run",
431
- run
432
- });
433
- emitted += seg.textWidth;
434
- break;
435
- case "word-space":
436
- text.push({ type: "space" });
437
- emitted += seg.width;
438
- }
488
+ const texts = line.texts.map(textPieces);
439
489
  const out = {
440
- notes: notesText(layout, line),
490
+ notes: notesText(line),
441
491
  breakMarker: line.breakMarkerLeftPx !== void 0,
442
- text
492
+ text: texts[0],
493
+ texts
443
494
  };
444
495
  if (line.breakMarkerLeftPx !== void 0) out.breakMarkerTabStopPt = finite ? layout.starTarget * PT_PER_PX : (line.notesEnd + line.breakMarkerLeftPx + layout.starWidth) * PT_PER_PX;
445
496
  return out;
@@ -475,7 +526,7 @@ function wordLayoutText(layout) {
475
526
  case "space": return " ";
476
527
  }
477
528
  };
478
- return layout.lines.flatMap((line) => [line.notes + (line.breakMarker ? " *" : ""), line.text.map(pieceText).join("")]).join("\n");
529
+ return layout.lines.flatMap((line) => [line.notes + (line.breakMarker ? " *" : ""), ...line.texts.map((text) => text.map(pieceText).join(""))]).join("\n");
479
530
  }
480
531
  /**
481
532
  * Renders the score as the plain-text equivalent of the Word export: the
@@ -569,7 +620,8 @@ async function copyPlainText(text) {
569
620
  * - class check: every character classified into its expected role — the
570
621
  * Guido HU neume repertoire on notes lines, text characters and marker
571
622
  * glyphs on text lines — with unknown characters reported at position;
572
- * - construction check: alternating nota/textus paragraphs, a clef
623
+ * - construction check: alternating nota/textus paragraphs (one or more
624
+ * textus per nota, for stacked stanzas), a clef
573
625
  * starting each notes line, legal group syntax, spacer structure, and
574
626
  * the tab + `*` break marker on broken notes lines;
575
627
  * - gap census: which spacer mechanism the pasted text uses and the
@@ -643,6 +695,7 @@ function buildNotesRepertoire() {
643
695
  for (const c of SCORE_MARKERS) chars.add(c);
644
696
  for (const c of SPECIAL_NOTES) chars.add(c);
645
697
  for (const c of NOTE_MODIFIERS) chars.add(c);
698
+ for (const c of Object.keys(CLEF_GLYPHS)) chars.add(c);
646
699
  for (let i = 0; i < 10; i++) chars.add(String(i));
647
700
  for (let i = 0; i < 26; i++) {
648
701
  chars.add(String.fromCharCode(97 + i));
@@ -920,7 +973,7 @@ function checkWordHtml(html) {
920
973
  }
921
974
  const prev = paragraphs[i - 1];
922
975
  if (i === 0 && para.kind !== "nota") error("The first paragraph must be the notes line (the nota style)", i);
923
- if (prev && prev.kind === para.kind) error(`Paragraphs ${i} and ${i + 1} are both ${para.kind} — the notes and text lines must alternate`, i);
976
+ if (prev && prev.kind === "nota" && para.kind === "nota") error(`Paragraphs ${i} and ${i + 1} are both nota — the notes and text lines must alternate`, i);
924
977
  });
925
978
  paragraphs.forEach((para, i) => {
926
979
  if (para.kind !== "nota") return;
@@ -984,7 +1037,7 @@ function checkNotesParagraph(para, error, warn) {
984
1037
  warn("Empty notes line", para.index);
985
1038
  return;
986
1039
  }
987
- if (!/[A-Za-z<=]/.test(text[0])) error(`Notes line does not start with a clef (found ${JSON.stringify(text[0])})`, para.index, 0);
1040
+ if (!/[A-Za-z<=]/.test(text[0]) && !Object.hasOwn(CLEF_GLYPHS, text[0])) error(`Notes line does not start with a clef (found ${JSON.stringify(text[0])})`, para.index, 0);
988
1041
  const isNotesWhitespace = (ch) => ch === " " || ch === "\xA0" || ch === " ";
989
1042
  const MARKER_TAIL = /* @__PURE__ */ new Set([
990
1043
  ...SCORE_MARKERS,
@@ -1,4 +1,4 @@
1
- import { GuidoScript } from './guidoScript';
1
+ import { LayoutSource } from './chantLayout';
2
2
  import { WordExportOptions } from './wordExport';
3
3
  export interface CopyResult {
4
4
  /** The Word-flavoured HTML document (the text/html flavour) */
@@ -11,12 +11,12 @@ export interface CopyResult {
11
11
  * with text/plain as the fallback flavour. Returns what was prepared.
12
12
  * Throws when no clipboard path works.
13
13
  */
14
- export declare function copyWordHtml(source: GuidoScript | string, options?: WordExportOptions): Promise<CopyResult>;
14
+ export declare function copyWordHtml(source: LayoutSource, options?: WordExportOptions): Promise<CopyResult>;
15
15
  /**
16
16
  * The deliberate plain-text-only copy: the same layout and spacer counts
17
17
  * without the HTML envelope, for workflows that want the raw text.
18
18
  */
19
- export declare function copyWordPlainText(source: GuidoScript | string, options?: WordExportOptions): Promise<string>;
19
+ export declare function copyWordPlainText(source: LayoutSource, options?: WordExportOptions): Promise<string>;
20
20
  /**
21
21
  * Copies raw text with no export flavour — the same write path as the
22
22
  * Word copy's plain fallback, for copies of the script source itself.