@n1kname/charts 0.10.0 → 0.12.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.12.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -11,12 +11,17 @@
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",
17
19
  "./pointer.css": "./src/pointer.css",
18
20
  "./months": "./src/months.mjs",
19
- "./drawn": "./src/drawn.mjs"
21
+ "./drawn": "./src/drawn.mjs",
22
+ "./trace": "./src/trace.mjs",
23
+ "./trace.css": "./src/trace.css",
24
+ "./hexbin": "./src/hexbin.mjs"
20
25
  },
21
26
  "dependencies": {
22
27
  "@observablehq/plot": "0.6.17",
@@ -35,6 +40,6 @@
35
40
  "src"
36
41
  ],
37
42
  "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"
43
+ "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 && node src/trace.test.mjs && node src/hexbin.test.mjs"
39
44
  }
40
45
  }
package/src/enter.mjs CHANGED
@@ -9,8 +9,12 @@
9
9
  // there. Runs on the Web Animations API, so a mark keeps its own transform and the page needs no
10
10
  // stylesheet for it.
11
11
 
12
- const BAR = 700;
13
- const LINE = 1000;
12
+ import { ms } from './update.mjs';
13
+
14
+ // Bars grow and lines draw over the tokens' grow and draw, read as a chart arrives, so a site
15
+ // that tunes them is followed.
16
+ const BAR = () => ms('--motion-grow', 700);
17
+ const LINE = () => ms('--motion-draw', 1000);
14
18
  const CELL = 420;
15
19
  const SWEEP = 420; // the longest a left-to-right stagger may take
16
20
 
@@ -64,26 +68,26 @@ const svgParts = (svg) => {
64
68
  rects.forEach((rect, i) => {
65
69
  rect.style.transformBox = 'view-box';
66
70
  rect.style.transformOrigin = `0 ${zero}px`;
67
- parts.push([rect, [{ transform: 'scaleY(0)' }, { transform: 'scaleY(1)' }], { duration: BAR, delay: at(i), easing: spring() }]);
71
+ parts.push([rect, [{ transform: 'scaleY(0)' }, { transform: 'scaleY(1)' }], { duration: BAR(), delay: at(i), easing: spring() }]);
68
72
  });
69
73
  }
70
74
  svg.querySelectorAll('.enter-line path').forEach((path) => {
71
75
  path.setAttribute('pathLength', '1');
72
- parts.push([path, [{ strokeDasharray: '1 1', strokeDashoffset: 1 }, { strokeDasharray: '1 1', strokeDashoffset: 0 }], { duration: LINE, easing: DRAW }]);
76
+ parts.push([path, [{ strokeDasharray: '1 1', strokeDashoffset: 1 }, { strokeDasharray: '1 1', strokeDashoffset: 0 }], { duration: LINE(), easing: DRAW }]);
73
77
  });
74
- // A dot appears as its line reaches it; the line covers the width in LINE.
78
+ // A dot fades in, from nearly its size, as its line reaches it; the line covers the width in LINE.
75
79
  const dots = [...svg.querySelectorAll('.enter-dot circle')];
76
- const dotAt = sweep(dots, LINE * 0.8);
80
+ const dotAt = sweep(dots, LINE() * 0.8);
77
81
  dots.forEach((dot, i) => {
78
82
  dot.style.transformBox = 'fill-box';
79
83
  dot.style.transformOrigin = 'center';
80
- parts.push([dot, [{ opacity: 0, transform: 'scale(0.4)' }, { opacity: 1, transform: 'scale(1)' }], { duration: 280, delay: dotAt(i), easing: OUT }]);
84
+ parts.push([dot, [{ opacity: 0, transform: 'scale(0.8)' }, { opacity: 1, transform: 'scale(1)' }], { duration: 280, delay: dotAt(i), easing: OUT }]);
81
85
  });
82
86
  const cells = [...svg.querySelectorAll('.enter-cell rect')];
83
87
  const cellAt = sweep(cells, 500);
84
88
  cells.forEach((cell, i) => parts.push([cell, [{ opacity: 0 }, { opacity: 1 }], { duration: CELL, delay: cellAt(i), easing: OUT }]));
85
89
  // Words and shading land once the marks they belong to have.
