barmark 0.16.0 → 0.17.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.
@@ -0,0 +1,178 @@
1
+ import { isBar } from "./barLine.js";
2
+ import { readSyllable } from "./syllable.js";
3
+ /** `lyrics:` or `lyrics N:`, then a bar line (grammar 7.7). */
4
+ export const LYRIC_ROW = /^lyrics(?:\s+(\d+))?:\s*(\|.*)$/i;
5
+ /** One token of a lyric row: `/` a hold, `--` a breath, else a syllable (4.3); null when none reads. */
6
+ function readToken(token) {
7
+ if (token === "/")
8
+ return { kind: "hold" };
9
+ if (token === "--")
10
+ return { kind: "breath" };
11
+ if (/["{}]/.test(token))
12
+ return null;
13
+ const syllable = readSyllable(token);
14
+ return syllable?.kind === "sung" ? { kind: "syllable", syllable } : null;
15
+ }
16
+ /** A slot: a token, or tokens joined by `_` into a group. */
17
+ function readSlot(token) {
18
+ const members = token.split("_").map(readToken);
19
+ if (members.some((m) => m === null))
20
+ return null;
21
+ const read = members;
22
+ return read.length === 1 ? (read[0] ?? null) : { kind: "group", members: read };
23
+ }
24
+ const problemOf = (token) => /["{}]/.test(token)
25
+ ? "a lyric row holds syllables only: no quotes or braces"
26
+ : `not a syllable: ${token}`;
27
+ /** A row's cells, each a list of slots, with a diagnostic for each that doesn't read. */
28
+ function readCells(bar, line) {
29
+ const diagnostics = [];
30
+ const parts = bar.split("|").slice(1);
31
+ if (parts.at(-1)?.trim() === "")
32
+ parts.pop();
33
+ else
34
+ diagnostics.push({
35
+ line,
36
+ severity: "warning",
37
+ message: "missing trailing |",
38
+ token: parts.at(-1)?.trim() ?? "",
39
+ });
40
+ const cells = parts.map((part) => {
41
+ const tokens = part.trim().split(/\s+/).filter(Boolean);
42
+ if (!tokens.length)
43
+ diagnostics.push({
44
+ line,
45
+ severity: "error",
46
+ message: "empty bar in a lyric row; a bar with nothing sung is --",
47
+ token: "| |",
48
+ });
49
+ return tokens.flatMap((token) => {
50
+ const slot = readSlot(token);
51
+ if (!slot)
52
+ diagnostics.push({ line, severity: "error", message: problemOf(token), token });
53
+ return slot ? [slot] : [];
54
+ });
55
+ });
56
+ return { cells, diagnostics };
57
+ }
58
+ /** Why a verse number can't be read, or null: from 1 up to the largest safe integer, so it prints back as written. */
59
+ const verseProblem = (verse) => {
60
+ if (verse === 0)
61
+ return "a verse is numbered from 1";
62
+ return verse > Number.MAX_SAFE_INTEGER
63
+ ? `a verse number goes up to ${Number.MAX_SAFE_INTEGER}`
64
+ : null;
65
+ };
66
+ /**
67
+ * A lyric row (grammar 7.7), not yet attached to the bars it covers. Null
68
+ * when the line isn't one, or when it has an error.
69
+ */
70
+ export function readLyricRow(text, line) {
71
+ const m = LYRIC_ROW.exec(text);
72
+ if (!m)
73
+ return { row: null, diagnostics: [] };
74
+ const verse = m[1] === undefined ? null : Number(m[1]);
75
+ const problem = verse === null ? null : verseProblem(verse);
76
+ if (problem)
77
+ return { row: null, diagnostics: [{ line, severity: "error", message: problem, token: text }] };
78
+ const { cells, diagnostics } = readCells(m[2] ?? "", line);
79
+ const failed = diagnostics.some((d) => d.severity === "error");
80
+ return { row: failed ? null : { kind: "lyrics", line, verse, cells, covers: [] }, diagnostics };
81
+ }
82
+ /** A lyric row, or a line kept as text because its row has an error: either holds its place. */
83
+ const isRow = (l) => l.kind === "lyrics" || (l.kind === "text" && !l.escaped && LYRIC_ROW.test(l.text));
84
+ const isCovered = (l) => l.kind === "bars" || l.kind === "invalid";
85
+ const normalize = (name) => name.toLowerCase().replace(/\s+/g, " ").trim();
86
+ const plural = (n, what) => `${n} ${what}${n === 1 ? "" : "s"}`;
87
+ /** Why a row can't lie under a unit, or null: its bar count must be the unit's. */
88
+ function countProblem(row, unit) {
89
+ const ref = unit.find((l) => l.kind === "bars" && !l.dropped);
90
+ if (ref?.kind !== "bars")
91
+ return null;
92
+ const n = ref.cells.filter(isBar).length;
93
+ if (row.cells.length === n)
94
+ return null;
95
+ return `this lyric row has ${plural(row.cells.length, "bar")}; the bar line it covers has ${n} (line ${ref.line})`;
96
+ }
97
+ function sectionsOf(lines) {
98
+ const sections = [{ name: null, lines: [] }];
99
+ for (const l of lines)
100
+ if (l.kind === "section")
101
+ sections.push({ name: l.name, lines: [] });
102
+ else
103
+ sections.at(-1)?.lines.push(l);
104
+ return sections;
105
+ }
106
+ /** A section's bar lines as units, and each row under a unit with the unit it lies under. */
107
+ function unitsOf(lines) {
108
+ const units = [];
109
+ const under = new Map();
110
+ let above = null;
111
+ for (const l of lines) {
112
+ if (isCovered(l)) {
113
+ if (above && l.system !== undefined && above[0]?.system === l.system)
114
+ above.push(l);
115
+ else {
116
+ above = [l];
117
+ units.push(above);
118
+ }
119
+ }
120
+ else if (isRow(l))
121
+ under.set(l, above);
122
+ else
123
+ above = null;
124
+ }
125
+ return { units, under };
126
+ }
127
+ const NOT_UNDER = "a lyric row goes under a bar line, or under a replay heading";
128
+ /** A row's verse as written, so each verse's rows under a replay count apart. */
129
+ const verseOf = (row) => row.kind === "lyrics"
130
+ ? String(row.verse ?? "")
131
+ : row.kind === "text"
132
+ ? (LYRIC_ROW.exec(row.text)?.[1] ?? "")
133
+ : "";
134
+ /** Rows under a replay heading: each verse's rows cover the replayed section's units in turn. */
135
+ function replayRows(rows, source, name) {
136
+ const counts = new Map();
137
+ const problem = `${name} has ${plural(source.length, "bar line")} to cover; this lyric row is one too many`;
138
+ return rows.map((row) => {
139
+ const k = counts.get(verseOf(row)) ?? 0;
140
+ counts.set(verseOf(row), k + 1);
141
+ return { row, unit: source[k], problem };
142
+ });
143
+ }
144
+ /** Where each row of a section lies, recording a written section's units for its replays. */
145
+ function placeRows(s, definitions) {
146
+ const { units, under } = unitsOf(s.lines);
147
+ const key = s.name === null ? null : normalize(s.name);
148
+ const source = key === null ? undefined : definitions.get(key);
149
+ if (key !== null && units.length)
150
+ definitions.set(key, units);
151
+ if (units.length || !source)
152
+ return [...under].map(([row, unit]) => ({ row, unit, problem: NOT_UNDER }));
153
+ return replayRows([...under.keys()], source, s.name ?? "");
154
+ }
155
+ /**
156
+ * Attach each lyric row to the bar lines it covers (grammar 7.7): the bar
157
+ * line or system just above it, or under a replay heading the replayed
158
+ * section's lines, one row each per verse. A row covering nothing, or with
159
+ * a bar count other than its unit's, is an error. Never throws.
160
+ */
161
+ export function attachLyrics(lines) {
162
+ const diagnostics = [];
163
+ const covers = new Map();
164
+ const definitions = new Map();
165
+ const placed = sectionsOf(lines).flatMap((s) => placeRows(s, definitions));
166
+ // A row with an error of its own (kept as text) only holds its place.
167
+ for (const { row, unit, problem } of placed) {
168
+ if (row.kind !== "lyrics")
169
+ continue;
170
+ const why = unit ? countProblem(row, unit) : problem;
171
+ if (why)
172
+ diagnostics.push({ line: row.line, severity: "error", message: why, token: "lyrics" });
173
+ if (unit)
174
+ covers.set(row, unit.map((l) => l.line));
175
+ }
176
+ const out = lines.map((l) => (l.kind === "lyrics" ? { ...l, covers: covers.get(l) ?? [] } : l));
177
+ return { lines: out, diagnostics };
178
+ }
@@ -12,7 +12,9 @@ export declare function parseChart(text: string): ChartParse;
12
12
  * its own bars, and `N.C.` marked `tacet` where it rests. With `lineName`,
13
13
  * one of the part's lines alone (grammar 7.6), as a converter writes each
14
14
  * line: the part's first line also plays its bare and tutti lines, and a
15
- * line rests where it isn't written. Null when the chart declares no part
15
+ * line rests where it isn't written. A part that writes its bare line
16
+ * beside its named lines makes it a line of its own (`lineName` `""`), and
17
+ * the named lines no longer play it. Null when the chart declares no part
16
18
  * with that label, or the part no line of that name. Never throws.
17
19
  */
18
20
  export declare function extractPart(text: string, label: string, lineName?: string): ChartParse | null;
@@ -2,6 +2,7 @@ import { readDocument } from "./document.js";
2
2
  import { expand, flattenBars } from "./expand.js";
3
3
  import { projectPart, projectPartLines } from "./parts.js";
4
4
  import { pedalWarnings } from "./pedal.js";
5
+ import { together, voicesIn, voicesOf, withSings } from "./verses.js";
5
6
  const RANK = { error: 0, warning: 1 };
6
7
  /** Sorted by line, errors before warnings. */
7
8
  const sortDiagnostics = (all) => all.sort((a, b) => a.line - b.line || RANK[a.severity] - RANK[b.severity]);
@@ -21,9 +22,15 @@ function mergeReports(each) {
21
22
  }
22
23
  const partBar = (b) => b.tacet ? null : { line: b.line, slots: b.slots, ...(b.words && { words: b.words }) };
23
24
  const meterText = (b) => `${b.meter.n}/${b.meter.d}`;
24
- /** One bar of every part: shared fields from the first, the meter from the first that plays. */
25
+ /** Every stream's words in a bar, in verse order, then score order (grammar 7.7). */
26
+ const lyricsOf = (bars) => bars.flatMap((b) => b.lyrics ?? []).sort((a, b) => a.verse - b.verse);
27
+ /**
28
+ * One bar of every part: shared fields from the first, the meter from the
29
+ * first that plays, the words of every stream that sings.
30
+ */
25
31
  function zipBar(bars, report) {
26
32
  const [first, ...rest] = bars;
33
+ const lyrics = lyricsOf(bars);
27
34
  const playing = bars.filter((b) => !b.tacet);
28
35
  const meter = playing[0]?.meter ?? first.meter;
29
36
  const meters = [...new Set(playing.map(meterText))];
@@ -36,7 +43,13 @@ function zipBar(bars, report) {
36
43
  message: `the parts disagree on this bar's meter (${meters.join(", ")})`,
37
44
  token: "|",
38
45
  });
39
- return { ...first, meter, parts: [first, ...rest].map(partBar) };
46
+ const { lyrics: _l, ...shared } = first;
47
+ return {
48
+ ...shared,
49
+ meter,
50
+ parts: [first, ...rest].map(partBar),
51
+ ...(lyrics.length && { lyrics }),
52
+ };
40
53
  }
41
54
  const lineOf = (e) => (e.kind === "bar" ? e.bar.line : e.line);
42
55
  /** The first event at which some part's timeline differs in shape from the lead's, or -1. */
@@ -79,6 +92,8 @@ export function zipEvents(each, report) {
79
92
  return e;
80
93
  });
81
94
  }
