guidex 0.3.0 → 0.3.2

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.
@@ -1,11 +1,7 @@
1
1
  import { GuidoScript } from './guidoScript';
2
+ import { SCORE_MARKERS } from './noteGroups';
2
3
  import { StyleSet, StyleSetName, SyllablePart } from './guidoStyles';
3
- /**
4
- * Score marker characters: they carry no pitch, and when they sit at the
5
- * start or end of a note group (with the adjacent dash) they act as
6
- * whitespace rather than note width.
7
- */
8
- export declare const SCORE_MARKERS = ",.:?'\"+!%/=()\u00D6\u00DC\u00D3;";
4
+ export { SCORE_MARKERS };
9
5
  /**
10
6
  * Special reciting notes: when such a note stands alone in a note group it
11
7
  * marks recited text. The glyph shows at a run's first syllable (the
@@ -117,9 +113,26 @@ export interface LineEndDashSegment {
117
113
  textEndPx: number;
118
114
  }
119
115
  export type LayoutSegment = GapSegment | ConnectorSegment | SylSegment | WordSpaceSegment | LineEndDashSegment;
116
+ /** One text line under a notes line: one underlay's (stanza's) ordered
117
+ * segments with their ideal absolute positions. */
118
+ export interface LayoutTextLine {
119
+ segments: LayoutSegment[];
120
+ /** Where the text line ends (the text cursor when the line closed) */
121
+ textCursor: number;
122
+ /** Whether the text line's last syllable ends its word; null when it
123
+ * carries no syllable at all */
124
+ lastWordEnd: boolean | null;
125
+ }
120
126
  /** One rendered line pair's layout: the notes-line model and the text
121
- * line's ordered segments with their ideal absolute positions. */
127
+ * line's ordered segments with their ideal absolute positions. Stacked
128
+ * stanzas (issue #84) put several text lines under the one notes line
129
+ * (`texts`, one per underlay in order); `segments`, `textCursor` and
130
+ * `lastWordEnd` are the first one's. */
122
131
  export interface LayoutLine {
132
+ /** The clef group the notes line opens with (clef, key and one dash;
133
+ * empty when the script has no clef): the clef and key in effect at
134
+ * the line's start */
135
+ clefPrefix: string;
123
136
  notesParts: string[];
124
137
  segments: LayoutSegment[];
125
138
  /** Where the text line ends (the text cursor when the line closed) */
@@ -129,12 +142,17 @@ export interface LayoutLine {
129
142
  /** Whether the line's last syllable ends its word; null when the
130
143
  * line carries no syllable at all */
131
144
  lastWordEnd: boolean | null;
145
+ /** Every text line under the notes, in underlay order (the first is
146
+ * `segments`/`textCursor`/`lastWordEnd`) */
147
+ texts: LayoutTextLine[];
132
148
  /** The break marker's relative left offset; only set on broken
133
149
  * (non-final) lines, after their staff fill dashes */
134
150
  breakMarkerLeftPx?: number;
135
151
  }
136
152
  export interface LayoutResult {
137
153
  lines: LayoutLine[];
154
+ /** The opening clef prefix (the first line's); later lines carry
155
+ * their own (`LayoutLine.clefPrefix`) after a clef or key change */
138
156
  clefPrefix: string;
139
157
  styleSet: StyleSet;
140
158
  styleName: StyleSetName;
@@ -148,6 +166,12 @@ export interface LayoutResult {
148
166
  starTarget: number;
149
167
  starWidth: number;
150
168
  }
169
+ /** The scripts a layout lays out: one script, or several underlays of
170
+ * one melody stacked under a shared staff (issue #84) — one text line per
171
+ * script, in order. Stacked scripts must have the same tokens with the
172
+ * same notes (`stackStanzas` builds them); only their syllable text, word
173
+ * ends, holds and empty slots may differ. */
174
+ export type LayoutSource = GuidoScript | string | readonly (GuidoScript | string)[];
151
175
  /**
152
176
  * Lays a GuidoScript score out: a notes line in the chant font, and a text
153
177
  * line where each syllable is centered below its notes. The dashes of the
@@ -156,6 +180,15 @@ export interface LayoutResult {
156
180
  * overlap the previous one, it starts right after it and the notes group is
157
181
  * padded with extra dashes until it covers the text.
158
182
  *
183
+ * Stacked stanzas (issue #84): given several underlays of one melody, every
184
+ * line pair gets one text line per underlay. Each text line keeps its own
185
+ * cursor and runs the placement rules on its own (tight pairs, connectors,
186
+ * hyphens, recitation flow); a group takes the most pad dashes any of them
187
+ * asks for, so the notes spacing serves every text line, and a line breaks
188
+ * wherever any of them has to. A group that every underlay holds joins its
189
+ * run with the held join; one that some underlay sings takes the normal
190
+ * junction.
191
+ *
159
192
  * This is the shared layout pass behind every emitter: the DOM renderer
160
193
  * turns the returned lines into (notes div, text paragraph) pairs, and the
161
194
  * Word export turns them into fake-spaced Word HTML. Both consume the same
@@ -166,4 +199,4 @@ export interface LayoutResult {
166
199
  * text/notes sizes. Throws when the style set is unknown or one of its
167
200
  * fonts cannot be loaded.
168
201
  */
169
- export declare function layoutScore(source: GuidoScript | string, options?: LayoutOptions): Promise<LayoutResult>;
202
+ export declare function layoutScore(source: LayoutSource, options?: LayoutOptions): Promise<LayoutResult>;
@@ -0,0 +1,71 @@
1
+ import { TranspositionTarget } from './exactTranspose';
2
+ import { TransposeOverflow } from './guidoScriptTransforms';
3
+ /** A part's transposition: a staff-degree count (`transposeBy`, the
4
+ * renderer's slider: noteheads move, clef and key stay) or an exact
5
+ * target (`transposeScript`: a spelled interval or a final, sounding
6
+ * pitch kept, re-notated). */
7
+ export type PartTranspose = number | TranspositionTarget;
8
+ /** A slice of a script: its text-bearing syllables `from` (inclusive,
9
+ * default 0) to `to` (exclusive, default: the end) — the indices of
10
+ * `scriptSyllables`, like `Array.slice`. A syllable comes with its held
11
+ * groups. Without `from` the slice starts at the script's first token,
12
+ * without `to` it runs to its last (empty slots and statements there
13
+ * included). `stripTrailingMarkers` removes the closing markers (a bar)
14
+ * from the slice's last note group, and drops marker-only held groups
15
+ * after it. The script's stanzas are sliced at the same slots. */
16
+ export interface ScriptSlicePart {
17
+ script: string;
18
+ from?: number;
19
+ to?: number;
20
+ transpose?: PartTranspose;
21
+ stripTrailingMarkers?: boolean;
22
+ }
23
+ /** A text-less run, e.g. a psalm-tone ending, written in the clef and
24
+ * key in effect where it joins. Its note groups (source notation,
25
+ * escapes included) are joined by `separator` (default `--`) into one
26
+ * `~(…)` empty slot; a whitespace separator writes one `~(…)` per
27
+ * entry instead. A target transposition here takes no `clef` or `key`. */
28
+ export interface NotesPart {
29
+ notes: string[];
30
+ transpose?: PartTranspose;
31
+ separator?: string;
32
+ }
33
+ /** A sign between parts:
34
+ *
35
+ * - `intonation`: the BNS `**` star as a syllable of its own, where the
36
+ * choir takes over from the cantor;
37
+ * - `bar` / `finalBar`: a divisio (`,` by default) / the divisio
38
+ * finalis (`.` by default), or `glyph` instead. A bar leads the notes
39
+ * part right after it (`~(,--4…)`), or else closes the note group
40
+ * before it (`3-,`). */
41
+ export interface MarkerPart {
42
+ marker: 'intonation' | 'bar' | 'finalBar';
43
+ glyph?: string;
44
+ }
45
+ export type ScriptPart = ScriptSlicePart | NotesPart | MarkerPart;
46
+ export interface ComposeOptions {
47
+ /** What happens to a part whose clef or key differs from the one in
48
+ * effect where it joins (the first part's, unless an earlier part
49
+ * changes it): `inline` (default) writes a `(@clef …)` or `(@key …)`
50
+ * statement before it, `renotate` re-notates it into the clef and
51
+ * key in effect with `transposeScript`, keeping its sounding pitch
52
+ * (and throws when that runs past the glyph range). */
53
+ clefs?: 'inline' | 'renotate';
54
+ /** Past the end of a pitch row in a staff-degree transposition:
55
+ * `error` (default) throws, `clamp` and `null` behave as in
56
+ * `transposeBy`. */
57
+ overflow?: TransposeOverflow;
58
+ }
59
+ /**
60
+ * Builds one script from parts of others (see `ScriptPart`): script
61
+ * slices, text-less note runs and signs, joined in order with a space
62
+ * (every part boundary is a word boundary). The result opens with the
63
+ * first part's clef; later clef or key differences are reconciled as
64
+ * `options.clefs` says. Stanza k of the result is stanza k of every
65
+ * part in turn: a part without one (every notes and marker part, and a
66
+ * script with fewer stanzas) gets `~` empty slots there; the stanzas
67
+ * are written as `(@stanza …)` statements at the end. Throws on a bad
68
+ * slice, a clef that cannot be reconciled, a transposition past the
69
+ * glyph range, or a bar with no note group to attach to.
70
+ */
71
+ export declare function composeScript(parts: ScriptPart[], options?: ComposeOptions): string;
@@ -168,6 +168,12 @@ export type SaveChantsResult = {
168
168
  quota: boolean;
169
169
  };
170
170
  export declare function newChantId(): string;
171
+ /** Per-field sanitization of a prefs snapshot — stored chant blobs and
172
+ * the shared-link URL fragment (src/app/shareLink.ts) both run their
173
+ * raw, untrusted values through this: anything missing, wrong-typed, or
174
+ * out of range falls back to the corresponding default editor setting;
175
+ * the rest passes through clamped. */
176
+ export declare function sanitizeChantPrefs(raw: unknown): ChantPrefs;
171
177
  /** The stored library, sanitized — an empty array when absent, corrupt,
172
178
  * or written by an unknown schema version. Never throws. */
173
179
  export declare function loadChants(): SavedChant[];
@@ -1,3 +1,4 @@
1
+ import { EmptySlots, StanzaStack, StanzaWarning } from '../stanzas';
1
2
  import { StyleSetName } from '../guidoStyles';
2
3
  export declare const version: string;
3
4
  /** Line-breaking budget: a fixed pixel width, or 'auto' to fit the
@@ -12,8 +13,31 @@ export interface EmbedOptions {
12
13
  bold?: boolean;
13
14
  textPx?: number;
14
15
  transpose?: number;
16
+ /** The stanza sung under the notes (1-based; 1 is the script's own
17
+ * text, 2… its `(@stanza …)` statements or the `stanzas` option). */
18
+ stanza?: number;
19
+ /** Stacked stanzas under one staff (issue #84): `'all'`, or the
20
+ * stanza numbers in order. Replaces `stanza` when set. */
21
+ stack?: StanzaStack;
22
+ /** `'small'` draws the slots the rendered stanza leaves empty while
23
+ * another stanza sings them with small heads (issue #69); stacked,
24
+ * the slots no stacked stanza sings while another stanza does.
25
+ * `'partial'` draws every slot some stanza sings and another does not
26
+ * with small heads, whatever is rendered. */
27
+ emptySlots?: EmptySlots;
15
28
  debug?: boolean;
16
29
  }
30
+ /** Per-element options of `renderScore`: the site-wide ones, plus the
31
+ * stanza texts that replace the script's `(@stanza …)` statements. */
32
+ export interface RenderScoreOptions extends Omit<EmbedOptions, 'selector'> {
33
+ stanzas?: string[];
34
+ }
35
+ /** What a finished render reports: the rendered stanzas' count
36
+ * mismatches (missing syllables show as placeholders, extra ones are
37
+ * dropped). */
38
+ export interface RenderResult {
39
+ warnings: StanzaWarning[];
40
+ }
17
41
  /** Cleans up a programmatically rendered element: stops resize
18
42
  * re-rendering and drops the cached source and option overrides. Does
19
43
  * not remove the rendered score itself. */
@@ -23,8 +47,10 @@ export declare function dispose(el: HTMLElement): void;
23
47
  * element's own text content is replaced by the rendered score and
24
48
  * re-rendered on resize. Call again with a new source to update.
25
49
  * Options set here override `init` defaults; data attributes on the
26
- * element still win. Resolves when the score has finished rendering. */
27
- export declare function renderScore(el: HTMLElement, source: string, options?: Omit<EmbedOptions, 'selector'>): Promise<void>;
50
+ * element still win. `stanzas` replaces the script's `(@stanza …)`
51
+ * statements. Resolves when the score has finished rendering, with the
52
+ * rendered stanza's count mismatches. */
53
+ export declare function renderScore(el: HTMLElement, source: string, options?: RenderScoreOptions): Promise<RenderResult>;
28
54
  /** Renders every target under `root` (default: the whole document).
29
55
  * Already-rendered targets re-render from their cached source, so a
30
56
  * host can change data attributes or the source text and call this to
@@ -1,4 +1,4 @@
1
- import { a as dispose, c as renderScore, i as scoreSvg, l as version, n as downloadScoreSvg, o as init, r as scorePngBlob, s as renderAll, t as downloadScorePng } from "../scoreImage-DnFIbtF_.js";
1
+ import { a as dispose, c as renderScore, i as scoreSvg, l as version, n as downloadScoreSvg, o as init, r as scorePngBlob, s as renderAll, t as downloadScorePng } from "../scoreImage-DSEupCru.js";
2
2
  //#region src/embed/index.ts
3
3
  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", () => init(), { once: true });
4
4
  else init();
@@ -3,7 +3,14 @@
3
3
  * runtime's imperative API without any auto-rendering. Nothing happens
4
4
  * until you call `renderScore`, `renderAll`, or `init`. Also re-exports
5
5
  * the script parser and text extraction (`GuidoScript`, `chantText`,
6
- * `unescape`), the marked-up text export (`chantRuns`, `chantHtml`,
6
+ * `unescape`, the syllable walker `scriptSyllables`), the script helpers
7
+ * (`PITCH_ROWS`, `transposeNotes`, `SCORE_MARKERS`, `splitNoteMarkers`)
8
+ * and `composeScript`, which builds one script from parts of others, the
9
+ * transpositions (`transposeBy`, the exact
10
+ * `transposeScript`/`transposeExact` with `parseInterval` and
11
+ * `KEY_SIGNATURES`), the stanzas (`withStanza`, `selectStanza`,
12
+ * `parseStanza`, `stanzaWarnings`, `padStanza`, `stanzaCount`,
13
+ * `slotCount`, and the stacked `stackStanzas`), the marked-up text export (`chantRuns`, `chantHtml`,
7
14
  * plus the raw run resolver `resolveSyllableParts`), the style-set
8
15
  * registry (`STYLE_SETS`, `DEFAULT_STYLE_SET`), the
9
16
  * Word-compatible export (`toWordHtml`, `toWordText`, `layoutForWord`,
@@ -12,13 +19,16 @@
12
19
  * (`scoreSvg`, `scorePngBlob`, `downloadScorePng`, `downloadScoreSvg`).
13
20
  */
14
21
  export * from './core';
15
- export { GuidoScript, unescape, chantText } from '../guidoScript';
22
+ export { GuidoScript, unescape, chantText, scriptSyllables, type ScriptSyllable, } from '../guidoScript';
23
+ export { SCORE_MARKERS, splitNoteMarkers, type NoteGroupParts } from '../noteGroups';
24
+ export { composeScript, type ComposeOptions, type MarkerPart, type NotesPart, type PartTranspose, type ScriptPart, type ScriptSlicePart, } from '../composeScript';
16
25
  export { chantRuns, chantHtml } from '../chantMarkup';
17
26
  export { STYLE_SETS, DEFAULT_STYLE_SET, resolveSyllableParts } from '../guidoStyles';
18
- export type { ScriptTransform } from '../guidoScriptTransforms';
27
+ export { KEY_SIGNATURES, PITCH_ROWS, STANZA_PLACEHOLDER, padStanza, parseInterval, parseStanza, selectStanza, slotCount, smallHeads, stackStanzas, stackedStanzaNumbers, stanzaCount, stanzaTexts, stanzaWarnings, transposeBy, transposeExact, transposeNotes, transposeScript, TranspositionRangeError, withStanza, type EmptySlots, type SelectStanzaOptions, type ScriptTransform, type StanzaOptions, type StanzaStack, type StanzaSyllable, type StanzaWarning, type SpelledInterval, type TransposeOverflow, type TranspositionTarget, } from '../guidoScriptTransforms';
19
28
  export type { StyleSetName, SyllablePart, PartStyle, ChantRunKind } from '../guidoStyles';
20
29
  export type { ChantRun, ChantSyllable, ChantWord, ChantMarkupOptions } from '../chantMarkup';
21
30
  export { DEFAULT_SPACER, DEFAULT_TAB_INTERVAL_PT, SpacerMeter, layoutForWord, toWordHtml, toWordText, wordLayoutText, type SpacerChar, type SpacerConfig, type SpacerWidth, type WordExportOptions, type WordLayout, type WordLine, type WordRun, type WordStyleNames, type WordTextPiece, } from '../wordExport';
31
+ export { baseOf, gClefPitchOf, modifyDown, modifyNatural, modifyUp, toCephalicus, toConnectDown, toLonga, toSmallHead, toSmallPoint, toVirga, variantOf, type VariantRole, } from '../glyphFamilies';
22
32
  export { copyWordHtml, copyWordPlainText, type CopyResult } from '../wordClipboard';
23
33
  export { checkWordHtml, type WordCheckIssue, type WordCheckReport, type WordGapClass, type WordGapMechanism, type WordGapStat, type WordParagraphDiag, } from '../wordChecker';
24
34
  export { downloadScorePng, downloadScoreSvg, scorePngBlob, scoreSvg, type ScoreDownloadOptions, type ScoreImageOptions, } from '../scoreImage';
@@ -1,6 +1,326 @@
1
- import { a as dispose, c as renderScore, i as scoreSvg, l as version, n as downloadScoreSvg, o as init, r as scorePngBlob, s as renderAll, t as downloadScorePng } from "../scoreImage-DnFIbtF_.js";
2
- import { f as GuidoScript, m as unescape, o as DEFAULT_STYLE_SET, p as chantText, s as STYLE_SETS, u as resolveSyllableParts } from "../chantLayout-GAfg2iKS.js";
3
- 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 dispose, c as renderScore, i as scoreSvg, l as version, n as downloadScoreSvg, o as init, r as scorePngBlob, s as renderAll, t as downloadScorePng } from "../scoreImage-DSEupCru.js";
2
+ import { $ as variantOf, A as stanzaWarnings, C as selectStanza, D as stackedStanzaNumbers, E as stackStanzas, F as chantText, G as modifyNatural, H as gClefPitchOf, I as escape, J as toConnectDown, K as modifyUp, L as scriptSyllables, M as SCORE_MARKERS, N as splitNoteMarkers, O as stanzaCount, P as GuidoScript, Q as toVirga, R as statementSource, S as parseStanza, T as smallHeads, U as isClefGlyph, V as baseOf, W as modifyDown, X as toSmallHead, Y as toLonga, Z as toSmallPoint, _ as transposeExact, a as DEFAULT_STYLE_SET, b as isSlot, d as transposeBy, f as transposeNotes, g as sameKeyGlyphs, h as parseInterval, j as withStanza, k as stanzaTexts, l as resolveSyllableParts, m as TranspositionRangeError, o as STYLE_SETS, p as KEY_SIGNATURES, q as toCephalicus, u as PITCH_ROWS, v as transposeScript, w as slotCount, x as padStanza, y as STANZA_PLACEHOLDER, z as unescape } from "../chantLayout-B0xiaMo9.js";
3
+ 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-EQx8frRp.js";
4
+ //#region src/composeScript.ts
5
+ /**
6
+ * Combining scripts (issue #71): one GuidoScript built from parts of
7
+ * others — an antiphon intonation (the antiphon through a syllable, then
8
+ * a psalm-tone ending as a text-less run), a reprise (the antiphon with
9
+ * the BNS `**` after its intonation), a hymn with an Amen.
10
+ *
11
+ * Every part boundary is a word boundary: the parts are joined with a
12
+ * space. The result keeps the first part's clef; a later part written in
13
+ * another clef or key is reconciled the way the caller chooses (an
14
+ * inline `(@clef …)` / `(@key …)` statement, or a re-notation into the
15
+ * clef and key in effect), so the result is correct or an error, never
16
+ * a quietly wrong score. Stanzas (issue #69) join one by one across the
17
+ * parts and are written back as `(@stanza …)` statements at the end.
18
+ */
19
+ var DEFAULT_GLYPHS = {
20
+ bar: ",",
21
+ finalBar: "."
22
+ };
23
+ /** The opening clef group's content as a clef state; throws when it
24
+ * does not start with a clef glyph. */
25
+ function readClef(content) {
26
+ if (content === void 0 || content.trim() === "") return void 0;
27
+ const group = content.trim();
28
+ if (!isClefGlyph(group[0])) throw new Error(`The opening group "(${content})" does not start with a clef glyph`);
29
+ return {
30
+ clef: group[0],
31
+ key: group.slice(1)
32
+ };
33
+ }
34
+ function clefGroup(state) {
35
+ return state ? `(${state.clef}${state.key})` : "";
36
+ }
37
+ /** The clef in effect after `tokens`, starting from `state`. */
38
+ function stateAfter(tokens, state) {
39
+ for (const tok of tokens) if (tok.kind === "clef") state = {
40
+ clef: tok.clef,
41
+ key: tok.key
42
+ };
43
+ else if (tok.kind === "key") state = {
44
+ clef: state?.clef ?? "M",
45
+ key: tok.key
46
+ };
47
+ return state;
48
+ }
49
+ /** Tokens written back as script source (the `GuidoScript.toString`
50
+ * rules: an empty slot always writes its `~`). */
51
+ function writeTokens(tokens) {
52
+ return tokens.map((tok, i) => {
53
+ const prefix = i > 0 && tok.spaceBefore ? " " : "";
54
+ if (tok.kind !== "syllable") return prefix + statementSource(tok);
55
+ return `${prefix}${tok.empty ? "~" : tok.text === "~" ? "\\~" : escape(tok.text)}(${escape(tok.notes)})`;
56
+ }).join("");
57
+ }
58
+ /** A stanza item written back as stanza text (see `parseStanza`). */
59
+ function stanzaItemSource(item) {
60
+ if (item.kind === "hold") return "-";
61
+ if (item.kind === "empty") return "~";
62
+ const text = Array.from(item.text, (ch) => /\s/.test(ch) ? "~" : "\\-=­~()".includes(ch) ? `\\${ch}` : ch).join("");
63
+ return item.wordEnd ? text : `${text}-`;
64
+ }
65
+ /** Applies a staff-degree or exact transposition to a whole script. */
66
+ function transposed(source, transpose, overflow) {
67
+ if (transpose === void 0) return source;
68
+ if (typeof transpose === "number") {
69
+ if (!Number.isInteger(transpose)) throw new Error(`A staff-degree transposition is a whole number, not ${transpose}`);
70
+ return transposeBy(transpose, { overflow }).apply(source);
71
+ }
72
+ return transposeScript(source, transpose);
73
+ }
74
+ /** The token index just past syllable `token`'s held run. */
75
+ function afterHeldRun(tokens, token) {
76
+ let last = token;
77
+ for (let i = token + 1; i < tokens.length; i++) {
78
+ const tok = tokens[i];
79
+ if (tok.kind !== "syllable") continue;
80
+ if (!tok.held) break;
81
+ last = i;
82
+ }
83
+ return last + 1;
84
+ }
85
+ /** Strips the closing markers of the last note group (marker-only held
86
+ * groups after it go). */
87
+ function stripTrailing(tokens) {
88
+ for (let i = tokens.length - 1; i >= 0; i--) {
89
+ const tok = tokens[i];
90
+ if (tok.kind !== "syllable" || tok.notes === "") continue;
91
+ const parts = splitNoteMarkers(tok.notes);
92
+ if (parts.core === "") {
93
+ if (tok.held) tokens.splice(i, 1);
94
+ continue;
95
+ }
96
+ tokens[i] = {
97
+ ...tok,
98
+ notes: parts.leading + parts.core
99
+ };
100
+ return;
101
+ }
102
+ }
103
+ /** A script part as a chunk; `state` is the clef in effect where it
104
+ * joins (undefined for the first part). */
105
+ function scriptChunk(part, state, first, options) {
106
+ const script = new GuidoScript(part.script);
107
+ const tokens = script.tokens;
108
+ const syllables = scriptSyllables(script);
109
+ const from = part.from ?? 0;
110
+ const to = part.to ?? syllables.length;
111
+ for (const [name, value] of [["from", part.from], ["to", part.to]]) if (value !== void 0 && (!Number.isInteger(value) || value < 0 || value > syllables.length)) throw new RangeError(`"${name}" ${value} is outside the script's ${syllables.length} text-bearing syllables`);
112
+ if (from >= to) throw new RangeError(`The slice from ${from} to ${to} is empty`);
113
+ const start = part.from === void 0 ? 0 : syllables[from].token;
114
+ const end = part.to === void 0 ? tokens.length : afterHeldRun(tokens, syllables[to - 1].token);
115
+ const opening = stateAfter(tokens.slice(0, start), readClef(script.clef)) ?? state;
116
+ const slice = tokens.slice(start, end);
117
+ if (part.stripTrailingMarkers) stripTrailing(slice);
118
+ const slotIndices = tokens.flatMap((tok, i) => isSlot(tok) ? [i] : []);
119
+ const before = slotIndices.filter((i) => i < start).length;
120
+ const inside = slotIndices.filter((i) => i >= start && i < end).length;
121
+ const stanzas = script.stanzas.map((text) => {
122
+ const items = parseStanza(text);
123
+ return Array.from({ length: inside }, (_, i) => items[before + i] ?? {
124
+ kind: "syllable",
125
+ text: "_…_",
126
+ wordEnd: true
127
+ });
128
+ });
129
+ let source = transposed(clefGroup(opening) + writeTokens(slice), part.transpose, options.overflow);
130
+ let own = readClef(new GuidoScript(source).clef);
131
+ let lead;
132
+ if (!first && own) {
133
+ const current = state ?? {
134
+ clef: "M",
135
+ key: ""
136
+ };
137
+ if (own.clef !== current.clef || !sameKeyGlyphs(own.key, current.key, current.clef)) {
138
+ if (options.clefs === "renotate") {
139
+ source = transposeScript(source, {
140
+ clef: current.clef,
141
+ key: current.key
142
+ });
143
+ own = readClef(new GuidoScript(source).clef);
144
+ } else lead = own.clef !== current.clef ? {
145
+ kind: "clef",
146
+ clef: own.clef,
147
+ key: own.key,
148
+ spaceBefore: false
149
+ } : {
150
+ kind: "key",
151
+ key: own.key,
152
+ spaceBefore: false
153
+ };
154
+ }
155
+ }
156
+ const body = new GuidoScript(source).tokens;
157
+ const slots = body.filter(isSlot).length;
158
+ if (slots !== inside) throw new Error(`Internal error: the slice has ${slots} slots, its stanzas ${inside}`);
159
+ return {
160
+ chunk: {
161
+ tokens: lead ? [lead, ...body] : body,
162
+ stanzas,
163
+ slots
164
+ },
165
+ opening: own,
166
+ end: stateAfter(body, own ?? state)
167
+ };
168
+ }
169
+ /** A notes part as a chunk of `~(…)` empty slots. */
170
+ function notesChunk(part, state, options) {
171
+ if (part.notes.length === 0) throw new Error("A notes part needs at least one note group");
172
+ const separator = part.separator ?? "--";
173
+ const groups = /^\s+$/.test(separator) ? part.notes : [part.notes.join(separator)];
174
+ let source = groups.map((notes) => `~(${notes})`).join(" ");
175
+ const { transpose } = part;
176
+ if (typeof transpose === "number") {
177
+ if (!Number.isInteger(transpose)) throw new Error(`A staff-degree transposition is a whole number, not ${transpose}`);
178
+ source = groups.map((notes) => `~(${transposeNotes(notes, transpose, { overflow: options.overflow })})`).join(" ");
179
+ } else if (transpose !== void 0) {
180
+ if (transpose.clef !== void 0 || transpose.key !== void 0) throw new Error("A notes part is written in the clef in effect: its transposition takes no clef or key");
181
+ const current = state ?? {
182
+ clef: "M",
183
+ key: ""
184
+ };
185
+ const moved = transposeScript(`${clefGroup(current)}${source}`, {
186
+ ...transpose,
187
+ clef: current.clef,
188
+ key: current.key
189
+ });
190
+ source = moved.slice(moved.indexOf(")") + 1);
191
+ }
192
+ const tokens = new GuidoScript(`(M)${source}`).tokens;
193
+ return {
194
+ tokens,
195
+ stanzas: [],
196
+ slots: tokens.filter(isSlot).length
197
+ };
198
+ }
199
+ /** Writes `glyph` as the leading marker of a note group. */
200
+ function leadWith(notes, glyph) {
201
+ return splitNoteMarkers(notes).leading === "" ? `${glyph}--${notes}` : glyph + notes;
202
+ }
203
+ /** Writes `glyph` as the closing marker of a note group. */
204
+ function closeWith(notes, glyph) {
205
+ return splitNoteMarkers(notes).trailing === "" ? `${notes}-${glyph}` : notes + glyph;
206
+ }
207
+ /**
208
+ * Builds one script from parts of others (see `ScriptPart`): script
209
+ * slices, text-less note runs and signs, joined in order with a space
210
+ * (every part boundary is a word boundary). The result opens with the
211
+ * first part's clef; later clef or key differences are reconciled as
212
+ * `options.clefs` says. Stanza k of the result is stanza k of every
213
+ * part in turn: a part without one (every notes and marker part, and a
214
+ * script with fewer stanzas) gets `~` empty slots there; the stanzas
215
+ * are written as `(@stanza …)` statements at the end. Throws on a bad
216
+ * slice, a clef that cannot be reconciled, a transposition past the
217
+ * glyph range, or a bar with no note group to attach to.
218
+ */
219
+ function composeScript(parts, options = {}) {
220
+ const opts = {
221
+ clefs: options.clefs ?? "inline",
222
+ overflow: options.overflow ?? "error"
223
+ };
224
+ if (opts.clefs !== "inline" && opts.clefs !== "renotate") throw new Error(`Unknown clef handling "${String(opts.clefs)}"`);
225
+ const out = [];
226
+ const chunks = [];
227
+ let state;
228
+ let opening;
229
+ let started = false;
230
+ let pendingBar;
231
+ const append = (chunk) => {
232
+ chunk.tokens.forEach((tok, i) => {
233
+ out.push(i === 0 ? {
234
+ ...tok,
235
+ spaceBefore: out.length > 0
236
+ } : tok);
237
+ });
238
+ chunks.push(chunk);
239
+ };
240
+ for (const [p, part] of parts.entries()) {
241
+ if ("marker" in part) {
242
+ if (part.marker === "intonation") {
243
+ if (pendingBar !== void 0) throw new Error("A bar must stand next to a note group");
244
+ append({
245
+ tokens: [{
246
+ kind: "syllable",
247
+ text: "**",
248
+ notes: "",
249
+ wordEnd: true,
250
+ spaceBefore: false
251
+ }],
252
+ stanzas: [],
253
+ slots: 0
254
+ });
255
+ continue;
256
+ }
257
+ if (part.marker !== "bar" && part.marker !== "finalBar") throw new Error(`Unknown marker "${String(part.marker)}"`);
258
+ const glyph = part.glyph ?? DEFAULT_GLYPHS[part.marker];
259
+ const next = parts[p + 1];
260
+ if (next !== void 0 && "notes" in next) {
261
+ if (pendingBar !== void 0) throw new Error("Two bars in a row");
262
+ pendingBar = glyph;
263
+ continue;
264
+ }
265
+ let i = out.length - 1;
266
+ while (i >= 0 && out[i].kind !== "syllable") i--;
267
+ const last = out[i];
268
+ if (last?.kind !== "syllable" || splitNoteMarkers(last.notes).core === "") throw new Error(`The ${part.marker === "bar" ? "bar" : "final bar"} has no note group to close`);
269
+ out[i] = {
270
+ ...last,
271
+ notes: closeWith(last.notes, glyph)
272
+ };
273
+ continue;
274
+ }
275
+ if ("notes" in part) {
276
+ const chunk = notesChunk(part, state, opts);
277
+ if (pendingBar !== void 0) {
278
+ const head = chunk.tokens[0];
279
+ chunk.tokens[0] = {
280
+ ...head,
281
+ notes: leadWith(head.notes, pendingBar)
282
+ };
283
+ pendingBar = void 0;
284
+ }
285
+ append(chunk);
286
+ started = true;
287
+ continue;
288
+ }
289
+ if (!("script" in part)) throw new Error("A part is a script slice, a notes run or a marker");
290
+ const result = scriptChunk(part, state, !started, opts);
291
+ if (!started) opening = result.opening;
292
+ started = true;
293
+ state = result.end;
294
+ append(result.chunk);
295
+ }
296
+ const count = Math.max(1, ...chunks.map((c) => c.stanzas.length + 1));
297
+ const stanzas = [];
298
+ for (let k = 2; k <= count; k++) {
299
+ const items = chunks.flatMap((chunk) => {
300
+ if (chunk.slots === 0) return [];
301
+ const items = [...chunk.stanzas[k - 2] ?? Array.from({ length: chunk.slots }, () => ({ kind: "empty" }))];
302
+ if (items[0].kind === "hold") items[0] = { kind: "empty" };
303
+ for (let i = items.length - 1; i >= 0; i--) {
304
+ const item = items[i];
305
+ if (item.kind !== "syllable") continue;
306
+ items[i] = {
307
+ ...item,
308
+ wordEnd: true
309
+ };
310
+ break;
311
+ }
312
+ return items;
313
+ });
314
+ const text = items.map((item, i) => {
315
+ const prev = items[i - 1];
316
+ const joined = prev?.kind === "syllable" && !prev.wordEnd && item.kind === "syllable";
317
+ return (i === 0 || joined ? "" : " ") + stanzaItemSource(item);
318
+ }).join("");
319
+ stanzas.push(`(@stanza${text === "" ? "" : ` ${text}`})`);
320
+ }
321
+ return clefGroup(opening) + writeTokens(out) + stanzas.join("");
322
+ }
323
+ //#endregion
4
324
  //#region src/chantMarkup.ts
5
325
  /**
6
326
  * The marked-up sung text of a chant script, for other applications: the
@@ -40,4 +360,4 @@ var runHtml = (run) => {
40
360
  };
41
361
  var escapeHtml = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
42
362
  //#endregion
43
- export { DEFAULT_SPACER, DEFAULT_STYLE_SET, DEFAULT_TAB_INTERVAL_PT, GuidoScript, STYLE_SETS, SpacerMeter, chantHtml, chantRuns, chantText, checkWordHtml, copyWordHtml, copyWordPlainText, dispose, downloadScorePng, downloadScoreSvg, init, layoutForWord, renderAll, renderScore, resolveSyllableParts, scorePngBlob, scoreSvg, toWordHtml, toWordText, unescape, version, wordLayoutText };
363
+ export { DEFAULT_SPACER, DEFAULT_STYLE_SET, DEFAULT_TAB_INTERVAL_PT, GuidoScript, KEY_SIGNATURES, PITCH_ROWS, SCORE_MARKERS, STANZA_PLACEHOLDER, STYLE_SETS, SpacerMeter, TranspositionRangeError, baseOf, chantHtml, chantRuns, chantText, checkWordHtml, composeScript, copyWordHtml, copyWordPlainText, dispose, downloadScorePng, downloadScoreSvg, gClefPitchOf, init, layoutForWord, modifyDown, modifyNatural, modifyUp, padStanza, parseInterval, parseStanza, renderAll, renderScore, resolveSyllableParts, scorePngBlob, scoreSvg, scriptSyllables, selectStanza, slotCount, smallHeads, splitNoteMarkers, stackStanzas, stackedStanzaNumbers, stanzaCount, stanzaTexts, stanzaWarnings, toCephalicus, toConnectDown, toLonga, toSmallHead, toSmallPoint, toVirga, toWordHtml, toWordText, transposeBy, transposeExact, transposeNotes, transposeScript, unescape, variantOf, version, withStanza, wordLayoutText };
@@ -0,0 +1,54 @@
1
+ import { ScriptTransform } from './guidoScriptTransforms';
2
+ /** A spelled interval: letter steps (a third is 2) and semitones (a
3
+ * major third is 4). Negative values move down. */
4
+ export interface SpelledInterval {
5
+ steps: number;
6
+ semitones: number;
7
+ }
8
+ /** The target of an exact transposition. `interval` (a spelled interval
9
+ * or a name like `'P4'`, `'-P5'`, `'m3'`) or `final` (the pitch letter
10
+ * the script's last note should land on, e.g. `'g'`, `'bb'`, `'f#'`)
11
+ * gives the move; neither means unison. `clef` (a clef glyph)
12
+ * re-notates the whole script in that clef; `key` replaces the opening
13
+ * key — a signed count (−2 = two flats, 3 = three sharps) or modifier
14
+ * glyphs read under the target clef. */
15
+ export interface TranspositionTarget {
16
+ interval?: SpelledInterval | string;
17
+ final?: string;
18
+ clef?: string;
19
+ key?: number | string;
20
+ }
21
+ /** A transposed note past the end of the glyph range. Thrown as its own
22
+ * class so the octave search for a `final` can tell it apart. */
23
+ export declare class TranspositionRangeError extends Error {
24
+ constructor(message: string);
25
+ }
26
+ /** The key-signature glyphs per clef glyph (issue #70): flats in the
27
+ * order b e a d g c f, sharps in the order f c g d a e b, each at the
28
+ * highest octave of the shape that stays on the staff. A key of n signs
29
+ * is the first n glyphs of its row. */
30
+ export declare const KEY_SIGNATURES: Readonly<Record<string, {
31
+ flats: string;
32
+ sharps: string;
33
+ }>>;
34
+ /** Whether two keys written as modifier glyphs under `clef` alter the
35
+ * same pitch letters the same way (glyph order and octave aside). */
36
+ export declare function sameKeyGlyphs(a: string, b: string, clef: string): boolean;
37
+ /** Parses an interval name: an optional sign, a quality (`P`, `M`, `m`,
38
+ * `A`, `d`) and a number (`P1`, `-P5`, `M3`, `A4`, `P8`, `M9`). */
39
+ export declare function parseInterval(name: string): SpelledInterval;
40
+ /**
41
+ * Transposes a script exactly: moves its sounding pitches and
42
+ * re-notates them under the target clef and key (see
43
+ * `TranspositionTarget`). Without a key, the key moves with the
44
+ * interval; without a clef, the clefs stay as written (mid-script
45
+ * `(@clef …)` included); `(@key …)` statements always move with the
46
+ * interval. A target clef re-notates the whole script in that clef and
47
+ * removes mid-script `(@clef …)` statements (one that changed the key
48
+ * leaves a `(@key …)` behind). With a `final`, the octave whose result
49
+ * fits the glyph range wins — the smaller move when several fit.
50
+ * Throws past the glyph range and on a missing glyph variant.
51
+ */
52
+ export declare function transposeScript(source: string, target: TranspositionTarget): string;
53
+ /** The exact transposition as a script transform (see `transposeScript`). */
54
+ export declare function transposeExact(target: TranspositionTarget): ScriptTransform;