@n1kname/charts 0.10.0 → 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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@n1kname/charts",
3
- "version": "0.10.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/index.mjs CHANGED
@@ -4,3 +4,4 @@ export * from './plot.mjs';
4
4
  export * from './lines.mjs';
5
5
  export * from './bars.mjs';
6
6
  export * from './heatmap.mjs';
7
+ export * from './spark.mjs';
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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
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');