@n1kname/charts 0.5.0 → 0.7.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.5.0",
3
+ "version": "0.7.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -10,7 +10,9 @@
10
10
  "./theme": "./src/theme.mjs",
11
11
  "./lines": "./src/lines.mjs",
12
12
  "./bars": "./src/bars.mjs",
13
- "./heatmap": "./src/heatmap.mjs"
13
+ "./heatmap": "./src/heatmap.mjs",
14
+ "./enter": "./src/enter.mjs",
15
+ "./update": "./src/update.mjs"
14
16
  },
15
17
  "dependencies": {
16
18
  "@observablehq/plot": "0.6.17",
package/src/bars.mjs CHANGED
@@ -108,6 +108,7 @@ export const bars = (
108
108
  stroke: edge ? s.color : 'var(--c-surface)',
109
109
  strokeWidth: 1,
110
110
  strokeDasharray: edge ? '3 2' : undefined,
111
+ className: 'enter-bar',
111
112
  // The last series is the top of the bar: rounded there, square on the baseline. Grouped,
112
113
  // every bar is its own top.
113
114
  ...(grouped || i === series.length - 1 ? { ry1: 4 } : {}),
@@ -118,7 +119,7 @@ export const bars = (
118
119
  const shaded = shade ? rows.slice(rows.findIndex((r) => r[x] === shade.from), rows.findIndex((r) => r[x] === shade.to) + 1) : [];
119
120
  const shading = shaded.length
120
121
  ? [
121
- Plot.barY(shaded, { x, y1: () => domain[0], y2: () => domain[1], fill: chrome.neutral, fillOpacity: 0.16, inset: -(step - band) / 2 }),
122
+ Plot.barY(shaded, { x, y1: () => domain[0], y2: () => domain[1], fill: chrome.neutral, fillOpacity: 0.16, inset: -(step - band) / 2, className: 'enter-fade' }),
122
123
  Plot.text([shaded[0]], {
123
124
  x,
124
125
  frameAnchor: 'middle',
@@ -126,6 +127,7 @@ export const bars = (
126
127
  text: () => shade.text,
127
128
  fill: 'var(--c-text-secondary)',
128
129
  fontSize: 11,
130
+ className: 'enter-fade',
129
131
  }),
130
132
  ]
131
133
  : [];
@@ -147,6 +149,7 @@ export const bars = (
147
149
  textAnchor: grouped && i === 0 ? 'end' : 'start',
148
150
  fill: 'var(--c-text-secondary)',
149
151
  fontSize: 10,
152
+ className: 'enter-fade',
150
153
  }),
151
154
  ];
152
155
  });
@@ -173,10 +176,10 @@ export const bars = (
173
176
  piece(s, i, pieces[i].filter((p) => dashed(p.row)), true),
174
177
  ]),
175
178
  ...(values
176
- ? [Plot.text(drawn, { x, y: total, text: (r) => format(total(r), digits), dy: -8, lineAnchor: 'bottom', fill: chrome.text, fontSize: 12 })]
179
+ ? [Plot.text(drawn, { x, y: total, text: (r) => format(total(r), digits), dy: -8, lineAnchor: 'bottom', fill: chrome.text, fontSize: 12, className: 'enter-fade' })]
177
180
  : []),
178
181
  ...tags,
179
- Plot.ruleY([0], { stroke: chrome.axis }),
182
+ Plot.ruleY([0], { stroke: chrome.axis, className: 'enter-zero' }),
180
183
  Plot.tip(tipped, Plot.pointerX({ x, y: top, title: says, ...tipStyle })),
181
184
  ],
182
185
  };
