swiftplot 0.0.1 → 0.3.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 (115) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +348 -3
  3. package/dist/chart.d.ts +7 -0
  4. package/dist/chart.js +1311 -0
  5. package/dist/charts/build.d.ts +52 -0
  6. package/dist/charts/build.js +63 -0
  7. package/dist/charts/candlestick.d.ts +8 -0
  8. package/dist/charts/candlestick.js +105 -0
  9. package/dist/charts/combo.d.ts +8 -0
  10. package/dist/charts/combo.js +50 -0
  11. package/dist/charts/controller.d.ts +32 -0
  12. package/dist/charts/controller.js +231 -0
  13. package/dist/charts/defaults.d.ts +20 -0
  14. package/dist/charts/defaults.js +121 -0
  15. package/dist/charts/distribution.d.ts +15 -0
  16. package/dist/charts/distribution.js +178 -0
  17. package/dist/charts/fields.d.ts +64 -0
  18. package/dist/charts/fields.js +251 -0
  19. package/dist/charts/flow.d.ts +15 -0
  20. package/dist/charts/flow.js +189 -0
  21. package/dist/charts/heatmap.d.ts +9 -0
  22. package/dist/charts/heatmap.js +104 -0
  23. package/dist/charts/index.d.ts +13 -0
  24. package/dist/charts/index.js +10 -0
  25. package/dist/charts/mount.d.ts +5 -0
  26. package/dist/charts/mount.js +21 -0
  27. package/dist/charts/parts.d.ts +23 -0
  28. package/dist/charts/parts.js +66 -0
  29. package/dist/charts/radar.d.ts +7 -0
  30. package/dist/charts/radar.js +77 -0
  31. package/dist/charts/source.d.ts +24 -0
  32. package/dist/charts/source.js +225 -0
  33. package/dist/charts/types.d.ts +643 -0
  34. package/dist/charts/types.js +1 -0
  35. package/dist/charts/xy.d.ts +46 -0
  36. package/dist/charts/xy.js +421 -0
  37. package/dist/features/animate.d.ts +20 -0
  38. package/dist/features/animate.js +118 -0
  39. package/dist/features/brush.d.ts +15 -0
  40. package/dist/features/brush.js +128 -0
  41. package/dist/features/legend.d.ts +13 -0
  42. package/dist/features/legend.js +236 -0
  43. package/dist/features/pointer.d.ts +29 -0
  44. package/dist/features/pointer.js +23 -0
  45. package/dist/features/tooltip.d.ts +22 -0
  46. package/dist/features/tooltip.js +192 -0
  47. package/dist/features/zoom.d.ts +14 -0
  48. package/dist/features/zoom.js +246 -0
  49. package/dist/gl.d.ts +5 -0
  50. package/dist/gl.js +52 -0
  51. package/dist/index.d.ts +62 -0
  52. package/dist/index.js +32 -0
  53. package/dist/marks/arcs.d.ts +31 -0
  54. package/dist/marks/arcs.js +125 -0
  55. package/dist/marks/area.d.ts +25 -0
  56. package/dist/marks/area.js +106 -0
  57. package/dist/marks/bar.d.ts +52 -0
  58. package/dist/marks/bar.js +243 -0
  59. package/dist/marks/box.d.ts +33 -0
  60. package/dist/marks/box.js +182 -0
  61. package/dist/marks/candlestick.d.ts +22 -0
  62. package/dist/marks/candlestick.js +133 -0
  63. package/dist/marks/common.d.ts +102 -0
  64. package/dist/marks/common.js +250 -0
  65. package/dist/marks/dots.d.ts +16 -0
  66. package/dist/marks/dots.js +158 -0
  67. package/dist/marks/errorBars.d.ts +24 -0
  68. package/dist/marks/errorBars.js +99 -0
  69. package/dist/marks/funnel.d.ts +30 -0
  70. package/dist/marks/funnel.js +122 -0
  71. package/dist/marks/heatmap.d.ts +20 -0
  72. package/dist/marks/heatmap.js +139 -0
  73. package/dist/marks/line.d.ts +21 -0
  74. package/dist/marks/line.js +75 -0
  75. package/dist/marks/radar.d.ts +29 -0
  76. package/dist/marks/radar.js +162 -0
  77. package/dist/marks/radialBars.d.ts +34 -0
  78. package/dist/marks/radialBars.js +111 -0
  79. package/dist/marks/rects.d.ts +43 -0
  80. package/dist/marks/rects.js +120 -0
  81. package/dist/marks/rule.d.ts +47 -0
  82. package/dist/marks/rule.js +83 -0
  83. package/dist/marks/sankey.d.ts +53 -0
  84. package/dist/marks/sankey.js +369 -0
  85. package/dist/marks/sunburst.d.ts +31 -0
  86. package/dist/marks/sunburst.js +186 -0
  87. package/dist/marks/ticks.d.ts +12 -0
  88. package/dist/marks/ticks.js +26 -0
  89. package/dist/marks/tree.d.ts +49 -0
  90. package/dist/marks/tree.js +113 -0
  91. package/dist/marks/treemap.d.ts +30 -0
  92. package/dist/marks/treemap.js +164 -0
  93. package/dist/paint.d.ts +35 -0
  94. package/dist/paint.js +71 -0
  95. package/dist/scale.d.ts +16 -0
  96. package/dist/scale.js +97 -0
  97. package/dist/scales/band.d.ts +12 -0
  98. package/dist/scales/band.js +27 -0
  99. package/dist/scales/bare.d.ts +6 -0
  100. package/dist/scales/bare.js +10 -0
  101. package/dist/scales/color.d.ts +20 -0
  102. package/dist/scales/color.js +21 -0
  103. package/dist/scales/log.d.ts +27 -0
  104. package/dist/scales/log.js +98 -0
  105. package/dist/scales/time.d.ts +37 -0
  106. package/dist/scales/time.js +183 -0
  107. package/dist/text.d.ts +8 -0
  108. package/dist/text.js +33 -0
  109. package/dist/theme.d.ts +10 -0
  110. package/dist/theme.js +8 -0
  111. package/dist/transforms.d.ts +47 -0
  112. package/dist/transforms.js +119 -0
  113. package/dist/types.d.ts +465 -0
  114. package/dist/types.js +1 -0
  115. package/package.json +31 -6
