@n1kname/charts 0.14.0 → 0.16.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@n1kname/charts",
3
- "version": "0.14.0",
3
+ "version": "0.16.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
package/src/lines.mjs CHANGED
@@ -6,6 +6,18 @@
6
6
  // Rows are wide: one object per x, a number (or null for no value) per series key. A null
7
7
  // breaks the line rather than joining across it. With `time`, x is a Date per row and the
8
8
  // steps need not be even, such as weeks with one missing.
9
+ //
10
+ // A band shades the range between two keys, such as a benchmark envelope from its lowest to its
11
+ // highest value, behind the lines, and ends in its own label.
12
+ //
13
+ // A reference is a level to read the lines against, such as a target price: a dashed rule behind
14
+ // the lines, its label at the left end, in muted text over a halo of the surface. The scale
15
+ // stretches to take it in, so the gap between the lines and the target shows. With
16
+ // `stretch: false` a reference outside the lines' range isn't drawn; its label sits at the chart's
17
+ // edge and says the target is below (or above) the chart instead.
18
+ //
19
+ // `curve` is Plot's: 'step-after' for a value that changes in steps, such as a price, where a
20
+ // slope between two days would show a change that never happened. Per series or for the chart.
9
21
 
10
22
  import * as Plot from '@observablehq/plot';
11
23
  import { chrome, tipStyle } from './theme.mjs';
@@ -45,12 +57,24 @@ export const lines = (
45
57
  marginTop = 10,
46
58
  // Room on the right: by default for the end labels, or a little for the last x label with a legend.
47
59
  marginRight = legend ? 8 : 58,
60
+ // Ranges shaded behind the lines: { low, high, label, color }, two keys per row.
61
+ bands = [],
62
+ // Levels to read the lines against: { y, label, tone?: 'neutral' | 'good', stretch? }.
63
+ references = [],
64
+ // Plot's curve for every line and band, such as 'step-after'; a series' own `curve` wins.
65
+ curve,
48
66
  },
49
67
  width,
