@n1kname/charts 0.9.1 → 0.11.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 +4 -2
- package/src/heatmap.mjs +4 -1
- package/src/heatmap.test.mjs +5 -0
- package/src/index.mjs +1 -0
- package/src/pointer.css +24 -0
- package/src/pointer.mjs +132 -20
- package/src/spark.css +66 -0
- package/src/spark.mjs +73 -0
- package/src/spark.test.mjs +69 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@n1kname/charts",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -11,6 +11,8 @@
|
|
|
11
11
|
"./lines": "./src/lines.mjs",
|
|
12
12
|
"./bars": "./src/bars.mjs",
|
|
13
13
|
"./heatmap": "./src/heatmap.mjs",
|
|
14
|
+
"./spark": "./src/spark.mjs",
|
|
15
|
+
"./spark.css": "./src/spark.css",
|
|
14
16
|
"./enter": "./src/enter.mjs",
|
|
15
17
|
"./update": "./src/update.mjs",
|
|
16
18
|
"./pointer": "./src/pointer.mjs",
|
|
@@ -35,6 +37,6 @@
|
|
|
35
37
|
"src"
|
|
36
38
|
],
|
|
37
39
|
"scripts": {
|
|
38
|
-
"check": "node src/donut.test.mjs && node src/lines.test.mjs && node src/bars.test.mjs && node src/heatmap.test.mjs && node src/months.test.mjs"
|
|
40
|
+
"check": "node src/donut.test.mjs && node src/lines.test.mjs && node src/bars.test.mjs && node src/heatmap.test.mjs && node src/months.test.mjs && node src/spark.test.mjs"
|
|
39
41
|
}
|
|
40
42
|
}
|
package/src/heatmap.mjs
CHANGED
|
@@ -28,6 +28,9 @@ export const heatmap = (
|
|
|
28
28
|
rowHeight = 30,
|
|
29
29
|
// The tooltip's text per cell.
|
|
30
30
|
title,
|
|
31
|
+
// Plot's own tooltip. Leave on for a chart drawn at build time; turn off when the page says
|
|
32
|
+
// what is under the pointer itself, with `pointerCells` from ./pointer.mjs.
|
|
33
|
+
pointer = true,
|
|
31
34
|
// The labels on each axis. xTick gets (value, index, width).
|
|
32
35
|
xTick = (v) => v,
|
|
33
36
|
yTick = (v) => v,
|
|
@@ -45,5 +48,5 @@ export const heatmap = (
|
|
|
45
48
|
x: { domain: xDomain, label: null, tickSize: 0, tickFormat: (v, i) => xTick(v, i, width) },
|
|
46
49
|
y: { domain: yDomain, label: null, tickSize: 0, tickFormat: yTick },
|
|
47
50
|
color: { type: 'threshold', domain: steps, range: colors },
|
|
48
|
-
marks: [Plot.cell(cells, { x, y, fill: value, tip: tipStyle, title, className: 'enter-cell' })],
|
|
51
|
+
marks: [Plot.cell(cells, { x, y, fill: value, ...(pointer ? { tip: tipStyle, title } : {}), className: 'enter-cell' })],
|
|
49
52
|
});
|
package/src/heatmap.test.mjs
CHANGED
|
@@ -44,4 +44,9 @@ assert.deepEqual(labels(renderPlot(heatmap(spec, 280))), ['20h', '22h'], 'fewer
|
|
|
44
44
|
|
|
45
45
|
assert.equal(options.marks[0].channels.title.value(cells[1]), 'D1 21:00\n650 units', "the tooltip's own words");
|
|
46
46
|
|
|
47
|
+
// pointer: false leaves out Plot's tooltip, for a page that says what is under the pointer itself.
|
|
48
|
+
const own = heatmap({ ...spec, pointer: false }, 400);
|
|
49
|
+
assert.ok(options.marks[0].channels.title, 'a title by default');
|
|
50
|
+
assert.ok(!own.marks[0].channels.title, 'no title with pointer: false');
|
|
51
|
+
|
|
47
52
|
console.log('heatmap: all assertions pass');
|
package/src/index.mjs
CHANGED
package/src/pointer.css
CHANGED
|
@@ -84,6 +84,23 @@
|
|
|
84
84
|
font-variant-numeric: tabular-nums;
|
|
85
85
|
}
|
|
86
86
|
|
|
87
|
+
/* A total or another figure that isn't a series: under a hairline, without a swatch. */
|
|
88
|
+
.chart-pointer-card dl div:not(.is-extra) + .is-extra {
|
|
89
|
+
margin-top: 2px;
|
|
90
|
+
padding-top: 4px;
|
|
91
|
+
border-top: 1px solid var(--c-border);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
.chart-pointer-one + dl {
|
|
95
|
+
margin-top: var(--sp-1);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/* A line at the foot, such as the unit. */
|
|
99
|
+
.chart-pointer-note {
|
|
100
|
+
margin-top: var(--sp-1) !important;
|
|
101
|
+
color: var(--c-text-muted);
|
|
102
|
+
}
|
|
103
|
+
|
|
87
104
|
.chart-pointer-card i {
|
|
88
105
|
display: inline-block;
|
|
89
106
|
width: 8px;
|
|
@@ -116,6 +133,13 @@
|
|
|
116
133
|
box-shadow: 0 0 0 2px var(--c-surface);
|
|
117
134
|
}
|
|
118
135
|
|
|
136
|
+
/* A heatmap's cell: a frame round it, in the text colour, gliding from cell to cell. */
|
|
137
|
+
.chart-pointer-cell {
|
|
138
|
+
border: 2px solid var(--c-text);
|
|
139
|
+
border-radius: 3px;
|
|
140
|
+
box-shadow: 0 0 0 1px var(--c-surface);
|
|
141
|
+
}
|
|
142
|
+
|
|
119
143
|
/* Dimming: while one is pointed at, the other bars and slices step back to 55%, and so do the
|
|
120
144
|
swatches of the other rows in a donut's list. Their words keep full contrast. */
|
|
121
145
|
.chart-pointer-dims svg .enter-bar > *,
|
package/src/pointer.mjs
CHANGED
|
@@ -56,12 +56,31 @@ const layer = (box) => {
|
|
|
56
56
|
return l;
|
|
57
57
|
};
|
|
58
58
|
|
|
59
|
-
// The card's words: the step's name, then one figure, or a row per series with its swatch.
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
59
|
+
// The card's words: the step's name, then one figure, or a row per series with its swatch. Then
|
|
60
|
+
// any extra: a [label, value] pair is a row without a swatch, under a hairline, such as a total;
|
|
61
|
+
// text is a quiet line at the foot, such as the unit.
|
|
62
|
+
const words = (title, items, extra = []) => {
|
|
63
|
+
const pairs = extra.filter(Array.isArray);
|
|
64
|
+
const notes = extra.filter((e) => !Array.isArray(e));
|
|
65
|
+
const one = items.length === 1 && !items[0].swatch;
|
|
66
|
+
const rows = [
|
|
67
|
+
...(one ? [] : items.map((i) => `<div><dt><i style="background:${i.color}"></i>${esc(i.label)}</dt><dd>${esc(i.value)}</dd></div>`)),
|
|
68
|
+
...pairs.map(([label, value]) => `<div class="is-extra"><dt>${esc(label)}</dt><dd>${esc(value)}</dd></div>`),
|
|
69
|
+
];
|
|
70
|
+
return (
|
|
71
|
+
`<p class="chart-pointer-title">${esc(title)}</p>` +
|
|
72
|
+
(one ? `<p class="chart-pointer-one">${esc(items[0].value)}</p>` : '') +
|
|
73
|
+
(rows.length ? `<dl>${rows.join('')}</dl>` : '') +
|
|
74
|
+
notes.map((n) => `<p class="chart-pointer-note">${esc(n)}</p>`).join('')
|
|
75
|
+
);
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
// The same words, said: for the live region, from the keyboard.
|
|
79
|
+
const said = (title, items, extra = []) =>
|
|
80
|
+
`${title}: ${[
|
|
81
|
+
...items.map((t) => (items.length > 1 ? `${t.label} ${t.value}` : t.value)),
|
|
82
|
+
...extra.map((e) => (Array.isArray(e) ? e.join(' ') : e)),
|
|
83
|
+
].join(', ')}`;
|
|
65
84
|
|
|
66
85
|
// Appearing, moving, leaving. The first showing is in place; after that, everything glides.
|
|
67
86
|
const presence = (l, onLeave) => {
|
|
@@ -102,10 +121,17 @@ const keys = (box, count, at, go, leave) => {
|
|
|
102
121
|
// box: the element holding the chart's svg. rows: the rows drawn, one per x. x: the rows' x key.
|
|
103
122
|
// series: [{ key, label, color }], as given to bars() or lines(). format: (value, series) → text.
|
|
104
123
|
// label: (row) → the step's name. kind: 'bars' or 'lines'. focus (bars): 'dim', 'rule' or 'both'.
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
124
|
+
// grouped: bars side by side rather than stacked, as with bars({ grouped }).
|
|
125
|
+
// extra: (row) → more for the card after the series: [label, value] pairs and lines of text.
|
|
126
|
+
// empty: the text for a series with no value at a step, such as '–', so a missing figure is said
|
|
127
|
+
// rather than left out, and every row is a step, one without any figure too; by default such a
|
|
128
|
+
// series isn't listed, and such a row is passed over.
|
|
129
|
+
export const pointer = (box, { rows, x, series, format, label = (r) => String(r[x]), kind = 'bars', focus = 'dim', grouped = false, extra = () => [], empty }) => {
|
|
130
|
+
const steps = rows.map((r, i) => (empty !== undefined || series.some((s) => has(r, s.key)) ? i : -1)).filter((i) => i >= 0);
|
|
131
|
+
// The card lists a stack from the top down, as it is drawn; bars side by side from the left. On lines, as lines() tells it: a
|
|
132
|
+
// silent series (the dashed rest of another line) only where the line it continues has none.
|
|
133
|
+
const listed = kind === 'bars' ? (grouped ? series : [...series].reverse()) : [...series.filter((s) => !s.silent), ...series.filter((s) => s.silent)];
|
|
134
|
+
const told = (r, s) => (kind === 'lines' && s.silent ? s.continues && has(r, s.key) && !has(r, s.continues) : has(r, s.key) || empty !== undefined);
|
|
109
135
|
const l = layer(box);
|
|
110
136
|
const live = voice(box);
|
|
111
137
|
const ruled = kind === 'lines' || focus !== 'dim';
|
|
@@ -122,11 +148,14 @@ export const pointer = (box, { rows, x, series, format, label = (r) => String(r[
|
|
|
122
148
|
});
|
|
123
149
|
|
|
124
150
|
const svg = () => box.querySelector('svg');
|
|
125
|
-
// A bar's top: what its positive pieces add up to
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
151
|
+
// A bar's top: what its positive pieces add up to, or the tallest of bars side by side. A step
|
|
152
|
+
// on lines: its highest value.
|
|
153
|
+
// A step without any figure: null, and the card sits on the baseline.
|
|
154
|
+
const top = (r) => {
|
|
155
|
+
const values = series.filter((k) => has(r, k.key)).map((k) => r[k.key]);
|
|
156
|
+
if (!values.length) return null;
|
|
157
|
+
return kind === 'bars' && !grouped ? values.reduce((s, v) => s + (v > 0 ? v : 0), 0) : Math.max(...values);
|
|
158
|
+
};
|
|
130
159
|
const where = (i) => {
|
|
131
160
|
const s = svg();
|
|
132
161
|
const xs = s.scale('x');
|
|
@@ -137,7 +166,7 @@ export const pointer = (box, { rows, x, series, format, label = (r) => String(r[
|
|
|
137
166
|
return {
|
|
138
167
|
cx: r.left - b.left + xs.apply(rows[i][x]) + (xs.bandwidth ?? 0) / 2,
|
|
139
168
|
bw: xs.bandwidth ?? 0,
|
|
140
|
-
y: r.top - b.top + ys.apply(top(rows[i])),
|
|
169
|
+
y: r.top - b.top + (top(rows[i]) === null ? Math.max(...ys.range) : ys.apply(top(rows[i]))),
|
|
141
170
|
y0,
|
|
142
171
|
y1,
|
|
143
172
|
width: b.width,
|
|
@@ -148,8 +177,11 @@ export const pointer = (box, { rows, x, series, format, label = (r) => String(r[
|
|
|
148
177
|
if (i < 0) return;
|
|
149
178
|
at = i;
|
|
150
179
|
const r = rows[i];
|
|
151
|
-
const items = listed
|
|
152
|
-
|
|
180
|
+
const items = listed
|
|
181
|
+
.filter((s) => told(r, s))
|
|
182
|
+
.map((s) => ({ label: s.label, color: s.color, value: has(r, s.key) ? format(r[s.key], s) : empty, swatch: series.length > 1 }));
|
|
183
|
+
const more = extra(r) ?? [];
|
|
184
|
+
card.innerHTML = words(label(r), items, more);
|
|
153
185
|
const q = where(i);
|
|
154
186
|
if (ruled) {
|
|
155
187
|
rule.style.transform = `translateX(${q.cx}px)`;
|
|
@@ -161,7 +193,8 @@ export const pointer = (box, { rows, x, series, format, label = (r) => String(r[
|
|
|
161
193
|
const left = box.getBoundingClientRect().left;
|
|
162
194
|
for (const m of box.querySelectorAll('svg .enter-bar > *')) {
|
|
163
195
|
const b = m.getBoundingClientRect();
|
|
164
|
-
|
|
196
|
+
// Every bar in the step's band: one when stacked, each of a group side by side.
|
|
197
|
+
m.classList.toggle('is-on', Math.abs(b.left + b.width / 2 - left - q.cx) <= Math.max(q.bw, b.width, 2) / 2 + 1);
|
|
165
198
|
}
|
|
166
199
|
box.classList.add('is-dimming');
|
|
167
200
|
}
|
|
@@ -182,7 +215,7 @@ export const pointer = (box, { rows, x, series, format, label = (r) => String(r[
|
|
|
182
215
|
}
|
|
183
216
|
card.style.transform = `translate(${cx}px, ${cy}px)`;
|
|
184
217
|
p.show();
|
|
185
|
-
if (fromKeys) live.textContent =
|
|
218
|
+
if (fromKeys) live.textContent = said(label(r), items, more);
|
|
186
219
|
};
|
|
187
220
|
|
|
188
221
|
// The nearest step with a figure, as Plot's pointer picks it.
|
|
@@ -204,6 +237,85 @@ export const pointer = (box, { rows, x, series, format, label = (r) => String(r[
|
|
|
204
237
|
keys(box, steps.length, () => steps.indexOf(at), (k) => show(steps[k], true), () => p.leave());
|
|
205
238
|
};
|
|
206
239
|
|
|
240
|
+
// A heatmap drawn with heatmap({ pointer: false }): a frame round the cell pointed at, gliding from
|
|
241
|
+
// cell to cell, and the card beside it on the side with room. Keyboard: left and right step
|
|
242
|
+
// through the cells in reading order, up and down go to the same hour in the row above or below,
|
|
243
|
+
// Home and End to the first and last. cells, x, y and value as given to heatmap(); format:
|
|
244
|
+
// (value) → text; label: (cell) → its name; extra as for pointer().
|
|
245
|
+
export const pointerCells = (box, { cells, x, y, value, format = String, label = (c) => `${c[x]}, ${c[y]}`, extra = () => [] }) => {
|
|
246
|
+
const l = layer(box);
|
|
247
|
+
const live = voice(box);
|
|
248
|
+
const frame = el('div', 'chart-pointer-cell', l);
|
|
249
|
+
const card = el('div', 'chart-pointer-card', l);
|
|
250
|
+
const svg = () => box.querySelector('svg');
|
|
251
|
+
const scales = () => ({ xs: svg().scale('x'), ys: svg().scale('y') });
|
|
252
|
+
// Reading order: row by row, then across.
|
|
253
|
+
const { xs: x0, ys: y0 } = scales();
|
|
254
|
+
const order = cells
|
|
255
|
+
.filter((c) => typeof c[value] === 'number')
|
|
256
|
+
.sort((a, b) => y0.domain.indexOf(a[y]) - y0.domain.indexOf(b[y]) || x0.domain.indexOf(a[x]) - x0.domain.indexOf(b[x]));
|
|
257
|
+
let at = -1;
|
|
258
|
+
const p = presence(l, () => {
|
|
259
|
+
at = -1;
|
|
260
|
+
});
|
|
261
|
+
const place = (c) => {
|
|
262
|
+
const { xs, ys } = scales();
|
|
263
|
+
const r = svg().getBoundingClientRect();
|
|
264
|
+
const b = box.getBoundingClientRect();
|
|
265
|
+
return { left: r.left - b.left + xs.apply(c[x]), top: r.top - b.top + ys.apply(c[y]), w: xs.bandwidth, h: ys.bandwidth, width: b.width };
|
|
266
|
+
};
|
|
267
|
+
const show = (i, fromKeys) => {
|
|
268
|
+
if (i < 0) return;
|
|
269
|
+
at = i;
|
|
270
|
+
const c = order[i];
|
|
271
|
+
const items = [{ value: format(c[value]) }];
|
|
272
|
+
const more = extra(c) ?? [];
|
|
273
|
+
card.innerHTML = words(label(c), items, more);
|
|
274
|
+
const q = place(c);
|
|
275
|
+
frame.style.width = `${q.w}px`;
|
|
276
|
+
frame.style.height = `${q.h}px`;
|
|
277
|
+
frame.style.transform = `translate(${q.left}px, ${q.top}px)`;
|
|
278
|
+
const cw = card.offsetWidth;
|
|
279
|
+
const ch = card.offsetHeight;
|
|
280
|
+
const cx = q.left + q.w + 8 + cw > q.width ? q.left - 8 - cw : q.left + q.w + 8;
|
|
281
|
+
card.style.transform = `translate(${cx}px, ${Math.max(q.top + q.h / 2 - ch / 2, 0)}px)`;
|
|
282
|
+
p.show();
|
|
283
|
+
if (fromKeys) live.textContent = said(label(c), items, more);
|
|
284
|
+
};
|
|
285
|
+
const nearest = (e) => {
|
|
286
|
+
const { xs, ys } = scales();
|
|
287
|
+
const r = svg().getBoundingClientRect();
|
|
288
|
+
let best = -1;
|
|
289
|
+
let gap = Infinity;
|
|
290
|
+
order.forEach((c, i) => {
|
|
291
|
+
const d = Math.hypot(r.left + xs.apply(c[x]) + xs.bandwidth / 2 - e.clientX, r.top + ys.apply(c[y]) + ys.bandwidth / 2 - e.clientY);
|
|
292
|
+
if (d < gap) [best, gap] = [i, d];
|
|
293
|
+
});
|
|
294
|
+
return best;
|
|
295
|
+
};
|
|
296
|
+
// The same x in the row `by` rows away, or the nearest x there.
|
|
297
|
+
const vertical = (i, by) => {
|
|
298
|
+
const { xs, ys } = scales();
|
|
299
|
+
const row = ys.domain[ys.domain.indexOf(order[i][y]) + by];
|
|
300
|
+
const there = order.map((c, k) => [c, k]).filter(([c]) => c[y] === row);
|
|
301
|
+
if (!there.length) return i;
|
|
302
|
+
const want = xs.domain.indexOf(order[i][x]);
|
|
303
|
+
return there.reduce((a, b) => (Math.abs(xs.domain.indexOf(b[0][x]) - want) < Math.abs(xs.domain.indexOf(a[0][x]) - want) ? b : a))[1];
|
|
304
|
+
};
|
|
305
|
+
box.onpointermove = (e) => show(nearest(e));
|
|
306
|
+
box.onpointerleave = () => p.leave();
|
|
307
|
+
box.tabIndex = 0;
|
|
308
|
+
box.onkeydown = (e) => {
|
|
309
|
+
if (e.key === 'Escape') return p.leave();
|
|
310
|
+
const from = at < 0 ? 0 : at;
|
|
311
|
+
const to = { ArrowRight: from + 1, ArrowLeft: from - 1, ArrowDown: vertical(from, 1), ArrowUp: vertical(from, -1), Home: 0, End: order.length - 1 }[e.key];
|
|
312
|
+
if (to === undefined) return;
|
|
313
|
+
e.preventDefault();
|
|
314
|
+
show(at < 0 ? 0 : Math.min(Math.max(to, 0), order.length - 1), true);
|
|
315
|
+
};
|
|
316
|
+
box.onblur = () => p.leave();
|
|
317
|
+
};
|
|
318
|
+
|
|
207
319
|
// A donut drawn with donutRing, as in the Donut component: pointing at a slice, or at its row in
|
|
208
320
|
// the list beside the ring, dims the other slices and the other rows' swatches (their words keep
|
|
209
321
|
// full contrast), and the card sits in the ring's hole,
|
package/src/spark.css
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/* A sparkline (./spark.mjs), coloured by --tone on the spark or any parent: the chart colour of what
|
|
2
|
+
it shows, or a status colour when the card is about how a figure compares. Tokens only, so it
|
|
3
|
+
follows the theme. */
|
|
4
|
+
|
|
5
|
+
.spark {
|
|
6
|
+
--spark-tone: var(--tone, var(--c-chart-1));
|
|
7
|
+
display: block;
|
|
8
|
+
flex: none;
|
|
9
|
+
overflow: visible;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
.spark rect {
|
|
13
|
+
fill: var(--spark-tone);
|
|
14
|
+
fill-opacity: 0.85;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
.spark .spark-stroke {
|
|
18
|
+
fill: none;
|
|
19
|
+
stroke: var(--spark-tone);
|
|
20
|
+
stroke-width: 1.5;
|
|
21
|
+
stroke-linejoin: round;
|
|
22
|
+
stroke-linecap: round;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
.spark .spark-fill {
|
|
26
|
+
fill: var(--spark-tone);
|
|
27
|
+
fill-opacity: 0.18;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
.spark .spark-dot {
|
|
31
|
+
fill: var(--spark-tone);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/* The newest value: a ring of surface keeps it apart from the line it ends. */
|
|
35
|
+
.spark .spark-last {
|
|
36
|
+
stroke: var(--c-surface);
|
|
37
|
+
stroke-width: 1.5;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/* The reference: quiet, dashed, under the marks. */
|
|
41
|
+
.spark .spark-ref {
|
|
42
|
+
stroke: var(--c-text-muted);
|
|
43
|
+
stroke-opacity: 0.6;
|
|
44
|
+
stroke-dasharray: 3 2;
|
|
45
|
+
stroke-width: 1;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
@media (forced-colors: active) {
|
|
49
|
+
.spark rect,
|
|
50
|
+
.spark .spark-dot {
|
|
51
|
+
fill: CanvasText;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
.spark .spark-stroke {
|
|
55
|
+
stroke: CanvasText;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
.spark .spark-fill {
|
|
59
|
+
fill: none;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
.spark .spark-ref {
|
|
63
|
+
stroke: GrayText;
|
|
64
|
+
stroke-opacity: 1;
|
|
65
|
+
}
|
|
66
|
+
}
|
package/src/spark.mjs
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// A sparkline: a small chart beside a figure, for the shape of its recent run and nothing more.
|
|
2
|
+
// Bars, a line or an area, from zero, with a reference dashed across it when it falls inside, such
|
|
3
|
+
// as a benchmark or a target. No axes, no labels, no pointer: the figure beside it says the number.
|
|
4
|
+
//
|
|
5
|
+
// Output is an SVG string with classes, not colours: ./spark.css colours it from `--tone` on the
|
|
6
|
+
// spark or any parent, so a card sets its tone once for its badge and its spark. A string, so the
|
|
7
|
+
// same spark draws at build time and in the page.
|
|
8
|
+
//
|
|
9
|
+
// import { sparkline } from '@n1kname/charts/spark';
|
|
10
|
+
// import '@n1kname/charts/spark.css';
|
|
11
|
+
//
|
|
12
|
+
// card.insertAdjacentHTML('beforeend', sparkline([7.1, 7.4, 6.8, 7.9], { kind: 'line', reference: 7 }));
|
|
13
|
+
|
|
14
|
+
const esc = (s) => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
15
|
+
const n = (v) => +v.toFixed(2);
|
|
16
|
+
const has = (v) => typeof v === 'number' && Number.isFinite(v);
|
|
17
|
+
|
|
18
|
+
export const SPARK_KINDS = ['bar', 'line', 'area'];
|
|
19
|
+
|
|
20
|
+
// values: numbers, oldest first; a missing one (null) is a gap. kind: 'bar', 'line' or 'area'.
|
|
21
|
+
// reference: a value dashed across, drawn only when it falls inside the scale. width and height in
|
|
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. zero: false
|
|
24
|
+
// for a line or area scaled to its own values, for a rate that only moves a little; bars always
|
|
25
|
+
// stand on zero.
|
|
26
|
+
export const sparkline = (values, { kind = 'bar', reference, width = 72, height = 44, label, last = false, zero = true } = {}) => {
|
|
27
|
+
const shown = values.filter(has);
|
|
28
|
+
if (!shown.length) return '';
|
|
29
|
+
if (!SPARK_KINDS.includes(kind)) throw new Error(`sparkline: kind is one of ${SPARK_KINDS.join(', ')}, not ${kind}`);
|
|
30
|
+
// From zero, with a little headroom so the top bar or the peak doesn't touch the edge. Below
|
|
31
|
+
// zero when a value is. Without zero, the values' own range with a tenth of it either side.
|
|
32
|
+
const own = !zero && kind !== 'bar';
|
|
33
|
+
const spread = Math.max(...shown) - Math.min(...shown) || Math.abs(shown[0]) || 1;
|
|
34
|
+
const lo = own ? Math.min(...shown) - spread * 0.1 : Math.min(0, ...shown);
|
|
35
|
+
const hi = own ? Math.max(...shown) + spread * 0.1 : Math.max(0, ...shown) * 1.05 || 1;
|
|
36
|
+
const [l, r, t, b] = [2, 2, 4, 2];
|
|
37
|
+
const iw = width - l - r;
|
|
38
|
+
const ih = height - t - b;
|
|
39
|
+
const y = (v) => t + ih - ((v - lo) / (hi - lo || 1)) * ih;
|
|
40
|
+
// What bars stand on and an area closes on: zero, or the scale's foot when zero is below it.
|
|
41
|
+
const base = y(Math.max(lo, Math.min(0, hi)));
|
|
42
|
+
let marks = '';
|
|
43
|
+
if (kind === 'bar') {
|
|
44
|
+
const band = iw / values.length;
|
|
45
|
+
// Thin bars when there are many, so they stay apart.
|
|
46
|
+
const bw = Math.min(values.length > 8 ? 4 : 7, band * 0.8);
|
|
47
|
+
marks = values
|
|
48
|
+
.map((v, i) =>
|
|
49
|
+
has(v) ? `<rect x="${n(l + band * i + (band - bw) / 2)}" y="${n(Math.min(y(v), base))}" width="${n(bw)}" height="${n(Math.abs(base - y(v)))}" rx="1"/>` : '',
|
|
50
|
+
)
|
|
51
|
+
.join('');
|
|
52
|
+
} else {
|
|
53
|
+
const step = values.length > 1 ? iw / (values.length - 1) : 0;
|
|
54
|
+
// One run per stretch without a gap; one value alone sits in the middle.
|
|
55
|
+
const runs = [];
|
|
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('');
|
|
65
|
+
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
|
+
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 && has(values.at(-1)) ? paths.at(-1).at(-1) : null;
|
|
68
|
+
marks = fill + stroke + (end ? `<circle class="spark-dot spark-last" cx="${n(end[0])}" cy="${n(end[1])}" r="2.5"/>` : '');
|
|
69
|
+
}
|
|
70
|
+
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
|
+
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>`;
|
|
73
|
+
};
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// Synthetic values only.
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { parseHTML } from 'linkedom';
|
|
4
|
+
import { sparkline } from './spark.mjs';
|
|
5
|
+
|
|
6
|
+
const svg = (html) => parseHTML(`<div>${html}</div>`).document.querySelector('svg');
|
|
7
|
+
|
|
8
|
+
assert.equal(sparkline([]), '', 'nothing to draw, no svg');
|
|
9
|
+
assert.equal(sparkline([null, null]), '', 'only gaps, no svg');
|
|
10
|
+
assert.throws(() => sparkline([1], { kind: 'pie' }), /kind is one of/);
|
|
11
|
+
|
|
12
|
+
// Bars: one per value, from the baseline, a gap left empty.
|
|
13
|
+
const bars = svg(sparkline([4, 8, null, 2], { kind: 'bar' }));
|
|
14
|
+
assert.equal(bars.getAttribute('data-kind'), 'bar');
|
|
15
|
+
assert.equal(bars.querySelectorAll('rect').length, 3, 'a missing value draws no bar');
|
|
16
|
+
assert.equal(bars.getAttribute('aria-hidden'), 'true', 'hidden without a label');
|
|
17
|
+
const heights = [...bars.querySelectorAll('rect')].map((r) => Number(r.getAttribute('height')));
|
|
18
|
+
assert.ok(heights[1] > heights[0] && heights[0] > heights[2], 'taller for more');
|
|
19
|
+
const bottoms = [...bars.querySelectorAll('rect')].map((r) => Number(r.getAttribute('y')) + Number(r.getAttribute('height')));
|
|
20
|
+
assert.ok(bottoms.every((b) => Math.abs(b - bottoms[0]) < 0.02), 'every bar stands on the baseline');
|
|
21
|
+
|
|
22
|
+
// Many bars are thinner.
|
|
23
|
+
const thin = svg(sparkline(Array.from({ length: 12 }, (_, i) => i + 1)));
|
|
24
|
+
assert.ok(Number(thin.querySelector('rect').getAttribute('width')) <= 4);
|
|
25
|
+
|
|
26
|
+
// The reference: drawn inside the scale, left out above it.
|
|
27
|
+
assert.ok(svg(sparkline([4, 8], { reference: 6 })).querySelector('.spark-ref'), 'a reference inside is dashed across');
|
|
28
|
+
assert.equal(svg(sparkline([4, 8], { reference: 20 })).querySelector('.spark-ref'), null, 'a reference above the top is left out');
|
|
29
|
+
assert.equal(svg(sparkline([4, 8], { reference: null })).querySelector('.spark-ref'), null);
|
|
30
|
+
|
|
31
|
+
// Lines: a path per run, broken at a gap; a lone value is a dot.
|
|
32
|
+
const line = svg(sparkline([3, 5, null, 4, 6], { kind: 'line' }));
|
|
33
|
+
assert.equal(line.querySelectorAll('.spark-stroke').length, 2, 'a gap breaks the line');
|
|
34
|
+
assert.equal(line.querySelector('.spark-fill'), null, 'a line has no fill');
|
|
35
|
+
const lone = svg(sparkline([3, null, 5], { kind: 'line' }));
|
|
36
|
+
assert.equal(lone.querySelectorAll('.spark-dot').length, 2, 'a value between gaps is a dot');
|
|
37
|
+
|
|
38
|
+
// Areas: a fill under each run, closed on the baseline.
|
|
39
|
+
const area = svg(sparkline([3, 5, 4], { kind: 'area', last: true }));
|
|
40
|
+
assert.equal(area.querySelectorAll('.spark-fill').length, 1);
|
|
41
|
+
assert.match(area.querySelector('.spark-fill').getAttribute('d'), /Z$/);
|
|
42
|
+
assert.ok(area.querySelector('.spark-last'), 'last: a dot on the newest value');
|
|
43
|
+
|
|
44
|
+
// A label makes it an image with a name.
|
|
45
|
+
const named = svg(sparkline([1, 2], { label: 'Steps, last 12 months <rising>' }));
|
|
46
|
+
assert.equal(named.getAttribute('role'), 'img');
|
|
47
|
+
assert.equal(named.getAttribute('aria-label'), 'Steps, last 12 months <rising>');
|
|
48
|
+
|
|
49
|
+
// Below zero: the baseline moves up, bars run down from it.
|
|
50
|
+
const neg = svg(sparkline([-2, 4], { kind: 'bar' }));
|
|
51
|
+
const [down, up] = [...neg.querySelectorAll('rect')].map((r) => ({ y: Number(r.getAttribute('y')), h: Number(r.getAttribute('height')) }));
|
|
52
|
+
assert.ok(Math.abs(down.y - (up.y + up.h)) < 0.02, 'a negative bar hangs from the baseline');
|
|
53
|
+
|
|
54
|
+
// zero: false scales a line to its own values; bars keep zero.
|
|
55
|
+
const flat = svg(sparkline([7.0, 7.2], { kind: 'line' })).querySelector('.spark-stroke').getAttribute('d');
|
|
56
|
+
const own = svg(sparkline([7.0, 7.2], { kind: 'line', zero: false })).querySelector('.spark-stroke').getAttribute('d');
|
|
57
|
+
const rise = (d) => { const ys = [...d.matchAll(/[ML][\d.]+ ([\d.]+)/g)].map((m) => Number(m[1])); return ys[0] - ys[1]; };
|
|
58
|
+
assert.ok(rise(own) > rise(flat) * 5, 'its own range shows the change');
|
|
59
|
+
assert.ok(svg(sparkline([7.0, 7.2], { kind: 'line', zero: false, reference: 7.1 })).querySelector('.spark-ref'), 'a reference inside its range');
|
|
60
|
+
assert.equal(svg(sparkline([7.0, 7.2], { kind: 'line', zero: false, reference: 3 })).querySelector('.spark-ref'), null, 'one below it is left out');
|
|
61
|
+
const areaOwn = svg(sparkline([7.0, 7.2], { kind: 'area', zero: false, height: 44 })).querySelector('.spark-fill').getAttribute('d');
|
|
62
|
+
assert.match(areaOwn, / 42Z$/, 'an area on its own range closes on the foot');
|
|
63
|
+
const keepBars = svg(sparkline([7.0, 7.2], { kind: 'bar', zero: false }));
|
|
64
|
+
assert.ok(Number(keepBars.querySelector('rect').getAttribute('height')) > 30, 'bars always stand on zero');
|
|
65
|
+
|
|
66
|
+
// Size.
|
|
67
|
+
const big = svg(sparkline([1, 2], { width: 120, height: 32 }));
|
|
68
|
+
assert.equal(big.getAttribute('viewBox'), '0 0 120 32');
|
|
69
|
+
console.log('spark: all assertions pass');
|