@n1kname/charts 0.15.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.15.0",
3
+ "version": "0.16.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
package/src/lines.mjs CHANGED
@@ -9,6 +9,15 @@
9
9
  //
10
10
  // A band shades the range between two keys, such as a benchmark envelope from its lowest to its
11
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.
12
21
 
13
22
  import * as Plot from '@observablehq/plot';
14
23
  import { chrome, tipStyle } from './theme.mjs';
@@ -50,13 +59,22 @@ export const lines = (
50
59
  marginRight = legend ? 8 : 58,
51
60
  // Ranges shaded behind the lines: { low, high, label, color }, two keys per row.
52
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,
53
66
  },
54
67
  width,
55
68
  ) => {
56
69
  const has = (r, key) => typeof r[key] === 'number';
57
70
  const keys = [...series.map((s) => s.key), ...bands.flatMap((b) => [b.low, b.high])];
58
71
  const values = rows.flatMap((r) => keys.filter((k) => has(r, k)).map((k) => r[k]));
59
- const domain = [y[0] === 'auto' ? Math.min(...values) : y[0], y[1] === 'auto' ? Math.max(...values) : y[1]];
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' };
60
78
 
61
79
  // The tooltip names every series with a value at that x. A silent one, such as the
62
80
  // dashed rest of another line, only where the line it `continues` has none, and after
@@ -87,11 +105,23 @@ export const lines = (
87
105
  marks: [
88
106
  Plot.gridY({ stroke: chrome.grid, strokeOpacity: 1, ticks: 5 }),
89
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
+ }),
90
120
  ...bands.flatMap((b) => {
91
121
  const inside = rows.filter((r) => has(r, b.low) && has(r, b.high));
92
122
  const last = inside.at(-1);
93
123
  return [
94
- Plot.areaY(inside, { x, y1: b.low, y2: b.high, fill: b.color ?? chrome.neutral, fillOpacity: b.opacity ?? 0.38, className: 'enter-fade' }),
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' }),
95
125
  ...(legend || !b.label
96
126
  ? []
97
127
  : [
@@ -112,6 +142,7 @@ export const lines = (
112
142
  Plot.line(rows, {
113
143
  x,
114
144
  y: (r) => (has(r, s.key) ? r[s.key] : NaN),
145
+ curve: s.curve ?? curve,
115
146
  stroke: s.color,
116
147
  strokeWidth: s.width ?? 2,
117
148
  strokeDasharray: s.dashed ? '4 3' : undefined,
@@ -119,6 +150,13 @@ export const lines = (
119
150
  className: s.dashed ? 'enter-fade' : 'enter-line',
120
151
  }),
121
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
+ }),
122
160
  // A series' own `dots` wins over the chart's.
123
161
  ...series
124
162
  .filter((s) => s.dots ?? dots)
@@ -111,3 +111,31 @@ console.log('lines: all assertions pass');
111
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
112
  console.log('lines: bands pass');
113
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
+ }