qvac-charts 0.2.0 → 0.4.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/README.md CHANGED
@@ -35,10 +35,37 @@ chart.summary // 'Ranked bar, 3 items, highlight USDT, $187B'
35
35
  chart.toSVG({ theme: 'light' }) // a 1080×1350 SVG string
36
36
  ```
37
37
 
38
- `summary` is one line a model can talk about the chart from, without seeing it. The model describes the data; the package picks the chart, does the arithmetic and draws it. There are 13 chart types, including a choropleth and a bubble map of the world or of one continent.
38
+ `summary` is one line a model can talk about the chart from, without seeing it. The model describes the data; the package picks the chart, does the arithmetic and draws it. There are 14 chart types, including a choropleth and a bubble map of the world or of one continent.
39
39
 
40
40
  A spec takes at most 30 items, the bound in `Chart.schema`; `Chart.from` throws a `RangeError` past it, or when no value is a finite number. Values that are not finite, such as `1e400` read from JSON, are dropped.
41
41
 
42
+ ### Scatter
43
+
44
+ A spec with `shape: 'pairs'` is a scatter: each item carries `x`, its number across, beside `value`, its number up. `horizontal` and `vertical` name the two axes. With `callout: 'trend'` the package fits a least-squares line, draws it and writes its R² on the chart and in `summary`; the highlighted item is the one point drawn with its name.
45
+
46
+ ```js
47
+ Chart.from({
48
+ shape: 'pairs',
49
+ title: 'More study, higher scores',
50
+ subtitle: 'Exam score against hours studied',
51
+ data: [
52
+ { label: 'Ana', x: 1, value: 52 },
53
+ { label: 'Bruno', x: 4, value: 70 },
54
+ { label: 'Carla', x: 8, value: 90 },
55
+ { label: 'Davi', x: 2, value: 94 }
56
+ ],
57
+ highlight: 'Davi',
58
+ scale: 'ones',
59
+ unit: 'number',
60
+ callout: 'trend',
61
+ horizontal: 'Hours studied',
62
+ vertical: 'Exam score',
63
+ source: 'User data'
64
+ }).summary // 'Scatter, 4 items, highlight Davi, 94, linear trend rising, R² 0.26'
65
+ ```
66
+
67
+ `scale` and `unit` apply to `value`; `x` is shown as written. Items without an `x` are left out, and `Chart.from` throws a `RangeError` when fewer than two have one.
68
+
42
69
  ### Brand mark
43
70
 
44
71
  The package ships no logo. A host that wants its mark in the footer passes it to `toSVG`; the source line then wraps short of it:
@@ -47,6 +74,17 @@ The package ships no logo. A host that wants its mark in the footer passes it to
47
74
  chart.toSVG({ theme: 'dark', mark: { href: 'data:image/png;base64,…', width: 110, height: 48 } })
48
75
  ```
49
76
 
77
+ ### Colors
78
+
79
+ `toSVG` takes an `accent` and a `palette` that replace the theme's. The accent colors the highlighted item, the callout and the deep end of a map's shading; the palette colors the other items or series, in order, and repeats when there are more of them than colors. An accent given alone leaves the theme's palette in place.
80
+
81
+ ```js
82
+ chart.toSVG({ theme: 'light', accent: 'blue' })
83
+ chart.toSVG({ theme: 'dark', accent: '#1d4ed8', palette: ['teal', 'tomato', 'gold'] })
84
+ ```
85
+
86
+ A color is a CSS color name, read loosely (`'Light Blue'` is `lightblue`), or a 3- or 6-digit hex, with or without `#`, so a model can pass on what the user said. Anything else, and a palette that is empty or longer than 12, throws a `RangeError`. A color too close to the theme's background to read against it is darkened on the light theme and lightened on the dark one until it reaches a 3:1 contrast ratio. Without colors the chart is drawn exactly as before.
87
+
50
88
  ### Maps
51
89
 
52
90
  The map data is its own entry, so a host that draws no maps does not load it. `mapsFor` takes the places a spec names and returns the world (about 120 KB) with the one continent that holds them (8 to 43 KB), loaded on demand:
@@ -9,6 +9,8 @@ export interface ChartOptions {
9
9
  export interface SVGOptions {
10
10
  theme?: ThemeName;
11
11
  mark?: Mark;
12
+ accent?: string;
13
+ palette?: ReadonlyArray<string>;
12
14
  }
13
15
  export declare class Chart {
14
16
  static schema: {
@@ -40,6 +42,9 @@ export declare class Chart {
40
42
  value: {
41
43
  type: string;
42
44
  };
45
+ x: {
46
+ type: string;
47
+ };
43
48
  group: {
44
49
  type: string;
45
50
  maxLength: number;
@@ -83,6 +88,14 @@ export declare class Chart {
83
88
  callout: {
84
89
  enum: string[];
85
90
  };
91
+ horizontal: {
92
+ type: string;
93
+ maxLength: number;
94
+ };
95
+ vertical: {
96
+ type: string;
97
+ maxLength: number;
98
+ };
86
99
  source: {
87
100
  type: string;
88
101
  maxLength: number;
@@ -96,5 +109,5 @@ export declare class Chart {
96
109
  readonly summary: string;
97
110
  private normalized;
98
111
  private constructor();
99
- toSVG({ theme, mark }?: SVGOptions): string;
112
+ toSVG({ theme, mark, accent, palette }?: SVGOptions): string;
100
113
  }
package/dist-lib/index.js CHANGED
@@ -15,8 +15,8 @@ export class Chart {
15
15
  this.type = normalized.type;
16
16
  this.summary = summarize(normalized);
17
17
  }
18
- toSVG({ theme = 'dark', mark } = {}) {
19
- return render(this.normalized, { theme, mark });
18
+ toSVG({ theme = 'dark', mark, accent, palette } = {}) {
19
+ return render(this.normalized, { theme, mark, accent, palette });
20
20
  }
21
21
  }
22
22
  function summarize(chart) {
@@ -24,5 +24,11 @@ function summarize(chart) {
24
24
  const kind = name[0].toUpperCase() + name.slice(1);
25
25
  const lead = chart.data.find((d) => d.label === chart.highlight);
26
26
  const focus = lead ? `, highlight ${lead.label}, ${formatter(chart)(lead.value)}` : '';
27
- return `${kind}, ${chart.data.length} items${focus}`;
27
+ return `${kind}, ${chart.data.length} items${focus}${fitted(chart)}`;
28
+ }
29
+ function fitted({ trend }) {
30
+ if (!trend) {
31
+ return '';
32
+ }
33
+ return `, linear trend ${trend.slope < 0 ? 'falling' : 'rising'}, R² ${trend.r2.toFixed(2)}`;
28
34
  }
@@ -1,6 +1,7 @@
1
1
  import { bubbleMap, choropleth } from './maps.js';
2
2
  import { bubbles, donut, stacked, treemap, waffle } from './parts.js';
3
3
  import { radial, rankedBar } from './ranking.js';
4
+ import { scatter } from './scatter.js';
4
5
  import { slope } from './slope.js';
5
6
  import { column, line, multiLine } from './time.js';
6
7
  export const charts = {
@@ -16,5 +17,6 @@ export const charts = {
16
17
  'multi-line': multiLine,
17
18
  slope,
18
19
  choropleth,
19
- 'bubble-map': bubbleMap
20
+ 'bubble-map': bubbleMap,
21
+ scatter
20
22
  };
@@ -1,6 +1,6 @@
1
1
  import { callout } from '../frame.js';
2
2
  import { arc, bounds, dodge, largestRemainder, pack, polar, squarify } from '../geometry.js';
3
- import { text, wrap } from '../svg.js';
3
+ import { clamp, fit, stack, text, wrap } from '../svg.js';
4
4
  import { colors } from '../themes.js';
5
5
  const byValue = (data) => [...data].sort((a, c) => c.value - a.value);
6
6
  const sum = (data) => data.reduce((s, d) => s + d.value, 0);
@@ -216,12 +216,14 @@ export function stacked({ out, spec, t, b }) {
216
216
  const labelW = Math.min(240, Math.max(...rows.map((r) => r.length)) * 28 * 0.56) + 24;
217
217
  const x0 = b.x + labelW;
218
218
  const span = b.w - labelW;
219
+ const room = { width: labelW - 24, height: rowH * 0.9 };
220
+ const name = { ...fit(rows, room, [28, 24, 20]), ...room, x: b.x, weight: 700, fill: t.text };
219
221
  rows.forEach((r, ri) => {
220
222
  const cy = top + ri * rowH + rowH / 2;
221
223
  const cells = parts.map((p) => spec.data.find((d) => d.label === r && (d.group ?? '') === p)?.value ?? 0);
222
224
  const total = cells.reduce((s, v) => s + v, 0) || 1;
223
225
  let cx = x0;
224
- out.push(text(r, { x: b.x, y: cy + 10, size: 28, weight: 700, fill: t.text }));
226
+ out.push(...stack(clamp(r, name), { ...name, y: cy + 10 }));
225
227
  cells.forEach((v, pi) => {
226
228
  const w = (v / total) * span;
227
229
  if (w <= 0) {
@@ -1,6 +1,6 @@
1
1
  import { callout } from '../frame.js';
2
2
  import { ceiling, stroke } from '../geometry.js';
3
- import { text } from '../svg.js';
3
+ import { clamp, fit, stack, text } from '../svg.js';
4
4
  export function rankedBar(d) {
5
5
  const { out, spec, t, b, fmt } = d;
6
6
  const rows = [...spec.data].sort((a, c) => c.value - a.value);
@@ -8,6 +8,7 @@ export function rankedBar(d) {
8
8
  const max = ceiling(rows.map((r) => r.value));
9
9
  const rowH = Math.min(86, b.h / rows.length);
10
10
  const labelW = Math.min(300, Math.max(...rows.map((r) => r.label.length)) * 30 * 0.56);
11
+ const name = fit(rows.map((r) => r.label), { width: labelW, height: rowH * 0.9 }, [30, 26, 22, 18]);
11
12
  const x0 = b.x + 64 + labelW + 20;
12
13
  const span = b.x + b.w - x0 - 170;
13
14
  rows.forEach((r, i) => {
@@ -24,7 +25,13 @@ export function rankedBar(d) {
24
25
  fill: on ? t.bg : t.muted,
25
26
  anchor: 'middle'
26
27
  }));
27
- out.push(text(r.label, { x: b.x + 64, y: cy + 10, size: 30, weight: on ? 800 : 500, fill: t.text }));
28
+ out.push(...stack(clamp(r.label, { ...name, width: labelW }), {
29
+ ...name,
30
+ x: b.x + 64,
31
+ y: cy + 10,
32
+ weight: on ? 800 : 500,
33
+ fill: t.text
34
+ }));
28
35
  out.push(`<rect x="${x0}" y="${cy - rowH * 0.31}" width="${w}" height="${rowH * 0.62}" rx="6" fill="${fill}"/>`);
29
36
  out.push(text(fmt(r.value), {
30
37
  x: x0 + w + 14,
@@ -0,0 +1,2 @@
1
+ import type { Draw } from '../frame.ts';
2
+ export declare function scatter(d: Draw): void;
@@ -0,0 +1,70 @@
1
+ import { spread } from '../geometry.js';
2
+ import { halo, text } from '../svg.js';
3
+ import { paired } from '../trend.js';
4
+ const across = (v) => v.toLocaleString('en-US', { maximumFractionDigits: 2 });
5
+ export function scatter(d) {
6
+ const { spec, b } = d;
7
+ const pts = spec.data.filter(paired);
8
+ const xs = spread(pts.map((p) => p.x));
9
+ const ys = spread(pts.map((p) => p.value));
10
+ const [left, right, top, bottom] = [b.x + 100, b.x + b.w - 40, b.y + 70, b.y + b.h - 110];
11
+ const px = (v) => left + ((v - xs[0]) / (xs[xs.length - 1] - xs[0])) * (right - left);
12
+ const py = (v) => bottom - ((v - ys[0]) / (ys[ys.length - 1] - ys[0])) * (bottom - top);
13
+ const plot = { xs, ys, px, py, left, right, top, bottom };
14
+ axes(d, plot);
15
+ line(d, plot);
16
+ points(d, { plot, pts });
17
+ }
18
+ function axes({ out, spec, t, fmt }, { xs, ys, px, py, left, right, top, bottom }) {
19
+ const td = ys.some((v) => !Number.isInteger(v)) ? 1 : 0;
20
+ for (const v of ys) {
21
+ out.push(`<rect x="${left}" y="${py(v)}" width="${right - left}" height="1.5" fill="${t.faint}"/>`);
22
+ out.push(text(fmt(v, td), { x: left - 14, y: py(v) + 8, size: 22, fill: t.muted, anchor: 'end' }));
23
+ }
24
+ for (const v of xs) {
25
+ out.push(`<rect x="${px(v)}" y="${top}" width="1.5" height="${bottom - top}" fill="${t.faint}"/>`);
26
+ out.push(text(across(v), { x: px(v), y: bottom + 36, size: 22, fill: t.muted, anchor: 'middle' }));
27
+ }
28
+ const name = { size: 24, weight: 700, fill: t.text };
29
+ out.push(text(spec.vertical ?? '', { ...name, x: left - 100, y: top - 40 }));
30
+ out.push(text(spec.horizontal ?? '', { ...name, x: right, y: bottom + 84, anchor: 'end' }));
31
+ }
32
+ function line({ out, spec, t }, { xs, ys, px, py, right, top }) {
33
+ const fit = spec.trend;
34
+ if (!fit) {
35
+ return;
36
+ }
37
+ const at = (x) => fit.intercept + fit.slope * x;
38
+ const inside = (x) => Math.min(Math.max(x, xs[0]), xs[xs.length - 1]);
39
+ const [lo, hi] = [ys[0], ys[ys.length - 1]];
40
+ const ends = fit.slope
41
+ ? [(lo - fit.intercept) / fit.slope, (hi - fit.intercept) / fit.slope].sort((a, c) => a - c)
42
+ : [xs[0], xs[xs.length - 1]];
43
+ const [x0, x1] = ends.map(inside);
44
+ out.push(`<path d="M${px(x0)},${py(at(x0))}L${px(x1)},${py(at(x1))}" fill="none" stroke="${t.text}" stroke-width="4" stroke-dasharray="14 10" stroke-linecap="round" stroke-opacity="0.75"/>`);
45
+ out.push(text(`Linear trend, R² = ${fit.r2.toFixed(2)}`, {
46
+ x: right,
47
+ y: top - 40,
48
+ size: 24,
49
+ weight: 700,
50
+ fill: t.text,
51
+ anchor: 'end'
52
+ }));
53
+ }
54
+ function points({ out, spec, t, fmt }, { plot: { px, py, left, right }, pts }) {
55
+ const on = pts.find((p) => p.label === spec.highlight);
56
+ for (const p of pts) {
57
+ if (p !== on) {
58
+ out.push(`<circle cx="${px(p.x)}" cy="${py(p.value)}" r="11" fill="${t.palette[3]}" fill-opacity="0.9" stroke="${t.bg}" stroke-width="3"/>`);
59
+ }
60
+ }
61
+ if (!on) {
62
+ return;
63
+ }
64
+ const [x, y] = [px(on.x), py(on.value)];
65
+ const end = x > (left + right) / 2;
66
+ const name = { x: end ? x - 24 : x + 24, anchor: end ? 'end' : 'start', stroke: t.bg };
67
+ out.push(`<circle cx="${x}" cy="${y}" r="15" fill="${t.accent}" stroke="${t.bg}" stroke-width="3"/>`);
68
+ out.push(halo(on.label, { ...name, y: y + 2, size: 26, weight: 800, fill: t.accent }));
69
+ out.push(halo(`${across(on.x)}, ${fmt(on.value)}`, { ...name, y: y + 30, size: 22, fill: t.muted }));
70
+ }
@@ -1,6 +1,6 @@
1
1
  import { callout } from '../frame.js';
2
2
  import { ceiling, dodge, ticks } from '../geometry.js';
3
- import { text, wrap } from '../svg.js';
3
+ import { clamp, fit, text, wrap } from '../svg.js';
4
4
  function grid({ out, t, fmt }, { py, left, width, max }) {
5
5
  const tk = ticks(max);
6
6
  const td = tk.some((v) => !Number.isInteger(v)) ? 1 : 0;
@@ -9,6 +9,16 @@ function grid({ out, t, fmt }, { py, left, width, max }) {
9
9
  out.push(text(fmt(v, td), { x: left - 14, y: py(v) + 8, size: 22, fill: t.muted, anchor: 'end' }));
10
10
  }
11
11
  }
12
+ function names({ t }, { names, x, step, y }) {
13
+ const every = Math.ceil(64 / step);
14
+ const width = step * every - 8;
15
+ const kept = (i) => (names.length - 1 - i) % every === 0;
16
+ const shown = names.filter((_, i) => kept(i));
17
+ const { size, lines, gap } = fit(shown, { width, height: 72 }, [24, 20, 16]);
18
+ return (i) => kept(i)
19
+ ? clamp(names[i], { width, size, lines }).map((l, j) => text(l, { x: x(i), y: y + j * gap, size, fill: t.muted, anchor: 'middle' }))
20
+ : [];
21
+ }
12
22
  export function line(d) {
13
23
  const { out, spec, t, b } = d;
14
24
  const pts = spec.data;
@@ -18,13 +28,13 @@ export function line(d) {
18
28
  const py = (v) => b.y + b.h - pad.b - (v / max) * (b.h - pad.t - pad.b);
19
29
  const axes = { px, py, left: b.x + pad.l, width: b.w - pad.l - pad.r };
20
30
  grid(d, { ...axes, max });
21
- pts.forEach((p, i) => out.push(text(p.label, {
22
- x: px(i),
23
- y: b.y + b.h - pad.b + 40,
24
- size: 24,
25
- fill: t.muted,
26
- anchor: 'middle'
27
- })));
31
+ const name = names(d, {
32
+ names: pts.map((p) => p.label),
33
+ x: px,
34
+ step: axes.width / Math.max(1, pts.length - 1),
35
+ y: b.y + b.h - pad.b + 40
36
+ });
37
+ pts.forEach((_, i) => out.push(...name(i)));
28
38
  const path = pts.map((p, i) => `${i ? 'L' : 'M'}${px(i)},${py(p.value)}`).join('');
29
39
  out.push(`<defs><linearGradient id="area" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="${t.accent}" stop-opacity="0.45"/><stop offset="1" stop-color="${t.accent}" stop-opacity="0"/></linearGradient></defs>`);
30
40
  out.push(`<path d="${path}L${px(pts.length - 1)},${py(0)}L${px(0)},${py(0)}Z" fill="url(#area)"/>`);
@@ -62,10 +72,17 @@ export function column(d) {
62
72
  const base = b.y + b.h - 60;
63
73
  const slot = b.w / pts.length;
64
74
  const bw = Math.min(140, slot * 0.64);
75
+ const left = (i) => b.x + i * slot + (slot - bw) / 2;
76
+ const name = names(d, {
77
+ names: pts.map((p) => p.label),
78
+ x: (i) => left(i) + bw / 2,
79
+ step: slot,
80
+ y: base + 40
81
+ });
65
82
  pts.forEach((p, i) => {
66
83
  const on = p.label === hl;
67
84
  const h = (Math.max(0, p.value) / max) * (base - top);
68
- const x = b.x + i * slot + (slot - bw) / 2;
85
+ const x = left(i);
69
86
  out.push(`<rect x="${x}" y="${base - h}" width="${bw}" height="${h}" rx="6" fill="${on ? t.accent : t.base}"/>`);
70
87
  out.push(text(fmt(p.value), {
71
88
  x: x + bw / 2,
@@ -75,7 +92,7 @@ export function column(d) {
75
92
  fill: on ? t.accent : t.text,
76
93
  anchor: 'middle'
77
94
  }));
78
- out.push(text(p.label, { x: x + bw / 2, y: base + 40, size: 24, fill: t.muted, anchor: 'middle' }));
95
+ out.push(...name(i));
79
96
  });
80
97
  out.push(`<rect x="${b.x}" y="${base}" width="${b.w}" height="2" fill="${t.faint}"/>`);
81
98
  callout(d, { x: b.x, y: b.y + 100, w: 420 });
@@ -91,7 +108,13 @@ export function multiLine(d) {
91
108
  const color = (g, i) => g === spec.highlight ? t.accent : t.palette[(i + 1) % t.palette.length];
92
109
  const ends = [];
93
110
  grid(d, { px, py, left: b.x + pad.l, width: b.w - pad.l - pad.r, max });
94
- labels.forEach((l, i) => out.push(text(l, { x: px(i), y: b.y + b.h - pad.b + 40, size: 24, fill: t.muted, anchor: 'middle' })));
111
+ const name = names(d, {
112
+ names: labels,
113
+ x: px,
114
+ step: (b.w - pad.l - pad.r) / Math.max(1, labels.length - 1),
115
+ y: b.y + b.h - pad.b + 40
116
+ });
117
+ labels.forEach((_, i) => out.push(...name(i)));
95
118
  groups.forEach((g, gi) => {
96
119
  const pts = labels.flatMap((l, i) => {
97
120
  const p = spec.data.find((q) => (q.group ?? '') === g && q.label === l);
@@ -0,0 +1,11 @@
1
+ import { type Theme } from './themes.ts';
2
+ export declare const MAX_PALETTE = 12;
3
+ export declare const MIN_CONTRAST = 3;
4
+ export interface Overrides {
5
+ accent?: string | undefined;
6
+ palette?: ReadonlyArray<string> | undefined;
7
+ }
8
+ export declare function parseColor(input: unknown): string;
9
+ export declare function contrastRatio(a: string, b: string): number;
10
+ export declare function readable(color: string, bg: string): string;
11
+ export declare function withColors(t: Theme, { accent, palette }: Overrides): Theme;
@@ -0,0 +1,205 @@
1
+ import { mix } from './themes.js';
2
+ const named = {
3
+ aliceblue: '#f0f8ff',
4
+ antiquewhite: '#faebd7',
5
+ aqua: '#00ffff',
6
+ aquamarine: '#7fffd4',
7
+ azure: '#f0ffff',
8
+ beige: '#f5f5dc',
9
+ bisque: '#ffe4c4',
10
+ black: '#000000',
11
+ blanchedalmond: '#ffebcd',
12
+ blue: '#0000ff',
13
+ blueviolet: '#8a2be2',
14
+ brown: '#a52a2a',
15
+ burlywood: '#deb887',
16
+ cadetblue: '#5f9ea0',
17
+ chartreuse: '#7fff00',
18
+ chocolate: '#d2691e',
19
+ coral: '#ff7f50',
20
+ cornflowerblue: '#6495ed',
21
+ cornsilk: '#fff8dc',
22
+ crimson: '#dc143c',
23
+ cyan: '#00ffff',
24
+ darkblue: '#00008b',
25
+ darkcyan: '#008b8b',
26
+ darkgoldenrod: '#b8860b',
27
+ darkgray: '#a9a9a9',
28
+ darkgreen: '#006400',
29
+ darkgrey: '#a9a9a9',
30
+ darkkhaki: '#bdb76b',
31
+ darkmagenta: '#8b008b',
32
+ darkolivegreen: '#556b2f',
33
+ darkorange: '#ff8c00',
34
+ darkorchid: '#9932cc',
35
+ darkred: '#8b0000',
36
+ darksalmon: '#e9967a',
37
+ darkseagreen: '#8fbc8f',
38
+ darkslateblue: '#483d8b',
39
+ darkslategray: '#2f4f4f',
40
+ darkslategrey: '#2f4f4f',
41
+ darkturquoise: '#00ced1',
42
+ darkviolet: '#9400d3',
43
+ deeppink: '#ff1493',
44
+ deepskyblue: '#00bfff',
45
+ dimgray: '#696969',
46
+ dimgrey: '#696969',
47
+ dodgerblue: '#1e90ff',
48
+ firebrick: '#b22222',
49
+ floralwhite: '#fffaf0',
50
+ forestgreen: '#228b22',
51
+ fuchsia: '#ff00ff',
52
+ gainsboro: '#dcdcdc',
53
+ ghostwhite: '#f8f8ff',
54
+ gold: '#ffd700',
55
+ goldenrod: '#daa520',
56
+ gray: '#808080',
57
+ green: '#008000',
58
+ greenyellow: '#adff2f',
59
+ grey: '#808080',
60
+ honeydew: '#f0fff0',
61
+ hotpink: '#ff69b4',
62
+ indianred: '#cd5c5c',
63
+ indigo: '#4b0082',
64
+ ivory: '#fffff0',
65
+ khaki: '#f0e68c',
66
+ lavender: '#e6e6fa',
67
+ lavenderblush: '#fff0f5',
68
+ lawngreen: '#7cfc00',
69
+ lemonchiffon: '#fffacd',
70
+ lightblue: '#add8e6',
71
+ lightcoral: '#f08080',
72
+ lightcyan: '#e0ffff',
73
+ lightgoldenrodyellow: '#fafad2',
74
+ lightgray: '#d3d3d3',
75
+ lightgreen: '#90ee90',
76
+ lightgrey: '#d3d3d3',
77
+ lightpink: '#ffb6c1',
78
+ lightsalmon: '#ffa07a',
79
+ lightseagreen: '#20b2aa',
80
+ lightskyblue: '#87cefa',
81
+ lightslategray: '#778899',
82
+ lightslategrey: '#778899',
83
+ lightsteelblue: '#b0c4de',
84
+ lightyellow: '#ffffe0',
85
+ lime: '#00ff00',
86
+ limegreen: '#32cd32',
87
+ linen: '#faf0e6',
88
+ magenta: '#ff00ff',
89
+ maroon: '#800000',
90
+ mediumaquamarine: '#66cdaa',
91
+ mediumblue: '#0000cd',
92
+ mediumorchid: '#ba55d3',
93
+ mediumpurple: '#9370db',
94
+ mediumseagreen: '#3cb371',
95
+ mediumslateblue: '#7b68ee',
96
+ mediumspringgreen: '#00fa9a',
97
+ mediumturquoise: '#48d1cc',
98
+ mediumvioletred: '#c71585',
99
+ midnightblue: '#191970',
100
+ mintcream: '#f5fffa',
101
+ mistyrose: '#ffe4e1',
102
+ moccasin: '#ffe4b5',
103
+ navajowhite: '#ffdead',
104
+ navy: '#000080',
105
+ oldlace: '#fdf5e6',
106
+ olive: '#808000',
107
+ olivedrab: '#6b8e23',
108
+ orange: '#ffa500',
109
+ orangered: '#ff4500',
110
+ orchid: '#da70d6',
111
+ palegoldenrod: '#eee8aa',
112
+ palegreen: '#98fb98',
113
+ paleturquoise: '#afeeee',
114
+ palevioletred: '#db7093',
115
+ papayawhip: '#ffefd5',
116
+ peachpuff: '#ffdab9',
117
+ peru: '#cd853f',
118
+ pink: '#ffc0cb',
119
+ plum: '#dda0dd',
120
+ powderblue: '#b0e0e6',
121
+ purple: '#800080',
122
+ rebeccapurple: '#663399',
123
+ red: '#ff0000',
124
+ rosybrown: '#bc8f8f',
125
+ royalblue: '#4169e1',
126
+ saddlebrown: '#8b4513',
127
+ salmon: '#fa8072',
128
+ sandybrown: '#f4a460',
129
+ seagreen: '#2e8b57',
130
+ seashell: '#fff5ee',
131
+ sienna: '#a0522d',
132
+ silver: '#c0c0c0',
133
+ skyblue: '#87ceeb',
134
+ slateblue: '#6a5acd',
135
+ slategray: '#708090',
136
+ slategrey: '#708090',
137
+ snow: '#fffafa',
138
+ springgreen: '#00ff7f',
139
+ steelblue: '#4682b4',
140
+ tan: '#d2b48c',
141
+ teal: '#008080',
142
+ thistle: '#d8bfd8',
143
+ tomato: '#ff6347',
144
+ turquoise: '#40e0d0',
145
+ violet: '#ee82ee',
146
+ wheat: '#f5deb3',
147
+ white: '#ffffff',
148
+ whitesmoke: '#f5f5f5',
149
+ yellow: '#ffff00',
150
+ yellowgreen: '#9acd32'
151
+ };
152
+ export const MAX_PALETTE = 12;
153
+ export const MIN_CONTRAST = 3;
154
+ export function parseColor(input) {
155
+ if (typeof input !== 'string') {
156
+ throw new RangeError(`A color is a name such as "blue" or a #hex such as "#1d4ed8", not ${typeof input}`);
157
+ }
158
+ const key = input
159
+ .trim()
160
+ .toLowerCase()
161
+ .replace(/[\s_-]+/g, '');
162
+ const digits = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/.exec(key)?.[1];
163
+ if (digits) {
164
+ return '#' + (digits.length === 3 ? digits.replace(/./g, (c) => c + c) : digits);
165
+ }
166
+ if (key in named) {
167
+ return named[key];
168
+ }
169
+ throw new RangeError(`Unknown color "${input}": use a name such as "blue" or a #hex such as "#1d4ed8"`);
170
+ }
171
+ const channel = (v) => {
172
+ const s = v / 255;
173
+ return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
174
+ };
175
+ const luminance = (hex) => [1, 3, 5].reduce((sum, i, k) => sum + channel(parseInt(hex.slice(i, i + 2), 16)) * [0.2126, 0.7152, 0.0722][k], 0);
176
+ export function contrastRatio(a, b) {
177
+ const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
178
+ return (hi + 0.05) / (lo + 0.05);
179
+ }
180
+ export function readable(color, bg) {
181
+ const toward = luminance(bg) > 0.5 ? '#000000' : '#ffffff';
182
+ let out = color;
183
+ for (let f = 0.05; contrastRatio(out, bg) < MIN_CONTRAST && f <= 1; f += 0.05) {
184
+ out = mix(color, { to: toward, f });
185
+ }
186
+ return out;
187
+ }
188
+ export function withColors(t, { accent, palette }) {
189
+ if (accent === undefined && palette === undefined)
190
+ return t;
191
+ const fit = (c) => readable(parseColor(c), t.bg);
192
+ const lead = accent === undefined ? t.accent : fit(accent);
193
+ const rest = palette === undefined ? t.palette.slice(1) : listed(palette).map(fit);
194
+ const colors = [lead, ...cycled(rest, t.palette.length - 1)];
195
+ return { ...t, accent: lead, palette: colors };
196
+ }
197
+ function listed(palette) {
198
+ if (!Array.isArray(palette) || palette.length === 0 || palette.length > MAX_PALETTE) {
199
+ throw new RangeError(`A palette is a list of 1 to ${MAX_PALETTE} colors`);
200
+ }
201
+ return palette;
202
+ }
203
+ function cycled(list, min) {
204
+ return Array.from({ length: Math.max(min, list.length) }, (_, i) => list[i % list.length]);
205
+ }
@@ -48,3 +48,4 @@ export declare function bounds(cs: ReadonlyArray<Circle>): Bounds;
48
48
  export declare function squarify(values: ReadonlyArray<number>, rect: Rect): Rect[];
49
49
  export declare function ceiling(values: ReadonlyArray<number>): number;
50
50
  export declare function ticks(max: number): number[];
51
+ export declare function spread(values: ReadonlyArray<number>): number[];
@@ -164,3 +164,13 @@ export function ticks(max) {
164
164
  }
165
165
  return out;
166
166
  }
167
+ export function spread(values) {
168
+ const lo = Math.min(...values);
169
+ const hi = Math.max(...values);
170
+ const range = hi - lo || Math.abs(hi) || 1;
171
+ const step = Math.pow(10, Math.floor(Math.log10(range / 4)));
172
+ const unit = [1, 2, 2.5, 5].map((m) => m * step).find((s) => range / s <= 5) ?? 10 * step;
173
+ const first = Math.floor(lo / unit);
174
+ const count = Math.max(1, Math.ceil(hi / unit - 1e-9) - first);
175
+ return Array.from({ length: count + 1 }, (_, i) => (first + i) * unit);
176
+ }
@@ -1,6 +1,7 @@
1
1
  import { lookup, mapFor, WORLD } from './places.js';
2
2
  import { pick } from './pick.js';
3
3
  import { MAX_ITEMS } from './schema.js';
4
+ import { paired, trend } from './trend.js';
4
5
  const prefixes = {
5
6
  dollars: '$',
6
7
  euros: '€',
@@ -80,7 +81,10 @@ export function normalize(input, maps) {
80
81
  maps,
81
82
  from: spec.from,
82
83
  to: spec.to,
83
- annotations: spec.annotations ?? []
84
+ annotations: spec.annotations ?? [],
85
+ horizontal: spec.horizontal,
86
+ vertical: spec.vertical,
87
+ trend: type === 'scatter' && spec.callout === 'trend' ? trend(data.filter(paired)) : undefined
84
88
  };
85
89
  }
86
90
  function largest(max) {
@@ -93,7 +97,11 @@ function largest(max) {
93
97
  function finite(spec) {
94
98
  const data = spec.data
95
99
  .filter((d) => Number.isFinite(d.value))
96
- .map((d) => ({ ...d, previous: Number.isFinite(d.previous) ? d.previous : undefined }));
100
+ .map((d) => ({
101
+ ...d,
102
+ previous: Number.isFinite(d.previous) ? d.previous : undefined,
103
+ x: Number.isFinite(d.x) ? d.x : undefined
104
+ }));
97
105
  if (data.length === 0) {
98
106
  throw new RangeError('A chart needs at least one finite value');
99
107
  }
@@ -115,7 +123,14 @@ function arranged(input, maps) {
115
123
  if (spec.shape === 'change' && !spec.data.some((d) => d.previous !== undefined)) {
116
124
  spec = pairs(spec);
117
125
  }
118
- return spec;
126
+ return spec.shape === 'pairs' || spec.type === 'scatter' ? scattered(spec) : spec;
127
+ }
128
+ function scattered(spec) {
129
+ const data = spec.data.filter(paired);
130
+ if (data.length < 2) {
131
+ throw new RangeError('Pairs need two numbers per item: x across and value up');
132
+ }
133
+ return { ...spec, shape: 'pairs', type: undefined, data };
119
134
  }
120
135
  function unitSuffix(unit, scale) {
121
136
  return unit === 'percent' ? '%' : (scale ?? '');
@@ -9,6 +9,9 @@ export function pick(spec, data) {
9
9
  if (spec.shape === 'ranking') {
10
10
  return v === 'radial' && n <= 10 ? 'radial' : 'ranked-bar';
11
11
  }
12
+ if (spec.shape === 'pairs') {
13
+ return 'scatter';
14
+ }
12
15
  if (spec.shape === 'sizes') {
13
16
  return 'bubbles';
14
17
  }
@@ -1,8 +1,9 @@
1
+ import { type Overrides } from './colors.ts';
1
2
  import { type Mark } from './frame.ts';
2
3
  import type { Chart } from './spec.ts';
3
4
  import { type ThemeName } from './themes.ts';
4
- export interface RenderOptions {
5
+ export interface RenderOptions extends Overrides {
5
6
  theme: ThemeName;
6
7
  mark?: Mark | undefined;
7
8
  }
8
- export declare function render(chart: Chart, { theme, mark }: RenderOptions): string;
9
+ export declare function render(chart: Chart, { theme, mark, accent, palette }: RenderOptions): string;
@@ -1,10 +1,11 @@
1
1
  import { charts } from './charts/index.js';
2
+ import { withColors } from './colors.js';
2
3
  import { formatter } from './format.js';
3
4
  import { frame, svg } from './frame.js';
4
5
  import { fixed } from './svg.js';
5
6
  import { themes } from './themes.js';
6
- export function render(chart, { theme, mark }) {
7
- const t = themes[theme];
7
+ export function render(chart, { theme, mark, accent, palette }) {
8
+ const t = withColors(themes[theme], { accent, palette });
8
9
  const { out: head, box } = frame(chart, { t, mark });
9
10
  const out = [];
10
11
  charts[chart.type]({ out, spec: chart, t, b: box, fmt: formatter(chart) });
@@ -32,6 +32,9 @@ export declare const chartSchema: {
32
32
  value: {
33
33
  type: string;
34
34
  };
35
+ x: {
36
+ type: string;
37
+ };
35
38
  group: {
36
39
  type: string;
37
40
  maxLength: number;
@@ -75,6 +78,14 @@ export declare const chartSchema: {
75
78
  callout: {
76
79
  enum: string[];
77
80
  };
81
+ horizontal: {
82
+ type: string;
83
+ maxLength: number;
84
+ };
85
+ vertical: {
86
+ type: string;
87
+ maxLength: number;
88
+ };
78
89
  source: {
79
90
  type: string;
80
91
  maxLength: number;
@@ -4,12 +4,13 @@ const item = {
4
4
  properties: {
5
5
  label: { type: 'string', maxLength: 32 },
6
6
  value: { type: 'number' },
7
+ x: { type: 'number' },
7
8
  group: { type: 'string', maxLength: 24 }
8
9
  },
9
10
  required: ['label', 'value'],
10
11
  additionalProperties: false
11
12
  };
12
- export const SHAPES = ['ranking', 'parts', 'over-time', 'change', 'sizes', 'places'];
13
+ export const SHAPES = ['ranking', 'parts', 'over-time', 'change', 'sizes', 'places', 'pairs'];
13
14
  export const VARIANTS = [
14
15
  'bar',
15
16
  'radial',
@@ -47,7 +48,9 @@ export const chartSchema = {
47
48
  additionalProperties: false
48
49
  }
49
50
  },
50
- callout: { enum: ['none', 'share', 'growth', 'ratio'] },
51
+ callout: { enum: ['none', 'share', 'growth', 'ratio', 'trend'] },
52
+ horizontal: { type: 'string', maxLength: 32 },
53
+ vertical: { type: 'string', maxLength: 32 },
51
54
  source: { type: 'string', maxLength: 120 }
52
55
  },
53
56
  required: [
@@ -1,8 +1,10 @@
1
1
  import type { Maps } from './places.ts';
2
- export type ChartType = 'ranked-bar' | 'bubbles' | 'treemap' | 'line' | 'column' | 'multi-line' | 'donut' | 'waffle' | 'stacked' | 'slope' | 'radial' | 'choropleth' | 'bubble-map';
2
+ import type { Trend } from './trend.ts';
3
+ export type ChartType = 'ranked-bar' | 'bubbles' | 'treemap' | 'line' | 'column' | 'multi-line' | 'donut' | 'waffle' | 'stacked' | 'slope' | 'radial' | 'choropleth' | 'bubble-map' | 'scatter';
3
4
  export interface Item {
4
5
  label: string;
5
6
  value: number;
7
+ x?: number | undefined;
6
8
  group?: string | undefined;
7
9
  previous?: number | undefined;
8
10
  note?: string | undefined;
@@ -31,6 +33,8 @@ export interface Spec {
31
33
  annotations?: ReadonlyArray<Annotation>;
32
34
  callout?: string | Callout;
33
35
  source: string;
36
+ horizontal?: string;
37
+ vertical?: string;
34
38
  map?: string;
35
39
  from?: string | undefined;
36
40
  to?: string | undefined;
@@ -55,4 +59,7 @@ export interface Chart {
55
59
  from: string | undefined;
56
60
  to: string | undefined;
57
61
  annotations: ReadonlyArray<Annotation>;
62
+ horizontal: string | undefined;
63
+ vertical: string | undefined;
64
+ trend: Trend | undefined;
58
65
  }
@@ -17,5 +17,23 @@ export interface Measure {
17
17
  width: number;
18
18
  size: number;
19
19
  }
20
- export declare function wrap(str: string, { width, size }: Measure): string[];
20
+ export declare function wrap(str: string, m: Measure): string[];
21
+ export interface Clamp extends Measure {
22
+ lines: number;
23
+ }
24
+ export declare function clamp(str: string, { lines, ...m }: Clamp): string[];
25
+ export interface Room {
26
+ width: number;
27
+ height: number;
28
+ }
29
+ export interface Fit {
30
+ size: number;
31
+ lines: number;
32
+ gap: number;
33
+ }
34
+ export declare function fit(strs: ReadonlyArray<string>, room: Room, sizes: ReadonlyArray<number>): Fit;
35
+ export interface Stack extends TextStyle {
36
+ gap: number;
37
+ }
38
+ export declare function stack(lines: ReadonlyArray<string>, { gap, ...style }: Stack): string[];
21
39
  export declare function fixed(svg: string): string;
@@ -13,8 +13,8 @@ export function text(str, style) {
13
13
  export function halo(str, { stroke, ...style }) {
14
14
  return text(str, style).replace('<text ', `<text stroke="${stroke}" stroke-width="6" stroke-linejoin="round" paint-order="stroke" `);
15
15
  }
16
- export function wrap(str, { width, size }) {
17
- const per = Math.floor(width / (size * 0.54));
16
+ export function wrap(str, m) {
17
+ const per = chars(m);
18
18
  const lines = [];
19
19
  let line = '';
20
20
  for (const word of str.split(/\s+/)) {
@@ -31,6 +31,38 @@ export function wrap(str, { width, size }) {
31
31
  }
32
32
  return lines;
33
33
  }
34
+ export function clamp(str, { lines, ...m }) {
35
+ const per = chars(m);
36
+ const all = wrap(str, m);
37
+ const kept = all.slice(0, lines);
38
+ if (all.length > lines) {
39
+ kept[lines - 1] += '…';
40
+ }
41
+ return kept.map((l) => (l.length > per ? l.slice(0, Math.max(0, per - 1)).trimEnd() + '…' : l));
42
+ }
43
+ export function fit(strs, room, sizes) {
44
+ for (const size of sizes) {
45
+ const f = leading(size, room);
46
+ if (strs.every((s) => whole(s, { ...f, width: room.width }))) {
47
+ return f;
48
+ }
49
+ }
50
+ return leading(Math.min(...sizes), room);
51
+ }
52
+ function leading(size, { height }) {
53
+ const gap = size * 1.15;
54
+ return { size, gap, lines: Math.max(1, Math.floor(height / gap)) };
55
+ }
56
+ function whole(str, { lines, ...m }) {
57
+ const all = wrap(str, m);
58
+ return all.length <= lines && all.every((l) => l.length <= chars(m));
59
+ }
60
+ export function stack(lines, { gap, ...style }) {
61
+ return lines.map((l, j) => text(l, { ...style, y: style.y + (j - (lines.length - 1) / 2) * gap }));
62
+ }
63
+ function chars({ width, size }) {
64
+ return Math.floor(width / (size * 0.54));
65
+ }
34
66
  export function fixed(svg) {
35
67
  return svg.replace(/<[^<>]+>/g, (tag) => tag.replace(/(?<![\w-])([\w-]+)="([^"]*)"/g, rounded));
36
68
  }
@@ -25,4 +25,9 @@ export interface Ramp {
25
25
  hi: number;
26
26
  }
27
27
  export declare function ramp(data: ReadonlyArray<Row>, t: Theme): Ramp;
28
+ export interface Blend {
29
+ to: string;
30
+ f: number;
31
+ }
32
+ export declare function mix(from: string, { to, f }: Blend): string;
28
33
  export declare function contrast(fill: string, t: Theme): string;
@@ -54,7 +54,7 @@ export function ramp(data, t) {
54
54
  const shade = (v) => mix(t.bg, { to: t.accent, f: 0.28 + 0.72 * (hi === lo ? 1 : (v - lo) / (hi - lo)) });
55
55
  return { shade, lo, hi };
56
56
  }
57
- function mix(from, { to, f }) {
57
+ export function mix(from, { to, f }) {
58
58
  const [x, y] = [from, to].map((h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16)));
59
59
  return ('#' +
60
60
  x
@@ -0,0 +1,14 @@
1
+ export interface Trend {
2
+ slope: number;
3
+ intercept: number;
4
+ r2: number;
5
+ }
6
+ export interface Pair {
7
+ x: number;
8
+ value: number;
9
+ }
10
+ export declare function trend(pairs: ReadonlyArray<Pair>): Trend | undefined;
11
+ export interface Across {
12
+ x?: number | undefined;
13
+ }
14
+ export declare function paired<T extends Across>(d: T): d is T & Pair;
@@ -0,0 +1,16 @@
1
+ export function trend(pairs) {
2
+ const n = pairs.length;
3
+ const mx = pairs.reduce((s, p) => s + p.x, 0) / n;
4
+ const my = pairs.reduce((s, p) => s + p.value, 0) / n;
5
+ const sxx = pairs.reduce((s, p) => s + (p.x - mx) ** 2, 0);
6
+ const syy = pairs.reduce((s, p) => s + (p.value - my) ** 2, 0);
7
+ const sxy = pairs.reduce((s, p) => s + (p.x - mx) * (p.value - my), 0);
8
+ if (n < 3 || sxx === 0 || syy === 0) {
9
+ return undefined;
10
+ }
11
+ const slope = sxy / sxx;
12
+ return { slope, intercept: my - slope * mx, r2: (sxy * sxy) / (sxx * syy) };
13
+ }
14
+ export function paired(d) {
15
+ return d.x !== undefined;
16
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "qvac-charts",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Renders a small JSON chart spec into an SVG, on Bare and Node",
5
5
  "type": "module",
6
6
  "exports": {