@n1kname/charts 0.12.0 → 0.14.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 +1 -1
- package/src/bars.mjs +79 -13
- package/src/bars.test.mjs +43 -2
- package/src/plot.mjs +5 -3
- package/src/spark.css +20 -0
- package/src/spark.mjs +32 -20
- package/src/spark.test.mjs +23 -0
- package/src/theme.mjs +4 -1
package/package.json
CHANGED
package/src/bars.mjs
CHANGED
|
@@ -7,13 +7,35 @@
|
|
|
7
7
|
// bought still reads. A row can be drawn fainter (`fade`) and with a dashed edge (`dashed`),
|
|
8
8
|
// for figures that are not settled yet; say what each means in a Legend. A run of steps can be
|
|
9
9
|
// set apart as one shaded block with a word on why (`shade`), and a series can carry a short
|
|
10
|
-
// `tag` over its first bar, so two series are not told apart by colour alone.
|
|
10
|
+
// `tag` over its first bar, so two series are not told apart by colour alone. The bars that
|
|
11
|
+
// carry the story can say their figure all the time (`callout`), so a reader on a phone, with no
|
|
12
|
+
// pointer, still gets the numbers that matter.
|
|
11
13
|
|
|
12
14
|
import * as Plot from '@observablehq/plot';
|
|
13
15
|
import { chrome, tipStyle } from './theme.mjs';
|
|
14
16
|
|
|
15
17
|
const plain = (v, digits) => v.toFixed(digits);
|
|
16
18
|
|
|
19
|
+
// d3's nice(), with the count Plot uses, so the shade can reach the top of the frame exactly.
|
|
20
|
+
const increment = (start, stop, count) => {
|
|
21
|
+
const step = (stop - start) / count;
|
|
22
|
+
const power = Math.floor(Math.log10(step));
|
|
23
|
+
const error = step / 10 ** power;
|
|
24
|
+
const factor = error >= Math.sqrt(50) ? 10 : error >= Math.sqrt(10) ? 5 : error >= Math.sqrt(2) ? 2 : 1;
|
|
25
|
+
return power >= 0 ? factor * 10 ** power : -(10 ** -power) / factor;
|
|
26
|
+
};
|
|
27
|
+
export const niceDomain = ([start, stop], count = 10) => {
|
|
28
|
+
let previous;
|
|
29
|
+
for (let i = 0; i < 10 && stop > start; i++) {
|
|
30
|
+
const step = increment(start, stop, count);
|
|
31
|
+
if (step === previous || !Number.isFinite(step) || step === 0) break;
|
|
32
|
+
if (step > 0) [start, stop] = [Math.floor(start / step) * step, Math.ceil(stop / step) * step];
|
|
33
|
+
else [start, stop] = [Math.ceil(start * step) / step, Math.floor(stop * step) / step];
|
|
34
|
+
previous = step;
|
|
35
|
+
}
|
|
36
|
+
return [start, stop];
|
|
37
|
+
};
|
|
38
|
+
|
|
17
39
|
export const bars = (
|
|
18
40
|
{
|
|
19
41
|
rows,
|
|
@@ -29,6 +51,10 @@ export const bars = (
|
|
|
29
51
|
y = ['auto', 'auto'],
|
|
30
52
|
// The total written on top of each bar.
|
|
31
53
|
values = false,
|
|
54
|
+
// A figure written over a bar that matters, without the pointer: gets (row, series) and
|
|
55
|
+
// returns true to write that series' value over its bar in that row. Stacked, the series
|
|
56
|
+
// is the top one and the figure is the total. Pick a few: every bar is what `values` is for.
|
|
57
|
+
callout = null,
|
|
32
58
|
// Opacity per row, 1 for a settled figure.
|
|
33
59
|
fade = () => 1,
|
|
34
60
|
// A dashed edge per row, in the series' colour.
|
|
@@ -78,10 +104,11 @@ export const bars = (
|
|
|
78
104
|
const bottom = (r) => (grouped ? Math.min(0, ...valuesOf(r)) : sum(valuesOf(r).filter((v) => v < 0)));
|
|
79
105
|
const total = (r) => series.reduce((sum, s) => sum + (has(r, s.key) ? r[s.key] : 0), 0);
|
|
80
106
|
const drawn = rows.filter((r) => series.some((s) => has(r, s.key)));
|
|
81
|
-
|
|
107
|
+
// Rounded out to round numbers here rather than by Plot, so the shade knows where the frame ends.
|
|
108
|
+
const domain = niceDomain([
|
|
82
109
|
y[0] === 'auto' ? Math.min(0, ...drawn.map(bottom)) : y[0],
|
|
83
110
|
y[1] === 'auto' ? Math.max(0, ...drawn.map(top)) : y[1],
|
|
84
|
-
];
|
|
111
|
+
]);
|
|
85
112
|
// Stacked, the tooltip lists the parts from the top, as they are drawn; grouped, in order.
|
|
86
113
|
const listed = grouped ? series : [...series].reverse();
|
|
87
114
|
const says = title ?? ((r) => [r[x], ...listed.filter((s) => has(r, s.key)).map((s) => `${s.label} ${format(r[s.key], digits)}`), unit].join('\n'));
|
|
@@ -122,10 +149,13 @@ export const bars = (
|
|
|
122
149
|
const shaded = shade ? rows.slice(rows.findIndex((r) => r[x] === shade.from), rows.findIndex((r) => r[x] === shade.to) + 1) : [];
|
|
123
150
|
const shading = shaded.length
|
|
124
151
|
? [
|
|
125
|
-
Plot.barY(shaded, { x, y1: () => domain[0], y2: () => domain[1], fill: chrome.neutral, fillOpacity: 0.16,
|
|
152
|
+
Plot.barY(shaded, { x, y1: () => domain[0], y2: () => domain[1], fill: chrome.neutral, fillOpacity: 0.16, insetLeft: -(step - band) / 2, insetRight: -(step - band) / 2, className: 'enter-fade' }),
|
|
153
|
+
// The word at the top of the block, where bars are least likely to be.
|
|
126
154
|
Plot.text([shaded[0]], {
|
|
127
155
|
x,
|
|
128
|
-
frameAnchor: '
|
|
156
|
+
frameAnchor: 'top',
|
|
157
|
+
dy: 10,
|
|
158
|
+
lineAnchor: 'top',
|
|
129
159
|
dx: ((shaded.length - 1) * step) / 2,
|
|
130
160
|
text: () => shade.text,
|
|
131
161
|
fill: 'var(--c-text-secondary)',
|
|
@@ -135,21 +165,28 @@ export const bars = (
|
|
|
135
165
|
]
|
|
136
166
|
: [];
|
|
137
167
|
|
|
138
|
-
// A series' tag over its first bar. The first grows leftward from its bar's right
|
|
139
|
-
// the rest rightward from their left edge, so two tags never touch.
|
|
168
|
+
// A series' tag over its first bar with a value. The first grows leftward from its bar's right
|
|
169
|
+
// edge and the rest rightward from their left edge, so two tags never touch. A tag runs over
|
|
170
|
+
// the steps beside its bar, so it sits above the tallest bar it crosses, not on top of it.
|
|
171
|
+
const TAG_EM = 6;
|
|
140
172
|
const tags = series.flatMap((s, i) => {
|
|
141
|
-
const
|
|
173
|
+
const at = rows.findIndex((r) => has(r, s.key) && r[s.key] !== 0);
|
|
174
|
+
const first = rows[at];
|
|
142
175
|
if (!s.tag || !first) return [];
|
|
143
|
-
const
|
|
176
|
+
const leftward = grouped && i === 0;
|
|
177
|
+
const edge = grouped ? (leftward ? left(i) + barWidth : left(i)) - band / 2 : 0;
|
|
178
|
+
const reach = Math.ceil((s.tag.length * TAG_EM) / step);
|
|
179
|
+
const crossed = leftward ? rows.slice(Math.max(0, at - reach), at + 1) : rows.slice(at, at + reach + 1);
|
|
180
|
+
const lift = Math.max(...crossed.map(top));
|
|
144
181
|
return [
|
|
145
182
|
Plot.text([first], {
|
|
146
183
|
x,
|
|
147
|
-
y: (
|
|
184
|
+
y: () => lift,
|
|
148
185
|
text: () => s.tag,
|
|
149
186
|
dx: edge,
|
|
150
187
|
dy: -6,
|
|
151
188
|
lineAnchor: 'bottom',
|
|
152
|
-
textAnchor:
|
|
189
|
+
textAnchor: leftward ? 'end' : 'start',
|
|
153
190
|
fill: 'var(--c-text-secondary)',
|
|
154
191
|
fontSize: 10,
|
|
155
192
|
className: 'enter-fade',
|
|
@@ -157,16 +194,44 @@ export const bars = (
|
|
|
157
194
|
];
|
|
158
195
|
});
|
|
159
196
|
|
|
197
|
+
// Callouts: the figure over each bar picked, centred on it. Stacked, over the whole bar.
|
|
198
|
+
const callouts = callout
|
|
199
|
+
? series.flatMap((s, i) => {
|
|
200
|
+
if (!grouped && i !== series.length - 1) return [];
|
|
201
|
+
const picked = rows.filter((r) => (grouped ? has(r, s.key) : series.some((t) => has(r, t.key))) && callout(r, s));
|
|
202
|
+
if (!picked.length) return [];
|
|
203
|
+
return [
|
|
204
|
+
Plot.text(picked, {
|
|
205
|
+
x,
|
|
206
|
+
y: (r) => (grouped ? Math.max(0, r[s.key]) : top(r)),
|
|
207
|
+
text: (r) => format(grouped ? r[s.key] : total(r), digits),
|
|
208
|
+
dx: grouped ? left(i) + barWidth / 2 - band / 2 : 0,
|
|
209
|
+
dy: -6,
|
|
210
|
+
lineAnchor: 'bottom',
|
|
211
|
+
fill: chrome.text,
|
|
212
|
+
// A halo in the surface colour, so a figure that crosses a taller bar beside it
|
|
213
|
+
// still reads.
|
|
214
|
+
stroke: 'var(--c-surface)',
|
|
215
|
+
strokeWidth: 3,
|
|
216
|
+
paintOrder: 'stroke',
|
|
217
|
+
fontSize: 12,
|
|
218
|
+
fontWeight: 600,
|
|
219
|
+
className: 'enter-fade',
|
|
220
|
+
}),
|
|
221
|
+
];
|
|
222
|
+
})
|
|
223
|
+
: [];
|
|
224
|
+
|
|
160
225
|
const labels = (v, i) => tick(v, i, width);
|
|
161
226
|
return {
|
|
162
227
|
width,
|
|
163
228
|
height,
|
|
164
|
-
marginTop: values || series.some((s) => s.tag) ? 24 : 10,
|
|
229
|
+
marginTop: values || callout || series.some((s) => s.tag) ? 24 : 10,
|
|
165
230
|
marginLeft,
|
|
166
231
|
marginRight,
|
|
167
232
|
marginBottom,
|
|
168
233
|
x: { type: 'band', domain: rows.map((r) => r[x]), padding, ...(grouped ? { round: false } : {}), label: null, tickSize: 0, tickFormat: labels, axis: null },
|
|
169
|
-
y: { domain,
|
|
234
|
+
y: { domain, label: yLabel, tickSize: 0, ticks: 5, tickFormat: (v) => format(v, yDigits) },
|
|
170
235
|
opacity: { type: 'identity' },
|
|
171
236
|
marks: [
|
|
172
237
|
Plot.axisX({ tickSize: 0, tickFormat: labels, lineWidth: wrap(width) }),
|
|
@@ -182,6 +247,7 @@ export const bars = (
|
|
|
182
247
|
? [Plot.text(drawn, { x, y: total, text: (r) => format(total(r), digits), dy: -8, lineAnchor: 'bottom', fill: chrome.text, fontSize: 12, className: 'enter-fade' })]
|
|
183
248
|
: []),
|
|
184
249
|
...tags,
|
|
250
|
+
...callouts,
|
|
185
251
|
Plot.ruleY([0], { stroke: chrome.axis, className: 'enter-zero' }),
|
|
186
252
|
...(pointer ? [Plot.tip(tipped, Plot.pointerX({ x, y: top, title: says, ...tipStyle }))] : []),
|
|
187
253
|
],
|
package/src/bars.test.mjs
CHANGED
|
@@ -52,8 +52,8 @@ const opacity = [...svg.matchAll(/fill="var\(--c-chart-2\)"[^>]*>((?:<(?:path|re
|
|
|
52
52
|
.flatMap((m) => [...m[1].matchAll(/fill-opacity="([\d.]+)"/g)].map((o) => Number(o[1])));
|
|
53
53
|
assert.deepEqual(opacity, [1, 1, 1, 0.5, 0.22], 'settled rows are solid, an estimate fainter, a projection fainter again');
|
|
54
54
|
|
|
55
|
-
// The domain holds the highest stack and the lowest negative.
|
|
56
|
-
assert.deepEqual(options.y.domain, [-
|
|
55
|
+
// The domain holds the highest stack and the lowest negative, rounded out the way Plot would.
|
|
56
|
+
assert.deepEqual(options.y.domain, [-4, 26], 'the y domain runs from the lowest piece to the highest stack, rounded out');
|
|
57
57
|
|
|
58
58
|
// The tooltip: each series from the top, a missing one left out.
|
|
59
59
|
const tip = options.marks.at(-1);
|
|
@@ -114,6 +114,47 @@ assert.ok(!renderPlot(bars({ ...spec, grouped: false }, 600)).includes('left out
|
|
|
114
114
|
|
|
115
115
|
console.log('bars: all assertions pass');
|
|
116
116
|
|
|
117
|
+
// Callouts: a figure over each bar picked, always on, centred on its own bar.
|
|
118
|
+
{
|
|
119
|
+
const c = bars({ rows: pairs, x: 'm', series: two, unit: 'units', grouped: true, callout: (r, s) => r.m === 'M1' || (r.m === 'M5' && s.key === 'old') }, 500);
|
|
120
|
+
const cSvg = renderPlot(c);
|
|
121
|
+
const figures = [...cSvg.matchAll(/font-weight="600"[^>]*>((?:<text[^>]*>[^<]*<\/text>)+)/g)]
|
|
122
|
+
.flatMap((m) => [...m[1].matchAll(/>([^<]+)<\/text>/g)].map((t) => t[1]));
|
|
123
|
+
assert.deepEqual(figures.sort(), ['20', '30', '5'], 'each picked bar says its own figure, and only those');
|
|
124
|
+
const stacked = renderPlot(bars({ ...spec, callout: (r) => r.month === 'M4' }, 600));
|
|
125
|
+
assert.ok(/font-weight="600"[^>]*><text[^>]*>23\.0<\/text>/.test(stacked), 'stacked, a callout is the total over the whole bar');
|
|
126
|
+
assert.ok(!/font-weight="600"/.test(svg), 'no callouts unless asked');
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// The shade spans the frame and no further: from the bottom of the scale to its rounded top.
|
|
130
|
+
{
|
|
131
|
+
const block = g.marks.find((m) => m.data?.[0]?.m === 'M3' && m.data.length === 2);
|
|
132
|
+
assert.ok(block, 'the shaded block is a mark of its own');
|
|
133
|
+
assert.equal(block.insetTop, 0, 'the block reaches the top of the frame, no further');
|
|
134
|
+
assert.equal(block.insetBottom, 0, 'and stops at the bottom of the scale, not below the axis');
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// A tag sits on the first bar with a value, above any taller bar it runs over.
|
|
138
|
+
{
|
|
139
|
+
const climb = [
|
|
140
|
+
{ m: 'A', a: null, b: 0 },
|
|
141
|
+
{ m: 'B', a: null, b: 2 },
|
|
142
|
+
{ m: 'C', a: 40, b: 9 },
|
|
143
|
+
{ m: 'D', a: 30, b: 3 },
|
|
144
|
+
];
|
|
145
|
+
// The second series' tag grows rightward, over the steps after its bar.
|
|
146
|
+
const t = bars({ rows: climb, x: 'm', series: [{ key: 'a', label: 'A', color: 'var(--c-chart-2)' }, { key: 'b', label: 'B', color: 'var(--c-chart-1)', tag: 'Prototype' }], grouped: true }, 160);
|
|
147
|
+
const tag = t.marks.find((m) => m.constructor.name === 'Text' && m.data?.[0]?.m && m.channels?.text?.value?.() === 'Prototype');
|
|
148
|
+
assert.equal(tag.data[0].m, 'B', 'a first bar of zero carries no tag; the first with a value does');
|
|
149
|
+
assert.equal(tag.channels.y.value(), 40, 'the tag clears the taller bar beside it');
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Labels in the system sans with tabular figures, not monospace.
|
|
153
|
+
assert.ok(!/monospace/.test(svg), 'no monospace in a chart');
|
|
154
|
+
assert.ok(/system-ui/.test(svg), 'the system sans');
|
|
155
|
+
|
|
156
|
+
console.log('bars: callouts, shade and tags pass');
|
|
157
|
+
|
|
117
158
|
// pointer: false leaves out Plot's tooltip and hover band, for a page that draws its own.
|
|
118
159
|
{
|
|
119
160
|
const own = bars({ ...spec, pointer: false }, 600);
|
package/src/plot.mjs
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
import * as Plot from '@observablehq/plot';
|
|
6
6
|
import { parseHTML } from 'linkedom';
|
|
7
|
-
import { chrome } from './theme.mjs';
|
|
7
|
+
import { chrome, SYSTEM_SANS } from './theme.mjs';
|
|
8
8
|
|
|
9
9
|
export { Plot };
|
|
10
10
|
|
|
@@ -20,8 +20,10 @@ export const renderPlot = (options) => {
|
|
|
20
20
|
color: chrome.textMuted,
|
|
21
21
|
// A system font on purpose. Safari lays out SVG text with the fallback font's
|
|
22
22
|
// widths and then paints the web font, which shifts anything centred or
|
|
23
|
-
// right-aligned. A font that never swaps has nothing to shift.
|
|
24
|
-
|
|
23
|
+
// right-aligned. A font that never swaps has nothing to shift. A sans, not mono, so
|
|
24
|
+
// labels read as words; tabular figures keep the numbers lined up all the same.
|
|
25
|
+
fontFamily: SYSTEM_SANS,
|
|
26
|
+
fontVariantNumeric: 'tabular-nums',
|
|
25
27
|
fontSize: '13px',
|
|
26
28
|
overflow: 'visible',
|
|
27
29
|
},
|
package/src/spark.css
CHANGED
|
@@ -37,6 +37,21 @@
|
|
|
37
37
|
stroke-width: 1.5;
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
+
/* The run compared against, such as last year's: a thin line in the muted text colour, under the
|
|
41
|
+
marks, so the run in colour reads as now and the grey one as then. */
|
|
42
|
+
.spark .spark-compare {
|
|
43
|
+
fill: none;
|
|
44
|
+
stroke: var(--c-text-muted);
|
|
45
|
+
stroke-opacity: 0.7;
|
|
46
|
+
stroke-width: 1.25;
|
|
47
|
+
stroke-linejoin: round;
|
|
48
|
+
stroke-linecap: round;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
.spark .spark-compare-dot {
|
|
52
|
+
fill: var(--c-text-muted);
|
|
53
|
+
}
|
|
54
|
+
|
|
40
55
|
/* The reference: quiet, dashed, under the marks. */
|
|
41
56
|
.spark .spark-ref {
|
|
42
57
|
stroke: var(--c-text-muted);
|
|
@@ -59,6 +74,11 @@
|
|
|
59
74
|
fill: none;
|
|
60
75
|
}
|
|
61
76
|
|
|
77
|
+
.spark .spark-compare {
|
|
78
|
+
stroke: GrayText;
|
|
79
|
+
stroke-opacity: 1;
|
|
80
|
+
}
|
|
81
|
+
|
|
62
82
|
.spark .spark-ref {
|
|
63
83
|
stroke: GrayText;
|
|
64
84
|
stroke-opacity: 1;
|
package/src/spark.mjs
CHANGED
|
@@ -20,12 +20,16 @@ export const SPARK_KINDS = ['bar', 'line', 'area'];
|
|
|
20
20
|
// values: numbers, oldest first; a missing one (null) is a gap. kind: 'bar', 'line' or 'area'.
|
|
21
21
|
// reference: a value dashed across, drawn only when it falls inside the scale. width and height in
|
|
22
22
|
// px. label: what a screen reader hears; without one the spark is hidden from it, because the
|
|
23
|
-
// figure beside it says the same. last: a dot on the newest value of a line or area
|
|
24
|
-
//
|
|
25
|
-
// stand on zero.
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
23
|
+
// figure beside it says the same. last: a dot on the newest value of a line or area, the newest
|
|
24
|
+
// one there is when the run ends in gaps. zero: false for a line or area scaled to its own
|
|
25
|
+
// values, for a rate that only moves a little; bars always stand on zero. compare: a second run
|
|
26
|
+
// over the same steps, such as the same months a year earlier, drawn as a quiet line under the
|
|
27
|
+
// marks and on the same scale, so the two can be read against each other.
|
|
28
|
+
export const sparkline = (values, { kind = 'bar', reference, width = 72, height = 44, label, last = false, zero = true, compare } = {}) => {
|
|
29
|
+
const other = Array.isArray(compare) ? compare : [];
|
|
30
|
+
if (other.length > values.length) values = [...values, ...Array(other.length - values.length).fill(null)];
|
|
31
|
+
const shown = [...values, ...other].filter(has);
|
|
32
|
+
if (!values.some(has)) return '';
|
|
29
33
|
if (!SPARK_KINDS.includes(kind)) throw new Error(`sparkline: kind is one of ${SPARK_KINDS.join(', ')}, not ${kind}`);
|
|
30
34
|
// From zero, with a little headroom so the top bar or the peak doesn't touch the edge. Below
|
|
31
35
|
// zero when a value is. Without zero, the values' own range with a tenth of it either side.
|
|
@@ -39,9 +43,27 @@ export const sparkline = (values, { kind = 'bar', reference, width = 72, height
|
|
|
39
43
|
const y = (v) => t + ih - ((v - lo) / (hi - lo || 1)) * ih;
|
|
40
44
|
// What bars stand on and an area closes on: zero, or the scale's foot when zero is below it.
|
|
41
45
|
const base = y(Math.max(lo, Math.min(0, hi)));
|
|
46
|
+
// Where step i stands across: a bar's middle, or a point along a line.
|
|
47
|
+
const band = iw / values.length;
|
|
48
|
+
const step = values.length > 1 ? iw / (values.length - 1) : 0;
|
|
49
|
+
const xAt = (i) => (kind === 'bar' ? l + band * i + band / 2 : values.length > 1 ? l + step * i : l + iw / 2);
|
|
50
|
+
const line = (pts) => pts.map(([px, py], i) => `${i ? 'L' : 'M'}${n(px)} ${n(py)}`).join('');
|
|
51
|
+
const runsOf = (vs) => {
|
|
52
|
+
const runs = [];
|
|
53
|
+
vs.forEach((v, i) => {
|
|
54
|
+
if (!has(v)) return runs.push(null);
|
|
55
|
+
const p = [xAt(i), y(v)];
|
|
56
|
+
const run = runs.at(-1);
|
|
57
|
+
if (run) run.push(p);
|
|
58
|
+
else runs.push([p]);
|
|
59
|
+
});
|
|
60
|
+
return runs.filter(Boolean);
|
|
61
|
+
};
|
|
62
|
+
const behind = runsOf(other.slice(0, values.length))
|
|
63
|
+
.map((pts) => (pts.length > 1 ? `<path class="spark-compare" d="${line(pts)}"/>` : `<circle class="spark-compare-dot" cx="${n(pts[0][0])}" cy="${n(pts[0][1])}" r="1.25"/>`))
|
|
64
|
+
.join('');
|
|
42
65
|
let marks = '';
|
|
43
66
|
if (kind === 'bar') {
|
|
44
|
-
const band = iw / values.length;
|
|
45
67
|
// Thin bars when there are many, so they stay apart.
|
|
46
68
|
const bw = Math.min(values.length > 8 ? 4 : 7, band * 0.8);
|
|
47
69
|
marks = values
|
|
@@ -50,24 +72,14 @@ export const sparkline = (values, { kind = 'bar', reference, width = 72, height
|
|
|
50
72
|
)
|
|
51
73
|
.join('');
|
|
52
74
|
} else {
|
|
53
|
-
const step = values.length > 1 ? iw / (values.length - 1) : 0;
|
|
54
75
|
// One run per stretch without a gap; one value alone sits in the middle.
|
|
55
|
-
const
|
|
56
|
-
values.forEach((v, i) => {
|
|
57
|
-
if (!has(v)) return runs.push(null);
|
|
58
|
-
const p = [values.length > 1 ? l + step * i : l + iw / 2, y(v)];
|
|
59
|
-
const run = runs.at(-1);
|
|
60
|
-
if (run) run.push(p);
|
|
61
|
-
else runs.push([p]);
|
|
62
|
-
});
|
|
63
|
-
const paths = runs.filter(Boolean);
|
|
64
|
-
const line = (pts) => pts.map(([px, py], i) => `${i ? 'L' : 'M'}${n(px)} ${n(py)}`).join('');
|
|
76
|
+
const paths = runsOf(values);
|
|
65
77
|
const fill = kind === 'area' ? paths.map((pts) => `<path class="spark-fill" d="${line(pts)}L${n(pts.at(-1)[0])} ${n(base)}L${n(pts[0][0])} ${n(base)}Z"/>`).join('') : '';
|
|
66
78
|
const stroke = paths.map((pts) => (pts.length > 1 ? `<path class="spark-stroke" d="${line(pts)}"/>` : `<circle class="spark-dot" cx="${n(pts[0][0])}" cy="${n(pts[0][1])}" r="1.5"/>`)).join('');
|
|
67
|
-
const end = last
|
|
79
|
+
const end = last ? paths.at(-1).at(-1) : null;
|
|
68
80
|
marks = fill + stroke + (end ? `<circle class="spark-dot spark-last" cx="${n(end[0])}" cy="${n(end[1])}" r="2.5"/>` : '');
|
|
69
81
|
}
|
|
70
82
|
const ref = has(reference) && reference <= hi && reference >= lo ? `<line class="spark-ref" x1="${l}" x2="${width - r}" y1="${n(y(reference))}" y2="${n(y(reference))}"/>` : '';
|
|
71
83
|
const a11y = label ? `role="img" aria-label="${esc(label)}"` : 'aria-hidden="true"';
|
|
72
|
-
return `<svg class="spark" data-kind="${kind}" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" ${a11y}>${ref}${marks}</svg>`;
|
|
84
|
+
return `<svg class="spark" data-kind="${kind}" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" ${a11y}>${ref}${behind}${marks}</svg>`;
|
|
73
85
|
};
|
package/src/spark.test.mjs
CHANGED
|
@@ -41,6 +41,29 @@ assert.equal(area.querySelectorAll('.spark-fill').length, 1);
|
|
|
41
41
|
assert.match(area.querySelector('.spark-fill').getAttribute('d'), /Z$/);
|
|
42
42
|
assert.ok(area.querySelector('.spark-last'), 'last: a dot on the newest value');
|
|
43
43
|
|
|
44
|
+
// last: on the newest value there is, when the run ends in gaps (a year so far).
|
|
45
|
+
const sofar = svg(sparkline([3, 5, 4, null, null], { kind: 'line', last: true }));
|
|
46
|
+
const dot = sofar.querySelector('.spark-last');
|
|
47
|
+
const ends = sofar.querySelector('.spark-stroke').getAttribute('d').match(/L([\d.]+) ([\d.]+)$/);
|
|
48
|
+
assert.ok(dot, 'a run that ends in gaps still gets its dot');
|
|
49
|
+
assert.equal(dot.getAttribute('cx'), ends[1], 'on the newest value drawn');
|
|
50
|
+
|
|
51
|
+
// compare: a quiet line under the marks, on the same scale, at the same steps.
|
|
52
|
+
const yoy = svg(sparkline([3, 5, null, null], { kind: 'line', compare: [4, 10, 6, 2] }));
|
|
53
|
+
const cmp = yoy.querySelector('.spark-compare');
|
|
54
|
+
assert.ok(cmp, 'the compared run is drawn');
|
|
55
|
+
assert.ok(yoy.innerHTML.indexOf('spark-compare') < yoy.innerHTML.indexOf('spark-stroke'), 'under the marks');
|
|
56
|
+
const cmpPts = [...cmp.getAttribute('d').matchAll(/[ML]([\d.]+) ([\d.]+)/g)].map((m) => [Number(m[1]), Number(m[2])]);
|
|
57
|
+
const nowPts = [...yoy.querySelector('.spark-stroke').getAttribute('d').matchAll(/[ML]([\d.]+) ([\d.]+)/g)].map((m) => [Number(m[1]), Number(m[2])]);
|
|
58
|
+
assert.equal(cmpPts.length, 4);
|
|
59
|
+
assert.deepEqual(nowPts.map((p) => p[0]), cmpPts.slice(0, 2).map((p) => p[0]), 'the same steps across');
|
|
60
|
+
assert.ok(cmpPts[1][1] < nowPts[1][1], 'one scale: the higher value stands higher');
|
|
61
|
+
assert.ok(cmpPts[1][1] < 6, 'the compared peak sets the top');
|
|
62
|
+
assert.ok(svg(sparkline([2, 4], { kind: 'bar', compare: [3, 3] })).querySelector('.spark-compare'), 'over bars too');
|
|
63
|
+
assert.equal(sparkline([null, null], { compare: [1, 2] }), '', 'nothing of its own, no svg');
|
|
64
|
+
const longer = svg(sparkline([1], { kind: 'line', compare: [1, 2, 3] }));
|
|
65
|
+
assert.equal([...longer.querySelector('.spark-compare').getAttribute('d').matchAll(/[ML]/g)].length, 3, 'a longer compared run sets the steps');
|
|
66
|
+
|
|
44
67
|
// A label makes it an image with a name.
|
|
45
68
|
const named = svg(sparkline([1, 2], { label: 'Steps, last 12 months <rising>' }));
|
|
46
69
|
assert.equal(named.getAttribute('role'), 'img');
|
package/src/theme.mjs
CHANGED
|
@@ -19,13 +19,16 @@ export const chrome = {
|
|
|
19
19
|
textMuted: v('text-muted'),
|
|
20
20
|
};
|
|
21
21
|
|
|
22
|
+
// The system's own sans: it never swaps, so Safari has nothing to misplace (see ./plot.mjs).
|
|
23
|
+
export const SYSTEM_SANS = "system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif";
|
|
24
|
+
|
|
22
25
|
// Plot's own tooltip, for charts drawn at build time: in a system font, because Safari misplaces
|
|
23
26
|
// centred SVG text in a web font. A chart drawn in the page can say it better with `pointer`
|
|
24
27
|
// (./pointer.mjs): an HTML card in the page's type that glides. Every value also needs a table.
|
|
25
28
|
export const tipStyle = {
|
|
26
29
|
fill: 'var(--c-surface)',
|
|
27
30
|
stroke: 'var(--c-border-strong)',
|
|
28
|
-
fontFamily:
|
|
31
|
+
fontFamily: SYSTEM_SANS,
|
|
29
32
|
fontSize: 12,
|
|
30
33
|
textPadding: 8,
|
|
31
34
|
};
|