@n1kname/charts 0.13.0 → 0.14.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.13.0",
3
+ "version": "0.14.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
package/src/bars.mjs CHANGED
@@ -7,13 +7,35 @@
7
7
  // bought still reads. A row can be drawn fainter (`fade`) and with a dashed edge (`dashed`),
8
8
  // for figures that are not settled yet; say what each means in a Legend. A run of steps can be
9
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.
10
+ // `tag` over its first bar, so two series are not told apart by colour alone. The bars that
11
+ // carry the story can say their figure all the time (`callout`), so a reader on a phone, with no
12
+ // pointer, still gets the numbers that matter.
11
13
 
12
14
  import * as Plot from '@observablehq/plot';
13
15
  import { chrome, tipStyle } from './theme.mjs';
14
16
 
15
17
  const plain = (v, digits) => v.toFixed(digits);
16
18
 
19
+ // d3's nice(), with the count Plot uses, so the shade can reach the top of the frame exactly.
20
+ const increment = (start, stop, count) => {
21
+ const step = (stop - start) / count;
22
+ const power = Math.floor(Math.log10(step));
23
+ const error = step / 10 ** power;
24
+ const factor = error >= Math.sqrt(50) ? 10 : error >= Math.sqrt(10) ? 5 : error >= Math.sqrt(2) ? 2 : 1;
25
+ return power >= 0 ? factor * 10 ** power : -(10 ** -power) / factor;
26
+ };
27
+ export const niceDomain = ([start, stop], count = 10) => {
28
+ let previous;
29
+ for (let i = 0; i < 10 && stop > start; i++) {
30
+ const step = increment(start, stop, count);
31
+ if (step === previous || !Number.isFinite(step) || step === 0) break;
32
+ if (step > 0) [start, stop] = [Math.floor(start / step) * step, Math.ceil(stop / step) * step];
33
+ else [start, stop] = [Math.ceil(start * step) / step, Math.floor(stop * step) / step];
34
+ previous = step;
35
+ }
36
+ return [start, stop];
37
+ };
38
+
17
39
  export const bars = (
18
40
  {
19
41
  rows,
@@ -29,6 +51,10 @@ export const bars = (
29
51
  y = ['auto', 'auto'],
30
52
  // The total written on top of each bar.
31
53
  values = false,
54
+ // A figure written over a bar that matters, without the pointer: gets (row, series) and
55
+ // returns true to write that series' value over its bar in that row. Stacked, the series
56
+ // is the top one and the figure is the total. Pick a few: every bar is what `values` is for.
57
+ callout = null,
32
58
  // Opacity per row, 1 for a settled figure.
33
59
  fade = () => 1,
34
60
  // A dashed edge per row, in the series' colour.
@@ -78,10 +104,11 @@ export const bars = (
78
104
  const bottom = (r) => (grouped ? Math.min(0, ...valuesOf(r)) : sum(valuesOf(r).filter((v) => v < 0)));
79
105
  const total = (r) => series.reduce((sum, s) => sum + (has(r, s.key) ? r[s.key] : 0), 0);
80
106
  const drawn = rows.filter((r) => series.some((s) => has(r, s.key)));
81
- const domain = [
107
+ // Rounded out to round numbers here rather than by Plot, so the shade knows where the frame ends.
108
+ const domain = niceDomain([
82
109
  y[0] === 'auto' ? Math.min(0, ...drawn.map(bottom)) : y[0],
83
110
  y[1] === 'auto' ? Math.max(0, ...drawn.map(top)) : y[1],
84
- ];
111
+ ]);
85
112
  // Stacked, the tooltip lists the parts from the top, as they are drawn; grouped, in order.
86
113
  const listed = grouped ? series : [...series].reverse();
87
114
  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'));
@@ -122,10 +149,13 @@ export const bars = (
122
149
  const shaded = shade ? rows.slice(rows.findIndex((r) => r[x] === shade.from), rows.findIndex((r) => r[x] === shade.to) + 1) : [];
123
150
  const shading = shaded.length
124
151
  ? [
125
- Plot.barY(shaded, { x, y1: () => domain[0], y2: () => domain[1], fill: chrome.neutral, fillOpacity: 0.16, inset: -(step - band) / 2, className: 'enter-fade' }),
152
+ Plot.barY(shaded, { x, y1: () => domain[0], y2: () => domain[1], fill: chrome.neutral, fillOpacity: 0.16, insetLeft: -(step - band) / 2, insetRight: -(step - band) / 2, className: 'enter-fade' }),
153
+ // The word at the top of the block, where bars are least likely to be.
126
154
  Plot.text([shaded[0]], {
127
155
  x,
128
- frameAnchor: 'middle',
156
+ frameAnchor: 'top',
157
+ dy: 10,
158
+ lineAnchor: 'top',
129
159
  dx: ((shaded.length - 1) * step) / 2,
130
160
  text: () => shade.text,
131
161
  fill: 'var(--c-text-secondary)',
@@ -135,21 +165,28 @@ export const bars = (
135
165
  ]
136
166
  : [];
137
167
 
138
- // A series' tag over its first bar. The first grows leftward from its bar's right edge and
139
- // the rest rightward from their left edge, so two tags never touch.
168
+ // A series' tag over its first bar with a value. The first grows leftward from its bar's right
169
+ // edge and the rest rightward from their left edge, so two tags never touch. A tag runs over
170
+ // the steps beside its bar, so it sits above the tallest bar it crosses, not on top of it.
171
+ const TAG_EM = 6;
140
172
  const tags = series.flatMap((s, i) => {
141
- const first = rows.find((r) => has(r, s.key));
173
+ const at = rows.findIndex((r) => has(r, s.key) && r[s.key] !== 0);
174
+ const first = rows[at];
142
175
  if (!s.tag || !first) return [];
143
- const edge = grouped ? (i === 0 ? left(i) + barWidth : left(i)) - band / 2 : 0;
176
+ const leftward = grouped && i === 0;
177
+ const edge = grouped ? (leftward ? left(i) + barWidth : left(i)) - band / 2 : 0;
178
+ const reach = Math.ceil((s.tag.length * TAG_EM) / step);
179
+ const crossed = leftward ? rows.slice(Math.max(0, at - reach), at + 1) : rows.slice(at, at + reach + 1);
180
+ const lift = Math.max(...crossed.map(top));
144
181
  return [
145
182
  Plot.text([first], {
146
183
  x,
147
- y: (r) => (grouped ? Math.max(0, r[s.key]) : top(r)),
184
+ y: () => lift,
148
185
  text: () => s.tag,
149
186
  dx: edge,
150
187
  dy: -6,
151
188
  lineAnchor: 'bottom',
152
- textAnchor: grouped && i === 0 ? 'end' : 'start',
189
+ textAnchor: leftward ? 'end' : 'start',
153
190
  fill: 'var(--c-text-secondary)',
154
191
  fontSize: 10,
155
192
  className: 'enter-fade',
@@ -157,16 +194,44 @@ export const bars = (
157
194
  ];
158
195
  });
159
196
 
197
+ // Callouts: the figure over each bar picked, centred on it. Stacked, over the whole bar.
198
+ const callouts = callout
199
+ ? series.flatMap((s, i) => {
200
+ if (!grouped && i !== series.length - 1) return [];
201
+ const picked = rows.filter((r) => (grouped ? has(r, s.key) : series.some((t) => has(r, t.key))) && callout(r, s));
202
+ if (!picked.length) return [];
203
+ return [
204
+ Plot.text(picked, {
205
+ x,
206
+ y: (r) => (grouped ? Math.max(0, r[s.key]) : top(r)),
207
+ text: (r) => format(grouped ? r[s.key] : total(r), digits),
208
+ dx: grouped ? left(i) + barWidth / 2 - band / 2 : 0,
209
+ dy: -6,
210
+ lineAnchor: 'bottom',
211
+ fill: chrome.text,
212
+ // A halo in the surface colour, so a figure that crosses a taller bar beside it
213
+ // still reads.
214
+ stroke: 'var(--c-surface)',
215
+ strokeWidth: 3,
216
+ paintOrder: 'stroke',
217
+ fontSize: 12,
218
+ fontWeight: 600,
219
+ className: 'enter-fade',
220
+ }),
221
+ ];
222
+ })
223
+ : [];
224
+
160
225
  const labels = (v, i) => tick(v, i, width);
161
226
  return {
162
227
  width,
163
228
  height,
164
- marginTop: values || series.some((s) => s.tag) ? 24 : 10,
229
+ marginTop: values || callout || series.some((s) => s.tag) ? 24 : 10,
165
230
  marginLeft,
166
231
  marginRight,
167
232
  marginBottom,
168
233
  x: { type: 'band', domain: rows.map((r) => r[x]), padding, ...(grouped ? { round: false } : {}), label: null, tickSize: 0, tickFormat: labels, axis: null },
169
- y: { domain, nice: true, label: yLabel, tickSize: 0, ticks: 5, tickFormat: (v) => format(v, yDigits) },
234
+ y: { domain, label: yLabel, tickSize: 0, ticks: 5, tickFormat: (v) => format(v, yDigits) },
170
235
  opacity: { type: 'identity' },
171
236
  marks: [
172
237
  Plot.axisX({ tickSize: 0, tickFormat: labels, lineWidth: wrap(width) }),
@@ -182,6 +247,7 @@ export const bars = (
182
247
  ? [Plot.text(drawn, { x, y: total, text: (r) => format(total(r), digits), dy: -8, lineAnchor: 'bottom', fill: chrome.text, fontSize: 12, className: 'enter-fade' })]
183
248
  : []),
184
249
  ...tags,
250
+ ...callouts,
185
251
  Plot.ruleY([0], { stroke: chrome.axis, className: 'enter-zero' }),
186
252
  ...(pointer ? [Plot.tip(tipped, Plot.pointerX({ x, y: top, title: says, ...tipStyle }))] : []),
187
253
  ],
package/src/bars.test.mjs CHANGED
@@ -52,8 +52,8 @@ const opacity = [...svg.matchAll(/fill="var\(--c-chart-2\)"[^>]*>((?:<(?:path|re
52
52
  .flatMap((m) => [...m[1].matchAll(/fill-opacity="([\d.]+)"/g)].map((o) => Number(o[1])));
53
53
  assert.deepEqual(opacity, [1, 1, 1, 0.5, 0.22], 'settled rows are solid, an estimate fainter, a projection fainter again');
54
54
 
55
- // The domain holds the highest stack and the lowest negative.
56
- assert.deepEqual(options.y.domain, [-3, 25], 'the y domain runs from the lowest piece to the highest stack');
55
+ // The domain holds the highest stack and the lowest negative, rounded out the way Plot would.
56
+ assert.deepEqual(options.y.domain, [-4, 26], 'the y domain runs from the lowest piece to the highest stack, rounded out');
57
57
 
58
58
  // The tooltip: each series from the top, a missing one left out.
59
59
  const tip = options.marks.at(-1);
@@ -114,6 +114,47 @@ assert.ok(!renderPlot(bars({ ...spec, grouped: false }, 600)).includes('left out
114
114
 
115
115
  console.log('bars: all assertions pass');
116
116
 
117
+ // Callouts: a figure over each bar picked, always on, centred on its own bar.
118
+ {
119
+ const c = bars({ rows: pairs, x: 'm', series: two, unit: 'units', grouped: true, callout: (r, s) => r.m === 'M1' || (r.m === 'M5' && s.key === 'old') }, 500);
120
+ const cSvg = renderPlot(c);
121
+ const figures = [...cSvg.matchAll(/font-weight="600"[^>]*>((?:<text[^>]*>[^<]*<\/text>)+)/g)]
122
+ .flatMap((m) => [...m[1].matchAll(/>([^<]+)<\/text>/g)].map((t) => t[1]));
123
+ assert.deepEqual(figures.sort(), ['20', '30', '5'], 'each picked bar says its own figure, and only those');
124
+ const stacked = renderPlot(bars({ ...spec, callout: (r) => r.month === 'M4' }, 600));
125
+ assert.ok(/font-weight="600"[^>]*><text[^>]*>23\.0<\/text>/.test(stacked), 'stacked, a callout is the total over the whole bar');
126
+ assert.ok(!/font-weight="600"/.test(svg), 'no callouts unless asked');
127
+ }
128
+
129
+ // The shade spans the frame and no further: from the bottom of the scale to its rounded top.
130
+ {
131
+ const block = g.marks.find((m) => m.data?.[0]?.m === 'M3' && m.data.length === 2);
132
+ assert.ok(block, 'the shaded block is a mark of its own');
133
+ assert.equal(block.insetTop, 0, 'the block reaches the top of the frame, no further');
134
+ assert.equal(block.insetBottom, 0, 'and stops at the bottom of the scale, not below the axis');
135
+ }
136
+
137
+ // A tag sits on the first bar with a value, above any taller bar it runs over.
138
+ {
139
+ const climb = [
140
+ { m: 'A', a: null, b: 0 },
141
+ { m: 'B', a: null, b: 2 },
142
+ { m: 'C', a: 40, b: 9 },
143
+ { m: 'D', a: 30, b: 3 },
144
+ ];
145
+ // The second series' tag grows rightward, over the steps after its bar.
146
+ const t = bars({ rows: climb, x: 'm', series: [{ key: 'a', label: 'A', color: 'var(--c-chart-2)' }, { key: 'b', label: 'B', color: 'var(--c-chart-1)', tag: 'Prototype' }], grouped: true }, 160);
147
+ const tag = t.marks.find((m) => m.constructor.name === 'Text' && m.data?.[0]?.m && m.channels?.text?.value?.() === 'Prototype');
148
+ assert.equal(tag.data[0].m, 'B', 'a first bar of zero carries no tag; the first with a value does');
149
+ assert.equal(tag.channels.y.value(), 40, 'the tag clears the taller bar beside it');
150
+ }
151
+
152
+ // Labels in the system sans with tabular figures, not monospace.
153
+ assert.ok(!/monospace/.test(svg), 'no monospace in a chart');
154
+ assert.ok(/system-ui/.test(svg), 'the system sans');
155
+
156
+ console.log('bars: callouts, shade and tags pass');
157
+
117
158
  // pointer: false leaves out Plot's tooltip and hover band, for a page that draws its own.
118
159
  {
119
160
  const own = bars({ ...spec, pointer: false }, 600);
package/src/plot.mjs CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  import * as Plot from '@observablehq/plot';
6
6
  import { parseHTML } from 'linkedom';
7
- import { chrome } from './theme.mjs';
7
+ import { chrome, SYSTEM_SANS } from './theme.mjs';
8
8
 
9
9
  export { Plot };
10
10
 
@@ -20,8 +20,10 @@ export const renderPlot = (options) => {
20
20
  color: chrome.textMuted,
21
21
  // A system font on purpose. Safari lays out SVG text with the fallback font's
22
22
  // widths and then paints the web font, which shifts anything centred or
23
- // right-aligned. A font that never swaps has nothing to shift.
24
- fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
23
+ // right-aligned. A font that never swaps has nothing to shift. A sans, not mono, so
24
+ // labels read as words; tabular figures keep the numbers lined up all the same.
25
+ fontFamily: SYSTEM_SANS,
26
+ fontVariantNumeric: 'tabular-nums',
25
27
  fontSize: '13px',
26
28
  overflow: 'visible',
27
29
  },
package/src/theme.mjs CHANGED
@@ -19,13 +19,16 @@ export const chrome = {
19
19
  textMuted: v('text-muted'),
20
20
  };
21
21
 
22
+ // The system's own sans: it never swaps, so Safari has nothing to misplace (see ./plot.mjs).
23
+ export const SYSTEM_SANS = "system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif";
24
+
22
25
  // Plot's own tooltip, for charts drawn at build time: in a system font, because Safari misplaces
23
26
  // centred SVG text in a web font. A chart drawn in the page can say it better with `pointer`
24
27
  // (./pointer.mjs): an HTML card in the page's type that glides. Every value also needs a table.
25
28
  export const tipStyle = {
26
29
  fill: 'var(--c-surface)',
27
30
  stroke: 'var(--c-border-strong)',
28
- fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
31
+ fontFamily: SYSTEM_SANS,
29
32
  fontSize: 12,
30
33
  textPadding: 8,
31
34
  };