@@ -0,0 +1,121 @@
1
+ import { palette, paletteDark } from '../paint.js';
2
+ import { dark, light } from '../theme.js';
3
+ export const DAY = 864e5;
4
+ const numbers = new Intl.NumberFormat('en-US', { maximumFractionDigits: 2 });
5
+ export const formatNumber = (v) => numbers.format(v);
6
+ const pad = (n, w = 2) => String(n).padStart(w, '0');
7
+ export function timeTitle(columns, utc, distinct = false) {
8
+ const parts = (t) => {
9
+ const d = new Date(t);
10
+ return utc
11
+ ? [
12
+ d.getUTCFullYear(),
13
+ d.getUTCMonth() + 1,
14
+ d.getUTCDate(),
15
+ d.getUTCHours(),
16
+ d.getUTCMinutes(),
17
+ d.getUTCSeconds(),
18
+ d.getUTCMilliseconds(),
19
+ ]
20
+ : [
21
+ d.getFullYear(),
22
+ d.getMonth() + 1,
23
+ d.getDate(),
24
+ d.getHours(),
25
+ d.getMinutes(),
26
+ d.getSeconds(),
27
+ d.getMilliseconds(),
28
+ ];
29
+ };
30
+ const midnight = (t) => {
31
+ const d = new Date(t);
32
+ return utc
33
+ ? t % DAY === 0
34
+ : d.getHours() === 0 && d.getMinutes() === 0 && d.getSeconds() === 0 && d.getMilliseconds() === 0;
35
+ };
36
+ let dateOnly = true;
37
+ for (const xs of columns)
38
+ for (let i = 0; i < xs.length && dateOnly; i++) {
39
+ if (Number.isFinite(xs[i]))
40
+ dateOnly = midnight(xs[i]);
41
+ }
42
+ const times = new Set();
43
+ if (distinct && !(dateOnly && utc))
44
+ for (const xs of columns)
45
+ for (let i = 0; i < xs.length; i++)
46
+ if (Number.isFinite(xs[i]))
47
+ times.add(xs[i]);
48
+ const collide = (unit) => new Set(Array.from(times, t => Math.floor(t / unit))).size < times.size;
49
+ const width = !collide(6e4) ? 5 : !collide(1e3) ? 8 : 12;
50
+ const unit = dateOnly ? DAY : width === 5 ? 6e4 : width === 8 ? 1e3 : 1;
51
+ const walls = new Map();
52
+ let zoned = false;
53
+ if (!utc)
54
+ for (const t of times) {
55
+ const offset = new Date(t).getTimezoneOffset();
56
+ const wall = Math.floor((t - offset * 6e4) / unit);
57
+ zoned ||= (walls.get(wall) ?? offset) !== offset;
58
+ walls.set(wall, offset);
59
+ }
60
+ const zone = (t) => {
61
+ if (!zoned)
62
+ return '';
63
+ const offset = -new Date(t).getTimezoneOffset();
64
+ const size = Math.abs(offset);
65
+ return ` UTC${offset < 0 ? '-' : '+'}${pad(Math.floor(size / 60))}:${pad(Math.floor(size % 60))}`;
66
+ };
67
+ return t => {
68
+ const [y, mo, day, h, mi, s, ms] = parts(t);
69
+ const date = `${y < 0 ? '-' : ''}${pad(Math.abs(y), 4)}-${pad(mo)}-${pad(day)}`;
70
+ const clock = dateOnly ? '' : ` ${`${pad(h)}:${pad(mi)}:${pad(s)}.${pad(ms, 3)}`.slice(0, width)}`;
71
+ return `${date}${clock}${zone(t)}`;
72
+ };
73
+ }
74
+ export const namesOf = (kind, categories, columns, utc) => kind === 'text' ? v => categories[v] : kind === 'time' ? timeTitle(columns, utc, true) : String;
75
+ export const bandTitle = (categories, x) => categories[Math.min(Math.max(Math.round(x), 0), categories.length - 1)];
76
+ /** 0.6 of the smallest gap between distinct x, or of fallback where there is none. */
77
+ export function spacing(x, fallback) {
78
+ const at = Float64Array.from(x).sort();
79
+ let gap = Infinity;
80
+ for (let i = 1; i < at.length; i++) {
81
+ const d = at[i] - at[i - 1];
82
+ if (d > 0 && d < gap)
83
+ gap = d;
84
+ }
85
+ return gap < Infinity
86
+ ? { width: gap * 0.6 }
87
+ : {
88
+ width: fallback * 0.6,
89
+ // A candle or bar alone would otherwise fill the axis, whose extent is its width.
90
+ ...(at.length &&
91
+ Number.isFinite(at[0]) && { lone: [at[0] - fallback / 2, at[0] + fallback / 2] }),
92
+ };
93
+ }
94
+ /** 'auto' reads the element's computed color-scheme; onChange fires when a 'light dark' page flips. */
95
+ export function themeOf(el, prop, onChange) {
96
+ const none = () => { };
97
+ if (prop === 'light')
98
+ return { theme: light, dispose: none };
99
+ if (prop === 'dark')
100
+ return { theme: dark, dispose: none };
101
+ if (prop !== undefined && prop !== 'auto')
102
+ return { theme: prop, dispose: none };
103
+ const fixed = () => {
104
+ const words = getComputedStyle(el).colorScheme.split(/\s+/);
105
+ if (!words.includes('dark'))
106
+ return light;
107
+ return words.includes('light') ? undefined : dark;
108
+ };
109
+ const theme = fixed();
110
+ if (theme)
111
+ return { theme, dispose: none };
112
+ const mq = matchMedia('(prefers-color-scheme: dark)');
113
+ const resolve = () => fixed() ?? (mq.matches ? dark : light);
114
+ const listen = () => onChange(resolve());
115
+ mq.addEventListener('change', listen);
116
+ return { theme: resolve(), dispose: () => mq.removeEventListener('change', listen) };
117
+ }
118
+ export function colorsFor(theme, colors, n) {
119
+ const list = colors?.length ? colors : theme === dark ? paletteDark : palette;
120
+ return Array.from({ length: n }, (_, i) => list[i % list.length]);
121
+ }
@@ -0,0 +1,15 @@
1
+ import type { BoxPlotProps, HistogramProps } from './types.js';
2
+ export declare const histogramChart: (<D extends import("./types.js").Input | undefined = undefined>(el: HTMLElement, props: HistogramProps<D>) => [D] extends [readonly never[] | undefined] ? Omit<import("./controller.js").EasyChart<never>, "update"> & {
3
+ update<D_1 extends import("./types.js").Input | undefined = undefined>(props: Partial<HistogramProps<D_1>> & {
4
+ data?: D_1 | null | undefined;
5
+ }): void;
6
+ } : import("./controller.js").EasyChart<HistogramProps<D>>) & {
7
+ spec: <D extends import("./types.js").Input | undefined = undefined>(props: HistogramProps<D>) => import("../types.js").Options;
8
+ };
9
+ export declare const boxPlotChart: (<D extends import("./types.js").Input | undefined = undefined>(el: HTMLElement, props: BoxPlotProps<D>) => [D] extends [readonly never[] | undefined] ? Omit<import("./controller.js").EasyChart<never>, "update"> & {
10
+ update<D_1 extends import("./types.js").Input | undefined = undefined>(props: Partial<BoxPlotProps<D_1>> & {
11
+ data?: D_1 | null | undefined;
12
+ }): void;
13
+ } : import("./controller.js").EasyChart<BoxPlotProps<D>>) & {
14
+ spec: <D extends import("./types.js").Input | undefined = undefined>(props: BoxPlotProps<D>) => import("../types.js").Options;
15
+ };
@@ -0,0 +1,178 @@
1
+ import { bar } from '../marks/bar.js';
2
+ import { box } from '../marks/box.js';
3
+ import { band } from '../scales/band.js';
4
+ import { bin, fiveNumbers } from '../transforms.js';
5
+ import { defined, easyChart, featuresOf, given, install, linear, sizeOf } from './build.js';
6
+ import { colorsFor, formatNumber, namesOf } from './defaults.js';
7
+ import { reader } from './fields.js';
8
+ const HISTOGRAM = 'histogramChart';
9
+ const MAX_BINS = 1_000_000;
10
+ /** Two decimals at most, or as many as tell the edges of the narrowest bin apart, in full past the 20 all engines take. */
11
+ function edgeFormat({ x1, x2 }) {
12
+ let narrowest = Infinity;
13
+ for (let i = 0; i < x1.length; i++) {
14
+ const w = x2[i] - x1[i];
15
+ if (w > 0 && w < narrowest)
16
+ narrowest = w;
17
+ }
18
+ const digits = Math.max(Math.ceil(-Math.log10(narrowest)) + 1, 2);
19
+ if (digits > 20)
20
+ return String;
21
+ const f = new Intl.NumberFormat('en-US', { maximumFractionDigits: digits });
22
+ return (v) => f.format(v);
23
+ }
24
+ function count(s, named, by) {
25
+ const { fail, check, sole, numeric } = reader(s, HISTOGRAM);
26
+ if (!s.length)
27
+ return undefined;
28
+ if (s.shape === 'pairs')
29
+ fail('a list of pairs has no one list of values', 'numbers, or rows or columns with a field of numbers for x');
30
+ if (typeof by === 'number' && by > MAX_BINS)
31
+ throw new Error(`${HISTOGRAM}: ${formatNumber(by)} bins are over the limit of ${formatNumber(MAX_BINS)}`);
32
+ const given = s.shape ? 'value' : named;
33
+ const x = sole('x', given, check([['x', given]], ['x']));
34
+ const bins = bin(numeric(x, 'x').values, by);
35
+ return { label: typeof x === 'string' ? x : '', bins, edge: edgeFormat(bins) };
36
+ }
37
+ const buildHistogram = (p, { source: s, theme, memo }) => {
38
+ if (s.length)
39
+ for (const k of ['y', 'label', 'value'])
40
+ if (given(p, k))
41
+ throw new Error(`${HISTOGRAM}: use x for the values counted, not ${k}`);
42
+ const { bins: by } = p;
43
+ const picked = memo('fields', [s, p.x, typeof by, ...(typeof by === 'object' ? Array.from(by) : [by])], () => count(s, p.x, by));
44
+ const features = featuresOf(p, 1);
45
+ const text = { picked, x: p.xAxis?.format ?? picked?.edge, y: p.yAxis?.format ?? formatNumber };
46
+ const ref = memo('tooltip', [], () => ({}));
47
+ ref.current = text;
48
+ return {
49
+ options: {
50
+ ...sizeOf(p),
51
+ theme,
52
+ x: linear(p.xAxis, picked?.label ?? ''),
53
+ y: linear(p.yAxis, picked ? 'count' : ''),
54
+ marks: picked
55
+ ? [
56
+ bar({
57
+ key: 'histogram',
58
+ label: 'count',
59
+ ...picked.bins,
60
+ color: colorsFor(theme, p.colors, 1)[0],
61
+ gap: 1,
62
+ }),
63
+ ]
64
+ : [],
65
+ },
66
+ features,
67
+ use: () => {
68
+ ref.current = text;
69
+ return install(features, {
70
+ mode: 'nearest',
71
+ text: (label, _x, v, row) => {
72
+ const { picked: shown, x, y } = ref.current;
73
+ const { x1, x2 } = shown.bins;
74
+ return `${x(x1[row])} – ${x(x2[row])} · ${label}: ${y(v)}`;
75
+ },
76
+ });
77
+ },
78
+ };
79
+ };
80
+ const BOX_PLOT = 'boxPlotChart';
81
+ function boxes(s, props) {
82
+ const { kinds, fail, check, sole, read, numeric } = reader(s, BOX_PLOT);
83
+ if (!s.length)
84
+ return undefined;
85
+ const p = s.shape === 'numbers' ? { y: 'value' } : s.shape === 'pairs' ? { x: 'x', y: 'y' } : props;
86
+ const pool = check([
87
+ ['x', p.x ?? undefined],
88
+ ['y', p.y],
89
+ ], ['y']);
90
+ const y = sole('y', p.y, pool);
91
+ const { values } = numeric(y, 'y');
92
+ let x = p.x;
93
+ if (x === undefined) {
94
+ const texts = pool.filter(f => kinds.get(f) === 'text');
95
+ const pass = 'or x: null for one box';
96
+ if (texts.length > 1)
97
+ fail(`${texts.map(f => `"${f}"`).join(', ')} are all fields of text, so x cannot be guessed`, `x as one of them, ${pass}`);
98
+ x = texts[0];
99
+ if (x !== undefined) {
100
+ const c = read(x, '', 'x');
101
+ if (c.categories.length === c.values.length - Array.from(c.values).filter(Number.isNaN).length)
102
+ fail(`no value of "${x}" repeats, so every box would hold one row`, `x as the field of groups, ${pass}`);
103
+ }
104
+ }
105
+ const groups = new Map();
106
+ let categories = [''];
107
+ if (x != null) {
108
+ const by = read(x, 'the accessor x', 'x');
109
+ for (let i = 0; i < s.length; i++) {
110
+ const g = by.values[i];
111
+ if (!Number.isFinite(g))
112
+ continue;
113
+ const group = groups.get(g);
114
+ if (group)
115
+ group.push(values[i]);
116
+ else
117
+ groups.set(g, [values[i]]);
118
+ }
119
+ const name = namesOf(by.kind, by.categories, [by.values], true);
120
+ categories = Array.from(groups.keys(), name);
121
+ }
122
+ return {
123
+ x: typeof x === 'string' ? x : '',
124
+ y: typeof y === 'string' ? y : '',
125
+ label: typeof y === 'string' ? y : 'y',
126
+ categories,
127
+ at: Float64Array.from(categories, (_, i) => i),
128
+ five: fiveNumbers(x == null ? [values] : [...groups.values()]),
129
+ };
130
+ }
131
+ const buildBoxPlot = (p, { source: s, theme, memo }) => {
132
+ if (s.length) {
133
+ if (given(p, 'label') || given(p, 'value'))
134
+ throw new Error(`${BOX_PLOT}: use x and y, not label and value`);
135
+ if (given(p, 'zoom'))
136
+ throw new Error(`${BOX_PLOT}: zoom does not apply to boxes`);
137
+ }
138
+ const picked = memo('fields', [s, p.x, p.y], () => boxes(s, p));
139
+ const features = featuresOf({ ...p, zoom: false }, 1);
140
+ const text = { picked, value: p.yAxis?.format ?? formatNumber };
141
+ const ref = memo('tooltip', [], () => ({}));
142
+ ref.current = text;
143
+ return {
144
+ options: {
145
+ ...sizeOf(p),
146
+ theme,
147
+ x: band({ label: p.xAxis?.label ?? picked?.x ?? '', categories: picked?.categories ?? [] }),
148
+ y: linear(p.yAxis, picked?.y ?? ''),
149
+ marks: picked
150
+ ? [
151
+ box(defined({
152
+ key: 'box',
153
+ label: picked.label,
154
+ x: picked.at,
155
+ ...picked.five,
156
+ color: colorsFor(theme, p.colors, 1)[0],
157
+ fill: p.fill,
158
+ })),
159
+ ]
160
+ : [],
161
+ },
162
+ features,
163
+ use: () => {
164
+ ref.current = text;
165
+ return install(features, {
166
+ mode: 'nearest',
167
+ text: (label, _x, _y, row) => {
168
+ const { picked: shown, value } = ref.current;
169
+ const group = shown.categories[row];
170
+ const numbers = Object.entries(shown.five).map(([k, v]) => `${k} ${value(v[row])}`);
171
+ return `${group ? `${group} · ` : ''}${label}: ${numbers.join(', ')}`;
172
+ },
173
+ });
174
+ },
175
+ };
176
+ };
177
+ export const histogramChart = easyChart(buildHistogram);
178
+ export const boxPlotChart = easyChart(buildBoxPlot);
@@ -0,0 +1,64 @@
1
+ import type { Col } from '../types.js';
2
+ import type { Accessor, Column, Kind, Source } from './source.js';
3
+ export type Field<R> = string | Accessor<R>;
4
+ export type FieldProps<R> = {
5
+ x?: Field<R>;
6
+ y?: Field<R> | readonly Field<R>[];
7
+ y2?: Field<R> | readonly Field<R>[];
8
+ series?: Field<R>;
9
+ r?: number | Field<R>;
10
+ errorBars?: {
11
+ low: Field<R>;
12
+ high: Field<R>;
13
+ axis?: 'x' | 'y';
14
+ };
15
+ xAxis?: {
16
+ utc?: boolean;
17
+ };
18
+ /** The prop each field of y and then of y2 came from, where it is not those; nothing is then guessed for y. */
19
+ roles?: readonly string[];
20
+ };
21
+ export type Family = 'xy' | 'scatter';
22
+ export type Series = {
23
+ name: string;
24
+ x: Col;
25
+ y: Col;
26
+ r?: Col;
27
+ low?: Col;
28
+ high?: Col;
29
+ yAxis?: 'y2';
30
+ };
31
+ export type Assigned = {
32
+ x: {
33
+ label: string;
34
+ kind: Kind | 'index';
35
+ categories?: string[];
36
+ };
37
+ y: {
38
+ label: string;
39
+ categories?: string[];
40
+ };
41
+ y2?: {
42
+ label: string;
43
+ };
44
+ ys: Series[];
45
+ /** The error bars run along x: low and high are values on the x axis. */
46
+ lying?: true;
47
+ /** Without series, where some row has no place on x: the rows of the data that the rows of ys are. */
48
+ rows?: number[];
49
+ /** With series and firstSeen: the distinct x across all series in order of first appearance. */
50
+ order?: number[];
51
+ };
52
+ export declare const list: <T>(f: T | readonly T[] | undefined) => readonly T[];
53
+ export declare function reader<R>(s: Source<R>, name: string): {
54
+ kinds: Map<string, Kind | undefined>;
55
+ fail: (why: string, pass: string, cause?: unknown) => never;
56
+ check: (roles: readonly (readonly [string, Field<R> | undefined])[], numberRoles: readonly string[]) => string[];
57
+ noNumbers: (role: string) => never;
58
+ sole: (role: string, named: Field<R> | undefined, pool: readonly string[]) => Field<R>;
59
+ read: (f: Field<R>, what: string, role: string, zone?: {
60
+ utc: boolean;
61
+ }) => Column;
62
+ numeric: (f: Field<R>, role: string, nth?: string, orText?: boolean) => Column;
63
+ };
64
+ export declare function assign<R>(s: Source<R>, props: FieldProps<R>, family: Family, name: string, firstSeen?: boolean): Assigned;
@@ -0,0 +1,251 @@
1
+ export const list = (f) => f === undefined ? [] : Array.isArray(f) ? f : [f];
2
+ const quote = (f) => `"${f}"`;
3
+ export function reader(s, name) {
4
+ const own = (read) => {
5
+ try {
6
+ return read();
7
+ }
8
+ catch (e) {
9
+ throw new Error(`${name}: ${e.message}`, { cause: e });
10
+ }
11
+ };
12
+ const fields = own(() => s.fields());
13
+ const kinds = new Map(fields.map(f => [f, own(() => s.kind(f))]));
14
+ const unplottable = (f) => {
15
+ if (kinds.get(f))
16
+ return false;
17
+ try {
18
+ s.column(f);
19
+ return false;
20
+ }
21
+ catch {
22
+ return true;
23
+ }
24
+ };
25
+ const describe = (f) => kinds.get(f) ?? (unplottable(f) ? 'not plottable' : 'no values');
26
+ const fail = (why, pass, cause) => {
27
+ const list = fields.length
28
+ ? `The fields are ${fields.map(f => `${f} (${describe(f)})`).join(', ')}`
29
+ : 'There are no fields';
30
+ throw new Error(`${name}: ${why}. ${list}. Pass ${pass}.`, { cause });
31
+ };
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: [] };
112
+ const r = family === 'scatter' && typeof p.r !== 'number' ? p.r : undefined;
113
+ const roles = [
114
+ ['x', p.x],
115
+ ...named.map((f, i) => [role(i, 'y'), f]),
116
+ ...named2.map((f, i) => [role(named.length + i, 'y2'), f]),
117
+ ['series', p.series],
118
+ ['r', r],
119
+ ['errorBars.low', p.errorBars?.low],
120
+ ['errorBars.high', p.errorBars?.high],
121
+ ];
122
+ const pool = check(roles, [
123
+ ...(family === 'scatter' ? [] : ['y']),
124
+ 'y2',
125
+ 'r',
126
+ 'errorBars.low',
127
+ 'errorBars.high',
128
+ ...(p.roles ?? []),
129
+ ]);
130
+ const first = (k, not) => pool.find(f => kinds.get(f) === k && f !== not);
131
+ let x = p.x;
132
+ if (x === undefined && family === 'scatter')
133
+ x = first('time') ?? first('number');
134
+ else if (x === undefined) {
135
+ x = first('time') ?? first('text');
136
+ const numbers = pool.filter(f => kinds.get(f) === 'number');
137
+ if (x === undefined && numbers.length > (named.length || p.roles ? 0 : 1))
138
+ x = numbers[0];
139
+ }
140
+ const xField = x;
141
+ const left = pool.filter(f => f !== xField && kinds.get(f) === 'number');
142
+ const ys = named.length || p.roles ? named : family === 'scatter' ? left.slice(0, 1) : left;
143
+ if (family === 'scatter') {
144
+ if (named.length > 1)
145
+ fail('a scatter chart has one y', 'y as one field');
146
+ if (!ys.length || (x === undefined && !s.shape))
147
+ fail('a scatter chart needs two fields of numbers or dates', 'x and y as fields of numbers or dates');
148
+ }
149
+ else if (!ys.length && !p.roles)
150
+ noNumbers('y');
151
+ const leftText = pool.find(f => f !== x && kinds.get(f) === 'text');
152
+ if (family === 'xy' && p.series === undefined && !named2.length && !p.roles && leftText !== undefined)
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');
162
+ if (p.series !== undefined && ys.length > 1)
163
+ fail('with series there is one y', 'y as one field');
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) => {
175
+ if (typeof f === 'string')
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,
196
+ };
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');
200
+ const xs = xColumn?.values ?? Float64Array.from({ length: s.length }, (_, i) => i);
201
+ const kept = [];
202
+ for (let i = 0; i < s.length; i++)
203
+ if (Number.isFinite(xs[i]) && (!rColumn || Number.isFinite(rColumn[i])))
204
+ kept.push(i);
205
+ const at = (c, rows) => (rows.length === s.length ? c : Float64Array.from(rows, i => c[i]));
206
+ const series = (label, rows, y) => ({
207
+ name: label,
208
+ x: at(xs, rows),
209
+ y: at(y, rows),
210
+ ...(rColumn && { r: at(rColumn, rows) }),
211
+ ...(bounds && { low: at(bounds.low, rows), high: at(bounds.high, rows) }),
212
+ });
213
+ let out;
214
+ let order;
215
+ if (p.series === undefined)
216
+ out = names.map((n, i) => ({
217
+ ...series(n, kept, yColumns[i].values),
218
+ ...(i >= ys.length && { yAxis: 'y2' }),
219
+ }));
220
+ else {
221
+ const by = read(p.series, 'the accessor series', 'series');
222
+ const groups = new Map();
223
+ if (firstSeen)
224
+ order = new Set();
225
+ for (const i of kept) {
226
+ const v = by.values[i];
227
+ if (Number.isNaN(v))
228
+ continue;
229
+ order?.add(xs[i]);
230
+ const rows = groups.get(v);
231
+ if (rows)
232
+ rows.push(i);
233
+ else
234
+ groups.set(v, [i]);
235
+ }
236
+ out = [...groups].map(([v, rows]) => series(by.categories?.[v] ?? String(v), rows, yColumns[0].values));
237
+ }
238
+ return {
239
+ x: {
240
+ label: typeof x === 'string' ? x : '',
241
+ kind: xColumn?.kind ?? 'index',
242
+ ...(xColumn?.categories && { categories: xColumn.categories }),
243
+ },
244
+ y: { ...labelled(ys), ...(yCategories && { categories: yCategories }) },
245
+ ...second,
246
+ ys: out,
247
+ ...(p.series === undefined && kept.length < s.length && { rows: kept }),
248
+ ...(order && { order: [...order] }),
249
+ ...(along === 'x' && { lying: true }),
250
+ };
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
+ };