50
68
  ) => {
51
69
  const has = (r, key) => typeof r[key] === 'number';
52
- const values = rows.flatMap((r) => series.filter((s) => has(r, s.key)).map((s) => r[s.key]));
53
- const domain = [y[0] === 'auto' ? Math.min(...values) : y[0], y[1] === 'auto' ? Math.max(...values) : y[1]];
70
+ const keys = [...series.map((s) => s.key), ...bands.flatMap((b) => [b.low, b.high])];
71
+ const values = rows.flatMap((r) => keys.filter((k) => has(r, k)).map((k) => r[k]));
72
+ const reached = [...values, ...references.filter((ref) => ref.stretch !== false).map((ref) => ref.y)];
73
+ const domain = [y[0] === 'auto' ? Math.min(...reached) : y[0], y[1] === 'auto' ? Math.max(...reached) : y[1]];
74
+ // A reference left out of the domain and outside it is only said, at the edge it lies beyond.
75
+ const beyond = (ref) => (ref.y < domain[0] ? 'below' : ref.y > domain[1] ? 'above' : null);
76
+ const refColor = (ref) => (ref.tone === 'good' ? 'var(--c-status-good)' : chrome.textMuted);
77
+ const halo = { stroke: 'var(--c-surface)', strokeWidth: 4, paintOrder: 'stroke', strokeLinejoin: 'round' };
54
78
 
55
79
  // The tooltip names every series with a value at that x. A silent one, such as the
56
80
  // dashed rest of another line, only where the line it `continues` has none, and after
@@ -60,7 +84,8 @@ export const lines = (
60
84
  ...series.filter((s) => s.silent && s.continues && has(r, s.key) && !has(r, s.continues)),
61
85
  ];
62
86
  const tipped = rows.filter((r) => told(r).length);
63
- const title = says ?? ((r) => [r[x], ...told(r).map((s) => `${s.label} ${format(r[s.key], digits)}`), unit].join('\n'));
87
+ const ranged = (r) => bands.filter((b) => has(r, b.low) && has(r, b.high)).map((b) => `${b.label} ${format(r[b.low], digits)}–${format(r[b.high], digits)}`);
88
+ const title = says ?? ((r) => [r[x], ...told(r).map((s) => `${s.label} ${format(r[s.key], digits)}`), ...ranged(r), unit].join('\n'));
64
89
 
65
90
  const named = series
66
91
  .map((s) => ({ s, name: s.endLabel ?? (s.silent ? false : s.label) }))
@@ -80,10 +105,44 @@ export const lines = (
80
105
  marks: [
81
106
  Plot.gridY({ stroke: chrome.grid, strokeOpacity: 1, ticks: 5 }),
82
107
  ...(zero ? [Plot.ruleY([0], { stroke: chrome.axis })] : []),
108
+ ...references.flatMap((ref) => {
109
+ const side = beyond(ref);
110
+ if (side) {
111
+ return ref.label
112
+ ? [Plot.text([ref], { frameAnchor: side === 'below' ? 'bottom-left' : 'top-left', text: () => `${ref.label}, ${side} the chart`, dx: 4, dy: side === 'below' ? -4 : 4, textAnchor: 'start', fill: chrome.textMuted, fontSize: 11, ...halo, className: 'enter-fade' })]
113
+ : [];
114
+ }
115
+ return [
116
+ Plot.ruleY([ref.y], { stroke: refColor(ref), strokeWidth: 1.5, strokeDasharray: '4 3', className: 'enter-fade' }),
117
+ ...(ref.label ? [Plot.text([ref], { y: 'y', frameAnchor: 'left', text: 'label', dx: 4, dy: -7, textAnchor: 'start', fill: chrome.textMuted, fontSize: 11, ...halo, className: 'enter-fade' })] : []),
118
+ ];
119
+ }),
120
+ ...bands.flatMap((b) => {
121
+ const inside = rows.filter((r) => has(r, b.low) && has(r, b.high));
122
+ const last = inside.at(-1);
123
+ return [
124
+ Plot.areaY(inside, { x, y1: b.low, y2: b.high, curve: b.curve ?? curve, fill: b.color ?? chrome.neutral, fillOpacity: b.opacity ?? 0.38, className: 'enter-fade' }),
125
+ ...(legend || !b.label
126
+ ? []
127
+ : [
128
+ Plot.text(last ? [last] : [], {
129
+ x,
130
+ y: (r) => (r[b.low] + r[b.high]) / 2,
131
+ text: () => b.endLabel ?? b.label,
132
+ dx: 7,
133
+ textAnchor: 'start',
134
+ fill: chrome.textMuted,
135
+ fontSize: 11,
136
+ className: 'enter-fade',
137
+ }),
138
+ ]),
139
+ ];
140
+ }),
83
141
  ...series.map((s) =>
84
142
  Plot.line(rows, {
85
143
  x,
86
144
  y: (r) => (has(r, s.key) ? r[s.key] : NaN),
145
+ curve: s.curve ?? curve,
87
146
  stroke: s.color,
88
147
  strokeWidth: s.width ?? 2,
89
148
  strokeDasharray: s.dashed ? '4 3' : undefined,
@@ -91,6 +150,13 @@ export const lines = (
91
150
  className: s.dashed ? 'enter-fade' : 'enter-line',
92
151
  }),
93
152
  ),
153
+ // A value alone between two gaps would draw no line at all: it gets a dot, dots or not.
154
+ ...series
155
+ .filter((s) => !(s.dots ?? dots))
156
+ .map((s) => {
157
+ const alone = rows.filter((r, i) => has(r, s.key) && !(i > 0 && has(rows[i - 1], s.key)) && !(i < rows.length - 1 && has(rows[i + 1], s.key)));
158
+ return Plot.dot(alone, { x, y: s.key, r: 2.5, fill: s.color, className: 'enter-dot' });
159
+ }),
94
160
  // A series' own `dots` wins over the chart's.
95
161
  ...series
96
162
  .filter((s) => s.dots ?? dots)
@@ -94,3 +94,48 @@ console.log('lines: all assertions pass');
94
94
  assert.ok(!names(own).includes('Tip') && !names(own).includes('RuleX'), 'no tip or crosshair with pointer: false');
95
95
  assert.ok(!own.marks.flat().some((m) => m?.r === 4), 'no pointer dot with pointer: false');
96
96
  }
97
+
98
+ // Bands: a range shaded behind the lines, in the domain, in the tooltip, with an end label.
99
+ {
100
+ const rows = [
101
+ { year: '2012', top: 100, lo: 100, hi: 100 },
102
+ { year: '2013', top: 121, lo: 112, hi: 116 },
103
+ { year: '2014', top: 146, lo: 125, hi: 135 },
104
+ ];
105
+ const o = lines({ rows, x: 'year', unit: 'index', series: [{ key: 'top', label: 'Top quartile', color: 'var(--c-chart-2)', endLabel: '21%' }], bands: [{ low: 'lo', high: 'hi', label: 'Benchmarks', endLabel: '12–16%' }] }, 500);
106
+ const svg = renderPlot(o);
107
+ assert.ok(o.marks.some((m) => m.constructor.name === 'Area'), 'the band is an area');
108
+ assert.ok(svg.includes('>12–16%<'), 'the band ends in its label');
109
+ assert.ok(o.y.domain[1] >= 146 && o.y.domain[0] <= 100, 'the domain takes in the band and the lines');
110
+ const tip = o.marks.at(-1);
111
+ assert.equal(tip.channels.title.value(rows[1]), '2013\nTop quartile 121\nBenchmarks 112–116\nindex', 'the tooltip gives the band as a range');
112
+ console.log('lines: bands pass');
113
+ }
114
+
115
+ // References: a dashed level behind the lines, with its label, in the domain unless told not.
116
+ {
117
+ const days = ['2026-01-01', '2026-01-02', '2026-01-05', '2026-01-06'].map((d, i) => ({ date: new Date(d), low: [24.99, 24.99, null, 22.49][i] }));
118
+ const spec = { rows: days, x: 'date', time: true, unit: 'euro', digits: 2, series: [{ key: 'low', label: 'Lowest', color: 'var(--c-chart-1)' }], legend: true, dots: false };
119
+ const o = lines({ ...spec, references: [{ y: 18, label: 'Target €18,00', tone: 'good' }], curve: 'step-after' }, 500);
120
+ const svg = renderPlot(o);
121
+ assert.ok(o.y.domain[0] <= 18, 'the scale stretches to take the reference in');
122
+ assert.ok(svg.includes('>Target €18,00<'), 'the reference carries its label');
123
+ assert.ok(/stroke="var\(--c-status-good\)"[^>]*stroke-dasharray="4 3"|stroke-dasharray="4 3"[^>]*stroke="var\(--c-status-good\)"/.test(svg), 'a good reference is a dashed rule in the status green');
124
+ assert.ok(svg.indexOf('stroke-dasharray="4 3"') < svg.indexOf('stroke="var(--c-chart-1)" fill="none"'), 'drawn behind the lines');
125
+ const path = svg.match(/<g[^>]*stroke="var\(--c-chart-1\)" fill="none"[^>]*><path d="([^"]+)"/)[1];
126
+ const runs = path.split('M').filter(Boolean).map((run) => run.replace(/Z$/, '').split('L').map((pt) => pt.split(',').map(Number)));
127
+ assert.ok(runs.every((pts) => pts.every((p, i) => i === 0 || p[0] === pts[i - 1][0] || p[1] === pts[i - 1][1])), 'a step-after curve draws flat runs and drops, no slopes');
128
+ assert.equal(runs.length, 2, 'a null still breaks a stepped line');
129
+ assert.equal((svg.match(/<circle/g) ?? []).length, 1, 'a value alone between gaps gets a dot, with dots off');
130
+
131
+ const kept = lines({ ...spec, references: [{ y: 18, label: 'Target €18,00', stretch: false }] }, 500);
132
+ const keptSvg = renderPlot(kept);
133
+ assert.ok(kept.y.domain[0] > 18, 'with stretch: false the scale stays on the lines');
134
+ assert.ok(keptSvg.includes('>Target €18,00, below the chart<'), 'and the label says where the target is');
135
+ assert.ok(!keptSvg.includes('stroke-dasharray'), 'with no rule drawn outside the chart');
136
+
137
+ const inside = renderPlot(lines({ ...spec, references: [{ y: 23.5, label: 'Target', stretch: false }] }, 500));
138
+ assert.ok(inside.includes('stroke-dasharray="4 3"') && inside.includes('>Target<'), 'a reference inside the range is drawn either way');
139
+ assert.ok(!/#[0-9a-f]{6}/i.test(svg), 'no hex: colours are tokens');
140
+ console.log('lines: references and curves pass');
141
+ }