package/src/bars.test.mjs CHANGED
@@ -29,6 +29,7 @@ const spec = {
29
29
 
30
30
  const options = bars(spec, 600);
31
31
  const svg = renderPlot(options);
32
+ assert.ok(/class="enter-bar"/.test(svg) && /class="enter-zero"/.test(svg), 'bars and the zero line are tagged to arrive');
32
33
  const ticks = [...svg.matchAll(/<text[^>]*>(M\d)<\/text>/g)].map((m) => m[1]);
33
34
  assert.deepEqual(ticks, ['M1', 'M3', 'M5'], 'only the ticks the tick function prints');
34
35
  assert.ok(!/#[0-9a-f]{6}/i.test(svg), 'no hex: colours are tokens');
package/src/enter.mjs ADDED
@@ -0,0 +1,135 @@
1
+ // A chart arrives once, as it first comes into view: bars grow from the zero line, left to
2
+ // right; lines draw from the first point, and their dots appear as the line reaches them; heatmap
3
+ // cells fill in column by column; the words come last. Never again on a resize or a redraw, and
4
+ // not at all under reduced motion.
5
+ //
6
+ // Browser only. The chart builders tag their marks (`enter-bar`, `enter-line`, `enter-dot`,
7
+ // `enter-cell`, `enter-fade`), so this works on a chart drawn at build time as well as one drawn
8
+ // in the page. Nothing is hidden until the motion is set up, so a chart without script is simply
9
+ // there. Runs on the Web Animations API, so a mark keeps its own transform and the page needs no
10
+ // stylesheet for it.
11
+
12
+ const BAR = 700;
13
+ const LINE = 1000;
14
+ const CELL = 420;
15
+ const SWEEP = 420; // the longest a left-to-right stagger may take
16
+
17
+ const reduced = () => matchMedia('(prefers-reduced-motion: reduce)').matches;
18
+
19
+ // The spring from the tokens, or ease-out where the page has an older token set.
20
+ const spring = () =>
21
+ getComputedStyle(document.documentElement).getPropertyValue('--ease-spring').trim() || 'cubic-bezier(0.22, 1, 0.36, 1)';
22
+ // A line draws at a hand's pace: easing in a little and out a little, so its dots keep up.
23
+ const DRAW = 'cubic-bezier(0.3, 0, 0.2, 1)';
24
+ const OUT = 'cubic-bezier(0.22, 1, 0.36, 1)';
25
+
26
+ const num = (el, name) => parseFloat(el.getAttribute(name)) || 0;
27
+
28
+ // Where an SVG element sits across, for the left-to-right order.
29
+ const across = (el) => {
30
+ const box = el.getBBox();
31
+ return box.x + box.width / 2;
32
+ };
33
+
34
+ // The zero line, in the drawing's own units: Plot's rule at 0 when there is one, otherwise the
35
+ // bottom of the lowest bar.
36
+ const zeroOf = (svg, bars) => {
37
+ const rule = svg.querySelector('.enter-zero line');
38
+ if (rule) {
39
+ const shift = /translate\([^,]+,\s*([-\d.]+)\)/.exec(rule.parentNode.getAttribute('transform') ?? '');
40
+ return num(rule, 'y1') + (shift ? parseFloat(shift[1]) : 0);
41
+ }
42
+ return Math.max(...bars.map((b) => {
43
+ const box = b.getBBox();
44
+ return box.y + box.height;
45
+ }));
46
+ };
47
+
48
+ // Spread a set of marks over the sweep by where they sit across.
49
+ const sweep = (marks, total = SWEEP) => {
50
+ if (!marks.length) return () => 0;
51
+ const xs = marks.map(across);
52
+ const min = Math.min(...xs);
53
+ const span = Math.max(...xs) - min || 1;
54
+ return (i) => ((xs[i] - min) / span) * total;
55
+ };
56
+
57
+ const svgParts = (svg) => {
58
+ const parts = [];
59
+ // A bar with only its top corners rounded is a path, the rest are rects.
60
+ const rects = [...svg.querySelectorAll('.enter-bar :is(rect, path)')];
61
+ if (rects.length) {
62
+ const zero = zeroOf(svg, rects);
63
+ const at = sweep(rects);
64
+ rects.forEach((rect, i) => {
65
+ rect.style.transformBox = 'view-box';
66
+ rect.style.transformOrigin = `0 ${zero}px`;
67
+ parts.push([rect, [{ transform: 'scaleY(0)' }, { transform: 'scaleY(1)' }], { duration: BAR, delay: at(i), easing: spring() }]);
68
+ });
69
+ }
70
+ svg.querySelectorAll('.enter-line path').forEach((path) => {
71
+ path.setAttribute('pathLength', '1');
72
+ parts.push([path, [{ strokeDasharray: '1 1', strokeDashoffset: 1 }, { strokeDasharray: '1 1', strokeDashoffset: 0 }], { duration: LINE, easing: DRAW }]);
73
+ });
74
+ // A dot appears as its line reaches it; the line covers the width in LINE.
75
+ const dots = [...svg.querySelectorAll('.enter-dot circle')];
76
+ const dotAt = sweep(dots, LINE * 0.8);
77
+ dots.forEach((dot, i) => {
78
+ dot.style.transformBox = 'fill-box';
79
+ 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 }]);
81
+ });
82
+ const cells = [...svg.querySelectorAll('.enter-cell rect')];
83
+ const cellAt = sweep(cells, 500);
84
+ cells.forEach((cell, i) => parts.push([cell, [{ opacity: 0 }, { opacity: 1 }], { duration: CELL, delay: cellAt(i), easing: OUT }]));
85
+ // 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;
87
+ svg.querySelectorAll('.enter-fade').forEach((g) => parts.push([g, [{ opacity: 0 }, { opacity: 1 }], { duration: 300, delay: last, easing: OUT }]));
88
+ return parts;
89
+ };
90
+
91
+ // Ranked bars are HTML: each bar grows from the left, top to bottom.
92
+ const htmlParts = (root) =>
93
+ [...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 }],
96
+ ]).filter(([el]) => el);
97
+
98
+ /**
99
+ * Sets a chart up to arrive. `el` is the chart's SVG, or an element holding ranked bars. Call it
100
+ * once, on the first drawing only. The marks wait at their first frame until the chart is a
101
+ * little way into view, then play.
102
+ */
103
+ export const enter = (el) => {
104
+ if (!el || reduced() || typeof el.animate !== 'function') return;
105
+ // A drawing that isn't shown, such as the narrow one of a pair on a wide screen, stays as it is.
106
+ if (!el.getClientRects().length) return;
107
+ const parts = el instanceof SVGSVGElement ? svgParts(el) : htmlParts(el);
108
+ if (!parts.length) return;
109
+ const animations = parts.map(([node, frames, timing]) => {
110
+ if (node.style.transformOrigin === '' && frames[0].transform?.startsWith('scaleX')) node.style.transformOrigin = 'left center';
111
+ const a = node.animate(frames, { ...timing, fill: 'backwards' });
112
+ a.pause();
113
+ return a;
114
+ });
115
+ const play = () => animations.forEach((a) => a.play());
116
+ const box = el.getBoundingClientRect();
117
+ if (box.top < innerHeight * 0.9 && box.bottom > 0) return play();
118
+ const io = new IntersectionObserver(
119
+ (entries) => {
120
+ if (!entries.some((e) => e.isIntersecting)) return;
121
+ io.disconnect();
122
+ play();
123
+ },
124
+ { rootMargin: '0px 0px -10% 0px' },
125
+ );
126
+ io.observe(el);
127
+ };
128
+
129
+ /** Every chart under `selector` that is in the page now, for charts drawn at build time. */
130
+ export const enterAll = (selector) =>
131
+ document.querySelectorAll(selector).forEach((root) => {
132
+ const svgs = root.querySelectorAll('svg');
133
+ if (root.querySelector('.ranked-bars i') || root.matches('.ranked-bars')) enter(root);
134
+ svgs.forEach((svg) => enter(svg));
135
+ });
package/src/heatmap.mjs CHANGED
@@ -45,5 +45,5 @@ export const heatmap = (
45
45
  x: { domain: xDomain, label: null, tickSize: 0, tickFormat: (v, i) => xTick(v, i, width) },
46
46
  y: { domain: yDomain, label: null, tickSize: 0, tickFormat: yTick },
47
47
  color: { type: 'threshold', domain: steps, range: colors },
48
- marks: [Plot.cell(cells, { x, y, fill: value, tip: tipStyle, title })],
48
+ marks: [Plot.cell(cells, { x, y, fill: value, tip: tipStyle, title, className: 'enter-cell' })],
49
49
  });
