swiftplot 0.1.1 → 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.
Files changed (96) hide show
  1. package/README.md +86 -61
  2. package/dist/chart.d.ts +4 -0
  3. package/dist/chart.js +172 -89
  4. package/dist/charts/build.d.ts +53 -0
  5. package/dist/charts/build.js +69 -0
  6. package/dist/charts/candlestick.d.ts +8 -0
  7. package/dist/charts/candlestick.js +105 -0
  8. package/dist/charts/combo.d.ts +8 -0
  9. package/dist/charts/combo.js +50 -0
  10. package/dist/charts/controller.d.ts +2 -2
  11. package/dist/charts/controller.js +2 -2
  12. package/dist/charts/defaults.d.ts +10 -2
  13. package/dist/charts/defaults.js +67 -6
  14. package/dist/charts/distribution.d.ts +15 -0
  15. package/dist/charts/distribution.js +178 -0
  16. package/dist/charts/fields.d.ts +33 -3
  17. package/dist/charts/fields.js +150 -66
  18. package/dist/charts/flow.d.ts +15 -0
  19. package/dist/charts/flow.js +189 -0
  20. package/dist/charts/heatmap.d.ts +9 -0
  21. package/dist/charts/heatmap.js +104 -0
  22. package/dist/charts/index.d.ts +8 -1
  23. package/dist/charts/index.js +7 -0
  24. package/dist/charts/parts.d.ts +23 -0
  25. package/dist/charts/parts.js +66 -0
  26. package/dist/charts/radar.d.ts +7 -0
  27. package/dist/charts/radar.js +77 -0
  28. package/dist/charts/types.d.ts +564 -23
  29. package/dist/charts/xy.d.ts +35 -25
  30. package/dist/charts/xy.js +327 -126
  31. package/dist/features/animate.d.ts +10 -1
  32. package/dist/features/animate.js +3 -3
  33. package/dist/features/brush.d.ts +3 -1
  34. package/dist/features/brush.js +2 -1
  35. package/dist/features/legend.d.ts +1 -3
  36. package/dist/features/legend.js +4 -5
  37. package/dist/features/tooltip.d.ts +10 -2
  38. package/dist/features/tooltip.js +20 -15
  39. package/dist/features/zoom.d.ts +1 -0
  40. package/dist/features/zoom.js +22 -4
  41. package/dist/index.d.ts +2 -0
  42. package/dist/index.js +1 -0
  43. package/dist/marks/arcs.d.ts +10 -4
  44. package/dist/marks/arcs.js +2 -1
  45. package/dist/marks/area.d.ts +9 -8
  46. package/dist/marks/area.js +2 -2
  47. package/dist/marks/bar.d.ts +18 -10
  48. package/dist/marks/bar.js +5 -5
  49. package/dist/marks/box.d.ts +7 -1
  50. package/dist/marks/box.js +2 -8
  51. package/dist/marks/candlestick.d.ts +22 -0
  52. package/dist/marks/candlestick.js +133 -0
  53. package/dist/marks/common.d.ts +18 -0
  54. package/dist/marks/common.js +14 -0
  55. package/dist/marks/dots.d.ts +6 -5
  56. package/dist/marks/dots.js +20 -5
  57. package/dist/marks/errorBars.d.ts +9 -4
  58. package/dist/marks/errorBars.js +21 -1
  59. package/dist/marks/funnel.d.ts +8 -3
  60. package/dist/marks/funnel.js +2 -1
  61. package/dist/marks/heatmap.d.ts +8 -7
  62. package/dist/marks/line.d.ts +8 -6
  63. package/dist/marks/radar.d.ts +9 -2
  64. package/dist/marks/radar.js +9 -2
  65. package/dist/marks/radialBars.d.ts +12 -5
  66. package/dist/marks/rects.js +15 -5
  67. package/dist/marks/rule.d.ts +19 -0
  68. package/dist/marks/rule.js +4 -1
  69. package/dist/marks/sankey.d.ts +14 -2
  70. package/dist/marks/sankey.js +4 -1
  71. package/dist/marks/sunburst.d.ts +5 -0
  72. package/dist/marks/sunburst.js +2 -1
  73. package/dist/marks/ticks.d.ts +4 -1
  74. package/dist/marks/tree.d.ts +14 -6
  75. package/dist/marks/tree.js +6 -3
  76. package/dist/marks/treemap.d.ts +5 -0
  77. package/dist/marks/treemap.js +7 -2
  78. package/dist/paint.d.ts +6 -1
  79. package/dist/paint.js +6 -1
  80. package/dist/scale.d.ts +1 -1
  81. package/dist/scale.js +4 -3
  82. package/dist/scales/band.d.ts +3 -0
  83. package/dist/scales/band.js +5 -1
  84. package/dist/scales/bare.d.ts +4 -1
  85. package/dist/scales/bare.js +4 -1
  86. package/dist/scales/color.d.ts +2 -0
  87. package/dist/scales/log.d.ts +8 -1
  88. package/dist/scales/log.js +3 -2
  89. package/dist/scales/time.d.ts +7 -0
  90. package/dist/scales/time.js +3 -1
  91. package/dist/text.d.ts +8 -0
  92. package/dist/text.js +33 -0
  93. package/dist/transforms.d.ts +11 -7
  94. package/dist/transforms.js +8 -7
  95. package/dist/types.d.ts +44 -15
  96. package/package.json +2 -2