95
+ /** How a stream's line is labelled in its messages: `Pno.RH`, or the part's label for its bare line. */
96
+ const lineLabel = (label, name) => (name ? `${label}.${name}` : label);
82
97
  const streamsOf = (shown) => shown.flatMap((p, part) => p.lines?.length
83
98
  ? p.lines.map((name) => ({ part, label: p.label ?? "", name }))
84
99
  : [{ part, label: p.label ?? "", name: null }]);
@@ -133,13 +148,28 @@ function linedPedalWarnings(events, shown) {
133
148
  const bars = flattenBars(events);
134
149
  return shown.flatMap((p, i) => p.lines?.length ? pedalWarnings(bars.map((b) => partView(b, i, shown.length))) : []);
135
150
  }
151
+ /** The stream a voice sings on: its singing line, else its part's first; the first shown for the chart's words. */
152
+ function singingStream(streams, singer) {
153
+ const label = singer?.label?.toLowerCase();
154
+ if (label === undefined)
155
+ return 0;
156
+ const own = (s) => s.label.toLowerCase() === label;
157
+ const at = streams.findIndex((s) => own(s) && (s.name ?? "").toLowerCase() === singer?.sings?.toLowerCase());
158
+ return at >= 0 ? at : streams.findIndex(own);
159
+ }
160
+ /** Each stream's words: the voices singing on it, together. */
161
+ function singsOn(streams, voices) {
162
+ return streams.map((_, i) => together(voices.filter((v) => singingStream(streams, v.singer) === i).map((v) => v.sing)));
163
+ }
136
164
  /**
137
165
  * Parts and their lines: each stream projected and played, zipped into one
138
- * timeline, then folded into the parts shown (grammar 7.4, 7.6).
166
+ * timeline, then folded into the parts shown (grammar 7.4, 7.6). With a
167
+ * voice, the stream that sings takes the words.
139
168
  */
