@barmark/render 0.21.0 → 0.22.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.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,57 @@ package uses [semantic versioning](https://semver.org/).
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.22.0] - 2026-11-28
10
+
11
+ ### Added
12
+
13
+ - **Played bar numbers**: `barNumbers: "played"` (attribute
14
+ `bar-numbers="played"`, property `barNumbers`) numbers each row in play
15
+ order, from the parser's play order, so a chart lines up with a player or
16
+ a recording that counts bars as played. A row played more than once shows
17
+ each pass's number (`1 · 5`, up to three; `9 … 37` for four or more), a
18
+ row no pass plays shows none, and after an open repeat (`x ...`) the
19
+ numbers are approximate (`~11`). Each bar speaks its own ("bar 1 and bar
20
+ 5", "about bar 11"). A pickup's first pass is never numbered; a later
21
+ pass of its row is. The gutter widens to fit, on one line, and a section
22
+ wraps sooner to make room for it; in a chart without part labels,
23
+ headings, text lines and directives start where the bars do, and with
24
+ part labels they keep their place over the label column, as in written
25
+ mode. `layoutChart` takes `barNumbers: "played"` and gives
26
+ `playedNumbers` on rows and bars. `barNumbers` also takes `"off"`, as
27
+ the attribute does.
28
+ Written numbers stay the default, and a chart drawn with them is byte for
29
+ byte as before but for (a) the bars the fix below describes and (b) a
30
+ `%` that no pass plays on a line some pass plays, which now draws its
31
+ `%` sign where it drew an empty bar.
32
+ - **The layout model's `simile` can be `"unplayed"`** as well as `true`: a
33
+ `%` no pass plays on a line some pass plays. A host reading the model
34
+ sees the wider type.
35
+
36
+ ### Fixed
37
+
38
+ - **A bar a pass leaves early draws its own chord.** When a pass left a
39
+ row early and another pass played further along it, the later bars drew
40
+ an earlier bar's chords, holds, `%`, syllables and lyrics. A jump inside
41
+ the row does this (`To Coda`, a `D.S.` or `D.C.` before the row's end):
42
+ `| Segno | A | To Coda | B | D.S. al Coda | Coda | C |` drew its coda bar
43
+ as A. So does a `->` cut of a section that a jump skips where it is
44
+ written: with `| E | G |` skipped, then `## Skip ->` and `## Skip`, the
45
+ written section drew E twice and the cut bar said "E, cut on this pass".
46
+ Each bar now draws the bar written in it. A bar no pass plays before a
47
+ `Coda` keeps its written number, so the row and the bar after it are
48
+ numbered as written (`| E |
49
+ Coda | F |` is 3 and 4 after a two-bar row, not 4 and 5), and a `%` no
50
+ pass plays there draws the `%` sign.
51
+
52
+ ## [0.21.1] - 2026-11-19
53
+
54
+ ### Changed
55
+
56
+ - **With `melody: false`, a melisma's held place is not drawn**: the words
57
+ of a left-out melody take the space they would with no melody written,
58
+ so `maz- / ing_/` draws as `maz- / ing`, with no extender.
59
+
9
60
  ## [0.21.0] - 2026-11-19
10
61
 
11
62
  ### Added
@@ -591,7 +642,9 @@ that needs no script or as the `<barmark-chart>` web component. Requires
591
642
  zoom without sideways scrolling, the element renders and re-renders, and
592
643
  a screen reader hears "bar 9: D". Run them with `bun run test:browser`.
593
644
 
594
- [Unreleased]: https://github.com/kevinpeckham/barmark/compare/render-v0.21.0...HEAD
645
+ [Unreleased]: https://github.com/kevinpeckham/barmark/compare/render-v0.22.0...HEAD
646
+ [0.22.0]: https://github.com/kevinpeckham/barmark/compare/render-v0.21.1...render-v0.22.0
647
+ [0.21.1]: https://github.com/kevinpeckham/barmark/compare/render-v0.21.0...render-v0.21.1
595
648
  [0.21.0]: https://github.com/kevinpeckham/barmark/compare/render-v0.20.2...render-v0.21.0
596
649
  [0.20.2]: https://github.com/kevinpeckham/barmark/compare/render-v0.20.1...render-v0.20.2
597
650
  [0.20.1]: https://github.com/kevinpeckham/barmark/compare/render-v0.20.0...render-v0.20.1
package/README.md CHANGED
@@ -52,7 +52,9 @@ The element renders from its `text` property, its `src` URL, or a child
52
52
  whenever one changes; it fetches a `src` once, and renders once however
53
53
  many properties and attributes change together. A chart rendered on the
54
54
  server by `renderChart` keeps its music until it has a source of its own,
55
- and still follows `theme`, `bar-numbers`, `wrap` and `columns`; a change to
55
+ and still follows `theme`, `bar-numbers`, `wrap` and `columns` (its bar
56
+ numbers hide and show again, but stay written or played as they were
57
+ drawn: changing between the two needs the chart's text); a change to
56
58
  `numerals`, `rehearsal-letters`, `melody`, `show-part`, `chord-diagrams` or
57
59
  `diagram-hand` needs the chart's text, so it waits for a source.
58
60
 
@@ -79,11 +81,11 @@ the element loads, with `<style data-barmark-font>` holding
79
81
  | `renderChart` option | Element attribute (property) | Default | |
80
82
  |---|---|---|---|
81
83
  | `theme` | `theme` (`theme`) | `"auto"` | `"auto"` follows the system; `"light"` or `"dark"` force one |
82
- | `barNumbers` | `bar-numbers="off"` (`barNumbers`) | `true` | bar numbers at the start of each row |
84
+ | `barNumbers` | `bar-numbers="off"` or `"played"` (`barNumbers`) | `true` | bar numbers at the start of each row: `true` written numbers, `false` or `"off"` none, `"played"` numbers in play order (below). Any other attribute value is written |
83
85
  | `rehearsalLetters` | `rehearsal-letters` (`rehearsalLetters`) | `false` | boxed A, B, C… on each section as played; none when the chart writes a rehearsal mark of its own (below) |
84
86
  | `numerals` | `numerals` (`numerals`) | none | `"nashville"` (6m⁷) or `"roman"` (vi⁷): each chord as its degree in its bar's key |
85
87
  | `wrap` | `wrap="off"` (`wrap`) | `true` | wrap a section's rows when it is wider than the chart's box; off, rows keep their columns and the chart overflows, for its page to scroll |
86
- | `melody` | `melody="off"` (`melody`) | `true` | `false` leaves a voice part's singing line out of the grid; its words stay, drawn by beat under the chords. The melody is left out only beside a line that draws its bars; a melody on its own stays, and so does a line with a problem or one that writes chord names, `N.C.` or `?`. In a one-part lead sheet the chord line then draws as a plain row with no label. `@barmark/score`'s score view still shows it |
88
+ | `melody` | `melody="off"` (`melody`) | `true` | `false` leaves a voice part's singing line out of the grid; its words stay, drawn by beat under the chords. The melody is left out only beside a line that draws its bars; a melody on its own stays, and so does a line with a problem or one that writes chord names, `N.C.` or `?`. A melisma's held place is not drawn where the melody is left out, so the words take the space they would with no melody written. In a one-part lead sheet the chord line then draws as a plain row with no label. `@barmark/score`'s score view still shows it |
87
89
  | `columns` | `columns="row"` (`columns`) | `"shared"` | `"shared"`: a section's rows share column tracks, so bar lines line up down the section; `"row"`: each row sizes its own bars (below). Any other value is `"shared"` |
88
90
  | `part` | `show-part` (`showPart`) | none | draw only the part with this label, as one player reads it: tutti bars, its own bars, and "tacet" where it rests. The attribute isn't `part`, which HTML keeps for `::part()` styling |
89
91
  | `chordDiagrams` | `chord-diagrams="guitar"` (`chordDiagrams`) | none | `"guitar"`: a strip of guitar chord diagrams after the header, one for each distinct chord (below). Any other value is off |
@@ -113,6 +115,41 @@ their bar lines together. Only the layout changes: the music, the markup
113
115
  inside each bar and what a screen reader hears are the same. A section
114
116
  wraps on a narrow screen as before, once its widest row no longer fits.
115
117
 
118
+ ### Played bar numbers
119
+
120
+ With `barNumbers: "played"` (`bar-numbers="played"` on the element) each
121
+ row shows where its first bar falls in play order, for lining a chart up
122
+ with a player or a recording that counts bars as they are played. The
123
+ numbers come from the parser's play order (`parseChart(text).bars`); the
124
+ grid expands nothing itself. A row played once shows one number. A row
125
+ played more than once where it is drawn (inside `|: :|`, under `x N`, or
126
+ where a `D.S.` or `D.C.` returns) shows its first bar's number on each pass,
127
+ `1 · 5`, up to three; four or more show the first and the last, `9 … 37`.
128
+ A row no pass plays shows none. A pickup's first pass is 0 and never
129
+ shown, as with written numbers; a later pass of its row (inside `|: :|`,
130
+ or where a `D.C.` returns) shows its number. An open repeat (`x ...`) is
131
+ counted once, since its passes are unknown: every number after it is
132
+ approximate and shows as `~11`. A screen reader hears each bar's own
133
+ numbers: "bar 1 and bar 5", "bars 1, 5 and 9", "bars 9 to 37, 8 times",
134
+ "about bar 11", "about bars 12, 14 and 16". The gutter widens to the
135
+ longest numbers on one line, and a section wraps sooner to make room for
136
+ it. In a chart without part labels, headings, text lines and directives
137
+ start where the bars do, as with written numbers; with part labels they
138
+ keep their place over the label column, as in written mode. Played markup
139
+ carries the few rules that do this, so a page that includes `stylesheet`
140
+ needs nothing more. Written numbers stay the default because they are
141
+ what a printed chart and a band use; the model gives played numbers as
142
+ `playedNumbers` on each row and bar (`{ bar, approximate }`, a pass each)
143
+ only in this mode.
144
+
145
+ A played number is `PlayedBar.index`, less one when `parse.pickup` (the
146
+ pickup's first pass is 0). `@barmark/sync`'s timing map numbers bars by
147
+ `PlayedBar.index`, so its pickup is map bar 1: a host showing `barAt().bar`
148
+ beside a played chart subtracts one on a pickup chart to match. A chart
149
+ rendered on the server is drawn in one mode: `bar-numbers` can hide its
150
+ numbers and show them again, but changing between written and played
151
+ renders it again from its text.
152
+
116
153
  ### Numerals
117
154
 
118
155
  With `numerals`, each chord shows as its degree in the key its bar is
@@ -258,7 +295,8 @@ note is spoken by name ("dotted quarter note"), and the model gives it as
258
295
  At the default size chords are 16px and no label is under 12px.
259
296
 
260
297
  Chords appear in their canonical form whatever the author typed (`Cø`
261
- shows as Cm⁷(♭5)). `%` is drawn as the bar it copies; a replayed section
298
+ shows as Cm⁷(♭5)). `%` is drawn as the bar it copies (as the `%` sign
299
+ where no pass plays it); a replayed section
262
300
  is drawn in full, and its own lyrics replace the written section's. Bar
263
301
  numbers count the bars as written, each once, as a band counts them: a
264
302
  repeat, an ending, a jump or a replay doesn't move them, so a replayed
package/dist/element.js CHANGED
@@ -8,6 +8,8 @@ import { NUMERALS } from "./chord.js";
8
8
  import { FONT_FAMILY, fontFaceCss } from "./font.js";
9
9
  import { loadErrorContent, shadowContent, THEMES, } from "./html.js";
10
10
  const HANDS = ["left", "right"];
11
+ /** `bar-numbers`: "off" hides them, "played" counts in play order, anything else (none included) is written. */
12
+ const barNumbersOf = (value) => value === "played" ? "played" : value !== "off";
11
13
  export function optionsFromAttributes(el) {
12
14
  const theme = el.getAttribute("theme");
13
15
  const numerals = NUMERALS.find((n) => n === el.getAttribute("numerals"));
@@ -17,7 +19,7 @@ export function optionsFromAttributes(el) {
17
19
  const hand = HANDS.find((h) => h === el.getAttribute("diagram-hand"));
18
20
  return {
19
21
  theme: THEMES.find((t) => t === theme) ?? "auto",
20
- barNumbers: el.getAttribute("bar-numbers") !== "off",
22
+ barNumbers: barNumbersOf(el.getAttribute("bar-numbers")),
21
23
  rehearsalLetters: el.hasAttribute("rehearsal-letters"),
22
24
  wrap: el.getAttribute("wrap") !== "off",
23
25
  // Only "off" hides the melody; anything else, or none, leaves it unset.
@@ -119,11 +121,14 @@ function defineElement() {
119
121
  set theme(v) {
120
122
  this.setAttribute("theme", v);
121
123
  }
124
+ /** true for written numbers, "played" for numbers in play order, false for none (set `false`, `"off"` or any falsy value). */
122
125
  get barNumbers() {
123
- return optionsFromAttributes(this).barNumbers ?? true;
126
+ return barNumbersOf(this.getAttribute("bar-numbers"));
124
127
  }
125
128
  set barNumbers(v) {
126
- if (v)
129
+ if (v === "played")
130
+ this.setAttribute("bar-numbers", "played");
131
+ else if (v && v !== "off")
127
132
  this.removeAttribute("bar-numbers");
128
133
  else
129
134
  this.setAttribute("bar-numbers", "off");
@@ -246,8 +251,12 @@ function defineElement() {
246
251
  #restyle(options) {
247
252
  const chart = this.shadowRoot?.querySelector(".bm-chart");
248
253
  chart?.setAttribute("data-theme", options.theme ?? "auto");
254
+ // Written or played numbers are the music's: shown again, they are the ones drawn.
255
+ const played = chart?.getAttribute("style")?.includes("--bm-played") === true;
249
256
  if (options.barNumbers === false)
250
257
  chart?.setAttribute("data-bar-numbers", "off");
258
+ else if (played)
259
+ chart?.setAttribute("data-bar-numbers", "played");
251
260
  else
252
261
  chart?.removeAttribute("data-bar-numbers");
253
262
  if (options.wrap === false)
package/dist/html.d.ts CHANGED
@@ -1,7 +1,14 @@
1
1
  import { type Numerals } from "./chord.js";
2
2
  export type RenderOptions = {
3
3
  theme?: "auto" | "light" | "dark";
4
- barNumbers?: boolean;
4
+ /**
5
+ * Bar numbers at the start of each row: `true` (the default), written
6
+ * numbers; `false` or `"off"`, none; `"played"`, each row's place in play
7
+ * order, a number a pass (`1 · 5`), `~` after a vamp. Any other value is
8
+ * written, but for `0` or `""`, which hide them as `false` does; `null`,
9
+ * like none, is the default.
10
+ */
11
+ barNumbers?: boolean | "played" | "off";
5
12
  /**
6
13
  * Boxed letters A, B, C… on each section as played. None when any bar
7
14
  * carries its own rehearsal mark (`@A`, barmark's grammar 2.5): the
package/dist/html.js CHANGED
@@ -11,7 +11,7 @@ import { escapeHtml } from "./escape.js";
11
11
  import { fontFaceCss } from "./font.js";
12
12
  import { isTacet as isTacetCell, layoutChart, meloffChanged } from "./model.js";
13
13
  import { barLabel, speakBar, speakDiagram, speakVerses, UNPLAYABLE, VOICING_REPLACED, } from "./speech.js";
14
- import { FIT_STEPS, MIN_BAR, stylesheet } from "./styles.js";
14
+ import { FIT_STEPS, MIN_BAR, PLAYED_CSS, playedGutterExtra, stylesheet } from "./styles.js";
15
15
  import { beatLinesHtml, pitchHtml, sungBar, sungSlotHtml, verseNumbersHtml, verseWidth, } from "./verses-html.js";
16
16
  export function renderChart(text, options = {}) {
17
17
  return `${fontStyle(options)}<barmark-chart${elementAttributes(options)}><template shadowrootmode="open">${shadowContent(text, options)}</template></barmark-chart>`;
@@ -21,7 +21,7 @@ function elementAttributes(options) {
21
21
  const theme = themeOf(options);
22
22
  return [
23
23
  theme === "auto" ? "" : ` theme="${theme}"`,
24
- options.barNumbers === false ? ' bar-numbers="off"' : "",
24
+ barNumbersAttribute(options),
25
25
  options.rehearsalLetters ? " rehearsal-letters" : "",
26
26
  numeralsOf(options) ? ` numerals="${numeralsOf(options)}"` : "",
27
27
  options.wrap === false ? ' wrap="off"' : "",
@@ -31,6 +31,20 @@ function elementAttributes(options) {
31
31
  diagramAttributes(options),
32
32
  ].join("");
33
33
  }
34
+ /** `barNumbers` as drawn: played, written (true) or none; `"off"` and any falsy value but null are none, as `false` is. */
35
+ const numbersOf = (options) => {
36
+ const value = options.barNumbers ?? true;
37
+ return value === "played" ? value : value !== "off" && Boolean(value);
38
+ };
39
+ /** `bar-numbers` as the element reads it: written numbers need none. */
40
+ const barNumbersAttribute = (options) => {
41
+ const numbers = numbersOf(options);
42
+ return numbers === false
43
+ ? ' bar-numbers="off"'
44
+ : numbers === "played"
45
+ ? ' bar-numbers="played"'
46
+ : "";
47
+ };
34
48
  /** The chord diagrams' attributes: only the values the element reads. */
35
49
  function diagramAttributes(options) {
36
50
  const guitar = options.chordDiagrams === "guitar" ? ' chord-diagrams="guitar"' : "";
@@ -50,26 +64,65 @@ const fontStyle = (options) => options.fontUrl ? `<style>${fontFaceCss(options.f
50
64
  export function renderChartUnwrapped(text, options = {}) {
51
65
  return `${fontStyle(options)}${chartHtml(text, options)}`;
52
66
  }
67
+ /** What the model is laid out with: the options that change what is drawn. */
68
+ const layoutOptionsOf = (options) => ({
69
+ rehearsalLetters: options.rehearsalLetters ?? false,
70
+ ...(options.part && { part: options.part }),
71
+ ...(options.melody === false && { melody: false }),
72
+ ...(options.chordDiagrams === "guitar" && { chordDiagrams: "guitar" }),
73
+ ...(options.barNumbers === "played" && { barNumbers: "played" }),
74
+ });
53
75
  function chartHtml(text, options) {
54
- const model = layoutChart(text, {
55
- rehearsalLetters: options.rehearsalLetters ?? false,
56
- ...(options.part && { part: options.part }),
57
- ...(options.melody === false && { melody: false }),
58
- ...(options.chordDiagrams === "guitar" && { chordDiagrams: "guitar" }),
59
- });
60
- const barNumbers = options.barNumbers ?? true;
76
+ const model = layoutChart(text, layoutOptionsOf(options));
77
+ const barNumbers = numbersOf(options) !== false;
61
78
  const { parts, widest } = gutterOf(model, options);
79
+ const played = options.barNumbers === "played" ? { widest: playedWidest(model) } : null;
62
80
  const settings = {
63
81
  barNumbers,
82
+ played,
83
+ extra: played ? playedGutterExtra(played.widest, parts ? widest : null) : 0,
64
84
  gutter: barNumbers || parts,
65
85
  numerals: numeralsOf(options),
66
86
  rows: byRow(options),
67
87
  };
68
- const gutter = parts ? ` data-parts style="--bm-label-chars:${widest}"` : "";
69
- return `<div class="bm-chart" data-theme="${themeOf(options)}"${gutter}${layoutAttributes(options, settings)}>${headerHtml(model)}${diagramsHtml(model.diagrams, settings.numerals, handOf(options))}${model.blocks.map((b) => blockHtml(b, settings)).join("")}${copyrightHtml(model)}${options.diagnostics ? diagnosticsHtml(model) : ""}</div>`;
88
+ const blocks = model.blocks.map((b) => blockHtml(b, settings)).join("");
89
+ // Played numbers bring their own rules, so a chart of written numbers is styled as before.
90
+ const own = played ? `<style>${PLAYED_CSS}</style>` : "";
91
+ return `${own}<div class="bm-chart" data-theme="${themeOf(options)}"${gutterAttributes(parts ? widest : null, played)}${layoutAttributes(options, settings)}>${headerHtml(model)}${diagramsHtml(model.diagrams, settings.numerals, handOf(options))}${blocks}${copyrightHtml(model)}${options.diagnostics ? diagnosticsHtml(model) : ""}</div>`;
92
+ }
93
+ /** The widest played numbers any gutter shows, in em of their text: each row's, a system's first row's. */
94
+ function playedWidest(model) {
95
+ let widest = 0;
96
+ for (const b of model.blocks)
97
+ for (const i of b.items) {
98
+ const row = i.kind === "system" ? i.rows.find((p) => p.row.kind === "row")?.row : i;
99
+ if (row?.kind === "row")
100
+ widest = Math.max(widest, gutterWidth(playedText(row)));
101
+ }
102
+ return widest;
103
+ }
104
+ /** What sizes the gutter: the longest part label (null without labels), and the longest played numbers drawn. */
105
+ function gutterAttributes(labels, played) {
106
+ const label = labels === null ? "" : `--bm-label-chars:${labels}`;
107
+ const sizes = played
108
+ ? [label, `--bm-played-width:${Number(played.widest.toFixed(2))}`].filter(Boolean).join(";")
109
+ : label;
110
+ return `${labels === null ? "" : " data-parts"}${sizes ? ` style="${sizes}"` : ""}`;
111
+ }
112
+ /**
113
+ * A row's played numbers as the gutter shows them: up to three passes,
114
+ * `1 · 5 · 9`; four or more, the first and the last, `9 … 37`; `~` before an
115
+ * approximate one. None for a pickup's first pass, as with written numbers.
116
+ */
117
+ function playedText(row) {
118
+ // A pickup's first pass is 0, never shown; a later pass is.
119
+ const passes = (row.playedNumbers ?? []).filter((p) => p.bar !== 0);
120
+ const shown = passes.length > 3 ? [passes[0], passes.at(-1)] : passes;
121
+ const text = (p) => (p ? `${p.approximate ? "~" : ""}${p.bar}` : "");
122
+ return shown.map(text).join(passes.length > 3 ? " … " : " · ");
70
123
  }
71
124
  /** The chart's layout switches the stylesheet reads, each only when it is off its default. */
72
- const layoutAttributes = (options, settings) => `${settings.barNumbers ? "" : ' data-bar-numbers="off"'}${options.wrap === false ? ' data-wrap="off"' : ""}${settings.rows ? ' data-columns="row"' : ""}`;
125
+ const layoutAttributes = (options, settings) => `${settings.played ? ' data-bar-numbers="played"' : settings.barNumbers ? "" : ' data-bar-numbers="off"'}${options.wrap === false ? ' data-wrap="off"' : ""}${settings.rows ? ' data-columns="row"' : ""}`;
73
126
  /** Whether systems have labelled rows: several parts, or one part writing lines (barmark's grammar 7.6). */
74
127
  const labelled = (model) => model.parts.length > 1 || model.parts.some((p) => (p.lines?.length ?? 0) > 0);
75
128
  /**
@@ -203,18 +256,18 @@ function metaHtml(d, beat, labelled = false) {
203
256
  }
204
257
  function blockHtml(block, settings) {
205
258
  const label = block.heading === null ? "" : ` aria-label="${escapeHtml(block.heading)}"`;
206
- return `<section class="bm-section"${label}>${headingHtml(block)}<div class="bm-grid" style="--bm-cols:${Math.max(1, block.columns)}" data-fit="${fitWidth(block, settings.rows)}">${block.items.map((i) => itemHtml(i, block.columns, settings)).join("")}</div></section>`;
259
+ return `<section class="bm-section"${label}>${headingHtml(block)}<div class="bm-grid" style="--bm-cols:${Math.max(1, block.columns)}" data-fit="${fitWidth(block, settings)}">${block.items.map((i) => itemHtml(i, block.columns, settings)).join("")}</div></section>`;
207
260
  }
208
261
  /**
209
262
  * Roughly how many em a section needs, rounded up to a step the stylesheet
210
263
  * knows; narrower than that, its rows wrap. With shared columns that is the
211
264
  * widest cell of each column, added up; with `rows`, the widest row.
212
265
  */
213
- function fitWidth(block, rows) {
266
+ function fitWidth(block, { rows, extra }) {
214
267
  const lines = block.items.map(rowWidths);
215
268
  const sum = (widths) => widths.reduce((a, b) => a + b, 0);
216
269
  const needed = rows ? Math.max(0, ...lines.map(sum)) : sum(widest(lines));
217
- const total = 5 + needed;
270
+ const total = 5 + extra + needed;
218
271
  return FIT_STEPS.find((step) => step >= total) ?? FIT_STEPS.at(-1) ?? 0;
219
272
  }
220
273
  /** Em per cell of a row: its bar, or the words under it when they are wider. None for anything else. */
@@ -307,15 +360,23 @@ function systemHtml(item, columns, settings) {
307
360
  function gutterHtml(row, settings, part) {
308
361
  if (!settings.gutter)
309
362
  return "";
310
- const shown = settings.barNumbers && (!part || part.first) && row.barNumber !== 0;
311
- const number = shown ? (row.barNumber ?? "") : "";
363
+ const lead = settings.barNumbers && (!part || part.first);
364
+ const written = row.barNumber !== 0 ? (row.barNumber ?? "") : "";
365
+ const number = lead ? (settings.played ? playedText(row) : written) : "";
312
366
  const label = part
313
367
  ? `<span class="bm-part-label" part="part-label">${escapeHtml(part.label)}</span>`
314
368
  : "";
315
369
  return `<span class="bm-bar-number" part="bar-number" aria-hidden="true">${label}${number}</span>`;
316
370
  }
317
- /** A row's cells; a tacet row says "tacet" in its first bar. */
318
- function rowCells(row, numerals, ending) {
371
+ /**
372
+ * The em a gutter character takes in a wide system sans (DejaVu Sans
373
+ * measured .64 a digit, .84 `~`, .32 a space or `·`, 1 `…`), a little over,
374
+ * so the estimate is rarely short; when it is, the track still grows.
375
+ */
376
+ const GLYPH_EM = { " ": 0.33, "·": 0.33, "…": 1.02, "~": 0.86 };
377
+ const gutterWidth = (text) => [...text].reduce((w, c) => w + (GLYPH_EM[c] ?? 0.66), 0);
378
+ /** A row's cells; a tacet row says "tacet" in its first bar. Each bar says its own number, or with `played` its own played numbers. */
379
+ function rowCells(row, numerals, ending, played) {
319
380
  let n = row.barNumber;
320
381
  const firstTacet = row.cells.findIndex(isTacetCell);
321
382
  const firstBar = row.cells.findIndex((c) => c.kind === "slots");
@@ -330,9 +391,10 @@ function rowCells(row, numerals, ending) {
330
391
  first: i === firstBar,
331
392
  beats: beatLinesHtml(row.lyrics, i, i === firstBar),
332
393
  };
394
+ const name = played && cell.kind === "slots" ? (cell.playedNumbers ?? []) : n;
333
395
  const html = isTacetCell(cell)
334
- ? tacetHtml(cell, n, marks, i === firstTacet)
335
- : cellHtml(cell, n, marks, numerals, sung);
396
+ ? tacetHtml(cell, name, marks, i === firstTacet)
397
+ : cellHtml(cell, name, marks, numerals, sung);
336
398
  if (n !== null && cell.kind === "slots")
337
399
  n++;
338
400
  return html;
@@ -363,7 +425,7 @@ function rowOpening(row, part, ending) {
363
425
  const leads = (part) => !part || part.first;
364
426
  function rowHtml(row, columns, settings, part) {
365
427
  const label = row.ending && leads(part) ? endingLabel(row.ending) : null;
366
- const cells = rowCells(row, settings.numerals, label ? ` data-ending="${label.shown}"` : "");
428
+ const cells = rowCells(row, settings.numerals, label ? ` data-ending="${label.shown}"` : "", settings.played !== null);
367
429
  const goesOn = row.continues && leads(part) ? `${endingLabel(row.continues).spoken}, continued` : "";
368
430
  const empty = `<span class="bm-empty" aria-hidden="true"></span>`.repeat(Math.max(0, columns - row.cells.length));
369
431
  const said = rowOpening(row, part, label?.spoken ?? goesOn);
package/dist/model.js CHANGED
@@ -8,6 +8,27 @@ import { extractPart, parseChart, printedAsWritten, unreadSlots, } from "barmark
8
8
  import { chartDiagrams } from "./diagrams.js";
9
9
  import { tempoBeatOf, tempoBeats } from "./tempo.js";
10
10
  import { landings, rowVerses, singerOf, sungVerses } from "./verses.js";
11
+ /** The last bar's index among events, starting from `last`. */
12
+ const lastIndex = (events, last) => events.reduce((at, e) => (e.kind === "bar" ? e.bar.index : e.kind === "open" ? lastIndex(e.events, at) : at), last);
13
+ /** The index of the last bar of the first open repeat's pass; every bar when there is none. */
14
+ function exactThrough(events) {
15
+ let last = 0;
16
+ for (const e of events) {
17
+ if (e.kind === "open")
18
+ return lastIndex(e.events, last);
19
+ if (e.kind === "bar")
20
+ last = e.bar.index;
21
+ }
22
+ return Number.POSITIVE_INFINITY;
23
+ }
24
+ const numberingOf = (parse) => ({
25
+ pickup: parse.pickup,
26
+ exactThrough: exactThrough(parse.events),
27
+ });
28
+ const playedNumber = (b, n) => ({
29
+ bar: b.index - (n.pickup ? 1 : 0),
30
+ approximate: b.index > n.exactThrough,
31
+ });
11
32
  /** Models `melody: false` changed the drawing of: the markup sizes its label gutter from the rows drawn only for these. */
12
33
  const meloffModels = new WeakSet();
13
34
  export const meloffChanged = (model) => meloffModels.has(model);
@@ -30,6 +51,78 @@ function indexByLine(bars) {
30
51
  }
31
52
  return out;
32
53
  }
54
+ /** How many bars a bar line writes: its bars and `%`, not its fermatas, directions or rehearsal marks. */
55
+ const barCells = (l) => l.cells.filter((c) => c.kind === "slots" || c.kind === "simile").length;
56
+ /**
57
+ * How many written numbers a line, or a system's lines, take: the rule
58
+ * barmark's `projectPart` (chart/parts.ts) counts by, since each part's
59
+ * stream reads one line per system. A system writes what its reference
60
+ * line writes (`referenceOf`: its first bar line not `dropped`); a part
61
+ * whose own line is dropped plays a stand-in of the reference. With no
62
+ * reference, this counts `unread` of the system's first line: an invalid
63
+ * line's `written`, else none (a system of one dropped line writes none).
64
+ * The parser counts its first stream's own line there, which can differ
65
+ * (FINDINGS, "Known difference left alone"). A line
66
+ * outside a system counts its own: a bar line's bars, an invalid line's
67
+ * `written` (as `expand` adds it).
68
+ */
69
+ function writtenCount(group) {
70
+ const ref = group.find((l) => l.kind === "bars" && !l.dropped);
71
+ if (ref)
72
+ return barCells(ref);
73
+ const first = group[0];
74
+ if (first?.kind === "invalid")
75
+ return first.written;
76
+ return first && systemOf(first) === null ? barCells(first) : 0;
77
+ }
78
+ /**
79
+ * Each bar line's first written number. The parser numbers each written bar
80
+ * once, in written order (`PlayedBar.written`), so a line's bars run on
81
+ * from its first, a system's lines sharing them; but it gives a number only
82
+ * to a bar a pass plays. A line's played bars bound where it starts, and
83
+ * the count of bars written before it settles that when a pass leaves out
84
+ * its first bars (a jump lands after them). A line no pass plays has none.
85
+ */
86
+ function writtenStarts(lines, bars, pickup) {
87
+ const starts = new Map();
88
+ let next = pickup ? 0 : 1;
89
+ for (const group of barGroups(lines)) {
90
+ const n = writtenCount(group);
91
+ const start = startWithin(group, bars, n, next);
92
+ if (start !== null)
93
+ for (const g of group)
94
+ starts.set(g.line, start);
95
+ next = (start ?? next) + n;
96
+ }
97
+ return starts;
98
+ }
99
+ /** The lines that write bars, in written order: a line alone, or a system's lines together. */
100
+ function barGroups(lines) {
101
+ const groups = [];
102
+ for (const [i, l] of lines.entries()) {
103
+ if (l.kind !== "bars" && l.kind !== "invalid")
104
+ continue;
105
+ const system = systemOf(l);
106
+ if (system === null)
107
+ groups.push([l]);
108
+ else if (systemOf(lines[i - 1]) !== system)
109
+ groups.push(systemLines(lines, i));
110
+ }
111
+ return groups;
112
+ }
113
+ /** Where a line of `n` bars starts: `next` if its played bars allow it, else its first played bar; null when none plays. */
114
+ function startWithin(group, bars, n, next) {
115
+ let low = Number.POSITIVE_INFINITY;
116
+ let high = Number.NEGATIVE_INFINITY;
117
+ for (const g of group)
118
+ for (const b of bars.get(g.line) ?? []) {
119
+ low = Math.min(low, b.written);
120
+ high = Math.max(high, b.written);
121
+ }
122
+ if (low > high)
123
+ return null;
124
+ return next <= low && next >= high - n + 1 ? next : low;
125
+ }
33
126
  /** Each part's bars on its own lines, and each line's; a tutti bar once (barmark's grammar 7.4, 7.6). */
34
127
  function barsByLine(parse) {
35
128
  if (parse.parts.length < 2 && !parse.parts.some((p) => p.lines))
@@ -66,16 +159,19 @@ export function layoutChart(text, options = {}) {
66
159
  const parse = parseFor(text, options.part);
67
160
  const { header, body } = splitHeader(parse.lines);
68
161
  const groups = groupLines(body);
162
+ const bars = indexByLine(barsByLine(parse));
69
163
  const ctx = {
70
164
  parse,
71
165
  source: text.split(/\r?\n/),
72
166
  ...errorsByLine(parse),
73
167
  written: new Map(groups.flatMap((g) => (g.heading ? [[g.heading.line, g]] : []))),
74
- bars: indexByLine(barsByLine(parse)),
168
+ bars,
169
+ starts: writtenStarts(parse.lines, bars, parse.pickup),
75
170
  beats: tempoBeats(parse.lines),
76
171
  melody: options.melody !== false,
77
172
  changed: false,
78
173
  melodies: new Map(),
174
+ numbering: options.barNumbers === "played" ? numberingOf(parse) : null,
79
175
  };
80
176
  const blocks = groups.map((g) => layoutGroup(g, ctx));
81
177
  // A chart that writes its own rehearsal marks keeps them alone: letters beside them would mark each place twice.
@@ -188,10 +284,27 @@ function layoutGroup(group, ctx) {
188
284
  ...(broken ? [errorItem(h.line, ctx)] : []),
189
285
  ...(written && occurrence
190
286
  ? layoutReplay(written, group, occurrence, ctx)
191
- : layoutLines(group.lines, occurrence, ctx)),
287
+ : layoutLines(group.lines, drawnOccurrence(h, occurrence, broken), ctx)),
192
288
  ];
193
289
  return blockOf(broken ? null : h, occurrence, items);
194
290
  }
291
+ /** The occurrence a section's rows are laid out in: its heading's, or one that plays nothing when no pass plays the heading. */
292
+ const drawnOccurrence = (h, occurrence, broken) => occurrence ?? (h && !broken ? unplayed(h) : undefined);
293
+ /**
294
+ * A section no pass plays where it is written (a jump passes over it; a
295
+ * replay may play it later): its bars draw as written, from every pass on
296
+ * their lines (no range), and no occurrence of its heading plays them, so
297
+ * they have no played number.
298
+ */
299
+ const unplayed = (h) => ({
300
+ name: h.name,
301
+ line: h.line,
302
+ replayOf: null,
303
+ firstBar: null,
304
+ lastBar: null,
305
+ elided: false,
306
+ form: 0,
307
+ });
195
308
  /**
196
309
  * A replay draws its written section with its own bar numbers. Its own
197
310
  * text lines replace the written section's in order (extra ones follow the
@@ -296,7 +409,7 @@ function layoutSystemOf(written, occurrence, previous, ctx) {
296
409
  const [only] = lines;
297
410
  if (only && lines.length === 1 && loneBare(only, ctx)) {
298
411
  ctx.changed = true;
299
- return layoutOne(only, occurrence, previous, ctx);
412
+ return layoutOne(only, occurrence, previous, ctx, leftOutSingers(written, lines, ctx));
300
413
  }
301
414
  return layoutSystemAt(lines, written, occurrence, previous, ctx);
302
415
  }
@@ -305,6 +418,13 @@ const loneBare = (l, ctx) => ctx.parse.parts.length === 1 &&
305
418
  ctx.parse.parts[0]?.sings !== undefined &&
306
419
  l.lineName === undefined &&
307
420
  !sings(l, ctx);
421
+ /** The parts whose singing line the system's `written` lines lost to `drawn`: their words draw bare of melisma. */
422
+ function leftOutSingers(written, drawn, ctx) {
423
+ if (written.length === drawn.length)
424
+ return new Set();
425
+ const kept = new Set(drawn);
426
+ return new Set(written.flatMap((l) => l.kind === "bars" && !kept.has(l) ? (singerOf(l, ctx.parse) ?? []) : []));
427
+ }
308
428
  /** A line with a problem the grid draws where it is written: as written, or on its unreadable slots. */
309
429
  const flawed = (l, ctx) => ctx.errors.has(l.line) || ctx.unread.has(l.line);
310
430
  const sings = (l, ctx) => l.kind === "bars" && singerOf(l, ctx.parse) !== null;
@@ -349,14 +469,14 @@ function withoutMelody(lines, ctx) {
349
469
  /** A system, and the words under it that no line in it sings; `written` is every line the system writes, drawn or not. */
350
470
  function layoutSystemAt(lines, written, occurrence, previous, ctx) {
351
471
  const item = layoutSystem(lines, written, occurrence, previous, ctx);
352
- const lyrics = lyricRows(lines, occurrence, ctx);
472
+ const lyrics = lyricRows(lines, occurrence, ctx, leftOutSingers(written, lines, ctx));
353
473
  // The words go under the system: in its last row that plays.
354
474
  const last = item.rows.findLastIndex((p) => p.row.kind === "row" && !p.row.cells.some(isTacet));
355
475
  const rows = item.rows.map((p, i) => i === last && p.row.kind === "row" && lyrics.length ? { ...p, row: { ...p.row, lyrics } } : p);
356
476
  return { items: [{ ...item, rows }], previous: lastOfSystem(item) ?? previous };
357
477
  }
358
478
  /** A line outside a system: as written when it has an error; a bar line with the words under it. */
359
- function layoutOne(l, occurrence, previous, ctx) {
479
+ function layoutOne(l, occurrence, previous, ctx, leftOut = new Set()) {
360
480
  if (ctx.errors.has(l.line))
361
481
  return { items: [errorItem(l.line, ctx)], previous };
362
482
  const item = layoutLine(l, occurrence, previous, ctx);
@@ -364,45 +484,81 @@ function layoutOne(l, occurrence, previous, ctx) {
364
484
  return { items: [], previous };
365
485
  if (item.kind !== "row" || l.kind !== "bars")
366
486
  return { items: [item], previous };
367
- const lyrics = lyricRows([l], occurrence, ctx);
487
+ const lyrics = lyricRows([l], occurrence, ctx, leftOut);
368
488
  const row = lyrics.length ? { ...item, lyrics } : item;
369
489
  return { items: [row], previous: lastSlots(item.cells) ?? previous };
370
490
  }
371
491
  /** The written bars a bar line draws, as played in the occurrence: a cut bar as written. */
372
- function landingsOn(l, played, ctx) {
373
- const written = barsOn(l.line, ctx);
374
- let bar = 0;
375
- const bars = l.cells.map((cell) => {
492
+ function landingsOn(l, occurrence, ctx) {
493
+ const played = playedOn(l.line, occurrence, ctx);
494
+ const bars = cellBars(l, played, ctx);
495
+ return landings(bars, sungPasses(l.line, bars, played, occurrence, ctx));
496
+ }
497
+ /**
498
+ * The passes whose words a line draws: its occurrence's, and for a bar no
499
+ * pass there plays, the passes of the occurrences a jump makes of it (a
500
+ * `D.S.` return reaching past a `To Coda` in the row); every pass on the
501
+ * line when its occurrence plays none.
502
+ */
503
+ function sungPasses(line, bars, played, occurrence, ctx) {
504
+ if (!played.length)
505
+ return barsOn(line, ctx);
506
+ const here = new Set(played.map((b) => b.written));
507
+ // Only a row a jump leaves early looks further, so a long chart of replays reads each row once.
508
+ if (bars.every((b) => !b || here.has(b.written)))
509
+ return played;
510
+ const later = heardOn(line, occurrence, ctx).filter((b) => !here.has(b.written));
511
+ return [...played, ...later];
512
+ }
513
+ /** Each written number's first bar among `bars`. */
514
+ function firstByWritten(bars) {
515
+ const out = new Map();
516
+ for (const b of bars)
517
+ if (!out.has(b.written))
518
+ out.set(b.written, b);
519
+ return out;
520
+ }
521
+ /**
522
+ * The bar each cell draws, by its written number (a line's bars run on from
523
+ * its first): its first pass in the occurrence, else the line's first (a
524
+ * cut bar is not played: it draws what it played when written); none for a
525
+ * fermata, a direction or a rehearsal mark, or a bar no pass plays.
526
+ */
527
+ function cellBars(l, played, ctx) {
528
+ const start = ctx.starts.get(l.line);
529
+ if (start === undefined)
530
+ return l.cells.map(() => undefined);
531
+ const here = firstByWritten(played);
532
+ const anywhere = firstByWritten(barsOn(l.line, ctx));
533
+ let written = start;
534
+ return l.cells.map((cell) => {
376
535
  if (cell.kind !== "slots" && cell.kind !== "simile")
377
536
  return undefined;
378
- const i = bar++;
379
- return played[i] ?? written[i];
537
+ const n = written++;
538
+ return here.get(n) ?? anywhere.get(n);
380
539
  });
381
- return landings(bars, played.length ? played : written);
382
540
  }
383
541
  /**
384
542
  * The words under a row or system that no line in it sings under its
385
543
  * slots (barmark's grammar 7.7): a lyric row on no melody, spaced by beat.
386
544
  */
387
- function lyricRows(lines, occurrence, ctx) {
545
+ function lyricRows(lines, occurrence, ctx, leftOut) {
388
546
  const drawn = lines.filter((l) => l.kind === "bars" && !ctx.errors.has(l.line));
389
547
  const ref = drawn[0];
390
548
  if (!ref)
391
549
  return [];
392
550
  const sung = new Set(drawn.flatMap((l) => singerOf(l, ctx.parse) ?? []));
393
- const lands = landingsOn(ref, playedOn(ref.line, occurrence, ctx), ctx);
394
- return rowVerses(lands, sung);
551
+ const lands = landingsOn(ref, occurrence, ctx);
552
+ return rowVerses(lands, sung, leftOut);
395
553
  }
396
554
  const systemOf = (l) => (l?.kind === "bars" || l?.kind === "invalid") && l.system !== undefined ? l.system : null;
397
555
  /** The lines of the system that starts at `i`. */
398
556
  function systemLines(lines, i) {
399
557
  const system = systemOf(lines[i]);
400
558
  const out = [];
401
- for (const l of lines.slice(i)) {
402
- if (systemOf(l) !== system)
403
- break;
404
- out.push(l);
405
- }
559
+ // By index: a slice from `i` would copy the rest of the chart for every system.
560
+ for (let j = i; j < lines.length && systemOf(lines[j]) === system; j++)
561
+ out.push(lines[j]);
406
562
  return out;
407
563
  }
408
564
  const lastOfSystem = (item) => {
@@ -423,10 +579,10 @@ const labelOf = (l) => `${l.part ?? ""}${l.lineName === undefined ? "" : `.${l.l
423
579
  /** A row per declared part, or per line it writes, in score order: its own line, its error, or tacet bars. */
424
580
  function layoutSystem(lines, written, occurrence, previous, ctx) {
425
581
  const ref = lines.find((l) => l.kind === "bars" && !ctx.errors.has(l.line));
426
- const reference = ref ? layoutRow(ref, playedOn(ref.line, occurrence, ctx), previous, ctx) : null;
582
+ const reference = ref ? layoutRow(ref, occurrence, previous, ctx) : null;
427
583
  const ownRow = (own) => ctx.errors.has(own.line) || own.kind !== "bars"
428
584
  ? errorItem(own.line, ctx)
429
- : layoutRow(own, playedOn(own.line, occurrence, ctx), previous, ctx);
585
+ : layoutRow(own, occurrence, previous, ctx);
430
586
  const rows = ctx.parse.parts.flatMap((p) => {
431
587
  const own = ownLines(lines, p);
432
588
  // A part whose every line was left out has no row; one with no line written is tacet.
@@ -458,13 +614,22 @@ const NO_ROW = {
458
614
  /** The system's bars, with nothing played in them (barmark's grammar 7.4). */
459
615
  function tacetRow(reference, line) {
460
616
  const base = reference ?? NO_ROW;
461
- const cells = base.cells.map((c) => c.kind === "slots" ? { kind: "slots", meter: c.meter, slots: [], cut: false, tacet: true } : c);
617
+ const cells = base.cells.map((c) => c.kind === "slots"
618
+ ? {
619
+ kind: "slots",
620
+ meter: c.meter,
621
+ slots: [],
622
+ cut: false,
623
+ tacet: true,
624
+ ...(c.playedNumbers && { playedNumbers: c.playedNumbers }),
625
+ }
626
+ : c);
462
627
  return { ...base, line, cells };
463
628
  }
464
629
  function layoutLine(l, occurrence, previous, ctx) {
465
630
  switch (l.kind) {
466
631
  case "bars":
467
- return layoutRow(l, playedOn(l.line, occurrence, ctx), previous, ctx);
632
+ return layoutRow(l, occurrence, previous, ctx);
468
633
  case "text":
469
634
  return textItem(l.text);
470
635
  case "directive":
@@ -507,36 +672,81 @@ function rowMarks(l) {
507
672
  const marks = { opens: l.opens, closes: l.closes, repeat: l.repeat, ending: l.ending };
508
673
  return l.continues ? { ...marks, continues: l.continues } : marks;
509
674
  }
510
- function layoutRow(l, played, previous, ctx) {
675
+ function layoutRow(l, occurrence, previous, ctx) {
676
+ const played = playedOn(l.line, occurrence, ctx);
677
+ const bars = cellBars(l, played, ctx);
511
678
  const cells = [];
512
- // A cut bar is not played: what it would play is what the line's bar played when written.
513
- const written = barsOn(l.line, ctx);
514
- let bar = 0;
515
679
  let prev = previous;
516
- for (const cell of l.cells) {
517
- const model = layoutCell(cell, played[bar] ?? written[bar], prev);
518
- if (cell.kind === "slots" || cell.kind === "simile")
519
- bar++;
680
+ const partly = ctx.starts.has(l.line);
681
+ for (const [i, cell] of l.cells.entries()) {
682
+ const drawn = layoutCell(cell, bars[i], prev);
683
+ const model = partly && cell.kind === "simile" && !bars[i] ? unplayedSimile(drawn) : drawn;
520
684
  if (model.kind === "slots")
521
685
  prev = model;
522
686
  cells.push(model);
523
687
  }
524
- return {
688
+ const row = {
525
689
  kind: "row",
526
690
  line: l.line,
527
691
  // Numbered as written, as a band counts (issue #92): repeats, endings, jumps and replays don't move it.
528
- barNumber: (played[0] ?? written[0])?.written ?? null,
692
+ barNumber: ctx.starts.get(l.line) ?? null,
529
693
  ...rowMarks(l),
530
694
  cells: withUnread(cells, l, ctx),
531
- ...singing(l, cells, played, ctx),
695
+ ...singing(l, cells, occurrence, ctx),
696
+ };
697
+ return withPlayedNumbers(row, occurrence, ctx);
698
+ }
699
+ /**
700
+ * The bars a line plays in its drawn occurrence: the section occurrence the
701
+ * heading draws and any a jump makes of it (the parser gives a D.S. or D.C.
702
+ * return the same heading line), or every bar on the line before any heading.
703
+ */
704
+ function heardOn(line, occurrence, ctx) {
705
+ const all = barsOn(line, ctx);
706
+ if (!occurrence)
707
+ return all;
708
+ const drawn = ctx.parse.sections.filter((s) => s.line === occurrence.line);
709
+ return all.filter((b) => drawn.some((s) => s.firstBar !== null && s.lastBar !== null && b.index >= s.firstBar && b.index <= s.lastBar));
710
+ }
711
+ /**
712
+ * Played numbers, from the parser's play order: each bar's, a pass each in
713
+ * order, and the row's, its first bar's. A bar is known by its written
714
+ * number, which a line's bars each have once. Written numbers alone leave
715
+ * the row as it is.
716
+ */
717
+ function withPlayedNumbers(row, occurrence, ctx) {
718
+ const { numbering } = ctx;
719
+ if (!numbering)
720
+ return row;
721
+ const byWritten = new Map();
722
+ for (const b of heardOn(row.line, occurrence, ctx)) {
723
+ const list = byWritten.get(b.written);
724
+ if (list)
725
+ list.push(playedNumber(b, numbering));
726
+ else
727
+ byWritten.set(b.written, [playedNumber(b, numbering)]);
728
+ }
729
+ // Written numbers run on along a line, a bar a cell, whichever bars a pass leaves out.
730
+ let written = row.barNumber;
731
+ const cells = row.cells.map((c) => {
732
+ if (c.kind !== "slots")
733
+ return c;
734
+ const at = written === null ? undefined : byWritten.get(written++);
735
+ return { ...c, playedNumbers: at ?? [] };
736
+ });
737
+ const first = cells.find((c) => c.kind === "slots");
738
+ return {
739
+ ...row,
740
+ playedNumbers: first?.kind === "slots" ? (first.playedNumbers ?? []) : [],
741
+ cells,
532
742
  };
533
743
  }
534
744
  /** A singing line's fields: its note sets as pitch names, and the verses under its slots (barmark's grammar 7.7). */
535
- function singing(l, cells, played, ctx) {
745
+ function singing(l, cells, occurrence, ctx) {
536
746
  const singer = singerOf(l, ctx.parse);
537
747
  if (singer === null)
538
748
  return {};
539
- const verses = sungVerses(cells, landingsOn(l, played, ctx), singer);
749
+ const verses = sungVerses(cells, landingsOn(l, occurrence, ctx), singer);
540
750
  // A line with no words draws as any part line does.
541
751
  return verses.length ? { sings: true, verses } : {};
542
752
  }
@@ -551,6 +761,12 @@ function layoutCell(cell, played, previous) {
551
761
  return withPlayed(asWritten(cell, previous), played);
552
762
  return withPlayed(layoutBar(cell, played, previous), played);
553
763
  }
764
+ /**
765
+ * A `%` no pass plays on a line a pass does play (a jump lands past it):
766
+ * the parser resolves `%` only where it plays, so it draws as written, the
767
+ * sign itself, and is spoken as a bar with nothing resolved in it.
768
+ */
769
+ const unplayedSimile = (cell) => cell.kind === "slots" ? { ...cell, slots: [], simile: "unplayed" } : cell;
554
770
  /** A tutti bar as written: its own slots, holds as holds, or `%` itself. */
555
771
  function asWritten(cell, previous) {
556
772
  const bar = layoutBar(cell, undefined, previous);
package/dist/speech.d.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  * parsed structure, never from the symbol's text.
4
4
  */
5
5
  import { type ChordRecord, type Key, type Slot, type Syllable } from "barmark";
6
- import type { CellModel, DiagramEntry } from "./types.js";
6
+ import type { CellModel, DiagramEntry, PlayedNumber } from "./types.js";
7
7
  /** A chord's name; with a key, its degree first: "five, A seven". */
8
8
  export declare function speakChord(record: ChordRecord, key?: Key): string;
9
9
  /** A diagram with no shape, shown in its frame and said in its label. */
@@ -20,10 +20,12 @@ export declare const VOICING_REPLACED = "written voicing doesn't fit standard tu
20
20
  */
21
21
  export declare function speakDiagram(entry: DiagramEntry, key?: Key): string;
22
22
  export declare function speakSlot(slot: Slot, key?: Key): string;
23
- /** What a bar is called aloud: "pickup" for bar 0, "bar" with no number, else "bar 9". */
24
- export declare function barLabel(barNumber: number | null): string;
23
+ /** A bar's number: as written (null when it has none), or its played numbers, one a pass. */
24
+ export type BarName = number | null | readonly PlayedNumber[];
25
+ /** What a bar is called aloud: "pickup" for bar 0, "bar" with no number, else "bar 9"; played numbers as `playedLabel` says them. */
26
+ export declare function barLabel(barNumber: BarName): string;
25
27
  /** "bar 9: G, hold, D, hold"; a pickup (bar 0) says "pickup"; a fermata is held until cued. With `numerals`, each chord's degree comes first. */
26
- export declare function speakBar(barNumber: number | null, cell: CellModel, numerals?: boolean): string;
28
+ export declare function speakBar(barNumber: BarName, cell: CellModel, numerals?: boolean): string;
27
29
  /**
28
30
  * The words on a bar, each verse's: `sung “maz-ing”` (or `words “…”` in a
29
31
  * lyric row on no melody), or with several verses `verse 1 “maz-ing”,
package/dist/speech.js CHANGED
@@ -176,8 +176,45 @@ function speakDirection(d) {
176
176
  return d.kind;
177
177
  return `${d.to === "start" ? "da capo" : "dal segno"}${d.al ? ` al ${d.al}` : ""}`;
178
178
  }
179
- /** What a bar is called aloud: "pickup" for bar 0, "bar" with no number, else "bar 9". */
179
+ const about = (p) => `${p.approximate ? "about " : ""}${p.bar}`;
180
+ const aboutBar = (p) => `${p.approximate ? "about " : ""}bar ${p.bar}`;
181
+ /**
182
+ * Played numbers aloud: "bar 1", "bar 1 and bar 5", "bars 1, 5 and 9",
183
+ * "bars 9 to 37, 8 times"; after a vamp "about bar 11", and with every pass
184
+ * after it "about bars 2, 3 and 4"; the pickup first, "pickup, then bar 2";
185
+ * "bar" when no pass plays it.
186
+ */
187
+ function playedLabel(passes) {
188
+ const [first, ...rest] = passes;
189
+ const last = rest.at(-1);
190
+ if (!first)
191
+ return "bar";
192
+ if (first.bar === 0)
193
+ return rest.length ? `pickup, then ${playedLabel(rest)}` : "pickup";
194
+ if (!last)
195
+ return aboutBar(first);
196
+ if (passes.every((p) => p.approximate))
197
+ return `about ${barsLabel(passes.map((p) => ({ bar: p.bar, approximate: false })))}`;
198
+ if (rest.length === 1)
199
+ return `${aboutBar(first)} and ${aboutBar(last)}`;
200
+ return barsLabel(passes);
201
+ }
202
+ /** Two passes or more as one list: "bars 9 and 10", "bars 1, 5 and 9", "bars 9 to 37, 8 times". */
203
+ function barsLabel(passes) {
204
+ const [first, second, third] = passes;
205
+ const last = passes.at(-1);
206
+ if (!first || !second || !last)
207
+ return "bar";
208
+ if (passes.length === 2)
209
+ return `bars ${about(first)} and ${about(last)}`;
210
+ if (third && passes.length === 3)
211
+ return `bars ${about(first)}, ${about(second)} and ${about(third)}`;
212
+ return `bars ${about(first)} to ${about(last)}, ${passes.length} times`;
213
+ }
214
+ /** What a bar is called aloud: "pickup" for bar 0, "bar" with no number, else "bar 9"; played numbers as `playedLabel` says them. */
180
215
  export function barLabel(barNumber) {
216
+ if (typeof barNumber === "object" && barNumber !== null)
217
+ return playedLabel(barNumber);
181
218
  if (barNumber === 0)
182
219
  return "pickup";
183
220
  return barNumber === null ? "bar" : `bar ${barNumber}`;
@@ -191,7 +228,7 @@ export function speakBar(barNumber, cell, numerals = false) {
191
228
  if (cell.kind === "rehearsal")
192
229
  return `rehearsal ${cell.label}`;
193
230
  const bar = barLabel(barNumber);
194
- if (cell.simile)
231
+ if (cell.simile === true)
195
232
  return `${bar}: each part repeats its bar before`;
196
233
  const meter = cell.meter ? `, in ${cell.meter.n}/${cell.meter.d}` : "";
197
234
  const cut = cell.cut ? ", cut on this pass" : "";
package/dist/styles.d.ts CHANGED
@@ -15,6 +15,13 @@ export declare const PALETTES: {
15
15
  export declare const FIT_STEPS: number[];
16
16
  /** The rules only `columns: "row"` uses, at the stylesheet's end. */
17
17
  export declare const ROW_COLUMNS_CSS: string;
18
+ export declare const PLAYED_CSS: string;
19
+ /**
20
+ * How many chord em the played gutter's minimum is wider than the written
21
+ * gutter, from the numbers' width (`--bm-played-width`) and, with part
22
+ * labels, the longest label's characters: what a section's fit adds.
23
+ */
24
+ export declare function playedGutterExtra(width: number, labels: number | null): number;
18
25
  /** The strip's rules, between the shared rules and the row rules, so a chart drawn without it is styled byte for byte as before. */
19
26
  export declare const DIAGRAMS_CSS: string;
20
27
  export declare const stylesheet: string;
package/dist/styles.js CHANGED
@@ -230,6 +230,44 @@ const minify = (text) => text
230
230
  .replace(/:\s+/g, ":");
231
231
  /** The rules only `columns: "row"` uses, at the stylesheet's end. */
232
232
  export const ROW_COLUMNS_CSS = minify(rowCss);
233
+ /**
234
+ * `barNumbers: "played"`: the gutter is a track that grows to its numbers
235
+ * (`1 · 5 · 9`, `~101 … ~137`), on one line, and at least as wide as the
236
+ * chart's longest row of them needs, estimated from `--bm-played-width` (em
237
+ * of the numbers' text, from `html.ts`), so the sections and wrapped rows
238
+ * still start their bars together. Not in `stylesheet`: played markup
239
+ * carries these rules itself, so a chart of written numbers is styled byte
240
+ * for byte as before.
241
+ *
242
+ * `playedIndent` is that minimum in the em of text at `size`: headings, text
243
+ * lines and directives start where the bars do, as they do with written
244
+ * numbers. Part labels' charts keep the written indent, as they do with
245
+ * written numbers.
246
+ */
247
+ const playedIndent = (size) => `calc(max(${at(SIZES.barNumber, GUTTER)},var(--bm-played-width) * 1em + .5em) * ${Number((SIZES.barNumber / size).toFixed(4))})`;
248
+ const IS_PLAYED = '[data-bar-numbers="played"]';
249
+ const PLAYED = `.bm-chart${IS_PLAYED}`;
250
+ const playedCss = `
251
+ ${PLAYED} .bm-grid,${ROW}${IS_PLAYED} ${OWN}{grid-template-columns:auto ${CELLS}}
252
+ ${PLAYED} .bm-bar-number{width:auto;min-width:max(${at(SIZES.barNumber, GUTTER)},calc(var(--bm-played-width) * 1em + .5em));padding-right:.5em;white-space:nowrap}
253
+ ${PLAYED}[data-parts] .bm-bar-number{min-width:calc(var(--bm-label-chars) * .62em + var(--bm-played-width) * 1em + 1.4em)}
254
+ ${PLAYED}:not([data-parts]) .bm-heading{margin-left:${playedIndent(SIZES.heading)}}
255
+ ${PLAYED}:not([data-parts]) .bm-text{margin-left:${playedIndent(SIZES.text)}}
256
+ ${PLAYED}:not([data-parts]) .bm-directive{margin-left:${playedIndent(SIZES.directive)}}
257
+ `;
258
+ export const PLAYED_CSS = minify(playedCss);
259
+ /**
260
+ * How many chord em the played gutter's minimum is wider than the written
261
+ * gutter, from the numbers' width (`--bm-played-width`) and, with part
262
+ * labels, the longest label's characters: what a section's fit adds.
263
+ */
264
+ export function playedGutterExtra(width, labels) {
265
+ const played = labels === null
266
+ ? SIZES.barNumber * Math.max(GUTTER / SIZES.barNumber, width + 0.5)
267
+ : SIZES.barNumber * (labels * 0.62 + width + 1.4);
268
+ const written = labels === null ? GUTTER : GUTTER + 0.9 + labels * 0.62;
269
+ return Math.max(0, played - written);
270
+ }
233
271
  /**
234
272
  * A chord diagram, in chord sizes. A viewBox unit is 3.5/78 of a chord size,
235
273
  * so strings stand .45em apart in either image. A wide drawing (one with a
package/dist/types.d.ts CHANGED
@@ -18,6 +18,17 @@ export type LayoutOptions = {
18
18
  melody?: boolean;
19
19
  /** Give the model a diagram entry for each chord, as a guitar plays it; off when absent. */
20
20
  chordDiagrams?: "guitar";
21
+ /** `"played"`: give each row and bar its played numbers (`playedNumbers`); written numbers stay as they are. */
22
+ barNumbers?: boolean | "played";
23
+ };
24
+ /**
25
+ * A bar's number in play order (`PlayedBar.index`, a pickup 0 as written):
26
+ * approximate once play has passed an open repeat (`x ...`), whose passes
27
+ * are unknown.
28
+ */
29
+ export type PlayedNumber = {
30
+ bar: number;
31
+ approximate: boolean;
21
32
  };
22
33
  /** What to draw, with every musical decision already made. */
23
34
  export type ChartModel = {
@@ -81,6 +92,8 @@ export type BlockItem = {
81
92
  line: number;
82
93
  /** The written number of the row's first bar (`PlayedBar.written`); a replay shows its section's numbers. Null for a row with no bar. */
83
94
  barNumber: number | null;
95
+ /** With `barNumbers: "played"`: the played number of the row's first bar on each pass of this drawn occurrence, in order; empty when no pass plays it. */
96
+ playedNumbers?: PlayedNumber[];
84
97
  opens: boolean;
85
98
  closes: boolean;
86
99
  repeat: Repeat;
@@ -157,10 +170,16 @@ export type CellModel = {
157
170
  words?: Words[];
158
171
  /** A bar where the part rests, in a system (barmark's grammar 7.4). */
159
172
  tacet?: true;
160
- /** `%` on a tutti line whose parts each copy a different bar: drawn as `%`, its slots empty (barmark's grammar 7.4). */
161
- simile?: true;
173
+ /**
174
+ * Drawn as `%`, its slots empty: `true` on a tutti line whose parts each
175
+ * copy a different bar (barmark's grammar 7.4); `"unplayed"` where no
176
+ * pass plays it, on a line a pass does play.
177
+ */
178
+ simile?: true | "unplayed";
162
179
  /** The error message of each slot written here that can't be read, in order (barmark's grammar 2.3); absent when none. */
163
180
  unread?: string[];
181
+ /** With `barNumbers: "played"`: this bar's played number on each pass, as the row's `playedNumbers`. */
182
+ playedNumbers?: PlayedNumber[];
164
183
  } | {
165
184
  kind: "fermata";
166
185
  }
package/dist/verses.d.ts CHANGED
@@ -30,6 +30,10 @@ export declare function singerOf(l: BarsLine, parse: ChartParse): string | null;
30
30
  export declare function landings(bars: (PlayedBar | undefined)[], passes: PlayedBar[]): Landing[];
31
31
  /** The verses a singing line's part sings over its bars, each syllable under its slot. */
32
32
  export declare function sungVerses(cells: CellModel[], lands: Landing[], key: string): Verse[];
33
- /** The verses no row sings under its slots: the chart's words, or a singer's with no melody here, by beat. */
34
- export declare function rowVerses(lands: Landing[], sung: Set<string>): Verse[];
33
+ /**
34
+ * The verses no row sings under its slots: the chart's words, or a singer's
35
+ * with no melody here, by beat. A singer in `leftOut` had its melody left
36
+ * out of the system (`melody: false`): its melisma's held places take no step.
37
+ */
38
+ export declare function rowVerses(lands: Landing[], sung: Set<string>, leftOut?: Set<string>): Verse[];
35
39
  export {};
package/dist/verses.js CHANGED
@@ -150,11 +150,12 @@ function stepsFor(fractions) {
150
150
  return n;
151
151
  return MAX_STEPS;
152
152
  }
153
- /** A verse's syllables in a bar on its beats: equal steps, each syllable at its onset's. */
154
- function onBeats(landing, key, verse) {
153
+ /** A verse's syllables in a bar on its beats: equal steps, each syllable at its onset's; with `bare`, a held place is not one. */
154
+ function onBeats(landing, key, verse, bare) {
155
155
  if (!landing)
156
156
  return [];
157
- const sung = verseIn(landing, key, verse);
157
+ const heard = verseIn(landing, key, verse);
158
+ const sung = bare ? heard.filter((s) => s.syllable.kind !== "held") : heard;
158
159
  const length = barLength(landing.bar.meter);
159
160
  const steps = stepsFor(sung.map((s) => s.at / length));
160
161
  const out = Array.from({ length: steps }, () => []);
@@ -162,10 +163,18 @@ function onBeats(landing, key, verse) {
162
163
  out[Math.min(steps - 1, Math.round((s.at / length) * steps))]?.push(s.syllable);
163
164
  return out;
164
165
  }
165
- /** The verses no row sings under its slots: the chart's words, or a singer's with no melody here, by beat. */
166
- export function rowVerses(lands, sung) {
167
- return versesOf(lands, (k) => !sung.has(k)).map(([key, verse]) => ({
166
+ /**
167
+ * The verses no row sings under its slots: the chart's words, or a singer's
168
+ * with no melody here, by beat. A singer in `leftOut` had its melody left
169
+ * out of the system (`melody: false`): its melisma's held places take no step.
170
+ */
171
+ export function rowVerses(lands, sung, leftOut = new Set()) {
172
+ return versesOf(lands, (k) => !sung.has(k))
173
+ .filter(([key, verse]) => !leftOut.has(key) || sounds(lands, key, verse))
174
+ .map(([key, verse]) => ({
168
175
  verse,
169
- cells: lands.map((l) => onBeats(l, key, verse)),
176
+ cells: lands.map((l) => onBeats(l, key, verse, leftOut.has(key))),
170
177
  }));
171
178
  }
179
+ /** Whether a verse has a syllable that is not held somewhere in the row: one that only holds draws nothing bare. */
180
+ const sounds = (lands, key, verse) => lands.some((l) => verseIn(l, key, verse).some((s) => s.syllable.kind !== "held"));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@barmark/render",
3
- "version": "0.21.0",
3
+ "version": "0.22.0",
4
4
  "description": "Render barmark chord charts as a clean, accessible bar grid: HTML with Declarative Shadow DOM, or the <barmark-chart> web component.",
5
5
  "type": "module",
6
6
  "exports": {