@@ -27,6 +27,7 @@ const spec = {
27
27
 
28
28
  const options = heatmap(spec, 400);
29
29
  const svg = renderPlot(options);
30
+ assert.ok(/class="enter-cell"/.test(svg), 'cells are tagged to arrive');
30
31
  assert.equal(options.height, heatmapHeight(3), 'as tall as its rows');
31
32
  assert.ok(heatmapHeight(6) > heatmapHeight(3), 'and taller with more rows');
32
33
  assert.ok(!/#[0-9a-f]{6}/i.test(svg), 'no hex: colours are tokens');
package/src/lines.mjs CHANGED
@@ -84,6 +84,8 @@ export const lines = (
84
84
  stroke: s.color,
85
85
  strokeWidth: s.width ?? 2,
86
86
  strokeDasharray: s.dashed ? '4 3' : undefined,
87
+ // A dashed line can't draw itself in with a dash of its own, so it fades.
88
+ className: s.dashed ? 'enter-fade' : 'enter-line',
87
89
  }),
88
90
  ),
89
91
  // A series' own `dots` wins over the chart's.
@@ -97,6 +99,7 @@ export const lines = (
97
99
  fill: s.dashed ? 'var(--c-surface)' : s.color,
98
100
  stroke: s.color,
99
101
  strokeWidth: s.dashed ? 1.5 : 0,
102
+ className: 'enter-dot',
100
103
  }),
