@n1kname/charts 0.9.1 → 0.10.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.9.1",
3
+ "version": "0.10.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
package/src/heatmap.mjs CHANGED
@@ -28,6 +28,9 @@ export const heatmap = (
28
28
  rowHeight = 30,
29
29
  // The tooltip's text per cell.
30
30
  title,
31
+ // Plot's own tooltip. Leave on for a chart drawn at build time; turn off when the page says
32
+ // what is under the pointer itself, with `pointerCells` from ./pointer.mjs.
33
+ pointer = true,
31
34
  // The labels on each axis. xTick gets (value, index, width).
32
35
  xTick = (v) => v,
33
36
  yTick = (v) => v,
@@ -45,5 +48,5 @@ export const heatmap = (
45
48
  x: { domain: xDomain, label: null, tickSize: 0, tickFormat: (v, i) => xTick(v, i, width) },
46
49
  y: { domain: yDomain, label: null, tickSize: 0, tickFormat: yTick },
47
50
  color: { type: 'threshold', domain: steps, range: colors },
48
- marks: [Plot.cell(cells, { x, y, fill: value, tip: tipStyle, title, className: 'enter-cell' })],
51
+ marks: [Plot.cell(cells, { x, y, fill: value, ...(pointer ? { tip: tipStyle, title } : {}), className: 'enter-cell' })],
49
52
  });
@@ -44,4 +44,9 @@ assert.deepEqual(labels(renderPlot(heatmap(spec, 280))), ['20h', '22h'], 'fewer
44
44
 
45
45
  assert.equal(options.marks[0].channels.title.value(cells[1]), 'D1 21:00\n650 units', "the tooltip's own words");
46
46
 
47
+ // pointer: false leaves out Plot's tooltip, for a page that says what is under the pointer itself.
48
+ const own = heatmap({ ...spec, pointer: false }, 400);
49
+ assert.ok(options.marks[0].channels.title, 'a title by default');
50
+ assert.ok(!own.marks[0].channels.title, 'no title with pointer: false');
51
+
47
52
  console.log('heatmap: all assertions pass');
package/src/pointer.css CHANGED
@@ -84,6 +84,23 @@
84
84
  font-variant-numeric: tabular-nums;
85
85
  }
86
86
 
87
+ /* A total or another figure that isn't a series: under a hairline, without a swatch. */
88
+ .chart-pointer-card dl div:not(.is-extra) + .is-extra {
89
+ margin-top: 2px;
90
+ padding-top: 4px;
91
+ border-top: 1px solid var(--c-border);
92
+ }
93
+
94
+ .chart-pointer-one + dl {
95
+ margin-top: var(--sp-1);
96
+ }
97
+
98
+ /* A line at the foot, such as the unit. */
99
+ .chart-pointer-note {
100
+ margin-top: var(--sp-1) !important;
101
+ color: var(--c-text-muted);
102
+ }
103
+
87
104
  .chart-pointer-card i {
88
105
  display: inline-block;
89
106
  width: 8px;
@@ -116,6 +133,13 @@
116
133
  box-shadow: 0 0 0 2px var(--c-surface);
117
134
  }
118
135
 
136
+ /* A heatmap's cell: a frame round it, in the text colour, gliding from cell to cell. */
137
+ .chart-pointer-cell {
138
+ border: 2px solid var(--c-text);
139
+ border-radius: 3px;
140
+ box-shadow: 0 0 0 1px var(--c-surface);
141
+ }
142
+
119
143
  /* Dimming: while one is pointed at, the other bars and slices step back to 55%, and so do the
120
144
  swatches of the other rows in a donut's list. Their words keep full contrast. */
121
145
  .chart-pointer-dims svg .enter-bar > *,
package/src/pointer.mjs CHANGED
@@ -56,12 +56,31 @@ const layer = (box) => {
56
56
  return l;
57
57
  };
58
58
 