86
- const last = rects.length ? BAR + SWEEP * 0.6 : parts.length ? LINE * 0.7 : 0;
90
+ const last = rects.length ? BAR() + SWEEP * 0.6 : parts.length ? LINE() * 0.7 : 0;
87
91
  svg.querySelectorAll('.enter-fade').forEach((g) => parts.push([g, [{ opacity: 0 }, { opacity: 1 }], { duration: 300, delay: last, easing: OUT }]));
88
92
  return parts;
89
93
  };
@@ -91,8 +95,8 @@ const svgParts = (svg) => {
91
95
  // Ranked bars are HTML: each bar grows from the left, top to bottom.
92
96
  const htmlParts = (root) =>
93
97
  [...root.querySelectorAll('.ranked-bars i')].flatMap((bar, i, all) => [
94
- [bar, [{ transform: 'scaleX(0)' }, { transform: 'scaleX(1)' }], { duration: BAR, delay: (i / Math.max(all.length - 1, 1)) * SWEEP * 0.6, easing: spring() }],
95
- [bar.nextElementSibling, [{ opacity: 0 }, { opacity: 1 }], { duration: 300, delay: BAR * 0.6 + (i / Math.max(all.length - 1, 1)) * SWEEP * 0.6, easing: OUT }],
98
+ [bar, [{ transform: 'scaleX(0)' }, { transform: 'scaleX(1)' }], { duration: BAR(), delay: (i / Math.max(all.length - 1, 1)) * SWEEP * 0.6, easing: spring() }],
99
+ [bar.nextElementSibling, [{ opacity: 0 }, { opacity: 1 }], { duration: 300, delay: BAR() * 0.6 + (i / Math.max(all.length - 1, 1)) * SWEEP * 0.6, easing: OUT }],
96
100
  ]).filter(([el]) => el);
97
101
 
98
102
  /**
package/src/hexbin.mjs ADDED
@@ -0,0 +1,87 @@
1
+ // Points on a map, counted into hexagons: where things happen most, without a dot for each one.
2
+ // The hexagons are pointy-topped and the same size on the ground everywhere on the map (in metres,
3
+ // on a flat projection around `origin`), so a busy hexagon is busy, not big.
4
+ //
5
+ // Each hexagon gets two values from 0 to 1 for drawing, because counts like these are lopsided,
6
+ // with a few places that dwarf the rest:
7
+ // rank the count's place among the distinct counts: the colour. The busiest few always read
8
+ // as hot, and one huge count doesn't turn every other hexagon cold.
9
+ // height log(count) / log(most): how far it rises in 3D. A log, so one busy cell doesn't
10
+ // flatten the rest.
11
+ //
12
+ // Pure: no map library. Hand the features to MapLibre (see the components' hexmap.js) or anything
13
+ // that draws GeoJSON.
14
+ //
15
+ // import { hexbin, hexFeatures } from '@n1kname/charts/hexbin';
16
+ //
17
+ // const bins = hexbin(points, { size: 200, origin: [lon, lat] });
18
+ // map.getSource('hexes').setData(hexFeatures(bins));
19
+
20
+ const M_PER_DEG = 111_320;
21
+ // The corners of a pointy-top hexagon, from its centre.
22
+ const CORNERS = Array.from({ length: 6 }, (_, i) => ((30 + 60 * i) * Math.PI) / 180);
23
+
24
+ // Rounds fractional axial coordinates to the hexagon they fall in (cube rounding).
25
+ const roundAxial = (q, r) => {
26
+ const s = -q - r;
27
+ let rq = Math.round(q);
28
+ let rr = Math.round(r);
29
+ const rs = Math.round(s);
30
+ const [dq, dr, ds] = [Math.abs(rq - q), Math.abs(rr - r), Math.abs(rs - s)];
31
+ if (dq > dr && dq > ds) rq = -rr - rs;
32
+ else if (dr > ds) rr = -rq - rs;
33
+ return [rq, rr];
34
+ };
35
+
36
+ /** The middle of the points, rounded to a tenth of a degree, so the grid stays put as they change. */
37
+ export const centreOf = (points) => {
38
+ const avg = (k) => points.reduce((s, p) => s + p[k], 0) / points.length;
39
+ return [Math.round(avg('lon') * 10) / 10, Math.round(avg('lat') * 10) / 10];
40
+ };
41
+
42
+ // points: [{ lon, lat, count? }], count 1 when missing. size: a hexagon's centre to corner, in
43
+ // metres. origin: [lon, lat] the grid is measured from; give a fixed one so the hexagons don't move
44
+ // between, say, one year and the next. gap: the share of each hexagon left empty at its edge.
45
+ export const hexbin = (points, { size = 200, origin, gap = 0.08 } = {}) => {
46
+ const usable = points.filter((p) => Number.isFinite(p?.lon) && Number.isFinite(p?.lat));
47
+ if (!usable.length) return [];
48
+ const [lon0, lat0] = origin ?? centreOf(usable);
49
+ const latM = M_PER_DEG;
50
+ const lonM = M_PER_DEG * Math.cos((lat0 * Math.PI) / 180);
51
+ const bins = new Map();
52
+ for (const p of usable) {
53
+ const mx = (p.lon - lon0) * lonM;
54
+ const my = (p.lat - lat0) * latM;
55
+ const [q, r] = roundAxial(((Math.sqrt(3) / 3) * mx - (1 / 3) * my) / size, ((2 / 3) * my) / size);
56
+ const key = `${q},${r}`;
57
+ const count = p.count ?? 1;
58
+ const bin = bins.get(key);
59
+ if (bin) bin.count += count;
60
+ else bins.set(key, { key, x: size * Math.sqrt(3) * (q + r / 2), y: size * 1.5 * r, count });
61
+ }
62
+ const all = [...bins.values()].filter((b) => b.count > 0);
63
+ if (!all.length) return all;
64
+ const maxLog = Math.log1p(Math.max(...all.map((b) => b.count)));
65
+ const distinct = [...new Set(all.map((b) => b.count))].sort((a, b) => a - b);
66
+ const rank = new Map(distinct.map((c, i) => [c, distinct.length === 1 ? 1 : i / (distinct.length - 1)]));
67
+ const drawn = size * (1 - gap);
68
+ for (const b of all) {
69
+ b.rank = rank.get(b.count);
70
+ b.height = Math.log1p(b.count) / maxLog;
71
+ b.centre = [lon0 + b.x / lonM, lat0 + b.y / latM];
72
+ const ring = CORNERS.map((a) => [lon0 + (b.x + drawn * Math.cos(a)) / lonM, lat0 + (b.y + drawn * Math.sin(a)) / latM]);
73
+ b.ring = [...ring, ring[0]];
74
+ }
75
+ return all;
76
+ };
77
+
78
+ /** The hexagons as a GeoJSON FeatureCollection, with count, rank and height on each. */
79
+ export const hexFeatures = (bins) => ({
80
+ type: 'FeatureCollection',
81
+ features: bins.map((b) => ({
82
+ type: 'Feature',
83
+ id: b.key,
84
+ geometry: { type: 'Polygon', coordinates: [b.ring] },
85
+ properties: { key: b.key, count: b.count, rank: b.rank, height: b.height },
86
+ })),
87
+ });
@@ -0,0 +1,55 @@
1
+ // Synthetic points only, around 0° 0° in open sea.
2
+ import assert from 'node:assert/strict';
3
+ import { centreOf, hexbin, hexFeatures } from './hexbin.mjs';
4
+
5
+ assert.deepEqual(hexbin([]), []);
6
+ assert.deepEqual(hexbin([{ lon: NaN, lat: 0 }]), [], 'unusable points are skipped');
7
+
8
+ // Points within a few metres share a hexagon; their counts add up.
9
+ const near = hexbin([{ lon: 0, lat: 0, count: 3 }, { lon: 0.00001, lat: 0.00001, count: 2 }, { lon: 0, lat: 0 }], { origin: [0, 0] });
10
+ assert.equal(near.length, 1);
11
+ assert.equal(near[0].count, 6, 'counts add, a missing count is one');
12
+
13
+ // A point a kilometre away is another hexagon.
14
+ const apart = hexbin([{ lon: 0, lat: 0 }, { lon: 0.01, lat: 0 }], { origin: [0, 0], size: 200 });
15
+ assert.equal(apart.length, 2);
16
+
17
+ // Rank by distinct counts: the busiest is 1, the quietest 0, ties share a rank.
18
+ const spread = hexbin(
19
+ [
20
+ { lon: 0, lat: 0, count: 1 },
21
+ { lon: 0.01, lat: 0, count: 1 },
22
+ { lon: 0.02, lat: 0, count: 10 },
23
+ { lon: 0.03, lat: 0, count: 10000 },
24
+ ],
25
+ { origin: [0, 0] },
26
+ );
27
+ const by = Object.fromEntries(spread.map((b) => [b.count, b]));
28
+ assert.equal(by[1].rank, 0);
29
+ assert.equal(by[10].rank, 0.5, 'the middle count is half, however far below the top');
30
+ assert.equal(by[10000].rank, 1);
31
+ assert.equal(by[10000].height, 1);
32
+ assert.ok(by[10].height > 0.2, 'log height: 10 against 10,000 still rises');
33
+ assert.equal(hexbin([{ lon: 0, lat: 0, count: 4 }], { origin: [0, 0] })[0].rank, 1, 'one count alone is hot');
34
+
35
+ // The grid is fixed by its origin: the same point lands in the same hexagon with other points around.
36
+ const a = hexbin([{ lon: 0.0123, lat: 0.0045 }], { origin: [0, 0] })[0].key;
37
+ const b = hexbin([{ lon: 0.0123, lat: 0.0045 }, { lon: 0.05, lat: 0.05 }], { origin: [0, 0] }).find((x) => x.count === 1 && Math.abs(x.centre[0] - 0.0123) < 0.003).key;
38
+ assert.equal(a, b);
39
+
40
+ // Hexagons are closed rings of six corners, a little smaller than their spacing.
41
+ const [h] = hexbin([{ lon: 0, lat: 0 }], { origin: [0, 0], size: 200, gap: 0.1 });
42
+ assert.equal(h.ring.length, 7);
43
+ assert.deepEqual(h.ring[0], h.ring[6]);
44
+ const widthM = (Math.max(...h.ring.map((p) => p[0])) - Math.min(...h.ring.map((p) => p[0]))) * 111_320;
45
+ assert.ok(Math.abs(widthM - 200 * 0.9 * Math.sqrt(3)) < 1, 'pointy-top width is √3 × the drawn size');
46
+
47
+ // Without an origin, the grid is measured from the points' middle, to a tenth of a degree.
48
+ assert.deepEqual(centreOf([{ lon: 0.04, lat: -0.02 }, { lon: 0.08, lat: 0.06 }]), [0.1, 0]);
49
+
50
+ // GeoJSON for the map.
51
+ const fc = hexFeatures(spread);
52
+ assert.equal(fc.type, 'FeatureCollection');
53
+ assert.equal(fc.features.length, 4);
54
+ assert.deepEqual(Object.keys(fc.features[0].properties).sort(), ['count', 'height', 'key', 'rank']);
55
+ console.log('hexbin: ok');
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/pointer.mjs CHANGED
@@ -82,16 +82,22 @@ const said = (title, items, extra = []) =>
82
82
  ...extra.map((e) => (Array.isArray(e) ? e.join(' ') : e)),
83
83
  ].join(', ')}`;
84
84
 
85
- // Appearing, moving, leaving. The first showing is in place; after that, everything glides.
85
+ // Appearing, moving, leaving. The first showing is in place, and so is every step from the keys:
86
+ // a key press is one deliberate move, and a glide would make it wait. Pointer moves glide.
87
+ // The class is read once before it comes off, so a glide already started lands at once.
86
88
  const presence = (l, onLeave) => {
87
89
  let hide;
88
90
  return {
89
- show() {
91
+ show(fromKeys = false) {
90
92
  clearTimeout(hide);
91
93
  const first = !l.classList.contains('is-on');
92
- l.classList.toggle('is-jump', first);
94
+ const jump = first || fromKeys;
95
+ l.classList.toggle('is-jump', jump);
93
96
  l.classList.add('is-on');
94
- if (first) requestAnimationFrame(() => l.classList.remove('is-jump'));
97
+ if (jump) {
98
+ void l.offsetWidth;
99
+ requestAnimationFrame(() => l.classList.remove('is-jump'));
100
+ }
95
101
  return first;
96
102
  },
97
103
  leave() {
@@ -214,7 +220,7 @@ export const pointer = (box, { rows, x, series, format, label = (r) => String(r[
214
220
  cy = Math.min(Math.max(q.y - ch / 2, 0), q.y1 - ch);
215
221
  }
216
222
  card.style.transform = `translate(${cx}px, ${cy}px)`;
217
- p.show();
223
+ p.show(fromKeys);
218
224
  if (fromKeys) live.textContent = said(label(r), items, more);
219
225
  };
220
226
 
@@ -279,7 +285,7 @@ export const pointerCells = (box, { cells, x, y, value, format = String, label =
279
285
  const ch = card.offsetHeight;
280
286
  const cx = q.left + q.w + 8 + cw > q.width ? q.left - 8 - cw : q.left + q.w + 8;
281
287
  card.style.transform = `translate(${cx}px, ${Math.max(q.top + q.h / 2 - ch / 2, 0)}px)`;
282
- p.show();
288
+ p.show(fromKeys);
283
289
  if (fromKeys) live.textContent = said(label(c), items, more);
284
290
  };
285
291
  const nearest = (e) => {
@@ -349,7 +355,7 @@ export const pointerDonut = (root, { parts, format = String, share = true }) =>
349
355
  root.classList.add('is-dimming');
350
356
  const c = ring.getBoundingClientRect().width / 2;
351
357
  card.style.transform = `translate(${c - card.offsetWidth / 2}px, ${c - card.offsetHeight / 2}px)`;
352
- p.show();
358
+ p.show(fromKeys);
353
359
  if (fromKeys) live.textContent = `${d.label}: ${value}${share ? `, ${pct}` : ''}`;
354
360
  };
355
361
  [...paths, ...items].forEach((n, k) => {
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');
package/src/trace.css ADDED
@@ -0,0 +1,42 @@
1
+ /* A trace (./trace.mjs) on recorder paper: the paper tinted with the first chart colour, as ECG
2
+ paper is pink, and the line in the text colour, the darkest mark on the page in both themes. The
3
+ words are the page's muted text in a system font: Safari misplaces SVG text set in a web font. */
4
+
5
+ .trace {
6
+ display: block;
7
+ width: 100%;
8
+ height: auto;
9
+ overflow: visible;
10
+ }
11
+
12
+ .trace .trace-minor,
13
+ .trace .trace-major {
14
+ fill: none;
15
+ stroke: var(--c-chart-1);
16
+ stroke-width: 1;
17
+ vector-effect: non-scaling-stroke;
18
+ shape-rendering: crispEdges;
19
+ }
20
+
21
+ .trace .trace-minor {
22
+ stroke-opacity: 0.12;
23
+ }
24
+
25
+ .trace .trace-major {
26
+ stroke-opacity: 0.3;
27
+ }
28
+
29
+ .trace .trace-line {
30
+ fill: none;
31
+ stroke: var(--c-text);
32
+ stroke-width: 1.25;
33
+ stroke-linejoin: round;
34
+ stroke-linecap: round;
35
+ vector-effect: non-scaling-stroke;
36
+ }
37
+
38
+ .trace .trace-time {
39
+ fill: var(--c-text-muted);
40
+ font: 11px/1 system-ui, -apple-system, 'Segoe UI', sans-serif;
41
+ font-variant-numeric: tabular-nums;
42
+ }
package/src/trace.mjs ADDED
@@ -0,0 +1,142 @@
1
+ // A trace: one long signal sampled many times a second, such as an ECG, drawn on paper the way a
2
+ // recorder draws it. The recording is cut into strips of a few seconds, one under the other, so a
3
+ // 30-second recording stays readable at any width instead of squeezing into one flat line.
4
+ //
5
+ // The paper keeps the recorder's proportions: 0.2 seconds across is as wide as 0.5 millivolts is
6
+ // tall (25 mm/s and 10 mm/mV), so a beat has the shape a clinician expects. Its finest squares are
7
+ // left out when they would be closer than 6px.
8
+ //
9
+ // Every sample can't get a pixel: a 30-second ECG has over 15,000. Each column of the strip keeps
10
+ // its lowest and highest value, so the narrow spikes of a beat survive at any width. (Taking every
11
+ // nth sample, as dash's first version did, can drop a spike altogether.)
12
+ //
13
+ // Output is an SVG string with classes, not colours: ./trace.css colours the paper and the line
14
+ // from tokens. A string, so the same trace draws at build time and in the page. The line is tagged
15
+ // for ./enter.mjs, so it draws in from the start the first time it shows.
16
+ //
17
+ // import { trace } from '@n1kname/charts/trace';
18
+ // import '@n1kname/charts/trace.css';
19
+ //
20
+ // box.innerHTML = trace(samples, { rate: 512, width: box.clientWidth });
21
+
22
+ const n = (v) => +v.toFixed(1);
23
+ const esc = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
24
+
25
+ // The recorder's paper: the time each square stands for, finest first. Its height in millivolts is
26
+ // 2.5 times its width in seconds.
27
+ const SQUARES = [0.04, 0.2, 1, 5];
28
+ const MV_PER_S = 2.5;
29
+ // The shortest strip, in px per second, before strips get shorter: about 60px a second keeps a beat
30
+ // wider than it is tall.
31
+ const MIN_PX_PER_S = 60;
32
+ const STRIPS = [10, 5, 2.5];
33
+
34
+ /** How many seconds a strip holds at this width: 10, 5 or 2.5. */
35
+ export const stripSeconds = (width) => STRIPS.find((s) => width / s >= MIN_PX_PER_S) ?? STRIPS.at(-1);
36
+
37
+ // The lowest and highest value of each column, in sample order, so the path goes down and up
38
+ // through a spike instead of skipping it.
39
+ export const envelope = (values, columns) => {
40
+ if (values.length <= columns * 2) return values.map((v, i) => [i, v]);
41
+ const out = [];
42
+ const per = values.length / columns;
43
+ for (let c = 0; c < columns; c++) {
44
+ const from = Math.floor(c * per);
45
+ const to = Math.min(values.length, Math.floor((c + 1) * per));
46
+ let lo = from;
47
+ let hi = from;
48
+ for (let i = from; i < to; i++) {
49
+ if (values[i] < values[lo]) lo = i;
50
+ if (values[i] > values[hi]) hi = i;
51
+ }
52
+ if (lo === hi) out.push([lo, values[lo]]);
53
+ else if (lo < hi) out.push([lo, values[lo]], [hi, values[hi]]);
54
+ else out.push([hi, values[hi]], [lo, values[lo]]);
55
+ }
56
+ return out;
57
+ };
58
+
59
+ // values: the samples, in order. rate: samples per second. perMv: how many of the values' unit make
60
+ // a millivolt (1000 for microvolts). width: in px. seconds: per strip, or chosen by width. gain: 2
61
+ // draws the signal twice as tall on the same paper, for a weak one. label: what a screen reader
62
+ // hears.
63
+ export const trace = (values, { rate, perMv = 1000, width = 800, seconds, gain = 1, label = 'The trace' } = {}) => {
64
+ const samples = values.filter((v) => typeof v === 'number' && Number.isFinite(v));
65
+ if (!samples.length || !(rate > 0)) return '';
66
+ const strip = seconds ?? stripSeconds(width);
67
+ const duration = samples.length / rate;
68
+ const rows = Math.max(1, Math.ceil(duration / strip - 1e-9));
69
+ const [left, right, gap, labelRoom] = [0, 0, 10, 16];
70
+ const inner = width - left - right;
71
+ const pxPerS = inner / strip;
72
+ const pxPerMv = (pxPerS / MV_PER_S) * gain;
73
+
74
+ // The squares: the finest at least 6px apart, and every fifth one bold (the next size up).
75
+ const minor = SQUARES.find((s) => s * pxPerS >= 6) ?? SQUARES.at(-1);
76
+ const major = SQUARES[SQUARES.indexOf(minor) + 1] ?? minor * 5;
77
+
78
+ // Every strip has the same height and the same zero, from the whole recording: at least 2 mV,
79
+ // so a quiet trace doesn't fill the paper, and at most 6, so one artefact doesn't shrink the rest.
80
+ const mv = samples.map((v) => v / perMv);
81
+ const low = Math.max(-3, Math.min(-0.5, ...mv));
82
+ const high = Math.min(3, Math.max(1, ...mv));
83
+ const span = Math.max(2, high - low);
84
+ const pad = 4;
85
+ const band = span * pxPerMv + pad * 2;
86
+ const rowHeight = labelRoom + band;
87
+ const height = rows * rowHeight + (rows - 1) * gap;
88
+ // The square size in px, for the grid's horizontal lines, which share the vertical ones' spacing.
89
+ const minorPx = minor * pxPerS;
90
+ const majorPx = major * pxPerS;
91
+
92
+ const perStrip = Math.round(strip * rate);
93
+ const parts = [];
94
+ for (let r = 0; r < rows; r++) {
95
+ const top = r * (rowHeight + gap);
96
+ const paperTop = top + labelRoom;
97
+ const zero = paperTop + pad + high * pxPerMv;
98
+ const slice = samples.slice(r * perStrip, (r + 1) * perStrip);
99
+ const stripWidth = (slice.length / rate) * pxPerS;
100
+ // The paper runs the full width on every strip, so the last, shorter strip still reads as paper.
101
+ let minorLines = '';
102
+ let majorLines = '';
103
+ for (let x = 0; x <= inner + 0.01; x += minorPx) {
104
+ const at = n(left + x);
105
+ const isMajor = Math.abs(x / majorPx - Math.round(x / majorPx)) < 1e-6;
106
+ const line = `M${at} ${n(paperTop)}V${n(paperTop + band)}`;
107
+ if (isMajor) majorLines += line;
108
+ else minorLines += line;
109
+ }
110
+ // Horizontal lines step out from zero, so a bold line runs through 0 mV.
111
+ const rule = (y, isMajor) => {
112
+ const line = `M${left} ${n(y)}H${n(left + inner)}`;
113
+ if (isMajor) majorLines += line;
114
+ else minorLines += line;
115
+ };
116
+ for (let k = 0; zero - k * minorPx >= paperTop - 0.01; k++) rule(zero - k * minorPx, k % Math.round(majorPx / minorPx) === 0);
117
+ for (let k = 1; zero + k * minorPx <= paperTop + band + 0.01; k++) rule(zero + k * minorPx, k % Math.round(majorPx / minorPx) === 0);
118
+
119
+ const points = envelope(slice, Math.max(1, Math.round(stripWidth * 2)));
120
+ const toX = (i) => left + (i / rate) * pxPerS;
121
+ const toY = (v) => Math.min(paperTop + band, Math.max(paperTop, zero - (v / perMv) * pxPerMv));
122
+ const d = points.map(([i, v], k) => `${k ? 'L' : 'M'}${n(toX(i))} ${n(toY(v))}`).join('');
123
+ const from = r * strip;
124
+ parts.push(
125
+ `<g class="trace-strip">` +
126
+ `<text class="trace-time" x="${left}" y="${n(top + 11)}">${from === 0 ? '0 s' : `${+from.toFixed(1)} s`}</text>` +
127
+ `<path class="trace-minor" d="${minorLines}"/>` +
128
+ `<path class="trace-major" d="${majorLines}"/>` +
129
+ `<g class="enter-line"><path class="trace-line" d="${d}"/></g>` +
130
+ `</g>`,
131
+ );
132
+ }
133
+
134
+ return (
135
+ `<svg class="trace" width="${width}" height="${n(height)}" viewBox="0 0 ${width} ${n(height)}" role="img" aria-label="${esc(label)}"` +
136
+ ` data-strip="${strip}" data-rows="${rows}" data-minor="${minor}">${parts.join('')}</svg>`
137
+ );
138
+ };
139
+
140
+ /** What a trace holds, in words: "15,360 samples at 512 Hz, 30.0 s". */
141
+ export const traceSummary = (count, rate, { locale } = {}) =>
142
+ `${count.toLocaleString(locale)} samples at ${Math.round(rate)} Hz, ${(count / rate).toFixed(1)} s`;
@@ -0,0 +1,54 @@
1
+ // Synthetic values only: a made-up beat repeated, not a recording.
2
+ import assert from 'node:assert/strict';
3
+ import { parseHTML } from 'linkedom';
4
+ import { envelope, stripSeconds, trace, traceSummary } from './trace.mjs';
5
+
6
+ const svg = (html) => parseHTML(`<div>${html}</div>`).document.querySelector('svg');
7
+
8
+ // A beat a second at 512 Hz: flat, with one sample-wide spike of 1,200 µV in each second.
9
+ const rate = 512;
10
+ const beats = (seconds) => Array.from({ length: seconds * rate }, (_, i) => (i % rate === 200 ? 1200 : i % rate === 210 ? -300 : 20));
11
+
12
+ assert.equal(trace([], { rate }), '', 'nothing to draw, no svg');
13
+ assert.equal(trace([1, 2, 3]), '', 'no rate, no svg');
14
+
15
+ // Strips: 10 s when wide, shorter when narrow; a 30 s recording is three strips at 800px.
16
+ assert.equal(stripSeconds(800), 10);
17
+ assert.equal(stripSeconds(340), 5);
18
+ assert.equal(stripSeconds(120), 2.5);
19
+ const wide = svg(trace(beats(30), { rate, width: 800 }));
20
+ assert.equal(wide.getAttribute('data-rows'), '3');
21
+ assert.equal(wide.querySelectorAll('.trace-strip').length, 3);
22
+ assert.equal(wide.querySelectorAll('.enter-line .trace-line').length, 3, 'a line per strip, tagged to draw in');
23
+ assert.deepEqual([...wide.querySelectorAll('.trace-time')].map((t) => t.textContent), ['0 s', '10 s', '20 s']);
24
+ assert.equal(svg(trace(beats(31), { rate, width: 800 })).getAttribute('data-rows'), '4', 'a second past the strips starts another');
25
+ assert.equal(svg(trace(beats(30), { rate, width: 340 })).getAttribute('data-rows'), '6');
26
+
27
+ // The envelope keeps every spike, however narrow, where every nth sample would lose them.
28
+ const one = beats(30);
29
+ const kept = envelope(one, 600);
30
+ assert.ok(kept.length <= 1200, 'at most two points a column');
31
+ assert.equal(kept.filter(([, v]) => v === 1200).length, 30, 'all thirty spikes survive');
32
+ assert.equal(kept.filter(([, v]) => v === -300).length, 30, 'and their dips');
33
+ assert.ok(kept.every(([i], k) => k === 0 || i > kept[k - 1][0]), 'in sample order');
34
+ const naive = one.filter((_, i) => i % Math.floor(one.length / 800) === 0);
35
+ assert.ok(naive.filter((v) => v === 1200).length < 30, 'taking every nth sample loses spikes: why the envelope exists');
36
+ assert.deepEqual(envelope([1, 2, 3], 10), [[0, 1], [1, 2], [2, 3]], 'few samples are kept as they are');
37
+
38
+ // The paper: squares as wide in time as they are tall in millivolts (0.2 s = 0.5 mV).
39
+ const paper = svg(trace(beats(10), { rate, width: 800 }));
40
+ assert.equal(paper.getAttribute('data-minor'), '0.2', 'at 80px a second, 0.04 s squares would be 3px: left out');
41
+ const verticals = [...paper.querySelector('.trace-minor').getAttribute('d').matchAll(/M([\d.]+) [\d.]+V/g)].map((m) => +m[1]);
42
+ const horizontals = [...paper.querySelector('.trace-minor').getAttribute('d').matchAll(/M0 ([\d.]+)H/g)].map((m) => +m[1]).sort((a, b) => a - b);
43
+ assert.ok(Math.abs(verticals[1] - verticals[0] - (horizontals[1] - horizontals[0])) < 0.2, 'square squares');
44
+ assert.equal(svg(trace(beats(10), { rate, width: 4000 })).getAttribute('data-minor'), '0.04', 'wide enough: the finest squares');
45
+
46
+ // A line never leaves its paper, even for an artefact far off the scale.
47
+ const wild = svg(trace([...beats(2), 90000, ...beats(2)], { rate, width: 800, seconds: 10 }));
48
+ const ys = [...wild.querySelector('.trace-line').getAttribute('d').matchAll(/[ML][\d.]+ ([\d.]+)/g)].map((m) => +m[1]);
49
+ assert.ok(Math.max(...ys) <= +wild.getAttribute('height') && Math.min(...ys) >= 0, 'clamped to the paper');
50
+
51
+ // Named for a screen reader; the summary says what it holds.
52
+ assert.equal(svg(trace(beats(1), { rate, label: 'ECG <today>' })).getAttribute('aria-label'), 'ECG <today>');
53
+ assert.equal(traceSummary(15360, 512, { locale: 'en' }), '15,360 samples at 512 Hz, 30.0 s');
54
+ console.log('trace: ok');