@barmark/render 0.19.0 → 0.20.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,41 @@ package uses [semantic versioning](https://semver.org/).
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.20.0] - 2026-11-13
10
+
11
+ ### Added
12
+
13
+ - **Chord diagrams.** `chordDiagrams: "guitar"` draws a strip of guitar chord
14
+ diagrams after the header, one for each distinct chord in written order,
15
+ with its name (and, with `numerals`, its degree) beneath; `diagramHand:
16
+ "left"` mirrors the strings for a left hand. `<barmark-chart>` takes them
17
+ as the `chord-diagrams="guitar"` and `diagram-hand="left"` attributes, with
18
+ the `chordDiagrams` and `diagramHand` properties, and `renderChart` writes
19
+ both back on the element it returns. The strip has the `::part()` names
20
+ `diagrams` and `diagram`, follows the chart's palette, light, dark and
21
+ print, and takes the system text colour in forced-colours mode. Each
22
+ diagram is labelled for a screen reader: the chord, then its strings low to
23
+ high; one that replaced a written voicing names the chord and its strings,
24
+ then says the written voicing doesn't fit. `layoutChart`'s model gains
25
+ `diagrams` (empty unless the option is on). With the option off a chart
26
+ renders as before. Requires `@barmark/fretboard` 0.1.0. It adds about
27
+ 6.6 KB gzipped to the element (6,558 bytes on 46,302).
28
+
29
+ ### Changed
30
+
31
+ - **Unbundled pages: add `@barmark/fretboard` to the import map.** The
32
+ package imports it whether or not diagrams are on.
33
+
34
+ ## [0.19.1] - 2026-11-12
35
+
36
+ ### Fixed
37
+
38
+ - **A chart whose composer is "Traditional"** (or "Trad.", "Traditional, 16th
39
+ century") now prints that credit as written, not "Music by
40
+ Traditional"; the same name for words and music prints once, as written,
41
+ not "Words and music by Traditional". A real name, or one that only starts with "Trad", still
42
+ reads "Music by …"; the lyricist and arranger lines are unchanged.
43
+
9
44
  ## [0.19.0] - 2026-11-10
10
45
 
11
46
  ### Added
@@ -525,7 +560,9 @@ that needs no script or as the `<barmark-chart>` web component. Requires
525
560
  zoom without sideways scrolling, the element renders and re-renders, and
526
561
  a screen reader hears "bar 9: D". Run them with `bun run test:browser`.
527
562
 
528
- [Unreleased]: https://github.com/kevinpeckham/barmark/compare/render-v0.19.0...HEAD
563
+ [Unreleased]: https://github.com/kevinpeckham/barmark/compare/render-v0.20.0...HEAD
564
+ [0.20.0]: https://github.com/kevinpeckham/barmark/compare/render-v0.19.1...render-v0.20.0
565
+ [0.19.1]: https://github.com/kevinpeckham/barmark/compare/render-v0.19.0...render-v0.19.1
529
566
  [0.19.0]: https://github.com/kevinpeckham/barmark/compare/render-v0.18.0...render-v0.19.0
530
567
  [0.18.0]: https://github.com/kevinpeckham/barmark/compare/render-v0.17.1...render-v0.18.0
531
568
  [0.17.1]: https://github.com/kevinpeckham/barmark/compare/render-v0.17.0...render-v0.17.1
package/README.md CHANGED
@@ -30,6 +30,10 @@ themselves.
30
30
 
31
31
  ## As a web component
32
32
 
33
+ Without a bundler, the page's import map must also map `@barmark/fretboard`
34
+ (beside `barmark`): the package imports it whether or not diagrams are on,
35
+ so without it neither the element nor `renderChart` loads.
36
+
33
37
  ```html
34
38
  <script type="module">import "@barmark/render/element";</script>
35
39
 
@@ -49,8 +53,8 @@ whenever one changes; it fetches a `src` once, and renders once however
49
53
  many properties and attributes change together. A chart rendered on the
50
54
  server by `renderChart` keeps its music until it has a source of its own,
51
55
  and still follows `theme`, `bar-numbers`, `wrap` and `columns`; a change to
52
- `numerals`, `rehearsal-letters` or `show-part` needs the chart's text, so
53
- it waits for a source.
56
+ `numerals`, `rehearsal-letters`, `show-part`, `chord-diagrams` or
57
+ `diagram-hand` needs the chart's text, so it waits for a source.
54
58
 
55
59
  For a live editor, set `text`:
56
60
 
@@ -81,6 +85,8 @@ the element loads, with `<style data-barmark-font>` holding
81
85
  | `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 |
82
86
  | `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"` |
83
87
  | `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 |
88
+ | `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 |
89
+ | `diagramHand` | `diagram-hand="left"` (`diagramHand`) | `"right"` | `"left"` mirrors the diagrams for a left hand: the low string on the right. Any other value is right |
84
90
  | `diagnostics` | | `false` | list the chart's errors and warnings below it |
85
91
  | `fontUrl` | | none | emit Edwin's `@font-face` rule before the chart |
86
92
  | (the `text` argument) | (`text`) | `null` | the chart to draw; wins over `src` and the script child |
@@ -119,6 +125,45 @@ A bar with no key, note sets, N.C., `?` and `--` look as they always
119
125
  do, and a screen reader hears both: "bar 5: five, A seven". Numbered
120
126
  chords carry `data-numeral`. It's a view: the music and bar numbers don't change.
121
127
 
128
+ ### Chord diagrams
129
+
130
+ With `chordDiagrams: "guitar"` (or `chord-diagrams="guitar"` on the
131
+ element), a strip of guitar chord diagrams follows the header: one for
132
+ each distinct chord, in the order the chart first writes it, wrapping to
133
+ as many rows as the width needs. The shapes come from
134
+ [`@barmark/fretboard`](https://github.com/kevinpeckham/barmark/tree/main/packages/fretboard#readme)
135
+ (see its README for what it cannot find); this package draws them and
136
+ copies none. Under each diagram is the chord's name in letters; with
137
+ `numerals` on, its degree sits beneath, in the key where the chord first
138
+ appears. A chord with no shape in standard tuning says so instead of a
139
+ drawing.
140
+
141
+ ```js
142
+ renderChart("key: C\n| C | Am7 | {E4 A4 C#5 E5} |", { chordDiagrams: "guitar", numerals: "nashville" });
143
+ // <barmark-chart numerals="nashville" chord-diagrams="guitar"><template shadowrootmode="open">…
144
+ // diagram 1: aria-label "one, C: muted, 3, 2, open, 1, open"
145
+ // diagram 3: aria-label "notes E four, A four, C sharp five, E five: muted, muted, 14, 14, 14, 12"
146
+ ```
147
+
148
+ A voicing the chart writes is shown exactly when it fits standard tuning
149
+ (a note set is a diagram of those notes); when it does not, the diagram
150
+ shows the chord's own shape and a note saying the written voicing does
151
+ not fit. `diagramHand: "left"` writes `diagram-hand="left"` on the
152
+ element and mirrors the strings only: the low string is drawn on the
153
+ right and a fret number stays at the left. Each diagram has a label that
154
+ speaks the strings, low to high ("muted, 3, 2, open, 1, open"). Style the
155
+ strip through `::part(diagrams)` (the strip) and `::part(diagram)` (one
156
+ chord's diagram, its name and note). A chord's name in the strip carries
157
+ the same `chord` part as the names in the grid, so one `::part(chord)` rule
158
+ styles both (a note set's name in the strip does not). The dots and
159
+ strings follow the chart's colours, light, dark and print, and take the
160
+ system text colour in forced-colours mode. It is a view: the chart's music and bar numbers do not
161
+ change, and with the option off a chart renders as it always did.
162
+
163
+ The strip adds about 6.6 KB gzipped to the element (most of it the shape
164
+ finder). On a chart rendered on the server, setting `chord-diagrams` later
165
+ needs the chart's text, as the web component section says for `numerals`.
166
+
122
167
  ### Spoken names
123
168
 
124
169
  `speakChord(record, key?)` gives a chord the name a screen reader hears
@@ -165,7 +210,7 @@ barmark-chart::part(heading) {
165
210
  ```
166
211
 
167
212
  `::part()` names: `title`, `meta`, `heading`, `bar`, `chord`, `text`,
168
- `bar-number`, `rehearsal`, `lyrics` (each verse's line of words, inside
213
+ `bar-number`, `rehearsal`, `diagrams`, `diagram`, `lyrics` (each verse's line of words, inside
169
214
  its `bar`), `unread` (a slot that can't be read, drawn as written). These, the custom properties and the
170
215
  attributes are the public surface: changing them is a breaking change.
171
216
 
package/dist/credits.js CHANGED
@@ -5,14 +5,21 @@ function names(list) {
5
5
  return `${list.slice(0, -1).join(", ")} and ${list.at(-1)}`;
6
6
  }
7
7
  const same = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
8
+ /** "Traditional", "Trad.", "Traditional, 16th century": already a credit, so no "Music by". */
9
+ const traditional = /^trad(\.|itional\b)/i;
8
10
  /** The header's credit lines, as a score sets them; the copyright goes to the foot. */
9
11
  export function creditsText(credits) {
10
12
  const { composer, lyricist, arranger } = credits;
11
13
  const lines = [];
12
- if (composer.length > 0 && same(composer, lyricist))
14
+ const asWritten = composer.length === 1 && traditional.test(composer[0]);
15
+ if (asWritten && same(composer, lyricist))
16
+ lines.push(composer[0]);
17
+ else if (composer.length > 0 && same(composer, lyricist))
13
18
  lines.push(`Words and music by ${names(composer)}`);
14
19
  else {
15
- if (composer.length > 0)
20
+ if (asWritten)
21
+ lines.push(composer[0]);
22
+ else if (composer.length > 0)
16
23
  lines.push(`Music by ${names(composer)}`);
17
24
  if (lyricist.length > 0)
18
25
  lines.push(`Words by ${names(lyricist)}`);
@@ -0,0 +1,21 @@
1
+ /**
2
+ * One guitar chord diagram as inline SVG (design 5.3, 5.5): six strings,
3
+ * five fret spaces, a dot for each fretted string, a bar for a barre, `×`
4
+ * and `○` above the nut. Colours and strokes come from the stylesheet's
5
+ * classes, so themes, forced colours and print apply.
6
+ */
7
+ import type { Shape } from "@barmark/fretboard";
8
+ /** The two viewBoxes' widths, the room the wide one adds for the fret number, and their height. */
9
+ export declare const DIAGRAM_VIEW: {
10
+ narrow: number;
11
+ wide: number;
12
+ label: number;
13
+ height: number;
14
+ };
15
+ /**
16
+ * A shape as one `<svg role="img">` named by `label`: narrow in first
17
+ * position, wide (`bm-dg-fr`) with a fret number. Left-handed mirrors the
18
+ * strings only: the low string is drawn on the right, and the fret number
19
+ * stays at the left.
20
+ */
21
+ export declare function diagramSvg(shape: Shape, hand: "right" | "left", label: string): string;
@@ -0,0 +1,85 @@
1
+ import { escapeHtml } from "./escape.js";
2
+ /**
3
+ * The drawing, in the viewBox's units: strings 10 apart from x 41 (room at
4
+ * the left for a fret number as wide as `15fr`), fret lines 12 apart from
5
+ * y 13 (room above for the open and muted marks), dots 76% of a string's
6
+ * spacing across. The fret number is 13 units tall and ends 2 units short
7
+ * of a dot or barre on the first string. A drawing with no fret number is
8
+ * a narrow image, 5 units either side of the strings; one with a fret
9
+ * number is wider by the room at the left, with the same coordinates.
10
+ */
11
+ const STRING = { first: 41, gap: 10 };
12
+ const FRET = { top: 13, gap: 12 };
13
+ const DOT = 3.8;
14
+ const MARK = { y: 5, size: 2.8 };
15
+ const LABEL = { size: 13, gap: 2 };
16
+ const LAST = STRING.first + 5 * STRING.gap;
17
+ const SIDE = 5;
18
+ /** The two viewBoxes' widths, the room the wide one adds for the fret number, and their height. */
19
+ export const DIAGRAM_VIEW = {
20
+ narrow: LAST - STRING.first + 2 * SIDE,
21
+ wide: LAST + SIDE,
22
+ label: STRING.first - SIDE,
23
+ height: 75,
24
+ };
25
+ const n = (v) => String(Math.round(v * 10) / 10);
26
+ const range = (count) => Array.from({ length: count }, (_, i) => i);
27
+ /** The strings and fret lines: the same for either hand. */
28
+ const GRID = `<path class="bm-dg-grid" d="${[
29
+ ...range(6).map((i) => `M${STRING.first + i * STRING.gap} ${FRET.top}v${5 * FRET.gap}`),
30
+ ...range(6).map((k) => `M${STRING.first} ${FRET.top + k * FRET.gap}h${5 * STRING.gap}`),
31
+ ].join("")}"/>`;
32
+ /** First position: a thick nut over the top fret line. */
33
+ const NUT = `<rect class="bm-dg-nut" x="${STRING.first - 0.5}" y="${FRET.top - 3.5}" width="${5 * STRING.gap + 1}" height="4"/>`;
34
+ /** A string's x: low string at the left right-handed, at the right left-handed. */
35
+ const stringX = (i, hand) => hand === "left" ? LAST - i * STRING.gap : STRING.first + i * STRING.gap;
36
+ /** The middle of fret space `space` (1 to 5), counted from the shape's base. */
37
+ const spaceY = (space) => FRET.top + space * FRET.gap - FRET.gap / 2;
38
+ /** `×` over a muted string, `○` over an open one. */
39
+ function markSvg(fret, x) {
40
+ if (fret < 0) {
41
+ const s = MARK.size;
42
+ return `<path class="bm-dg-mark" d="M${n(x - s)} ${n(MARK.y - s)}l${2 * s} ${2 * s}m0-${2 * s}l-${2 * s} ${2 * s}"/>`;
43
+ }
44
+ return fret === 0
45
+ ? `<circle class="bm-dg-mark" cx="${n(x)}" cy="${MARK.y}" r="${MARK.size}"/>`
46
+ : "";
47
+ }
48
+ /** The barre: one rounded bar across its strings, at its fret. */
49
+ function barreSvg(shape, hand) {
50
+ const { barre } = shape;
51
+ if (!barre)
52
+ return "";
53
+ const ends = [stringX(barre.from, hand), stringX(barre.to, hand)];
54
+ const [lo, hi] = [Math.min(...ends), Math.max(...ends)];
55
+ const y = spaceY(barre.fret - shape.base + 1);
56
+ return `<rect class="bm-dg-barre" x="${n(lo - DOT)}" y="${n(y - DOT)}" width="${n(hi - lo + 2 * DOT)}" height="${n(2 * DOT)}" rx="${DOT}"/>`;
57
+ }
58
+ /** Whether string `i`'s note is held by the barre, so it gets no dot of its own. */
59
+ const underBarre = (shape, i) => {
60
+ const b = shape.barre;
61
+ return b !== undefined && shape.frets[i] === b.fret && i >= b.from && i <= b.to;
62
+ };
63
+ /** A dot on each fretted string the barre does not hold. */
64
+ const dotsSvg = (shape, hand) => shape.frets
65
+ .map((fret, i) => fret > 0 && !underBarre(shape, i)
66
+ ? `<circle class="bm-dg-dot" cx="${n(stringX(i, hand))}" cy="${n(spaceY(fret - shape.base + 1))}" r="${DOT}"/>`
67
+ : "")
68
+ .join("");
69
+ /** The nut in first position, else the first fret drawn, at the left beside the first space. */
70
+ const topSvg = (base) => base === 1
71
+ ? NUT
72
+ : `<text class="bm-dg-fret" x="${n(STRING.first - DOT - LABEL.gap)}" y="${n(spaceY(1) + 4.5)}" font-size="${LABEL.size}">${escapeHtml(`${base}fr`)}</text>`;
73
+ /**
74
+ * A shape as one `<svg role="img">` named by `label`: narrow in first
75
+ * position, wide (`bm-dg-fr`) with a fret number. Left-handed mirrors the
76
+ * strings only: the low string is drawn on the right, and the fret number
77
+ * stays at the left.
78
+ */
79
+ export function diagramSvg(shape, hand, label) {
80
+ const marks = shape.frets.map((fret, i) => markSvg(fret, stringX(i, hand))).join("");
81
+ const [wide, x, w] = shape.base === 1
82
+ ? ["", DIAGRAM_VIEW.label, DIAGRAM_VIEW.narrow]
83
+ : [" bm-dg-fr", 0, DIAGRAM_VIEW.wide];
84
+ return `<svg class="bm-diagram-svg${wide}" role="img" aria-label="${escapeHtml(label)}" viewBox="${x} 0 ${w} ${DIAGRAM_VIEW.height}">${GRID}${topSvg(shape.base)}${marks}${barreSvg(shape, hand)}${dotsSvg(shape, hand)}</svg>`;
85
+ }
@@ -0,0 +1,11 @@
1
+ import type { ChartParse } from "barmark";
2
+ import type { DiagramEntry, SectionBlock } from "./types.js";
3
+ /**
4
+ * The chart's chords as diagram entries: one for each distinct chord (a
5
+ * name, or a note set, with its written voicing), in written order, with
6
+ * the key in force where it first appears. A replay, a `%` and a later
7
+ * appearance add nothing. A line that is not its part's first gives none
8
+ * (7.6), and a note set on a singing line is melody, so it gives none (7.7);
9
+ * a chord name there is harmony and does.
10
+ */
11
+ export declare function chartDiagrams(blocks: SectionBlock[], parse: ChartParse): DiagramEntry[];
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Which chords of a chart get a diagram (design 4.2, 4.3, 5.2), and the
3
+ * shape `@barmark/fretboard` gives each. Nothing here draws.
4
+ */
5
+ import { shapeFor } from "@barmark/fretboard";
6
+ import { partOf, singerOf } from "./verses.js";
7
+ /** The rows of a block's items, in written order: a row, or each row of a system that has one. */
8
+ const rowsOf = (item) => item.kind === "row"
9
+ ? [item]
10
+ : item.kind === "system"
11
+ ? item.rows.flatMap((p) => (p.row.kind === "row" ? [p.row] : []))
12
+ : [];
13
+ /** The chords a slot writes: a group's members each. */
14
+ const chordsIn = (slot) => (slot.kind === "group" ? slot.members : [slot]);
15
+ /** One entry for a chord as written, or none: a single note is no chord. */
16
+ function entryFor(chord, voicing, key) {
17
+ const found = shapeFor(chord, voicing ?? undefined);
18
+ if (found.ok)
19
+ return { chord, voicing, key, shape: found.shape, caveat: found.caveat };
20
+ if (found.reason === "single-note")
21
+ return null;
22
+ return { chord, voicing, key, shape: null, caveat: null };
23
+ }
24
+ /** The lines that carry the harmony where they play: the parser's answer, the first line of each part playing in a played bar (barmark's grammar 7.6). */
25
+ function harmonyLines(parse) {
26
+ return new Set(parse.bars.flatMap((b) => [
27
+ ...(b.parts ?? []).flatMap((p) => (p ? [p.line] : [])),
28
+ ...(b.lines?.[0] ? [b.lines[0].line] : []),
29
+ ]));
30
+ }
31
+ /** Each bar line's role, by its line number. */
32
+ function rolesOf(parse) {
33
+ const harmony = harmonyLines(parse);
34
+ // A line of a part that writes no other line is its first.
35
+ const isFirst = (l) => {
36
+ const p = partOf(l, parse);
37
+ return !p?.lines || harmony.has(l.line);
38
+ };
39
+ return new Map(parse.lines.flatMap((l) => l.kind === "bars"
40
+ ? [[l.line, { first: isFirst(l), singing: singerOf(l, parse) !== null }]]
41
+ : []));
42
+ }
43
+ /** The chord slots of a row that may give an entry, each with the key of its bar: a note set on a singing line is melody (7.7). */
44
+ function candidates(row, role) {
45
+ return row.cells.flatMap((cell) => cell.kind === "slots"
46
+ ? cell.slots
47
+ .flatMap(chordsIn)
48
+ .flatMap((slot) => slot.kind !== "chord" || (role?.singing && slot.chord.kind === "notes")
49
+ ? []
50
+ : [{ slot, key: cell.key ?? null }])
51
+ : []);
52
+ }
53
+ /**
54
+ * The chart's chords as diagram entries: one for each distinct chord (a
55
+ * name, or a note set, with its written voicing), in written order, with
56
+ * the key in force where it first appears. A replay, a `%` and a later
57
+ * appearance add nothing. A line that is not its part's first gives none
58
+ * (7.6), and a note set on a singing line is melody, so it gives none (7.7);
59
+ * a chord name there is harmony and does.
60
+ */
61
+ export function chartDiagrams(blocks, parse) {
62
+ const roles = rolesOf(parse);
63
+ const seen = new Set();
64
+ const entries = [];
65
+ for (const row of blocks.flatMap((b) => b.items.flatMap(rowsOf))) {
66
+ const role = roles.get(row.line);
67
+ if (role && !role.first)
68
+ continue;
69
+ for (const { slot, key } of candidates(row, role)) {
70
+ const voicing = slot.voicing ?? null;
71
+ const id = `${slot.chord.canonical}\n${voicing?.canonical ?? ""}`;
72
+ if (seen.has(id))
73
+ continue;
74
+ seen.add(id);
75
+ const entry = entryFor(slot.chord, voicing, key);
76
+ if (entry)
77
+ entries.push(entry);
78
+ }
79
+ }
80
+ return entries;
81
+ }
package/dist/element.js CHANGED
@@ -7,11 +7,14 @@
7
7
  import { NUMERALS } from "./chord.js";
8
8
  import { FONT_FAMILY, fontFaceCss } from "./font.js";
9
9
  import { loadErrorContent, shadowContent, THEMES, } from "./html.js";
10
+ const HANDS = ["left", "right"];
10
11
  export function optionsFromAttributes(el) {
11
12
  const theme = el.getAttribute("theme");
12
13
  const numerals = NUMERALS.find((n) => n === el.getAttribute("numerals"));
13
14
  // Not `part`: that global attribute names an element for ::part() styling.
14
15
  const part = el.getAttribute("show-part");
16
+ const diagrams = el.getAttribute("chord-diagrams") === "guitar";
17
+ const hand = HANDS.find((h) => h === el.getAttribute("diagram-hand"));
15
18
  return {
16
19
  theme: THEMES.find((t) => t === theme) ?? "auto",
17
20
  barNumbers: el.getAttribute("bar-numbers") !== "off",
@@ -19,6 +22,8 @@ export function optionsFromAttributes(el) {
19
22
  wrap: el.getAttribute("wrap") !== "off",
20
23
  ...(numerals ? { numerals } : {}),
21
24
  ...(part ? { part } : {}),
25
+ ...(diagrams ? { chordDiagrams: "guitar" } : {}),
26
+ ...(hand ? { diagramHand: hand } : {}),
22
27
  // Only "row" changes the layout; anything else, or none, keeps the shared columns.
23
28
  ...(el.getAttribute("columns") === "row" ? { columns: "row" } : {}),
24
29
  };
@@ -63,6 +68,8 @@ function defineElement() {
63
68
  "wrap",
64
69
  "show-part",
65
70
  "columns",
71
+ "chord-diagrams",
72
+ "diagram-hand",
66
73
  ];
67
74
  #observer = new MutationObserver(() => this.#schedule());
68
75
  #renders = 0;
@@ -153,6 +160,26 @@ function defineElement() {
153
160
  else
154
161
  this.removeAttribute("columns");
155
162
  }
163
+ /** "guitar" when the chart draws its chords as guitar diagrams, else null. */
164
+ get chordDiagrams() {
165
+ return optionsFromAttributes(this).chordDiagrams ?? null;
166
+ }
167
+ set chordDiagrams(v) {
168
+ if (v === null)
169
+ this.removeAttribute("chord-diagrams");
170
+ else
171
+ this.setAttribute("chord-diagrams", v);
172
+ }
173
+ /** "left" when the diagrams are drawn for a left hand; "right", the default, otherwise. */
174
+ get diagramHand() {
175
+ return optionsFromAttributes(this).diagramHand ?? "right";
176
+ }
177
+ set diagramHand(v) {
178
+ if (v === "left")
179
+ this.setAttribute("diagram-hand", "left");
180
+ else
181
+ this.removeAttribute("diagram-hand");
182
+ }
156
183
  /** The label of the part to draw on its own, or null for the whole chart. */
157
184
  get showPart() {
158
185
  return this.getAttribute("show-part");
package/dist/html.d.ts CHANGED
@@ -30,6 +30,13 @@ export type RenderOptions = {
30
30
  * `"shared"`.
31
31
  */
32
32
  columns?: Columns;
33
+ /**
34
+ * A strip of guitar chord diagrams after the header: one for each distinct
35
+ * chord, in written order. Off when absent; any other value is off.
36
+ */
37
+ chordDiagrams?: "guitar";
38
+ /** The diagrams' hand: `"left"` mirrors the strings, low string on the right. Any other value is right. */
39
+ diagramHand?: "right" | "left";
33
40
  };
34
41
  export type Columns = "shared" | "row";
35
42
  export declare function renderChart(text: string, options?: RenderOptions): string;
package/dist/html.js CHANGED
@@ -6,10 +6,11 @@
6
6
  import { printDirection, printPasses, } from "barmark";
7
7
  import { glyphs, NUMERALS, splitPitch, typesetChord, typesetNumeral, } from "./chord.js";
8
8
  import { creditsText } from "./credits.js";
9
+ import { diagramSvg } from "./diagram.js";
9
10
  import { escapeHtml } from "./escape.js";
10
11
  import { fontFaceCss } from "./font.js";
11
12
  import { isTacet as isTacetCell, layoutChart } from "./model.js";
12
- import { barLabel, speakBar, speakVerses } from "./speech.js";
13
+ import { barLabel, speakBar, speakDiagram, speakVerses, UNPLAYABLE, VOICING_REPLACED, } from "./speech.js";
13
14
  import { FIT_STEPS, MIN_BAR, stylesheet } from "./styles.js";
14
15
  import { beatLinesHtml, pitchHtml, sungBar, sungSlotHtml, verseNumbersHtml, verseWidth, } from "./verses-html.js";
15
16
  export function renderChart(text, options = {}) {
@@ -26,8 +27,14 @@ function elementAttributes(options) {
26
27
  options.wrap === false ? ' wrap="off"' : "",
27
28
  options.part ? ` show-part="${escapeHtml(options.part)}"` : "",
28
29
  byRow(options) ? ' columns="row"' : "",
30
+ diagramAttributes(options),
29
31
  ].join("");
30
32
  }
33
+ /** The chord diagrams' attributes: only the values the element reads. */
34
+ function diagramAttributes(options) {
35
+ const guitar = options.chordDiagrams === "guitar" ? ' chord-diagrams="guitar"' : "";
36
+ return `${guitar}${options.diagramHand === "left" ? ' diagram-hand="left"' : ""}`;
37
+ }
31
38
  export const THEMES = ["auto", "light", "dark"];
32
39
  /** Only a known theme reaches the markup: hosts may pass any string through. */
33
40
  const themeOf = (options) => THEMES.find((t) => t === options.theme) ?? "auto";
@@ -46,6 +53,7 @@ function chartHtml(text, options) {
46
53
  const model = layoutChart(text, {
47
54
  rehearsalLetters: options.rehearsalLetters ?? false,
48
55
  ...(options.part && { part: options.part }),
56
+ ...(options.chordDiagrams === "guitar" && { chordDiagrams: "guitar" }),
49
57
  });
50
58
  const barNumbers = options.barNumbers ?? true;
51
59
  const parts = labelled(model);
@@ -58,7 +66,7 @@ function chartHtml(text, options) {
58
66
  // Every section's left column is as wide as the longest part label, so tutti rows line up with systems.
59
67
  const widest = Math.max(0, ...model.parts.flatMap(rowLabelsOf).map((l) => l.length));
60
68
  const gutter = parts ? ` data-parts style="--bm-label-chars:${widest}"` : "";
61
- return `<div class="bm-chart" data-theme="${themeOf(options)}"${gutter}${layoutAttributes(options, settings)}>${headerHtml(model)}${model.blocks.map((b) => blockHtml(b, settings)).join("")}${copyrightHtml(model)}${options.diagnostics ? diagnosticsHtml(model) : ""}</div>`;
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>`;
62
70
  }
63
71
  /** The chart's layout switches the stylesheet reads, each only when it is off its default. */
64
72
  const layoutAttributes = (options, settings) => `${settings.barNumbers ? "" : ' data-bar-numbers="off"'}${options.wrap === false ? ' data-wrap="off"' : ""}${settings.rows ? ' data-columns="row"' : ""}`;
@@ -84,6 +92,45 @@ function headerHtml(model) {
84
92
  return "";
85
93
  return `<header class="bm-header">${title}${credits}${meta ? `<p class="bm-meta" part="meta">${meta}</p>` : ""}</header>`;
86
94
  }
95
+ const handOf = (options) => options.diagramHand === "left" ? "left" : "right";
96
+ /** The chart's chords as guitar diagrams, in one wrapping row after the header (design 5.1); nothing when it has none. */
97
+ function diagramsHtml(entries, numerals, hand) {
98
+ if (entries.length === 0)
99
+ return "";
100
+ return `<section class="bm-diagrams" part="diagrams" aria-label="Guitar chords"><ul role="list">${entries.map((e) => diagramHtml(e, numerals, hand)).join("")}</ul></section>`;
101
+ }
102
+ /** One diagram: the drawing (or, with no shape, a frame saying why), its name, its numeral and its note. */
103
+ function diagramHtml(entry, numerals, hand) {
104
+ // With numerals on, the label says the degree, as the bar's speech does.
105
+ const label = speakDiagram(entry, numerals && entry.key ? entry.key : undefined);
106
+ const drawing = entry.shape
107
+ ? diagramSvg(entry.shape, hand, label)
108
+ : `<span class="bm-diagram-none" role="img" aria-label="${escapeHtml(label)}">${escapeHtml(UNPLAYABLE)}</span>`;
109
+ const note = entry.caveat === "voicing-replaced"
110
+ ? `<span class="bm-diagram-note" aria-hidden="true">${escapeHtml(VOICING_REPLACED)}</span>`
111
+ : "";
112
+ // A drawing with a fret number is wider at the left: its item makes room for it.
113
+ const wide = entry.shape && entry.shape.base > 1 ? " bm-diagram-fr" : "";
114
+ return `<li class="bm-diagram${wide}" part="diagram">${drawing}${diagramNameHtml(entry)}${diagramNumeralHtml(entry, numerals)}${note}</li>`;
115
+ }
116
+ /** A name as the grid marks it up, then its written voicing, smaller; a note set as written, free to wrap. */
117
+ function diagramNameHtml({ chord, voicing }) {
118
+ if (chord.kind === "notes" || !chord.parts)
119
+ return `<span class="bm-diagram-name bm-diagram-set" aria-hidden="true">${escapeHtml(chord.canonical)}</span>`;
120
+ const voiced = voicing
121
+ ? `<span class="bm-diagram-voicing">${escapeHtml(voicing.canonical)}</span>`
122
+ : "";
123
+ return `<span class="bm-diagram-name" aria-hidden="true">${piecesHtml(typesetChord(chord.parts), "")}${voiced}</span>`;
124
+ }
125
+ /** With `numerals`, a named chord's degree in the key where it first appears; the name above stays in letters. */
126
+ function diagramNumeralHtml({ chord, key }, numerals) {
127
+ if (!numerals || !key || chord.kind === "notes" || !chord.parts)
128
+ return "";
129
+ const pieces = typesetNumeral(chord.parts, key, numerals);
130
+ if (!pieces)
131
+ return "";
132
+ return `<span class="bm-diagram-numeral" aria-hidden="true">${piecesHtml(pieces, ` data-numeral="${numerals}"`)}</span>`;
133
+ }
87
134
  /** The copyright lines, small, at the chart's foot. */
88
135
  function copyrightHtml(model) {
89
136
  const lines = model.credits.copyright;
package/dist/model.js CHANGED
@@ -5,6 +5,7 @@
5
5
  * bar numbers and the slots `%` copies.
6
6
  */
7
7
  import { extractPart, parseChart, printedAsWritten, unreadSlots, } from "barmark";
8
+ import { chartDiagrams } from "./diagrams.js";
8
9
  import { tempoBeatOf, tempoBeats } from "./tempo.js";
9
10
  import { landings, rowVerses, singerOf, sungVerses } from "./verses.js";
10
11
  /** Whether a tutti bar's parts play different slots, as `%` or `/` on a tutti line can. */
@@ -83,6 +84,7 @@ export function layoutChart(text, options = {}) {
83
84
  tempoBeat: headerBeat(parse.lines, ctx.beats),
84
85
  blocks,
85
86
  diagnostics: parse.diagnostics,
87
+ diagrams: options.chordDiagrams === "guitar" ? chartDiagrams(blocks, parse) : [],
86
88
  };
87
89
  }
88
90
  /** The beat the header's tempo counts: its directives' (they share the next bar line), or the default. */
package/dist/speech.d.ts CHANGED
@@ -3,9 +3,22 @@
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 } from "./types.js";
6
+ import type { CellModel, DiagramEntry } 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
+ /** A diagram with no shape, shown in its frame and said in its label. */
10
+ export declare const UNPLAYABLE = "not playable in standard tuning";
11
+ /** A written voicing the diagram replaced with the name's shape, shown under the name and said in its label. */
12
+ export declare const VOICING_REPLACED = "written voicing doesn't fit standard tuning";
13
+ /**
14
+ * A chord diagram aloud: the chord as a bar says it (its degree first when a
15
+ * key is passed, its written voicing after), then its strings low to high,
16
+ * whatever the hand: "A minor: muted, open, 2, 2, 1, open". One with no
17
+ * shape says why: "C major seven, written voicing: not playable in
18
+ * standard tuning". A voicing the diagram replaced is not said as voiced: the
19
+ * strings do not play those notes.
20
+ */
21
+ export declare function speakDiagram(entry: DiagramEntry, key?: Key): string;
9
22
  export declare function speakSlot(slot: Slot, key?: Key): string;
10
23
  /** What a bar is called aloud: "pickup" for bar 0, "bar" with no number, else "bar 9". */
11
24
  export declare function barLabel(barNumber: number | null): string;
package/dist/speech.js CHANGED
@@ -105,6 +105,32 @@ export function speakChord(record, key) {
105
105
  const degree = key ? speakDegree(record.parts.root, key) : "";
106
106
  return `${degree ? `${degree}, ` : ""}${speakParts(record.parts)}`;
107
107
  }
108
+ /** A diagram with no shape, shown in its frame and said in its label. */
109
+ export const UNPLAYABLE = "not playable in standard tuning";
110
+ /** A written voicing the diagram replaced with the name's shape, shown under the name and said in its label. */
111
+ export const VOICING_REPLACED = "written voicing doesn't fit standard tuning";
112
+ /** What a diagram can't show, said after its strings. */
113
+ const CAVEAT = {
114
+ shell: ", altered tones not shown",
115
+ "voicing-replaced": `, ${VOICING_REPLACED}`,
116
+ };
117
+ /**
118
+ * A chord diagram aloud: the chord as a bar says it (its degree first when a
119
+ * key is passed, its written voicing after), then its strings low to high,
120
+ * whatever the hand: "A minor: muted, open, 2, 2, 1, open". One with no
121
+ * shape says why: "C major seven, written voicing: not playable in
122
+ * standard tuning". A voicing the diagram replaced is not said as voiced: the
123
+ * strings do not play those notes.
124
+ */
125
+ export function speakDiagram(entry, key) {
126
+ const name = speakChord(entry.chord, key);
127
+ if (!entry.shape)
128
+ return `${name}${entry.voicing ? ", written voicing" : ""}: ${UNPLAYABLE}`;
129
+ const shown = entry.caveat !== "voicing-replaced";
130
+ const voiced = entry.voicing && shown ? `${name} voiced ${entry.voicing.pitches.join(" ")}` : name;
131
+ const strings = entry.shape.frets.map((f) => (f < 0 ? "muted" : f === 0 ? "open" : String(f)));
132
+ return `${voiced}: ${strings.join(", ")}${entry.caveat ? CAVEAT[entry.caveat] : ""}`;
133
+ }
108
134
  const PUSHED = { eighth: "pushed", sixteenth: "pushed a sixteenth" };
109
135
  /** A chord with its voicing and articulation: "accented D", "G short hit", "C major seven voiced E3 G3". */
110
136
  function speakChordSlot(slot, key) {
package/dist/styles.d.ts CHANGED
@@ -15,4 +15,6 @@ 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
+ /** 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
+ export declare const DIAGRAMS_CSS: string;
18
20
  export declare const stylesheet: string;
package/dist/styles.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { DIAGRAM_VIEW } from "./diagram.js";
1
2
  import { FONT_FAMILY } from "./font.js";
2
3
  /**
3
4
  * The chart's styles. Everything is sized in em from `--barmark-size`, so
@@ -229,4 +230,45 @@ const minify = (text) => text
229
230
  .replace(/:\s+/g, ":");
230
231
  /** The rules only `columns: "row"` uses, at the stylesheet's end. */
231
232
  export const ROW_COLUMNS_CSS = minify(rowCss);
232
- export const stylesheet = minify(css) + ROW_COLUMNS_CSS;
233
+ /**
234
+ * A chord diagram, in chord sizes. A viewBox unit is 3.5/78 of a chord size,
235
+ * so strings stand .45em apart in either image. A wide drawing (one with a
236
+ * fret number) moves left by the room its number takes, and its item
237
+ * (`bm-diagram-fr`) pads that much on the left, so its strings sit over the
238
+ * name as a narrow drawing's do, and nothing reaches into the next item. The
239
+ * frame of a diagram with no shape is as tall as a drawing, a little wider
240
+ * so its words break in three lines; it and the note are in small print.
241
+ */
242
+ const UNIT = 3.5 / 78;
243
+ const DIAGRAM = {
244
+ narrow: DIAGRAM_VIEW.narrow * UNIT,
245
+ wide: DIAGRAM_VIEW.wide * UNIT,
246
+ label: DIAGRAM_VIEW.label * UNIT,
247
+ height: DIAGRAM_VIEW.height * UNIT,
248
+ frame: 4.9,
249
+ small: 0.6,
250
+ /** A note set's name: three notes to a line. */
251
+ set: 5.6,
252
+ };
253
+ /** The strip of chord diagrams (design 5): only charts drawn with `chordDiagrams` use it. */
254
+ const diagramsCss = `
255
+ .bm-diagrams ul{display:flex;flex-wrap:wrap;gap:.5em .6em;margin:0 0 .3em;padding:0;list-style:none}
256
+ .bm-diagram{display:flex;flex-direction:column;align-items:center;text-align:center;break-inside:avoid}
257
+ .bm-diagram-fr{padding-left:${em(DIAGRAM.label)}}
258
+ .bm-diagram-svg{fill:var(--bm-ink);display:block;width:${em(DIAGRAM.narrow)};height:${em(DIAGRAM.height)}}
259
+ .bm-dg-fr{width:${em(DIAGRAM.wide)};margin-left:${em(-DIAGRAM.label)}}
260
+ .bm-diagram-none{display:flex;align-items:center;justify-content:center;width:${at(DIAGRAM.small, DIAGRAM.frame)};height:${at(DIAGRAM.small, DIAGRAM.height)};padding:.3em;border:.1em dashed var(--bm-rule);border-radius:.4em;text-wrap:balance}
261
+ :is(.bm-diagram-none,.bm-diagram-note){font:${em(DIAGRAM.small)}/1.2 ${LABEL};color:var(--bm-muted)}
262
+ .bm-diagram-note{max-width:${at(DIAGRAM.small, DIAGRAM.frame)}}
263
+ .bm-diagram-name{padding-top:.35em;line-height:1.2}
264
+ .bm-diagram-set{max-width:${em(DIAGRAM.set)};white-space:normal}
265
+ :is(.bm-diagram-voicing,.bm-diagram-numeral){display:block;font-size:.75em;color:var(--bm-muted)}
266
+ .bm-diagram-voicing{max-width:${at(0.75, DIAGRAM.frame)}}
267
+ .bm-dg-grid{fill:none;stroke:var(--bm-rule);stroke-width:1.2}
268
+ .bm-dg-mark{fill:none;stroke:var(--bm-muted);stroke-width:1.3}
269
+ .bm-dg-fret{fill:var(--bm-muted);font-family:${TEXT};text-anchor:end}
270
+ @media (forced-colors:active){.bm-diagrams{--bm-rule:CanvasText;--bm-muted:CanvasText;--bm-ink:CanvasText}}
271
+ `;
272
+ /** 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. */
273
+ export const DIAGRAMS_CSS = minify(diagramsCss);
274
+ export const stylesheet = minify(css) + DIAGRAMS_CSS + ROW_COLUMNS_CSS;
package/dist/types.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import type { ChartDiagnostic, Credits, DeclaredPart, Direction, Directives, Key, Meter, Repeat, Slot, Syllable, Words } from "barmark";
1
+ import type { Shape } from "@barmark/fretboard";
2
+ import type { ChartDiagnostic, ChordRecord, Credits, DeclaredPart, Direction, Directives, Key, Meter, Repeat, Slot, Syllable, Words } from "barmark";
2
3
  /** `part`: draw only the part with this label (barmark's grammar 7.4), as a single-part chart. */
3
4
  export type LayoutOptions = {
4
5
  /**
@@ -8,6 +9,8 @@ export type LayoutOptions = {
8
9
  */
9
10
  rehearsalLetters?: boolean;
10
11
  part?: string;
12
+ /** Give the model a diagram entry for each chord, as a guitar plays it; off when absent. */
13
+ chordDiagrams?: "guitar";
11
14
  };
12
15
  /** What to draw, with every musical decision already made. */
13
16
  export type ChartModel = {
@@ -24,6 +27,21 @@ export type ChartModel = {
24
27
  tempoBeat: TempoBeat;
25
28
  blocks: SectionBlock[];
26
29
  diagnostics: ChartDiagnostic[];
30
+ /** The chart's chords as guitar diagrams show them, in written order; empty unless `chordDiagrams` is set. */
31
+ diagrams: DiagramEntry[];
32
+ };
33
+ /** One chord of the chart as a diagram shows it (design 4 and 5.2). */
34
+ export type DiagramEntry = {
35
+ /** The chord as written: a name, or a note set. */
36
+ chord: ChordRecord;
37
+ /** The notes written after a name (`Cmaj7{E3 G3}`), else null. */
38
+ voicing: ChordRecord | null;
39
+ /** The key in force where the chord first appears, for a numeral; null when the chart has none there. */
40
+ key: Key | null;
41
+ /** The fingering; null when the written notes cannot be played in standard tuning. */
42
+ shape: Shape | null;
43
+ /** "shell": a 7alt's root, third and flat seventh. "voicing-replaced": the written voicing did not fit, so the name's own shape is shown. */
44
+ caveat: "shell" | "voicing-replaced" | null;
27
45
  };
28
46
  /**
29
47
  * The note a `tempo:` counts (barmark's grammar 2.1), from the `time:` in
package/dist/verses.d.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * module only sorts them under the written bars a row draws: under a
5
5
  * singing line's slots, or spaced by beat in a lyric row on no melody.
6
6
  */
7
- import { type ChartParse, type Line, type PlayedBar, type PlayedLyrics } from "barmark";
7
+ import { type ChartParse, type DeclaredPart, type Line, type PlayedBar, type PlayedLyrics } from "barmark";
8
8
  import type { CellModel, Verse } from "./types.js";
9
9
  type BarsLine = Extract<Line, {
10
10
  kind: "bars";
@@ -14,6 +14,8 @@ export type Landing = {
14
14
  bar: PlayedBar;
15
15
  lyrics: PlayedLyrics[];
16
16
  } | null;
17
+ /** The declared part a bar line belongs to: its label's, or the lone part for a bare line; undefined when none. */
18
+ export declare function partOf(l: BarsLine, parse: ChartParse): DeclaredPart | undefined;
17
19
  /**
18
20
  * Whose words a row sings under its slots: the label of the part whose
19
21
  * singing line it is ("" in a chart that sings with no part declared), or
package/dist/verses.js CHANGED
@@ -11,6 +11,13 @@ const same = (a, b) => a.toLowerCase() === b.toLowerCase();
11
11
  const barLength = (m) => m.n / m.d;
12
12
  /** Whose words a verse is: its part's label, or "" for the chart's. */
13
13
  const keyOf = (v) => v.part ?? "";
14
+ /** The declared part a bar line belongs to: its label's, or the lone part for a bare line; undefined when none. */
15
+ export function partOf(l, parse) {
16
+ const { parts } = parse;
17
+ if (l.part === undefined)
18
+ return parts.length === 1 ? parts[0] : undefined;
19
+ return parts.find((x) => same(x.label ?? "", l.part ?? ""));
20
+ }
14
21
  /**
15
22
  * Whose words a row sings under its slots: the label of the part whose
16
23
  * singing line it is ("" in a chart that sings with no part declared), or
@@ -20,11 +27,7 @@ export function singerOf(l, parse) {
20
27
  const { parts } = parse;
21
28
  if (!parts.length)
22
29
  return l.part === undefined && singsOnNotes(parse) ? "" : null;
23
- const p = l.part === undefined
24
- ? parts.length === 1
25
- ? parts[0]
26
- : undefined
27
- : parts.find((x) => same(x.label ?? "", l.part ?? ""));
30
+ const p = partOf(l, parse);
28
31
  if (p?.sings === undefined)
29
32
  return null;
30
33
  // A bare line plays as the part's first line (7.6).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@barmark/render",
3
- "version": "0.19.0",
3
+ "version": "0.20.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": {
@@ -47,7 +47,8 @@
47
47
  "url": "https://github.com/kevinpeckham/barmark/issues"
48
48
  },
49
49
  "dependencies": {
50
- "barmark": "^0.23.0"
50
+ "@barmark/fretboard": "^0.1.0",
51
+ "barmark": "^0.23.1"
51
52
  },
52
53
  "scripts": {
53
54
  "build": "rm -rf dist && tsc -p tsconfig.build.json",