@n1kname/charts 0.4.0 → 0.6.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.4.0",
3
+ "version": "0.6.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -10,7 +10,8 @@
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"
14
15
  },
15
16
  "dependencies": {
16
17
  "@observablehq/plot": "0.6.17",
package/src/bars.mjs CHANGED
@@ -1,11 +1,13 @@
1
- // Bars on one axis, one per row: a single value, or a few series stacked in the order given,
2
- // bottom to top. Returns Plot options without a style, so the same chart draws at build time
1
+ // Bars on one axis, one per row: a single value, a few series stacked in the order given,
2
+ // bottom to top, or with `grouped` side by side, such as last year beside this one. Returns Plot options without a style, so the same chart draws at build time
3
3
  // (renderPlot) or in the browser (Plot.plot with the page's style).
4
4
  //
5
5
  // Rows are wide: one object per x, a number (or null for none) per series key. Positive
6
6
  // values stack up from zero and negative ones down, so a month that returned more than it
7
7
  // bought still reads. A row can be drawn fainter (`fade`) and with a dashed edge (`dashed`),
8
- // for figures that are not settled yet; say what each means in a Legend.
8
+ // for figures that are not settled yet; say what each means in a Legend. A run of steps can be
9
+ // set apart as one shaded block with a word on why (`shade`), and a series can carry a short
10
+ // `tag` over its first bar, so two series are not told apart by colour alone.
9
11
 
10
12
  import * as Plot from '@observablehq/plot';
11
13
  import { chrome, tipStyle } from './theme.mjs';
@@ -38,13 +40,20 @@ export const bars = (
38
40
  // How many ems an x label may run before it wraps onto another line, for long labels on
39
41
  // a narrow chart. Gets the width.
40
42
  wrap = () => Infinity,
41
- // Words on the y axis, such as its unit, when the chart has no subtitle to say it.
43
+ // Words on the y axis, such as its unit, when the chart has no subtitle to say it, and the
44
+ // decimals its labels show.
42
45
  yLabel = null,
46
+ yDigits = 0,
43
47
  marginLeft = 44,
44
48
  marginBottom = 30,
49
+ // The series side by side in each step, each bar from zero, instead of stacked.
50
+ grouped = false,
51
+ // A run of steps set apart: { from, to, text }, the first and last x and why.
52
+ shade = null,
45
53
  },
46
54
  width,
47
55
  ) => {
56
+ const marginRight = 4;
48
57
  const has = (r, key) => typeof r[key] === 'number';
49
58
  // Where each series' piece of each bar starts and ends.
50
59
  const pieces = series.map(() => []);
@@ -54,23 +63,39 @@ export const bars = (
54
63
  series.forEach((s, i) => {
55
64
  if (!has(r, s.key)) return;
56
65
  const v = r[s.key];
57
- const from = v >= 0 ? up : down;
66
+ const from = grouped ? 0 : v >= 0 ? up : down;
58
67
  if (v >= 0) up += v;
59
68
  else down += v;
60
69
  pieces[i].push({ row: r, y1: from, y2: from + v });
61
70
  });
62
71
  }
63
- const top = (r) => series.reduce((sum, s) => sum + (has(r, s.key) && r[s.key] > 0 ? r[s.key] : 0), 0);
64
- const bottom = (r) => series.reduce((sum, s) => sum + (has(r, s.key) && r[s.key] < 0 ? r[s.key] : 0), 0);
72
+ const valuesOf = (r) => series.filter((s) => has(r, s.key)).map((s) => r[s.key]);
73
+ const sum = (vs) => vs.reduce((a, b) => a + b, 0);
74
+ const top = (r) => (grouped ? Math.max(0, ...valuesOf(r)) : sum(valuesOf(r).filter((v) => v > 0)));
75
+ const bottom = (r) => (grouped ? Math.min(0, ...valuesOf(r)) : sum(valuesOf(r).filter((v) => v < 0)));
65
76
  const total = (r) => series.reduce((sum, s) => sum + (has(r, s.key) ? r[s.key] : 0), 0);
66
77
  const drawn = rows.filter((r) => series.some((s) => has(r, s.key)));
67
78
  const domain = [
68
79
  y[0] === 'auto' ? Math.min(0, ...drawn.map(bottom)) : y[0],
69
80
  y[1] === 'auto' ? Math.max(0, ...drawn.map(top)) : y[1],
70
81
  ];
71
- const says =
72
- title ??
73
- ((r) => [r[x], ...[...series].reverse().filter((s) => has(r, s.key)).map((s) => `${s.label} ${format(r[s.key], digits)}`), unit].join('\n'));
82
+ // Stacked, the tooltip lists the parts from the top, as they are drawn; grouped, in order.
83
+ const listed = grouped ? series : [...series].reverse();
84
+ const says = title ?? ((r) => [r[x], ...listed.filter((s) => has(r, s.key)).map((s) => `${s.label} ${format(r[s.key], digits)}`), unit].join('\n'));
85
+ // Grouped, every step has a tooltip, even one with no bars, so a step left out can say why.
86
+ const tipped = grouped ? rows : drawn;
87
+
88
+ // Where the bars sit in a step. Plot's band scale puts `padding` of a step on each side of
89
+ // the bands, so a step is the range over the number of rows plus that padding. Grouped, the
90
+ // scale is not rounded to whole pixels, so the bars land where this says.
91
+ const step = (width - marginLeft - marginRight) / (rows.length + padding);
92
+ const band = step * (1 - padding);
93
+ const GAP = 2;
94
+ const barWidth = Math.min(14, (band - GAP * (series.length - 1)) / series.length);
95
+ const group = barWidth * series.length + GAP * (series.length - 1);
96
+ // Each series' bar, from the left of its band.
97
+ const left = (i) => (band - group) / 2 + i * (barWidth + GAP);
98
+ const inset = (i) => (grouped ? { insetLeft: left(i), insetRight: band - left(i) - barWidth } : {});
74
99
 
75
100
  // Settled rows and dashed ones are separate marks, because a dash cannot vary per bar.
76
101
  const piece = (s, i, rowsOf, edge) =>
@@ -83,35 +108,79 @@ export const bars = (
83
108
  stroke: edge ? s.color : 'var(--c-surface)',
84
109
  strokeWidth: 1,
85
110
  strokeDasharray: edge ? '3 2' : undefined,
86
- // The last series is the top of the bar: rounded there, square on the baseline.
87
- ...(i === series.length - 1 ? { ry1: 4 } : {}),
111
+ className: 'enter-bar',
112
+ // The last series is the top of the bar: rounded there, square on the baseline. Grouped,
113
+ // every bar is its own top.
114
+ ...(grouped || i === series.length - 1 ? { ry1: 4 } : {}),
115
+ ...inset(i),
88
116
  });