140
- function playStreams(lines, parts, shown) {
169
+ function playStreams(lines, parts, shown, voices) {
141
170
  const streams = streamsOf(shown);
142
- const played = streams.map((s) => expand(projectPart(lines, parts, s.label, s.name), s.name === null ? s.label : `${s.label}.${s.name}`, streams.length, s.name === null));
171
+ const sings = singsOn(streams, voices);
172
+ const played = streams.map((s, i) => expand(projectPart(lines, parts, s.label, s.name), lineLabel(s.label, s.name), streams.length, s.name === null, sings[i]));
143
173
  const diagnostics = mergeReports(played.map((p) => p.diagnostics));
144
174
  const zipped = zipEvents(played.map((p) => p.events), (d) => diagnostics.push(d));
145
175
  const events = foldEvents(zipped, streams, shown);
@@ -147,57 +177,79 @@ function playStreams(lines, parts, shown) {
147
177
  return { events, sections: played[0]?.sections ?? [], diagnostics };
148
178
  }
149
179
  const lined = (parts) => parts.some((p) => p.lines?.length);
180
+ /** What the voices found as they sang (grammar 7.7), once playing is done. */
181
+ function sungChecks(voices) {
182
+ return voices.flatMap((v) => {
183
+ v.finish();
184
+ return v.diagnostics;
185
+ });
186
+ }
150
187
  /** Read a whole barmark chart: the document as written and the bars in play order. Never throws. */
151
188
  export function parseChart(text) {
152
189
  const doc = readDocument(text);
190
+ const voice = voicesOf(doc.lines, doc.parts);
153
191
  const played = doc.parts.length > 1 || lined(doc.parts)
154
- ? playStreams(doc.lines, doc.parts, doc.parts)
155
- : expand(doc.lines);
192
+ ? playStreams(doc.lines, doc.parts, doc.parts, voice.voices)
193
+ : expand(doc.lines, undefined, 1, true, together(voice.voices.map((v) => v.sing)));
194
+ const [part = null] = doc.part ? withSings([doc.part], voice.all) : [];
156
195
  return {
157
196
  title: doc.title,
158
- part: doc.part,
159
- parts: doc.parts,
197
+ part,
198
+ parts: withSings(doc.parts, voice.all),
160
199
  credits: doc.credits,
161
200
  lines: doc.lines,
162
201
  events: played.events,
163
202
  bars: flattenBars(played.events),
164
203
  sections: played.sections,
165
- diagnostics: sortDiagnostics([...doc.diagnostics, ...played.diagnostics]),
204
+ diagnostics: sortDiagnostics([
205
+ ...doc.diagnostics,
206
+ ...voice.diagnostics,
207
+ ...played.diagnostics,
208
+ ...sungChecks(voice.voices),
209
+ ]),
166
210
  };
167
211
  }
168
212
  /** What an extract holds and plays: one of the part's lines, the part with its lines, or the part. */
169
- function extractOf(doc, part, lineName) {
213
+ function extractOf(doc, part, voices, lineName) {
170
214
  const label = part.label ?? "";
215
+ const sing = together(voices.map((v) => v.sing));
171
216
  if (lineName !== undefined) {
172
217
  const name = part.lines?.find((n) => n.toLowerCase() === lineName.toLowerCase());
173
- if (!name)
218
+ if (name === undefined)
174
219
  return null;
175
220
  const lines = projectPart(doc.lines, doc.parts, label, name);
176
- return { lines, played: expand(lines, `${label}.${name}`) };
221
+ return { lines, played: expand(lines, lineLabel(label, name), 1, true, sing) };
177
222
  }
178
223
  if (part.lines?.length)
179
224
  return {
180
225
  lines: projectPartLines(doc.lines, label),
181
- played: playStreams(doc.lines, doc.parts, [part]),
226
+ played: playStreams(doc.lines, doc.parts, [part], voices),
182
227
  };
183
228
  const lines = doc.parts.length > 1 ? projectPart(doc.lines, doc.parts, label) : doc.lines;
184
- return { lines, played: expand(lines, part.label) };
229
+ return { lines, played: expand(lines, part.label, 1, true, sing) };
185
230
  }
186
231
  /**
187
232
  * One part of a chart as a single-part chart (grammar 7.4): the tutti bars,
188
233
  * its own bars, and `N.C.` marked `tacet` where it rests. With `lineName`,
189
234
  * one of the part's lines alone (grammar 7.6), as a converter writes each
190
235
  * line: the part's first line also plays its bare and tutti lines, and a
191
- * line rests where it isn't written. Null when the chart declares no part
236
+ * line rests where it isn't written. A part that writes its bare line
237
+ * beside its named lines makes it a line of its own (`lineName` `""`), and
238
+ * the named lines no longer play it. Null when the chart declares no part
192
239
  * with that label, or the part no line of that name. Never throws.
193
240
  */
194
241
  export function extractPart(text, label, lineName) {
195
242
  const doc = readDocument(text);
196
243
  const part = doc.parts.find((p) => p.label?.toLowerCase() === label.toLowerCase());
197
- const extract = part ? extractOf(doc, part, lineName) : null;
244
+ const voice = voicesOf(doc.lines, doc.parts);
245
+ const voices = part ? voicesIn(voice.voices, part, lineName) : [];
246
+ const extract = part ? extractOf(doc, part, voices, lineName) : null;
198
247
  if (!part || !extract)
199
248
  return null;
200
- const { lines, played } = extract;
249
+ const { played } = extract;
250
+ // The lyric rows are their owner's, or the chart's when no part sings (grammar 7.7).
251
+ const rows = voices.some((v) => v.singer === voice.owner);
252
+ const lines = rows ? extract.lines : extract.lines.filter((l) => l.kind !== "lyrics");
201
253
  const kept = new Set(lines.map((l) => l.line));
202
254
  // A stand-in may sit on another part's line; that part's problems are not this one's.
203
255
  for (const l of doc.lines)
@@ -205,16 +257,17 @@ export function extractPart(text, label, lineName) {
205
257
  kept.delete(l.line);
206
258
  return {
207
259
  title: doc.title,
208
- part,
209
- parts: [part],
260
+ part: withSings([part], voice.all)[0] ?? part,
261
+ parts: withSings([part], voice.all),
210
262
  credits: doc.credits,
211
263
  lines,
212
264
  events: played.events,
213
265
  bars: flattenBars(played.events),
214
266
  sections: played.sections,
215
267
  diagnostics: sortDiagnostics([
216
- ...doc.diagnostics.filter((d) => kept.has(d.line)),
268
+ ...[...doc.diagnostics, ...voice.diagnostics].filter((d) => kept.has(d.line)),
217
269
  ...played.diagnostics,
270
+ ...sungChecks(voices),
218
271
  ]),
219
272
  };
220
273
  }
@@ -41,12 +41,12 @@ function unlabelled(l) {
41
41
  return rest;
42
42
  }
43
43
  const plays = (l) => l?.kind === "bars" && !l.dropped;
44
- /** The stream's own line in a system, if written. */
44
+ /** The stream's own line in a system, if written; a bare line dropped from a part's lines is none of them (grammar 7.6). */
45
45
  const ownLine = (system, s) => system.find((m) => m.part?.toLowerCase() === s.key &&
46
46
  (s.name === null
47
47
  ? true
48
48
  : m.lineName === undefined
49
- ? s.first
49
+ ? s.first && !(m.kind === "bars" && m.dropped)
50
50
  : m.lineName.toLowerCase() === s.name.toLowerCase()));
51
51
  /** A tutti line as a stream other than its part's first hears it: tacet. */
52
52
  const restingTutti = (l) => l.kind === "bars" ? { ...l, cells: l.cells.map(standInCell) } : l;
@@ -51,9 +51,20 @@ function printMarks(s) {
51
51
  const pedal = s.kind === "chord" && s.pedal ? PEDALS[s.pedal] : "";
52
52
  return pedal + push + (s.kind === "chord" && s.articulation ? ARTICULATIONS[s.articulation] : "");
53
53
  }
54
+ /** A syllable as written after its note's colon (grammar 4.3). */
55
+ const printSyllable = (s) => s.kind === "held" ? "/" : s.parts.join("~") + (s.continues ? "-" : "");
56
+ /** A lyric row's slot as written (grammar 7.7); a group's members are joined with `_`. */
57
+ const printLyricSlot = (s) => {
58
+ if (s.kind === "group")
59
+ return s.members.map(printLyricSlot).join("_");
60
+ if (s.kind === "syllable")
61
+ return printSyllable(s.syllable);
62
+ return s.kind === "hold" ? "/" : "--";
63
+ };
54
64
  function printSimple(s) {
55
65
  const body = s.kind === "chord" ? s.chord.canonical + (s.voicing?.canonical ?? "") : SYMBOLS[s.kind];
56
- return printMarks(s) + body + (s.dotted ? "." : "");
66
+ const sung = s.kind === "chord" && s.syllable ? `:${printSyllable(s.syllable)}` : "";
67
+ return printMarks(s) + body + (s.dotted ? "." : "") + sung;
57
68
  }
58
69
  /** A slot in canonical spelling; a group's members are joined with `_`. */
59
70
  export function printSlot(s) {
@@ -127,6 +138,14 @@ function printDirectives(d) {
127
138
  parts.push(`feel: ${d.feel}${d.swingPercent === undefined ? "" : ` ${d.swingPercent}%`}`);
128
139
  return parts.join(", ");
129
140
  }
141
+ /** A lyric row's label: `lyrics:`, or `lyrics N:` for verse N. */
142
+ const lyricLabel = (l) => `lyrics${l.verse === null ? "" : ` ${l.verse}`}:`;
143
+ /** A lyric row's pieces, never reduced: its holds place the syllables. */
144
+ const lyricPieces = (l) => ({
145
+ open: "|",
146
+ cells: l.cells.map((c) => c.map(printLyricSlot).join(" ")),
147
+ close: "|",
148
+ });
130
149
  /** A bar line's opening, cells and closing, each printed. */
131
150
  function barPieces(l, beats) {
132
151
  return {
@@ -154,6 +173,10 @@ export function printLine(l, beats = []) {
154
173
  return `${l.role}: ${l.text}`;
155
174
  case "bars":
156
175
  return joinPieces(barPieces(l, beats));
176
+ case "break":
177
+ return "---";
178
+ case "lyrics":
179
+ return `${lyricLabel(l)} ${joinPieces(lyricPieces(l))}`;
157
180
  default:
158
181
  return l.text;
159
182
  }
@@ -170,7 +193,7 @@ export function printChart(text) {
170
193
  const labelOf = (l) => `${l.part ?? ""}${l.lineName === undefined ? "" : `.${l.lineName}`}`;
171
194
  const labelsOf = (p) => [
172
195
  p.label ?? "",
173
- ...(p.lines ?? []).map((n) => `${p.label}.${n}`),
196
+ ...(p.lines ?? []).map((n) => (n ? `${p.label}.${n}` : (p.label ?? ""))),
174
197
  ];
175
198
  /** Score order: by part, then by the part's line, a bare line first. */
176
199
  function scoreOf(l, parsed) {
@@ -178,33 +201,118 @@ function scoreOf(l, parsed) {
178
201
  const line = l.lineName === undefined ? -1 : (parsed.parts[at]?.lines ?? []).indexOf(l.lineName);
179
202
  return at * 10 + line + 1;
180
203
  }
181
- /** A system's lines in score order, labels padded and pipes lined up (section 8, grammar 7.4). */
182
- function alignSystem(system, parsed, beatsFor, edit) {
183
- const width = Math.max(...parsed.parts.flatMap(labelsOf).map((label) => label.length));
184
- const pieces = [...system]
185
- .sort((a, b) => scoreOf(a, parsed) - scoreOf(b, parsed))
186
- .map((l) => ({ label: labelOf(l), ...barPieces(edit(l), beatsFor(l)) }));
187
- const columns = pieces[0]?.cells.map((_, i) => Math.max(...pieces.map((p) => p.cells[i]?.length ?? 0)));
188
- return pieces.map((p) => `${p.label.padEnd(width)} ${joinPieces({ ...p, cells: p.cells.map((c, i) => c.padEnd(columns?.[i] ?? 0)) })}`.trimEnd());
204
+ /**
205
+ * The bar-line cells a row's cell `k` lies under: from its bar to the next
206
+ * bar, so a fermata, mark or direction falls in the cell before it, and
207
+ * any before the first bar in the first cell.
208
+ */
209
+ const spanOf = (k, bars, n) => [
210
+ k === 0 ? 0 : (bars[k] ?? 0),
211
+ (bars[k + 1] ?? n) - 1,
212
+ ];
213
+ const roomOf = (columns, [a, b]) => columns.slice(a, b + 1).reduce((x, y) => x + y, 0) + 3 * (b - a);
214
+ /** Each column's width: the widest of the bar lines' cells, widened for a row's cell that won't fit. */
215
+ function columnsOf(lines, rows, bars) {
216
+ const columns = (lines[0]?.cells ?? []).map((_, i) => Math.max(...lines.map((p) => p.cells[i]?.length ?? 0)));
217
+ for (const r of rows)
218
+ for (const [k, c] of r.cells.entries()) {
219
+ const room = roomOf(columns, spanOf(k, bars, columns.length));
220
+ const at = bars[k] ?? 0;
221
+ if (c.length > room)
222
+ columns[at] = (columns[at] ?? 0) + c.length - room;
223
+ }
224
+ return columns;
225
+ }
226
+ /**
227
+ * Bar lines and the lyric rows under them, labels padded to `width` and
228
+ * pipes lined up; a row's cell spans the cells of its bar (grammar 7.7).
229
+ */
230
+ function alignBlock(lines, rows, bars, width) {
231
+ const w = Math.max(width, ...rows.map((r) => r.label.length));
232
+ const columns = columnsOf(lines, rows, bars);
233
+ const print = (p, pad) => `${p.label.padEnd(w)} ${joinPieces({ ...p, cells: p.cells.map(pad) })}`.trimEnd();
234
+ const texts = new Map();
235
+ for (const p of lines)
236
+ texts.set(p.line, print(p, (c, i) => c.padEnd(columns[i] ?? 0)));
237
+ for (const r of rows)
238
+ texts.set(r.line, print(r, (c, k) => c.padEnd(roomOf(columns, spanOf(k, bars, columns.length)))));
239
+ return texts;
189
240
  }
190
- function systemsOf(lines) {
191
- const systems = new Map();
192
- for (const l of lines)
193
- if ((l.kind === "bars" || l.kind === "invalid") && l.system !== undefined)
194
- systems.set(l.system, [...(systems.get(l.system) ?? []), l]);
195
- return [...systems.values()];
241
+ /** A system's lines in score order, labels padded and pipes lined up, with its lyric rows (section 8, grammar 7.4, 7.7). */
242
+ function alignSystem(block, parsed, beatsFor, edit) {
243
+ const system = block.lines;
244
+ const labelled = system[0]?.system !== undefined;
245
+ const width = labelled
246
+ ? Math.max(...parsed.parts.flatMap(labelsOf).map((label) => label.length))
247
+ : 0;
248
+ const sorted = labelled
249
+ ? [...system].sort((a, b) => scoreOf(a, parsed) - scoreOf(b, parsed))
250
+ : system;
251
+ // Sorted lines take the written lines' places, so the system's rows stay together.
252
+ const pieces = sorted.map((l, i) => ({
253
+ label: labelled ? labelOf(l) : "",
254
+ line: system[i]?.line ?? l.line,
255
+ ...barPieces(edit(l), beatsFor(l)),
256
+ }));
257
+ const rows = block.rows.map((r) => ({ label: lyricLabel(r), line: r.line, ...lyricPieces(r) }));
258
+ const bars = (system[0]?.cells ?? []).flatMap((c, i) => (isBar(c) ? [i] : []));
259
+ return alignBlock(pieces, rows, bars, width);
196
260
  }
197
- /** Canonical text for the lines of a multi-part chart's systems, by line number. */
261
+ /** A row lies just under its bars unless a heading comes between: under a replay heading it doesn't. */
262
+ const isUnder = (r, lines) => {
263
+ if (!r.covers.length)
264
+ return false;
265
+ const last = Math.max(...r.covers);
266
+ return !lines.some((l) => l.kind === "section" && l.line > last && l.line < r.line);
267
+ };
268
+ /** The block a bar line is in: its system's, or its own. */
269
+ const blockKey = (l) => (l.kind === "bars" || l.kind === "invalid") && l.system !== undefined
270
+ ? `system ${l.system}`
271
+ : `line ${l.line}`;
272
+ const inSystem = (l) => (l.kind === "bars" || l.kind === "invalid") && l.system !== undefined;
273
+ function blockFor(blocks, l) {
274
+ const block = blocks.get(blockKey(l)) ?? { lines: [], rows: [] };
275
+ blocks.set(blockKey(l), block);
276
+ return block;
277
+ }
278
+ /** Each system, and each bar line with rows just under it, with those rows (grammar 7.4, 7.7). */
279
+ function blocksOf(lines) {
280
+ const blocks = new Map();
281
+ for (const l of lines.filter(inSystem))
282
+ blockFor(blocks, l).lines.push(l);
283
+ const byLine = new Map(lines.map((l) => [l.line, l]));
284
+ for (const r of lines) {
285
+ if (r.kind !== "lyrics" || !isUnder(r, lines))
286
+ continue;
287
+ // An extracted part keeps only some of a system's lines.
288
+ const first = r.covers.map((n) => byLine.get(n)).find((l) => l !== undefined);
289
+ if (!first)
290
+ continue;
291
+ const block = blockFor(blocks, first);
292
+ if (!block.lines.length)
293
+ block.lines.push(first);
294
+ block.rows.push(r);
295
+ }
296
+ return [...blocks.values()];
297
+ }
298
+ /** Canonical text for the lines of systems and of bar lines with lyric rows, by line number. */
198
299
  function systemTexts(parsed, errored, beatsFor, edit) {
199
300
  const texts = new Map();
200
- for (const lines of systemsOf(parsed.lines)) {
301
+ for (const block of blocksOf(parsed.lines)) {
302
+ const { lines } = block;
201
303
  const valid = lines.filter((l) => l.kind === "bars" && !errored.has(l.line));
304
+ const rows = block.rows.filter((r) => !errored.has(r.line));
305
+ const labelled = valid[0]?.system !== undefined;
306
+ if (!labelled && !rows.length)
307
+ continue;
202
308
  // A system with an error is neither sorted nor padded, so the error's line stays where it was written.
203
- const printed = valid.length === lines.length
204
- ? alignSystem(valid, parsed, beatsFor, edit)
205
- : valid.map((l) => `${labelOf(l)} ${printLine(edit(l), beatsFor(l))}`);
206
- for (const [i, l] of valid.entries())
207
- texts.set(l.line, printed[i] ?? "");
309
+ if (valid.length === lines.length) {
310
+ for (const [line, text] of alignSystem({ lines: valid, rows }, parsed, beatsFor, edit))
311
+ texts.set(line, text);
312
+ continue;
313
+ }
314
+ for (const l of valid)
315
+ texts.set(l.line, `${labelOf(l)} ${printLine(edit(l), beatsFor(l))}`);
208
316
  }
209
317
  return texts;
210
318
  }
@@ -300,7 +408,11 @@ export function printPart(text, label) {
300
408
  .lines.filter((l) =>
301
409
  // A `part:` demoted to text (a shared label) would declare a part again in the extract.
302
410
  (l.kind === "text" && /^part\s*:/i.test(l.text)) ||
303
- ((l.kind === "part" || l.kind === "bars" || l.kind === "invalid") && !kept.has(l.line)))
411
+ ((l.kind === "part" ||
412
+ l.kind === "bars" ||
413
+ l.kind === "invalid" ||
414
+ l.kind === "lyrics") &&
415
+ !kept.has(l.line)))
304
416
  .map((l) => l.line));
305
417
  return printLines(text, parsed, (l) => l, skip);
306
418
  }
@@ -91,6 +91,8 @@ function addEntry(st, entry) {
91
91
  else
92
92
  st.items.push({ kind: "line", ...entry });
93
93
  }
94
+ /** Lines that may sit between endings (grammar 5.1): they mean nothing to the timeline. */
95
+ const BETWEEN_ENDINGS = new Set(["text", "credit", "lyrics", "break"]);
94
96
  /**
95
97
  * Pair `|:` and `:|` within one section's lines, with the endings that
96
98
  * follow a repeat (grammar 5.1). Problems are reported, and what cannot
@@ -106,7 +108,7 @@ export function pairRepeats(lines, error) {
106
108
  for (const l of lines) {
107
109
  if (l.kind === "bars" && l.ending)
108
110
  takeEnding(st, l, error);
109
- else if (st.endings && (l.kind === "text" || l.kind === "credit"))
111
+ else if (st.endings && BETWEEN_ENDINGS.has(l.kind))
110
112
  st.endings.between.push({ line: l, repeat: null });
111
113
  else {
112
114
  finish();
@@ -1,6 +1,28 @@
1
- import type { SimpleSlot } from "./types.js";
1
+ import type { Meter } from "./types.js";
2
+ /** A slot that may be dotted: a bar line's (grammar 2.2) or a lyric row's, which never is. */
3
+ type Member = {
4
+ kind: string;
5
+ dotted?: true;
6
+ };
2
7
  /**
3
8
  * How a group divides its slot (grammar 2.2), as fractions summing to 1:
4
9
  * equally, or 3:1 (1:3) when one member of a pair is dotted.
5
10
  */
6
- export declare function memberShares(members: SimpleSlot[]): number[];
11
+ export declare function memberShares(members: Member[]): number[];
12
+ /** A simple slot with its onset from the bar's start and its length, both in whole notes. */
13
+ export type Timed<T> = {
14
+ slot: T;
15
+ at: number;
16
+ length: number;
17
+ };
18
+ /**
19
+ * Each simple slot of a bar in order, with its onset and length in whole
20
+ * notes: the bar split evenly among its slots (grammar 2.1), and a group's
21
+ * slot among its members (2.2). A lyric row's slots are timed as a bar
22
+ * line's (7.7).
23
+ */
24
+ export declare function slotTimes<T extends Member>(slots: (T | {
25
+ kind: "group";
26
+ members: T[];
27
+ })[], meter: Meter): Timed<T>[];
28
+ export {};