59
- // The card's words: the step's name, then one figure, or a row per series with its swatch.
60
- const words = (title, items) =>
61
- `<p class="chart-pointer-title">${esc(title)}</p>` +
62
- (items.length === 1 && !items[0].swatch
63
- ? `<p class="chart-pointer-one">${esc(items[0].value)}</p>`
64
- : `<dl>${items.map((i) => `<div><dt><i style="background:${i.color}"></i>${esc(i.label)}</dt><dd>${esc(i.value)}</dd></div>`).join('')}</dl>`);
59
+ // The card's words: the step's name, then one figure, or a row per series with its swatch. Then
60
+ // any extra: a [label, value] pair is a row without a swatch, under a hairline, such as a total;
61
+ // text is a quiet line at the foot, such as the unit.
62
+ const words = (title, items, extra = []) => {
63
+ const pairs = extra.filter(Array.isArray);
64
+ const notes = extra.filter((e) => !Array.isArray(e));
65
+ const one = items.length === 1 && !items[0].swatch;
66
+ const rows = [
67
+ ...(one ? [] : items.map((i) => `<div><dt><i style="background:${i.color}"></i>${esc(i.label)}</dt><dd>${esc(i.value)}</dd></div>`)),
68
+ ...pairs.map(([label, value]) => `<div class="is-extra"><dt>${esc(label)}</dt><dd>${esc(value)}</dd></div>`),
69
+ ];
70
+ return (
71
+ `<p class="chart-pointer-title">${esc(title)}</p>` +
72
+ (one ? `<p class="chart-pointer-one">${esc(items[0].value)}</p>` : '') +
73
+ (rows.length ? `<dl>${rows.join('')}</dl>` : '') +
74
+ notes.map((n) => `<p class="chart-pointer-note">${esc(n)}</p>`).join('')
75
+ );
76
+ };
77
+
78
+ // The same words, said: for the live region, from the keyboard.
79
+ const said = (title, items, extra = []) =>
80
+ `${title}: ${[
81
+ ...items.map((t) => (items.length > 1 ? `${t.label} ${t.value}` : t.value)),
82
+ ...extra.map((e) => (Array.isArray(e) ? e.join(' ') : e)),
83
+ ].join(', ')}`;
65
84
 
66
85
  // Appearing, moving, leaving. The first showing is in place; after that, everything glides.