101
104
  ),
102
105
  ...named.map(({ s, name }) => {
@@ -110,6 +113,7 @@ export const lines = (
110
113
  fill: chrome.text,
111
114
  fontWeight: 600,
112
115
  fontSize: 11,
116
+ className: 'enter-fade',
113
117
  });
114
118
  }),
115
119
  Plot.ruleX(tipped, Plot.pointerX({ x, stroke: chrome.axis })),
@@ -25,9 +25,11 @@ assert.ok(/>Alder</.test(svg) && />Birch</.test(svg), 'subject lines end in thei
25
25
  assert.ok(!/Birch, not settled/.test(svg), 'a silent line has no name at its end');
26
26
  assert.ok(svg.includes('stroke-dasharray="4 3"'), 'a dashed series is dashed');
27
27
  assert.ok(!/#[0-9a-f]{6}/i.test(svg), 'no hex: colours are tokens');
28
+ assert.ok(/class="enter-line"/.test(svg) && /class="enter-dot"/.test(svg), 'solid lines and dots are tagged to arrive');
29
+ assert.ok(/<g[^>]*class="enter-fade"[^>]*stroke-dasharray="4 3"|<g[^>]*stroke-dasharray="4 3"[^>]*class="enter-fade"/.test(svg), 'a dashed line fades in, its dash is its own');
28
30
 
29
31
  // A null breaks the line: Birch is drawn as two pieces, W1 alone and W3 to W4.
30
- const birch = svg.match(/<g(?![^>]*dasharray)[^>]*stroke="var\(--c-chart-2\)" fill="none"><path d="([^"]+)"/)[1];
32
+ const birch = svg.match(/<g(?![^>]*dasharray)[^>]*stroke="var\(--c-chart-2\)" fill="none"[^>]*><path d="([^"]+)"/)[1];
31
33
  assert.equal((birch.match(/M/g) ?? []).length, 2, 'a null breaks the line instead of joining across it');
32
34
 
33
35
  // The tooltip: every series with a value, and a silent one only where its line has none.