@@ -1,10 +1,6 @@
1
+ export const list = (f) => f === undefined ? [] : Array.isArray(f) ? f : [f];
1
2
  const quote = (f) => `"${f}"`;
2
- export function assign(s, props, family, name, firstSeen = false) {
3
- const p = s.shape === 'numbers'
4
- ? { xAxis: props.xAxis, y: 'value' }
5
- : s.shape === 'pairs'
6
- ? { xAxis: props.xAxis, x: 'x', y: 'y' }
7
- : props;
3
+ export function reader(s, name) {
8
4
  const own = (read) => {
9
5
  try {
10
6
  return read();
@@ -15,8 +11,6 @@ export function assign(s, props, family, name, firstSeen = false) {
15
11
  };
16
12
  const fields = own(() => s.fields());
17
13
  const kinds = new Map(fields.map(f => [f, own(() => s.kind(f))]));
18
- if (!s.length)
19
- return { x: { label: '', kind: 'index' }, y: { label: '' }, ys: [] };
20
14
  const unplottable = (f) => {
21
15
  if (kinds.get(f))
22
16
  return false;
@@ -35,39 +29,104 @@ export function assign(s, props, family, name, firstSeen = false) {
35
29
  : 'There are no fields';
36
30
  throw new Error(`${name}: ${why}. ${list}. Pass ${pass}.`, { cause });
37
31
  };
38
- const named = p.y === undefined ? [] : (Array.isArray(p.y) ? p.y : [p.y]);
32
+ const check = (roles, numberRoles) => {
33
+ for (const [role, f] of roles) {
34
+ if (typeof f !== 'string')
35
+ continue;
36
+ if (!kinds.has(f)) {
37
+ // fields() lists only the keys of the first rows, so a named field is looked up in every row
38
+ const kind = (() => {
39
+ try {
40
+ return s.kind(f);
41
+ }
42
+ catch {
43
+ return null;
44
+ }
45
+ })();
46
+ if (kind === null || (!kind && !unplottable(f)))
47
+ fail(`there is no field ${quote(f)}`, `${role} as one of these fields`);
48
+ kinds.set(f, kind ?? undefined);
49
+ }
50
+ if (unplottable(f))
51
+ fail(`${quote(f)} holds values that are not numbers, dates or text`, `${role} as another field`);
52
+ const kind = kinds.get(f);
53
+ if (numberRoles.includes(role) && kind && kind !== 'number')
54
+ fail(`${role} ${quote(f)} is ${kind}, not numbers`, `${role} as a field of numbers`);
55
+ }
56
+ const names = roles.map(([, f]) => f);
57
+ return fields.filter(f => kinds.get(f) && !names.includes(f));
58
+ };
59
+ const noNumbers = (role) => {
60
+ const asText = fields.filter(f => kinds.get(f) === 'text' &&
61
+ own(() => s.column(f)).categories.every(c => c.trim() !== '' && Number.isFinite(Number(c))));
62
+ const hint = asText.length
63
+ ? `; ${asText.map(quote).join(', ')} ${asText.length > 1 ? 'hold' : 'holds'} numbers as text: convert them with Number()`
64
+ : '';
65
+ return fail(`there is no field of numbers for ${role}${hint}`, `${role} as a field of numbers`);
66
+ };
67
+ const sole = (role, named, pool) => {
68
+ if (named !== undefined)
69
+ return named;
70
+ const numbers = pool.filter(f => kinds.get(f) === 'number');
71
+ if (numbers.length > 1)
72
+ fail(`${numbers.map(quote).join(', ')} are all fields of numbers, so ${role} cannot be guessed`, `${role} as one of them`);
73
+ return numbers[0] ?? noNumbers(role);
74
+ };
75
+ const read = (f, what, role, zone) => {
76
+ if (typeof f === 'string')
77
+ return own(() => s.column(f, zone));
78
+ try {
79
+ return s.column(f, zone);
80
+ }
81
+ catch (e) {
82
+ return fail(`${what} cannot be read: ${e.message}`, `${role} as another field`, e);
83
+ }
84
+ };
85
+ const numeric = (f, role, nth = '', orText = false) => {
86
+ const what = typeof f === 'string' ? `${role} ${quote(f)}` : `the accessor ${role}${nth}`;
87
+ const c = read(f, what, role);
88
+ if (c.kind !== 'number' && !(orText && c.kind === 'text')) {
89
+ const wanted = orText ? 'numbers or text' : 'numbers';
90
+ fail(`${what} is ${c.kind}, not ${wanted}`, `${role} as a field of ${wanted}`);
91
+ }
92
+ return c;
93
+ };
94
+ return { kinds, fail, check, noNumbers, sole, read, numeric };
95
+ }
96
+ export function assign(s, props, family, name, firstSeen = false) {
97
+ const p = s.shape === 'numbers'
98
+ ? { xAxis: props.xAxis, y: 'value' }
99
+ : s.shape === 'pairs'
100
+ ? { xAxis: props.xAxis, x: 'x', y: 'y' }
101
+ : props;
102
+ const { kinds, fail, check, noNumbers, read, numeric } = reader(s, name);
103
+ const named = list(p.y);
104
+ const named2 = list(p.y2);
105
+ const role = (i, otherwise) => p.roles?.[i] ?? otherwise;
106
+ const labelled = (fs) => ({
107
+ label: fs.length === 1 && typeof fs[0] === 'string' ? fs[0] : '',
108
+ });
109
+ const second = named2.length ? { y2: labelled(named2) } : {};
110
+ if (!s.length)
111
+ return { x: { label: '', kind: 'index' }, y: { label: '' }, ...second, ys: [] };
39
112
  const r = family === 'scatter' && typeof p.r !== 'number' ? p.r : undefined;
40
113
  const roles = [
41
114
  ['x', p.x],
42
- ...named.map(f => ['y', f]),
115
+ ...named.map((f, i) => [role(i, 'y'), f]),
116
+ ...named2.map((f, i) => [role(named.length + i, 'y2'), f]),
43
117
  ['series', p.series],
44
118
  ['r', r],
119
+ ['errorBars.low', p.errorBars?.low],
120
+ ['errorBars.high', p.errorBars?.high],
45
121
  ];
46
- const names = roles.map(([, f]) => f).filter((f) => typeof f === 'string');
47
- for (const [role, f] of roles) {
48
- if (typeof f !== 'string')
49
- continue;
50
- if (!kinds.has(f)) {
51
- // fields() lists only the keys of the first rows, so a named field is looked up in every row
52
- const kind = (() => {
53
- try {
54
- return s.kind(f);
55
- }
56
- catch {
57
- return null;
58
- }
59
- })();
60
- if (kind === null || (!kind && !unplottable(f)))
61
- fail(`there is no field ${quote(f)}`, `${role} as one of these fields`);
62
- kinds.set(f, kind ?? undefined);
63
- }
64
- if (unplottable(f))
65
- fail(`${quote(f)} holds values that are not numbers, dates or text`, `${role} as another field`);
66
- const kind = kinds.get(f);
67
- if ((role === 'y' || role === 'r') && kind && kind !== 'number')
68
- fail(`${role} ${quote(f)} is ${kind}, not numbers`, `${role} as a field of numbers`);
69
- }
70
- const pool = fields.filter(f => kinds.get(f) && !names.includes(f));
122
+ const pool = check(roles, [
123
+ ...(family === 'scatter' ? [] : ['y']),
124
+ 'y2',
125
+ 'r',
126
+ 'errorBars.low',
127
+ 'errorBars.high',
128
+ ...(p.roles ?? []),
129
+ ]);
71
130
  const first = (k, not) => pool.find(f => kinds.get(f) === k && f !== not);
72
131
  let x = p.x;
73
132
  if (x === undefined && family === 'scatter')
@@ -75,51 +134,69 @@ export function assign(s, props, family, name, firstSeen = false) {
75
134
  else if (x === undefined) {
76
135
  x = first('time') ?? first('text');
77
136
  const numbers = pool.filter(f => kinds.get(f) === 'number');
78
- if (x === undefined && numbers.length > (named.length ? 0 : 1))
137
+ if (x === undefined && numbers.length > (named.length || p.roles ? 0 : 1))
79
138
  x = numbers[0];
80
139
  }
81
140
  const xField = x;
82
141
  const left = pool.filter(f => f !== xField && kinds.get(f) === 'number');
83
- const ys = named.length ? named : family === 'scatter' ? left.slice(0, 1) : left;
142
+ const ys = named.length || p.roles ? named : family === 'scatter' ? left.slice(0, 1) : left;
84
143
  if (family === 'scatter') {
85
144
  if (named.length > 1)
86
145
  fail('a scatter chart has one y', 'y as one field');
87
146
  if (!ys.length || (x === undefined && !s.shape))
88
147
  fail('a scatter chart needs two fields of numbers or dates', 'x and y as fields of numbers or dates');
89
148
  }
90
- else if (!ys.length) {
91
- const asText = fields.filter(f => kinds.get(f) === 'text' &&
92
- own(() => s.column(f)).categories.every(c => c.trim() !== '' && Number.isFinite(Number(c))));
93
- const hint = asText.length
94
- ? `; ${asText.map(quote).join(', ')} ${asText.length > 1 ? 'hold' : 'holds'} numbers as text: convert them with Number()`
95
- : '';
96
- fail(`there is no field of numbers for y${hint}`, 'y as a field of numbers');
97
- }
149
+ else if (!ys.length && !p.roles)
150
+ noNumbers('y');
98
151
  const leftText = pool.find(f => f !== x && kinds.get(f) === 'text');
99
- if (family === 'xy' && p.series === undefined && leftText !== undefined)
152
+ if (family === 'xy' && p.series === undefined && !named2.length && !p.roles && leftText !== undefined)
100
153
  fail(`${quote(leftText)} is text, so the rows look like long data with one row per series and x`, `series: '${leftText}'`);
154
+ if (named2.length) {
155
+ if (p.series !== undefined)
156
+ fail('series and y2 do not go together', 'series or y2, not both');
157
+ if (p.errorBars)
158
+ fail('errorBars and y2 do not go together', 'errorBars or y2, not both');
159
+ }
160
+ if (p.errorBars?.axis !== undefined && family !== 'scatter')
161
+ fail('errorBars.axis applies to scatterChart only', 'errorBars without axis');
101
162
  if (p.series !== undefined && ys.length > 1)
102
163
  fail('with series there is one y', 'y as one field');
103
- const read = (f, what, role, zone) => {
164
+ if (p.errorBars && ys.length > 1)
165
+ fail('with errorBars there is one y', 'y as one field');
166
+ const drawn = [...ys, ...named2];
167
+ const twice = named2.find((f) => typeof f === 'string' && ys.includes(f));
168
+ if (twice !== undefined)
169
+ fail(`${quote(twice)} is named in both y and y2`, 'it in one of them');
170
+ const again = named2.find((f, i) => typeof f === 'string' && named2.indexOf(f) !== i);
171
+ if (again !== undefined)
172
+ fail(`${quote(again)} is named twice in y2`, 'it once');
173
+ const taken = new Set(drawn.filter(f => typeof f === 'string'));
174
+ const names = drawn.map((f, i) => {
104
175
  if (typeof f === 'string')
105
- return own(() => s.column(f, zone));
106
- try {
107
- return s.column(f, zone);
108
- }
109
- catch (e) {
110
- return fail(`${what} cannot be read: ${e.message}`, `${role} as another field`, e);
111
- }
112
- };
113
- const numeric = (f, i, role) => {
114
- const what = typeof f === 'string' ? `${role} ${quote(f)}` : `the accessor ${role}${i + 1}`;
115
- const c = read(f, what, role);
116
- if (c.kind !== 'number')
117
- fail(`${what} is ${c.kind}, not numbers`, `${role} as a field of numbers`);
118
- return c;
176
+ return f;
177
+ let n = i + 1;
178
+ while (taken.has(`y${n}`))
179
+ n++;
180
+ taken.add(`y${n}`);
181
+ return `y${n}`;
182
+ });
183
+ const yColumns = drawn.map((f, i) => p.roles
184
+ ? numeric(f, p.roles[i])
185
+ : i < ys.length
186
+ ? numeric(f, 'y', `${i + 1}`, family === 'scatter')
187
+ : numeric(f, 'y2'));
188
+ const yCategories = yColumns[0].categories;
189
+ const along = p.errorBars && (p.errorBars.axis ?? (yCategories ? 'x' : 'y'));
190
+ if (yCategories && along === 'y')
191
+ fail('errorBars along y do not apply to a text y', "errorBars.axis as 'x', or y as a field of numbers");
192
+ const rColumn = r === undefined ? undefined : numeric(r, 'r', '1').values;
193
+ const bounds = p.errorBars && {
194
+ low: numeric(p.errorBars.low, 'errorBars.low').values,
195
+ high: numeric(p.errorBars.high, 'errorBars.high').values,
119
196
  };
120
- const yColumns = ys.map((f, i) => numeric(f, i, 'y').values);
121
- const rColumn = r === undefined ? undefined : numeric(r, 0, 'r').values;
122
197
  const xColumn = x === undefined ? undefined : read(xField, 'the accessor x', 'x', { utc: p.xAxis?.utc ?? true });
198
+ if (along === 'x' && xColumn?.kind !== 'number')
199
+ fail('errorBars along x need an x of numbers', 'x as a field of numbers, or leave out errorBars');
123
200
  const xs = xColumn?.values ?? Float64Array.from({ length: s.length }, (_, i) => i);
124
201
  const kept = [];
125
202
  for (let i = 0; i < s.length; i++)
@@ -131,11 +208,15 @@ export function assign(s, props, family, name, firstSeen = false) {
131
208
  x: at(xs, rows),
132
209
  y: at(y, rows),
133
210
  ...(rColumn && { r: at(rColumn, rows) }),
211
+ ...(bounds && { low: at(bounds.low, rows), high: at(bounds.high, rows) }),
134
212
  });
135
213
  let out;
136
214
  let order;
137
215
  if (p.series === undefined)
138
- out = ys.map((f, i) => series(typeof f === 'string' ? f : `y${i + 1}`, kept, yColumns[i]));
216
+ out = names.map((n, i) => ({
217
+ ...series(n, kept, yColumns[i].values),
218
+ ...(i >= ys.length && { yAxis: 'y2' }),
219
+ }));
139
220
  else {
140
221
  const by = read(p.series, 'the accessor series', 'series');
141
222
  const groups = new Map();
@@ -152,7 +233,7 @@ export function assign(s, props, family, name, firstSeen = false) {
152
233
  else
153
234
  groups.set(v, [i]);
154
235
  }
155
- out = [...groups].map(([v, rows]) => series(by.categories?.[v] ?? String(v), rows, yColumns[0]));
236
+ out = [...groups].map(([v, rows]) => series(by.categories?.[v] ?? String(v), rows, yColumns[0].values));
156
237
  }
157
238
  return {
158
239
  x: {
@@ -160,8 +241,11 @@ export function assign(s, props, family, name, firstSeen = false) {
160
241
  kind: xColumn?.kind ?? 'index',
161
242
  ...(xColumn?.categories && { categories: xColumn.categories }),
162
243
  },
163
- y: { label: ys.length === 1 && typeof ys[0] === 'string' ? ys[0] : '' },
244
+ y: { ...labelled(ys), ...(yCategories && { categories: yCategories }) },
245
+ ...second,
164
246
  ys: out,
247
+ ...(p.series === undefined && kept.length < s.length && { rows: kept }),
165
248
  ...(order && { order: [...order] }),
249
+ ...(along === 'x' && { lying: true }),
166
250
  };
167
251
  }
@@ -0,0 +1,15 @@
1
+ import type { Options } from '../types.js';
2
+ import type { SankeyProps, TreemapProps } from './types.js';
3
+ export declare const sankeyChart: (<D extends import("./types.js").Input | undefined = undefined>(el: HTMLElement, props: SankeyProps<D>) => [D] extends [readonly never[] | undefined] ? Omit<import("./controller.js").EasyChart<never>, "update"> & {
4
+ update<D_1 extends import("./types.js").Input | undefined = undefined>(props: Partial<SankeyProps<D_1>> & {
5
+ data?: D_1 | null | undefined;
6
+ }): void;
7
+ } : import("./controller.js").EasyChart<SankeyProps<D>>) & {
8
+ spec: <D extends import("./types.js").Input | undefined = undefined>(props: SankeyProps<D>) => Options;
9
+ };
10
+ export declare const treemapChart: (<D extends import("./types.js").Input | undefined = undefined>(el: HTMLElement, props: TreemapProps) => [D] extends [readonly never[] | undefined] ? import("./controller.js").EasyChart<TreemapProps> : import("./controller.js").EasyChart<TreemapProps>) & {
11
+ spec: <D extends import("./types.js").Input | undefined = undefined>(props: TreemapProps) => Options;
12
+ };
13
+ export declare const sunburstChart: (<D extends import("./types.js").Input | undefined = undefined>(el: HTMLElement, props: import("./types.js").SunburstProps) => [D] extends [readonly never[] | undefined] ? import("./controller.js").EasyChart<import("./types.js").SunburstProps> : import("./controller.js").EasyChart<import("./types.js").SunburstProps>) & {
14
+ spec: <D extends import("./types.js").Input | undefined = undefined>(props: import("./types.js").SunburstProps) => Options;
15
+ };
@@ -0,0 +1,189 @@
1
+ import { fromLinks, sankey } from '../marks/sankey.js';
2
+ import { sunburst } from '../marks/sunburst.js';
3
+ import { fromTree } from '../marks/tree.js';
4
+ import { treemap } from '../marks/treemap.js';
5
+ import { defined, easyChart, featuresOf, given, install, noAxes, sizeOf } from './build.js';
6
+ import { colorsFor, formatNumber, namesOf } from './defaults.js';
7
+ import { reader } from './fields.js';
8
+ const SANKEY = 'sankeyChart';
9
+ const worth = (v) => (v > 0 && Number.isFinite(v) ? v : 0);
10
+ // Only finite sizes are added up, so a total that is not finite is a sum past the largest number.
11
+ const formatTotal = (v) => (Number.isFinite(v) ? formatNumber(v) : 'over 1.79e+308');
12
+ const hidden = (text) => (text === false ? false : undefined);
13
+ /** Runs a step of the core, whose errors start with its own name, under the chart's. */
14
+ function under(name, step) {
15
+ try {
16
+ return step();
17
+ }
18
+ catch (e) {
19
+ throw new Error(`${name}: ${e.message.replace(/^\w+: /, '')}`, { cause: e });
20
+ }
21
+ }
22
+ function links(s, p) {
23
+ const { kinds, fail, check, sole, read, numeric } = reader(s, SANKEY);
24
+ if (!s.length)
25
+ return undefined;
26
+ if (s.shape)
27
+ fail('a list of numbers or pairs has no links', 'rows or columns with fields for source, target and value');
28
+ const pool = check([
29
+ ['source', p.source],
30
+ ['target', p.target],
31
+ ['value', p.value],
32
+ ], ['value']);
33
+ const named = pool.filter(f => kinds.get(f) === 'text');
34
+ const end = (role) => p[role] ??
35
+ named.shift() ??
36
+ fail(`there is no field of text left for ${role}`, `${role} as a field of the nodes' names`);
37
+ const from = end('source');
38
+ const to = end('target');
39
+ const value = sole('value', p.value, pool);
40
+ const { values } = numeric(value, 'value');
41
+ const ends = [
42
+ read(from, 'the accessor source', 'source'),
43
+ read(to, 'the accessor target', 'target'),
44
+ ];
45
+ const namer = ({ kind, categories }) => namesOf(kind, categories, ends.filter(c => c.kind === kind).map(c => c.values), true);
46
+ const [source, target] = ends;
47
+ const [sourceName, targetName] = [namer(source), namer(target)];
48
+ const list = [];
49
+ for (let i = 0; i < s.length; i++) {
50
+ const [a, b] = [source.values[i], target.values[i]];
51
+ if (Number.isFinite(a) && Number.isFinite(b))
52
+ list.push({ source: sourceName(a), target: targetName(b), value: values[i] });
53
+ }
54
+ const flow = fromLinks(list);
55
+ const [out, into] = [new Float64Array(flow.nodes.length), new Float64Array(flow.nodes.length)];
56
+ flow.value.forEach((v, i) => {
57
+ out[flow.source[i]] += worth(v);
58
+ into[flow.target[i]] += worth(v);
59
+ });
60
+ return {
61
+ ...flow,
62
+ label: typeof value === 'string' ? value : 'value',
63
+ totals: out.map((v, i) => Math.max(v, into[i])),
64
+ };
65
+ }
66
+ const sankeyBuild = (p, { source: s, theme, memo }) => {
67
+ if (s.length) {
68
+ for (const k of ['x', 'y', 'label', 'series'])
69
+ if (given(p, k))
70
+ throw new Error(`${SANKEY}: use source, target and value, not ${k}`);
71
+ noAxes(p, SANKEY);
72
+ }
73
+ const picked = memo('fields', [s, p.source, p.target, p.value], () => links(s, p));
74
+ const colors = colorsFor(theme, p.colors, picked?.nodes.length ?? 0);
75
+ const marks = memo('marks', [picked, p.blend, hidden(p.text), ...colors], () => {
76
+ if (!picked)
77
+ return [];
78
+ const { nodes, source, target, value, label } = picked;
79
+ return under(SANKEY, () => [
80
+ sankey(defined({
81
+ key: 'sankey',
82
+ label,
83
+ nodes,
84
+ source,
85
+ target,
86
+ value,
87
+ colors,
88
+ blend: p.blend,
89
+ text: hidden(p.text),
90
+ })),
91
+ ]);
92
+ });
93
+ const features = featuresOf({ ...p, zoom: false }, 0);
94
+ const ref = memo('tooltip', [], () => ({}));
95
+ ref.current = picked;
96
+ return {
97
+ options: { ...sizeOf(p), theme, frame: 'blank', marks },
98
+ features,
99
+ use: () => {
100
+ ref.current = picked;
101
+ return install(features, {
102
+ mode: 'nearest',
103
+ text: (_label, _x, _y, row) => {
104
+ const { nodes, source, target, value, totals } = ref.current;
105
+ const link = row - nodes.length;
106
+ return link < 0
107
+ ? `${nodes[row]}: ${formatTotal(totals[row])}`
108
+ : `${nodes[source[link]]} → ${nodes[target[link]]}: ${formatNumber(worth(value[link]))}`;
109
+ },
110
+ });
111
+ },
112
+ };
113
+ };
114
+ function grown(data, name) {
115
+ if (!data || !Object.keys(data).length)
116
+ return undefined;
117
+ const tree = under(name, () => {
118
+ const bad = (cause) => new Error('data must be a root { name, value, children } or a list of roots', { cause });
119
+ try {
120
+ const made = fromTree(data);
121
+ if (made.nodes.some(n => typeof n !== 'string'))
122
+ throw bad();
123
+ return made;
124
+ }
125
+ catch (e) {
126
+ throw e instanceof TypeError ? bad(e) : e;
127
+ }
128
+ });
129
+ const { nodes, parent, value } = tree;
130
+ const totals = new Float64Array(nodes.length);
131
+ const leaf = new Uint8Array(nodes.length).fill(1);
132
+ for (const at of parent)
133
+ if (at >= 0)
134
+ leaf[at] = 0;
135
+ for (let i = nodes.length - 1; i >= 0; i--) {
136
+ if (leaf[i])
137
+ totals[i] = worth(value[i]);
138
+ if (parent[i] >= 0)
139
+ totals[parent[i]] += totals[i];
140
+ }
141
+ const below = (at) => parent.filter(up => up === at).length;
142
+ const roots = below(-1);
143
+ return { ...tree, totals, branches: roots > 1 ? roots : below(0) || 1 };
144
+ }
145
+ function trees(kind, frame, draw) {
146
+ const name = `${kind}Chart`;
147
+ return (p, { source: s, theme, memo }) => {
148
+ // The source stands for the data: a new one is made when the data or its version changes.
149
+ const tree = memo('tree', [s], () => grown(p.data, name));
150
+ if (tree) {
151
+ for (const k of ['x', 'y', 'series', 'label', 'value', 'source', 'target'])
152
+ if (given(p, k))
153
+ throw new Error(`${name}: ${k} does not apply, as data is a tree of { name, value, children }`);
154
+ noAxes(p, name);
155
+ }
156
+ const colors = colorsFor(theme, p.colors, tree?.branches ?? 0);
157
+ const marks = memo('marks', [tree, p.shade, hidden(p.text), ...colors], () => {
158
+ if (!tree)
159
+ return [];
160
+ const { nodes, parent, value } = tree;
161
+ return [
162
+ draw(defined({ key: kind, nodes, parent, value, colors, shade: p.shade, text: hidden(p.text) })),
163
+ ];
164
+ });
165
+ const features = featuresOf({ ...p, zoom: false }, 0);
166
+ const ref = memo('tooltip', [], () => ({}));
167
+ ref.current = tree;
168
+ return {
169
+ options: { ...sizeOf(p), theme, frame, marks },
170
+ features,
171
+ use: () => {
172
+ ref.current = tree;
173
+ return install(features, {
174
+ mode: 'nearest',
175
+ text: (_label, _x, _y, row) => {
176
+ const { nodes, parent, totals } = ref.current;
177
+ const path = [];
178
+ for (let i = row; i >= 0; i = parent[i])
179
+ path.push(nodes[i]);
180
+ return `${path.reverse().join(' · ')}: ${formatTotal(totals[row])}`;
181
+ },
182
+ });
183
+ },
184
+ };
185
+ };
186
+ }
187
+ export const sankeyChart = easyChart(sankeyBuild);
188
+ export const treemapChart = easyChart(trees('treemap', 'blank', treemap));
189
+ export const sunburstChart = easyChart(trees('sunburst', 'polar', sunburst));
@@ -0,0 +1,9 @@
1
+ import type { HeatmapProps } from './types.js';
2
+ export declare const fits: (columns: number, rows: number) => boolean;
3
+ export declare const heatmapChart: (<D extends import("./types.js").Input | undefined = undefined>(el: HTMLElement, props: HeatmapProps<D>) => [D] extends [readonly never[] | undefined] ? Omit<import("./controller.js").EasyChart<never>, "update"> & {
4
+ update<D_1 extends import("./types.js").Input | undefined = undefined>(props: Partial<HeatmapProps<D_1>> & {
5
+ data?: D_1 | null | undefined;
6
+ }): void;
7
+ } : import("./controller.js").EasyChart<HeatmapProps<D>>) & {
8
+ spec: <D extends import("./types.js").Input | undefined = undefined>(props: HeatmapProps<D>) => import("../types.js").Options;
9
+ };
@@ -0,0 +1,104 @@
1
+ import { heatmap } from '../marks/heatmap.js';
2
+ import { band } from '../scales/band.js';
3
+ import { defined, easyChart, featuresOf, given, install, sizeOf } from './build.js';
4
+ import { formatNumber, namesOf } from './defaults.js';
5
+ import { reader } from './fields.js';
6
+ const NAME = 'heatmapChart';
7
+ const MAX_CELLS = 10_000_000;
8
+ export const fits = (columns, rows) => columns * rows <= MAX_CELLS;
9
+ function pick(s, p) {
10
+ const { kinds, fail, check, sole, read, numeric } = reader(s, NAME);
11
+ if (!s.length)
12
+ return undefined;
13
+ if (s.shape)
14
+ fail('a list of numbers or pairs has no cells', 'rows or columns with fields for x, y and value');
15
+ const pool = check([
16
+ ['x', p.x],
17
+ ['y', p.y],
18
+ ['value', p.value],
19
+ ], ['value']);
20
+ const named = pool.filter(f => kinds.get(f) === 'text' || kinds.get(f) === 'time');
21
+ const side = (role) => p[role] ??
22
+ named.shift() ??
23
+ fail(`there is no field of text or dates left for ${role}`, `${role} as a field of the cells' places`);
24
+ const x = side('x');
25
+ const y = side('y');
26
+ const value = sole('value', p.value, pool);
27
+ const { values } = numeric(value, 'value');
28
+ const xs = read(x, 'the accessor x', 'x');
29
+ const ys = read(y, 'the accessor y', 'y');
30
+ const kept = Array.from({ length: s.length }, (_, i) => i).filter(i => Number.isFinite(xs.values[i]) && Number.isFinite(ys.values[i]));
31
+ const lay = (f, { kind, values: at, categories }) => {
32
+ const order = [...new Set(kept.map(i => at[i]))];
33
+ if (kind !== 'text')
34
+ order.sort((a, b) => a - b);
35
+ return {
36
+ label: typeof f === 'string' ? f : '',
37
+ categories: order.map(namesOf(kind, categories, [order], true)),
38
+ slots: new Map(order.map((v, i) => [v, i])),
39
+ };
40
+ };
41
+ const { slots: columns, ...across } = lay(x, xs);
42
+ const { slots: rows, ...up } = lay(y, ys);
43
+ if (!fits(columns.size, rows.size))
44
+ fail(`a grid of ${formatNumber(columns.size)} columns by ${formatNumber(rows.size)} rows is over the limit of ${formatNumber(MAX_CELLS)} cells`, 'x and y as fields with fewer distinct values');
45
+ const cells = new Float64Array(columns.size * rows.size).fill(Number.NaN);
46
+ for (const i of kept)
47
+ cells[rows.get(ys.values[i]) * columns.size + columns.get(xs.values[i])] = values[i];
48
+ return {
49
+ x: across,
50
+ y: up,
51
+ label: typeof value === 'string' ? value : 'value',
52
+ values: cells,
53
+ some: cells.some(Number.isFinite),
54
+ };
55
+ }
56
+ const build = (p, { source: s, theme, memo }) => {
57
+ if (s.length) {
58
+ if (given(p, 'label'))
59
+ throw new Error(`${NAME}: use x, y and value, not label and value`);
60
+ if (given(p, 'zoom'))
61
+ throw new Error(`${NAME}: zoom does not apply to a grid of cells`);
62
+ }
63
+ const picked = memo('fields', [s, p.x, p.y, p.value], () => pick(s, p));
64
+ const { color: scale } = p;
65
+ // By value, not identity: a scale made inline is new on every render.
66
+ const color = memo('color', scale ? [...(scale.domain ?? []), ...scale.stops, ...scale.table] : [], () => scale);
67
+ const axis = (side, label) => band({ label: label ?? side?.label ?? '', categories: side?.categories ?? [] });
68
+ const features = featuresOf({ ...p, zoom: false }, picked?.some ? 2 : 0);
69
+ const ref = memo('tooltip', [], () => ({}));
70
+ ref.current = picked;
71
+ return {
72
+ options: {
73
+ ...sizeOf(p),
74
+ theme,
75
+ x: axis(picked?.x, p.xAxis?.label),
76
+ y: axis(picked?.y, p.yAxis?.label),
77
+ marks: picked
78
+ ? [
79
+ heatmap(defined({
80
+ key: 'heatmap',
81
+ label: picked.label,
82
+ values: picked.values,
83
+ columns: picked.x.categories.length,
84
+ color,
85
+ })),
86
+ ]
87
+ : [],
88
+ },
89
+ features,
90
+ use: () => {
91
+ ref.current = picked;
92
+ return install(features, {
93
+ mode: 'nearest',
94
+ text: (label, _x, _y, row) => {
95
+ const { x, y, values } = ref.current;
96
+ const n = x.categories.length;
97
+ const [column, line] = [x.categories[row % n], y.categories[Math.floor(row / n)]];
98
+ return `${column} · ${line} · ${label}: ${formatNumber(values[row])}`;
99
+ },
100
+ });
101
+ },
102
+ };
103
+ };
104
+ export const heatmapChart = easyChart(build);
@@ -1,6 +1,13 @@
1
+ export { candlestickChart } from './candlestick.js';
2
+ export { comboChart } from './combo.js';
3
+ export { boxPlotChart, histogramChart } from './distribution.js';
4
+ export { sankeyChart, sunburstChart, treemapChart } from './flow.js';
5
+ export { heatmapChart } from './heatmap.js';
6
+ export { funnelChart, pieChart, radialBarChart } from './parts.js';
7
+ export { radarChart } from './radar.js';
1
8
  export { areaChart, barChart, lineChart, scatterChart } from './xy.js';
2
9
  export { equal, plain } from './controller.js';
3
10
  export type { EasyChart } from './controller.js';
4
11
  export { mount } from './mount.js';
5
12
  export type { Mount } from './mount.js';
6
- export type { AreaProps as AreaChartProps, BarProps as BarChartProps, LineProps as LineChartProps, ScatterProps as ScatterChartProps, } from './types.js';
13
+ export type { AreaProps as AreaChartProps, BarProps as BarChartProps, BoxPlotProps as BoxPlotChartProps, CandlestickProps as CandlestickChartProps, ComboProps as ComboChartProps, FunnelProps as FunnelChartProps, HeatmapProps as HeatmapChartProps, HistogramProps as HistogramChartProps, LineProps as LineChartProps, PieProps as PieChartProps, RadarProps as RadarChartProps, RadialBarProps as RadialBarChartProps, SankeyProps as SankeyChartProps, ScatterProps as ScatterChartProps, SunburstProps as SunburstChartProps, TreemapProps as TreemapChartProps, } from './types.js';
@@ -1,3 +1,10 @@
1
+ export { candlestickChart } from './candlestick.js';
2
+ export { comboChart } from './combo.js';
3
+ export { boxPlotChart, histogramChart } from './distribution.js';
4
+ export { sankeyChart, sunburstChart, treemapChart } from './flow.js';
5
+ export { heatmapChart } from './heatmap.js';
6
+ export { funnelChart, pieChart, radialBarChart } from './parts.js';
7
+ export { radarChart } from './radar.js';
1
8
  export { areaChart, barChart, lineChart, scatterChart } from './xy.js';
2
9
  export { equal, plain } from './controller.js';
3
10
  export { mount } from './mount.js';