89
117
 
118
+ // The shaded run, edge to edge across its steps, with its word in the middle.
119
+ const shaded = shade ? rows.slice(rows.findIndex((r) => r[x] === shade.from), rows.findIndex((r) => r[x] === shade.to) + 1) : [];
120
+ const shading = shaded.length
121
+ ? [
122
+ Plot.barY(shaded, { x, y1: () => domain[0], y2: () => domain[1], fill: chrome.neutral, fillOpacity: 0.16, inset: -(step - band) / 2, className: 'enter-fade' }),
123
+ Plot.text([shaded[0]], {
124
+ x,
125
+ frameAnchor: 'middle',
126
+ dx: ((shaded.length - 1) * step) / 2,
127
+ text: () => shade.text,
128
+ fill: 'var(--c-text-secondary)',
129
+ fontSize: 11,
130
+ className: 'enter-fade',
131
+ }),
132
+ ]
133
+ : [];
134
+
135
+ // A series' tag over its first bar. The first grows leftward from its bar's right edge and
136
+ // the rest rightward from their left edge, so two tags never touch.
137
+ const tags = series.flatMap((s, i) => {
138
+ const first = rows.find((r) => has(r, s.key));
139
+ if (!s.tag || !first) return [];
140
+ const edge = grouped ? (i === 0 ? left(i) + barWidth : left(i)) - band / 2 : 0;
141
+ return [
142
+ Plot.text([first], {
143
+ x,
144
+ y: (r) => (grouped ? Math.max(0, r[s.key]) : top(r)),
145
+ text: () => s.tag,
146
+ dx: edge,
147
+ dy: -6,
148
+ lineAnchor: 'bottom',
149
+ textAnchor: grouped && i === 0 ? 'end' : 'start',
150
+ fill: 'var(--c-text-secondary)',
151
+ fontSize: 10,
152
+ className: 'enter-fade',
153
+ }),
154
+ ];
155
+ });
156
+
90
157
  const labels = (v, i) => tick(v, i, width);