package/src/update.mjs ADDED
@@ -0,0 +1,93 @@
1
+ // A chart changing in place when its figures change, such as a new year in a filter. `enter`
2
+ // plays once, the first time a chart is drawn; this plays on every redraw with new figures after
3
+ // that, and never on a resize.
4
+ //
5
+ // Each bar is known by what it stands for: its series and its place on the x axis, through a key
6
+ // the page gives (by default the x value itself). A year's January and the next year's January
7
+ // share a key when the page keys months by their month of the year, so stepping through years
8
+ // moves each month's bar from its old height to its new one on the spring, and the eye follows
9
+ // what grew and what shrank. A bar with no match grows from the zero line, as on arrival, so
10
+ // months that are not the same are never shown turning into each other. The axis words fade in.
11
+ // Nothing moves under reduced motion.
12
+ //
13
+ // Browser only, on the Web Animations API, for bars made by `bars` and drawn with Plot in the
14
+ // page (the bars must be the plot's own `svg`, which knows its x scale).
15
+ //
16
+ // const before = snapshot(box.querySelector('svg'), key);
17
+ // box.replaceChildren(svg);
18
+ // update(before, svg, key);
19
+ const reduced = () => matchMedia('(prefers-reduced-motion: reduce)').matches;
20
+
21
+ // A motion token in milliseconds. The tokens are written in seconds (".34s"), so they are read
22
+ // with their unit.
23
+ export const ms = (name, fallback) => {
24
+ const v = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
25
+ const n = parseFloat(v);
26
+ if (Number.isNaN(n)) return fallback;
27
+ return v.endsWith('ms') ? n : v.endsWith('s') ? n * 1000 : n;
28
+ };
29
+ const ease = (name, fallback) => getComputedStyle(document.documentElement).getPropertyValue(name).trim() || fallback;
30
+
31
+ // Each bar with the x value it stands for, found from where it sits on the band scale.
32
+ const keyed = (svg, key = String) => {
33
+ const scale = svg.scale?.('x');
34
+ const domain = scale?.domain ?? [];
35
+ const half = (scale?.bandwidth ?? 0) / 2;
36
+ const centres = domain.map((d) => scale.apply(d) + half);
37
+ const out = new Map();
38
+ svg.querySelectorAll('.enter-bar').forEach((g, series) =>
39
+ [...g.children].forEach((el) => {
40
+ const b = el.getBBox();
41
+ const mid = b.x + b.width / 2;
42
+ let at = -1;
43
+ let best = Infinity;
44
+ centres.forEach((c, i) => {
45
+ const d = Math.abs(c - mid);
46
+ if (d < best) [best, at] = [d, i];
47
+ });
48
+ const x = at < 0 ? `#${out.size}` : key(domain[at]);
49
+ out.set(`${series}|${x}`, { el, box: b });
50
+ }),
51
+ );
52
+ return out;
53
+ };
54
+
55
+ // Where each bar is, before the chart is replaced.
56
+ export const snapshot = (svg, key) => (svg ? keyed(svg, key) : null);
57
+
58
+ export const update = (before, svg, key) => {
59
+ if (!before || reduced()) return;
60
+ const spring = { duration: ms('--motion-spring', 340), easing: ease('--ease-spring', 'ease-out') };
61
+ const base = { duration: ms('--motion-base', 180), easing: ease('--ease-out', 'ease-out') };
62
+ const after = keyed(svg, key);
63
+ if (!after.size) {
64
+ svg.animate([{ opacity: 0 }, { opacity: 1 }], base);
65
+ return;
66
+ }
67
+ const zero = Math.max(...[...after.values()].map(({ box }) => box.y + box.height));
68
+ for (const [k, { el, box }] of after) {
69
+ if (box.height < 0.5 || box.width < 0.5) continue;
70
+ const old = before.get(k)?.box;
71
+ if (old) {
72
+ // From the old box to the new one: scaled about the new top left, then moved there.
73
+ el.style.transformBox = 'fill-box';
74
+ el.style.transformOrigin = '0 0';
75
+ const from = `translate(${old.x - box.x}px, ${old.y - box.y}px) scale(${old.width / box.width}, ${old.height / box.height})`;
76
+ el.animate([{ transform: from }, { transform: 'none' }], spring);
77
+ } else {
78
+ el.style.transformBox = 'view-box';
79
+ el.style.transformOrigin = `0 ${zero}px`;
80
+ el.animate([{ transform: 'scaleY(0)' }, { transform: 'none' }], spring);
81
+ }
82
+ }
83
+ svg.querySelectorAll('[data-mark$="tick label"], [data-mark$="grid"]').forEach((n) => n.animate([{ opacity: 0 }, { opacity: 1 }], base));
84
+ };
85
+
86
+ // A figure that changes settles in place: it fades up from a little below, never counts.
87
+ export const settle = (el) => {
88
+ if (reduced()) return;
89
+ el.animate([{ opacity: 0.2, transform: 'translateY(3px)' }, { opacity: 1, transform: 'none' }], {
90
+ duration: ms('--motion-base', 180),
91
+ easing: ease('--ease-out', 'ease-out'),
92
+ });
93
+ };