67
86
  const presence = (l, onLeave) => {
@@ -102,10 +121,17 @@ const keys = (box, count, at, go, leave) => {
102
121
  // box: the element holding the chart's svg. rows: the rows drawn, one per x. x: the rows' x key.
103
122
  // series: [{ key, label, color }], as given to bars() or lines(). format: (value, series) → text.
104
123
  // label: (row) → the step's name. kind: 'bars' or 'lines'. focus (bars): 'dim', 'rule' or 'both'.
105
- export const pointer = (box, { rows, x, series, format, label = (r) => String(r[x]), kind = 'bars', focus = 'dim' }) => {
106
- const steps = rows.map((r, i) => (series.some((s) => has(r, s.key)) ? i : -1)).filter((i) => i >= 0);
107
- // The card lists a stack from the top down, as it is drawn.
108
- const listed = kind === 'bars' ? [...series].reverse() : series;
124
+ // grouped: bars side by side rather than stacked, as with bars({ grouped }).
125
+ // extra: (row) → more for the card after the series: [label, value] pairs and lines of text.
126
+ // empty: the text for a series with no value at a step, such as '–', so a missing figure is said
127
+ // rather than left out, and every row is a step, one without any figure too; by default such a
128
+ // series isn't listed, and such a row is passed over.
129
+ export const pointer = (box, { rows, x, series, format, label = (r) => String(r[x]), kind = 'bars', focus = 'dim', grouped = false, extra = () => [], empty }) => {
130
+ const steps = rows.map((r, i) => (empty !== undefined || series.some((s) => has(r, s.key)) ? i : -1)).filter((i) => i >= 0);
131
+ // The card lists a stack from the top down, as it is drawn; bars side by side from the left. On lines, as lines() tells it: a
132
+ // silent series (the dashed rest of another line) only where the line it continues has none.
133
+ const listed = kind === 'bars' ? (grouped ? series : [...series].reverse()) : [...series.filter((s) => !s.silent), ...series.filter((s) => s.silent)];
134
+ const told = (r, s) => (kind === 'lines' && s.silent ? s.continues && has(r, s.key) && !has(r, s.continues) : has(r, s.key) || empty !== undefined);
109
135
  const l = layer(box);
110
136
  const live = voice(box);
111
137
  const ruled = kind === 'lines' || focus !== 'dim';
@@ -122,11 +148,14 @@ export const pointer = (box, { rows, x, series, format, label = (r) => String(r[
122
148
  });
123
149
 
124
150
  const svg = () => box.querySelector('svg');
125
- // A bar's top: what its positive pieces add up to. A step on lines: its highest value.
126
- const top = (r) =>
127
- kind === 'bars'
128
- ? series.reduce((s, k) => s + (has(r, k.key) && r[k.key] > 0 ? r[k.key] : 0), 0)
129
- : Math.max(...series.filter((k) => has(r, k.key)).map((k) => r[k.key]));
151
+ // A bar's top: what its positive pieces add up to, or the tallest of bars side by side. A step
152
+ // on lines: its highest value.
153
+ // A step without any figure: null, and the card sits on the baseline.
154
+ const top = (r) => {
155
+ const values = series.filter((k) => has(r, k.key)).map((k) => r[k.key]);
156
+ if (!values.length) return null;
157
+ return kind === 'bars' && !grouped ? values.reduce((s, v) => s + (v > 0 ? v : 0), 0) : Math.max(...values);
158
+ };
130
159
  const where = (i) => {
131
160
  const s = svg();
132
161
  const xs = s.scale('x');
@@ -137,7 +166,7 @@ export const pointer = (box, { rows, x, series, format, label = (r) => String(r[
137
166
  return {
138
167
  cx: r.left - b.left + xs.apply(rows[i][x]) + (xs.bandwidth ?? 0) / 2,
139
168
  bw: xs.bandwidth ?? 0,
140
- y: r.top - b.top + ys.apply(top(rows[i])),
169
+ y: r.top - b.top + (top(rows[i]) === null ? Math.max(...ys.range) : ys.apply(top(rows[i]))),
141
170
  y0,
142
171
  y1,
143
172
  width: b.width,
@@ -148,8 +177,11 @@ export const pointer = (box, { rows, x, series, format, label = (r) => String(r[
148
177
  if (i < 0) return;
149
178
  at = i;
150
179
  const r = rows[i];
151
- const items = listed.filter((s) => has(r, s.key)).map((s) => ({ label: s.label, color: s.color, value: format(r[s.key], s), swatch: series.length > 1 }));
152
- card.innerHTML = words(label(r), items);
180
+ const items = listed
181
+ .filter((s) => told(r, s))
182
+ .map((s) => ({ label: s.label, color: s.color, value: has(r, s.key) ? format(r[s.key], s) : empty, swatch: series.length > 1 }));
183
+ const more = extra(r) ?? [];
184
+ card.innerHTML = words(label(r), items, more);
153
185
  const q = where(i);
154
186
  if (ruled) {
155
187
  rule.style.transform = `translateX(${q.cx}px)`;
@@ -161,7 +193,8 @@ export const pointer = (box, { rows, x, series, format, label = (r) => String(r[
161
193
  const left = box.getBoundingClientRect().left;
162
194
  for (const m of box.querySelectorAll('svg .enter-bar > *')) {
163
195
  const b = m.getBoundingClientRect();
164
- m.classList.toggle('is-on', Math.abs(b.left + b.width / 2 - left - q.cx) <= Math.max(b.width, 2) / 2 + 1);
196
+ // Every bar in the step's band: one when stacked, each of a group side by side.
197
+ m.classList.toggle('is-on', Math.abs(b.left + b.width / 2 - left - q.cx) <= Math.max(q.bw, b.width, 2) / 2 + 1);
165
198
  }
166
199
  box.classList.add('is-dimming');
167
200
  }
@@ -182,7 +215,7 @@ export const pointer = (box, { rows, x, series, format, label = (r) => String(r[
182
215
  }
183
216
  card.style.transform = `translate(${cx}px, ${cy}px)`;
184
217
  p.show();
185
- if (fromKeys) live.textContent = `${label(r)}: ${items.map((t) => (items.length > 1 ? `${t.label} ${t.value}` : t.value)).join(', ')}`;
218
+ if (fromKeys) live.textContent = said(label(r), items, more);
186
219
  };
187
220
 
188
221
  // The nearest step with a figure, as Plot's pointer picks it.
@@ -204,6 +237,85 @@ export const pointer = (box, { rows, x, series, format, label = (r) => String(r[
204
237
  keys(box, steps.length, () => steps.indexOf(at), (k) => show(steps[k], true), () => p.leave());
205
238
  };
206
239
 
240
+ // A heatmap drawn with heatmap({ pointer: false }): a frame round the cell pointed at, gliding from
241
+ // cell to cell, and the card beside it on the side with room. Keyboard: left and right step
242
+ // through the cells in reading order, up and down go to the same hour in the row above or below,
243
+ // Home and End to the first and last. cells, x, y and value as given to heatmap(); format:
244
+ // (value) → text; label: (cell) → its name; extra as for pointer().
245
+ export const pointerCells = (box, { cells, x, y, value, format = String, label = (c) => `${c[x]}, ${c[y]}`, extra = () => [] }) => {
246
+ const l = layer(box);
247
+ const live = voice(box);
248
+ const frame = el('div', 'chart-pointer-cell', l);
249
+ const card = el('div', 'chart-pointer-card', l);
250
+ const svg = () => box.querySelector('svg');
251
+ const scales = () => ({ xs: svg().scale('x'), ys: svg().scale('y') });
252
+ // Reading order: row by row, then across.
253
+ const { xs: x0, ys: y0 } = scales();
254
+ const order = cells
255
+ .filter((c) => typeof c[value] === 'number')
256
+ .sort((a, b) => y0.domain.indexOf(a[y]) - y0.domain.indexOf(b[y]) || x0.domain.indexOf(a[x]) - x0.domain.indexOf(b[x]));
257
+ let at = -1;
258
+ const p = presence(l, () => {
259
+ at = -1;
260
+ });
261
+ const place = (c) => {
262
+ const { xs, ys } = scales();
263
+ const r = svg().getBoundingClientRect();
264
+ const b = box.getBoundingClientRect();
265
+ return { left: r.left - b.left + xs.apply(c[x]), top: r.top - b.top + ys.apply(c[y]), w: xs.bandwidth, h: ys.bandwidth, width: b.width };
266
+ };
267
+ const show = (i, fromKeys) => {
268
+ if (i < 0) return;
269
+ at = i;
270
+ const c = order[i];
271
+ const items = [{ value: format(c[value]) }];
272
+ const more = extra(c) ?? [];
273
+ card.innerHTML = words(label(c), items, more);
274
+ const q = place(c);
275
+ frame.style.width = `${q.w}px`;
276
+ frame.style.height = `${q.h}px`;
277
+ frame.style.transform = `translate(${q.left}px, ${q.top}px)`;
278
+ const cw = card.offsetWidth;
279
+ const ch = card.offsetHeight;
280
+ const cx = q.left + q.w + 8 + cw > q.width ? q.left - 8 - cw : q.left + q.w + 8;
281
+ card.style.transform = `translate(${cx}px, ${Math.max(q.top + q.h / 2 - ch / 2, 0)}px)`;
282
+ p.show();
283
+ if (fromKeys) live.textContent = said(label(c), items, more);
284
+ };
285
+ const nearest = (e) => {
286
+ const { xs, ys } = scales();
287
+ const r = svg().getBoundingClientRect();
288
+ let best = -1;
289
+ let gap = Infinity;
290
+ order.forEach((c, i) => {
291
+ const d = Math.hypot(r.left + xs.apply(c[x]) + xs.bandwidth / 2 - e.clientX, r.top + ys.apply(c[y]) + ys.bandwidth / 2 - e.clientY);
292
+ if (d < gap) [best, gap] = [i, d];
293
+ });
294
+ return best;
295
+ };
296
+ // The same x in the row `by` rows away, or the nearest x there.
297
+ const vertical = (i, by) => {
298
+ const { xs, ys } = scales();
299
+ const row = ys.domain[ys.domain.indexOf(order[i][y]) + by];
300
+ const there = order.map((c, k) => [c, k]).filter(([c]) => c[y] === row);
301
+ if (!there.length) return i;
302
+ const want = xs.domain.indexOf(order[i][x]);
303
+ return there.reduce((a, b) => (Math.abs(xs.domain.indexOf(b[0][x]) - want) < Math.abs(xs.domain.indexOf(a[0][x]) - want) ? b : a))[1];
304
+ };
305
+ box.onpointermove = (e) => show(nearest(e));
306
+ box.onpointerleave = () => p.leave();
307
+ box.tabIndex = 0;
308
+ box.onkeydown = (e) => {
309
+ if (e.key === 'Escape') return p.leave();
310
+ const from = at < 0 ? 0 : at;
311
+ const to = { ArrowRight: from + 1, ArrowLeft: from - 1, ArrowDown: vertical(from, 1), ArrowUp: vertical(from, -1), Home: 0, End: order.length - 1 }[e.key];
312
+ if (to === undefined) return;
313
+ e.preventDefault();
314
+ show(at < 0 ? 0 : Math.min(Math.max(to, 0), order.length - 1), true);
315
+ };
316
+ box.onblur = () => p.leave();
317
+ };
318
+
207
319
  // A donut drawn with donutRing, as in the Donut component: pointing at a slice, or at its row in
208
320
  // the list beside the ring, dims the other slices and the other rows' swatches (their words keep
209
321
  // full contrast), and the card sits in the ring's hole,