91
158
  return {
92
159
  width,
93
160
  height,
94
- marginTop: values ? 24 : 10,
161
+ marginTop: values || series.some((s) => s.tag) ? 24 : 10,
95
162
  marginLeft,
96
- marginRight: 4,
163
+ marginRight,
97
164
  marginBottom,
98
- x: { type: 'band', domain: rows.map((r) => r[x]), padding, label: null, tickSize: 0, tickFormat: labels, axis: null },
99
- y: { domain, nice: true, label: yLabel, tickSize: 0, ticks: 5, tickFormat: (v) => format(v, 0) },
165
+ x: { type: 'band', domain: rows.map((r) => r[x]), padding, ...(grouped ? { round: false } : {}), label: null, tickSize: 0, tickFormat: labels, axis: null },
166
+ y: { domain, nice: true, label: yLabel, tickSize: 0, ticks: 5, tickFormat: (v) => format(v, yDigits) },
100
167
  opacity: { type: 'identity' },
101
168
  marks: [
102
169
  Plot.axisX({ tickSize: 0, tickFormat: labels, lineWidth: wrap(width) }),
170
+ ...shading,
103
171
  Plot.gridY({ stroke: chrome.grid, strokeOpacity: 1, ticks: 5 }),
104
172
  // The bar under the pointer, behind the bars.
105
- Plot.barY(drawn, Plot.pointerX({ x, y1: () => domain[0], y2: () => domain[1], fill: 'var(--c-surface-hover)', inset: -2 })),
173
+ Plot.barY(tipped, Plot.pointerX({ x, y1: () => domain[0], y2: () => domain[1], fill: 'var(--c-surface-hover)', inset: -2 })),
106
174
  ...series.flatMap((s, i) => [
107
175
  piece(s, i, pieces[i].filter((p) => !dashed(p.row)), false),
108
176
  piece(s, i, pieces[i].filter((p) => dashed(p.row)), true),
109
177
  ]),
110
178
  ...(values
111
- ? [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' })]
112
180
  : []),
113
- Plot.ruleY([0], { stroke: chrome.axis }),
114
- Plot.tip(drawn, Plot.pointerX({ x, y: top, title: says, ...tipStyle })),
181
+ ...tags,
182
+ Plot.ruleY([0], { stroke: chrome.axis, className: 'enter-zero' }),
183
+ Plot.tip(tipped, Plot.pointerX({ x, y: top, title: says, ...tipStyle })),
115
184
  ],
116
185
  };
117
186
  };
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');
@@ -71,5 +72,44 @@ const wrapped = renderPlot(bars({ ...long, wrap: () => 5 }, 300));
71
72
  assert.ok(!/>Before the works</.test(wrapped) && /Before/.test(wrapped), 'a long label wraps onto more lines');
