@n1kname/charts 0.11.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.11.0",
3
+ "version": "0.12.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -18,7 +18,10 @@
18
18
  "./pointer": "./src/pointer.mjs",
19
19
  "./pointer.css": "./src/pointer.css",
20
20
  "./months": "./src/months.mjs",
21
- "./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"
22
25
  },
23
26
  "dependencies": {
24
27
  "@observablehq/plot": "0.6.17",
@@ -37,6 +40,6 @@
37
40
  "src"
38
41
  ],
39
42
  "scripts": {
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"
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"
41
44
  }
42
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/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/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');