72
73
  assert.ok(/>Before the works</.test(renderPlot(bars(long, 300))), 'without wrap it stays on one line');
73
74
  assert.ok(/units a year/.test(wrapped), 'the y axis carries its words');
75
+ const small = renderPlot(bars({ ...long, rows: [{ k: 'A', v: 0.3 }, { k: 'B', v: 1.2 }], yDigits: 2 }, 300));
76
+ assert.ok(/>0\.40</.test(small) && !/>1</.test(small), 'small values keep their decimals on the y axis');
77
+
78
+ // Grouped: last year beside this one, each bar from zero, a run of steps shaded.
79
+ const pairs = [
80
+ { m: 'M1', old: 30, now: 20 },
81
+ { m: 'M2', old: 10, now: 12 },
82
+ { m: 'M3', old: null, now: null },
83
+ { m: 'M4', old: null, now: null },
84
+ { m: 'M5', old: 5, now: null },
85
+ ];
86
+ const two = [
87
+ { key: 'old', label: 'Then', color: 'var(--c-chart-2)', tag: '’24' },
88
+ { key: 'now', label: 'Now', color: 'var(--c-chart-1)', tag: '’25' },
89
+ ];
90
+ const g = bars({ rows: pairs, x: 'm', series: two, unit: 'units', grouped: true, shade: { from: 'M3', to: 'M4', text: 'left out' } }, 500);
91
+ const gSvg = renderPlot(g);
92
+ assert.deepEqual(g.y.domain, [0, 30], 'grouped, the y domain holds the highest bar, not a sum');
93
+ const [oldBars, , nowBars] = g.marks.slice(5);
94
+ assert.deepEqual([oldBars.data[0].y1, oldBars.data[0].y2, nowBars.data[0].y1, nowBars.data[0].y2], [0, 30, 0, 20], 'each bar stands on zero');
95
+ // The two bars of a step side by side, 2px apart, centred in the step and no wider than 14px.
96
+ // Each bar's left and right edge: the least and greatest x its path visits.
97
+ const rects = (color) => [...gSvg.matchAll(new RegExp(`fill="var\\(--c-${color}\\)"[^>]*>((?:<path[^>]*>)+)`, 'g'))]
98
+ .flatMap((m) => [...m[1].matchAll(/ d="([^"]+)"/g)])
99
+ .map(([, d]) => {
100
+ const xs = [...d.matchAll(/(?:[MLH]|0 0 1 )([\d.]+)/g)].map((n) => Number(n[1]));
101
+ return [Math.min(...xs), Math.max(...xs)];
102
+ });
103
+ const [o1, n1] = [rects('chart-2')[0], rects('chart-1')[0]];
104
+ assert.ok(o1 && n1, 'both bars of the first step are drawn');
105
+ assert.ok(Math.abs(n1[0] - o1[1] - 2) < 0.01, 'the second bar starts 2px after the first ends');
106
+ assert.ok(o1[1] - o1[0] <= 14.001, 'no bar is wider than 14px');
107
+ assert.ok(gSvg.includes('>left out<'), 'the shaded run says why');
108
+ assert.ok(gSvg.includes('>’24<') && gSvg.includes('>’25<'), 'each series carries its tag over its first bar');
109
+ const gTip = g.marks.at(-1);
110
+ assert.equal(gTip.data.length, 5, 'grouped, every step has a tooltip, even an empty one');
111
+ assert.equal(gTip.channels.title.value(pairs[0]), 'M1\nThen 30\nNow 20\nunits', 'grouped, the tooltip lists the series in order');
112
+ assert.equal(gTip.channels.title.value(pairs[2]), 'M3\nunits', 'an empty step says only its label and unit, not 0');
113
+ assert.ok(!renderPlot(bars({ ...spec, grouped: false }, 600)).includes('left out'), 'no shade unless asked');
74
114
 
75
115
  console.log('bars: all assertions pass');
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.