swiftplot 0.1.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 (95) hide show
  1. package/README.md +71 -47
  2. package/dist/chart.d.ts +4 -0
  3. package/dist/chart.js +171 -86
  4. package/dist/charts/build.d.ts +52 -0
  5. package/dist/charts/build.js +63 -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 +562 -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 +12 -10
  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 +3 -1
  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/rule.d.ts +19 -0
  67. package/dist/marks/rule.js +4 -1
  68. package/dist/marks/sankey.d.ts +14 -2
  69. package/dist/marks/sankey.js +4 -1
  70. package/dist/marks/sunburst.d.ts +5 -0
  71. package/dist/marks/sunburst.js +2 -1
  72. package/dist/marks/ticks.d.ts +4 -1
  73. package/dist/marks/tree.d.ts +14 -6
  74. package/dist/marks/tree.js +6 -3
  75. package/dist/marks/treemap.d.ts +5 -0
  76. package/dist/marks/treemap.js +7 -2
  77. package/dist/paint.d.ts +6 -1
  78. package/dist/paint.js +6 -1
  79. package/dist/scale.d.ts +1 -1
  80. package/dist/scale.js +4 -3
  81. package/dist/scales/band.d.ts +3 -0
  82. package/dist/scales/band.js +5 -1
  83. package/dist/scales/bare.d.ts +4 -1
  84. package/dist/scales/bare.js +4 -1
  85. package/dist/scales/color.d.ts +2 -0
  86. package/dist/scales/log.d.ts +8 -1
  87. package/dist/scales/log.js +3 -2
  88. package/dist/scales/time.d.ts +7 -0
  89. package/dist/scales/time.js +3 -1
  90. package/dist/text.d.ts +8 -0
  91. package/dist/text.js +33 -0
  92. package/dist/transforms.d.ts +11 -7
  93. package/dist/transforms.js +8 -7
  94. package/dist/types.d.ts +44 -13
  95. package/package.json +2 -2
@@ -1,36 +1,46 @@
1
- import type { Options } from '../types.js';
2
- import { type Build, type EasyChart } from './controller.js';
3
- import { type FieldProps } from './fields.js';
4
- import type { AreaProps, BarProps, Base, Input, LineProps, ScatterProps } from './types.js';
5
- type XyProps = Base & FieldProps<never> & {
1
+ import type { Build } from './controller.js';
2
+ import { type Field, type FieldProps } from './fields.js';
3
+ import type { Axes, Base, LineProps, Overlays, ScaledAxes, ErrorBarsOn, ScatterProps, SecondAxis } from './types.js';
4
+ type XyProps = Axes & SecondAxis & ScaledAxes & Overlays & Base & FieldProps<never> & {
6
5
  data?: unknown;
7
6
  curve?: LineProps<undefined>['curve'];
8
7
  join?: boolean;
8
+ fill?: LineProps<undefined>['fill'];
9
9
  stack?: boolean;
10
+ errorBars?: ErrorBarsOn<Field<never>>;
11
+ alpha?: number;
12
+ ring?: number;
13
+ shape?: ScatterProps<undefined>['shape'];
14
+ /** On a combo, which fields of y and then of y2 are bars. */
15
+ barred?: readonly boolean[];
10
16
  };
11
- export declare function xy(name: string, kind?: 'line' | 'area' | 'bar' | 'scatter'): Build<XyProps>;
12
- type Kinds<D> = {
13
- line: LineProps<D>;
14
- area: AreaProps<D>;
15
- bar: BarProps<D>;
16
- scatter: ScatterProps<D>;
17
- };
18
- type Later<K extends keyof Kinds<never>> = Omit<EasyChart<never>, 'update'> & {
19
- update<D extends Input | undefined = undefined>(props: Partial<Kinds<D>[K]> & {
20
- data?: D | null;
17
+ export declare function xy(name: string, kind?: 'line' | 'area' | 'bar' | 'scatter' | 'combo'): Build<XyProps>;
18
+ export declare const lineChart: (<D extends import("./types.js").Input | undefined = undefined>(el: HTMLElement, props: LineProps<D>) => [D] extends [readonly never[] | undefined] ? Omit<import("./controller.js").EasyChart<never>, "update"> & {
19
+ update<D_1 extends import("./types.js").Input | undefined = undefined>(props: Partial<LineProps<D_1>> & {
20
+ data?: D_1 | null | undefined;
21
21
  }): void;
22
+ } : import("./controller.js").EasyChart<LineProps<D>>) & {
23
+ spec: <D extends import("./types.js").Input | undefined = undefined>(props: LineProps<D>) => import("../types.js").Options;
22
24
  };
23
- type ChartOf<K extends keyof Kinds<never>, D> = [D] extends [undefined | readonly never[]] ? Later<K> : EasyChart<Kinds<D>[K]>;
24
- export declare const lineChart: (<D extends Input | undefined = undefined>(el: HTMLElement, props: LineProps<D>) => ChartOf<"line", D>) & {
25
- spec: <D extends Input | undefined = undefined>(props: LineProps<D>) => Options;
26
- };
27
- export declare const areaChart: (<D extends Input | undefined = undefined>(el: HTMLElement, props: AreaProps<D>) => ChartOf<"area", D>) & {
28
- spec: <D extends Input | undefined = undefined>(props: AreaProps<D>) => Options;
25
+ export declare const areaChart: (<D extends import("./types.js").Input | undefined = undefined>(el: HTMLElement, props: import("./types.js").AreaProps<D>) => [D] extends [readonly never[] | undefined] ? Omit<import("./controller.js").EasyChart<never>, "update"> & {
26
+ update<D_1 extends import("./types.js").Input | undefined = undefined>(props: Partial<import("./types.js").AreaProps<D_1>> & {
27
+ data?: D_1 | null | undefined;
28
+ }): void;
29
+ } : import("./controller.js").EasyChart<import("./types.js").AreaProps<D>>) & {
30
+ spec: <D extends import("./types.js").Input | undefined = undefined>(props: import("./types.js").AreaProps<D>) => import("../types.js").Options;
29
31
  };
30
- export declare const barChart: (<D extends Input | undefined = undefined>(el: HTMLElement, props: BarProps<D>) => ChartOf<"bar", D>) & {
31
- spec: <D extends Input | undefined = undefined>(props: BarProps<D>) => Options;
32
+ export declare const barChart: (<D extends import("./types.js").Input | undefined = undefined>(el: HTMLElement, props: import("./types.js").BarProps<D>) => [D] extends [readonly never[] | undefined] ? Omit<import("./controller.js").EasyChart<never>, "update"> & {
33
+ update<D_1 extends import("./types.js").Input | undefined = undefined>(props: Partial<import("./types.js").BarProps<D_1>> & {
34
+ data?: D_1 | null | undefined;
35
+ }): void;
36
+ } : import("./controller.js").EasyChart<import("./types.js").BarProps<D>>) & {
37
+ spec: <D extends import("./types.js").Input | undefined = undefined>(props: import("./types.js").BarProps<D>) => import("../types.js").Options;
32
38
  };
33
- export declare const scatterChart: (<D extends Input | undefined = undefined>(el: HTMLElement, props: ScatterProps<D>) => ChartOf<"scatter", D>) & {
34
- spec: <D extends Input | undefined = undefined>(props: ScatterProps<D>) => Options;
39
+ export declare const scatterChart: (<D extends import("./types.js").Input | undefined = undefined>(el: HTMLElement, props: ScatterProps<D>) => [D] extends [readonly never[] | undefined] ? Omit<import("./controller.js").EasyChart<never>, "update"> & {
40
+ update<D_1 extends import("./types.js").Input | undefined = undefined>(props: Partial<ScatterProps<D_1>> & {
41
+ data?: D_1 | null | undefined;
42
+ }): void;
43
+ } : import("./controller.js").EasyChart<ScatterProps<D>>) & {
44
+ spec: <D extends import("./types.js").Input | undefined = undefined>(props: ScatterProps<D>) => import("../types.js").Options;
35
45
  };
36
46
  export {};
package/dist/charts/xy.js CHANGED
@@ -1,26 +1,30 @@
1
- import { animate } from '../features/animate.js';
2
- import { legend } from '../features/legend.js';
3
- import { tooltip } from '../features/tooltip.js';
4
- import { zoom } from '../features/zoom.js';
1
+ import { brush } from '../features/brush.js';
5
2
  import { area } from '../marks/area.js';
6
3
  import { bar } from '../marks/bar.js';
4
+ import { upTo } from '../marks/common.js';
7
5
  import { dots } from '../marks/dots.js';
6
+ import { errorBars } from '../marks/errorBars.js';
8
7
  import { line } from '../marks/line.js';
8
+ import { rule, zone } from '../marks/rule.js';
9
+ import { ticks } from '../marks/ticks.js';
9
10
  import { band } from '../scales/band.js';
10
- import { time } from '../scales/time.js';
11
- import { dark, light } from '../theme.js';
12
- import { create, PASSED } from './controller.js';
13
- import { bandTitle, colorsFor, formatNumber, timeTitle } from './defaults.js';
14
- import { assign } from './fields.js';
11
+ import { log } from '../scales/log.js';
12
+ import { bands } from '../transforms.js';
13
+ import { dates, defined, easyChart, featuresOf, install, linear, on, sizeOf } from './build.js';
14
+ import { bandTitle, colorsFor, DAY, formatNumber, namesOf, spacing, timeTitle } from './defaults.js';
15
+ import { assign, list } from './fields.js';
15
16
  import { source } from './source.js';
16
- const defined = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
17
- const on = (v) => (v === true ? {} : v || false);
18
17
  const ascending = (x) => {
19
18
  for (let i = 1; i < x.length; i++)
20
19
  if (x[i] < x[i - 1])
21
20
  return false;
22
21
  return true;
23
22
  };
23
+ const columns = (s, cut) => ({
24
+ y: cut(s.y),
25
+ ...(s.low && { low: cut(s.low) }),
26
+ ...(s.high && { high: cut(s.high) }),
27
+ });
24
28
  /** Line and area need ascending x; equal x keep their order. */
25
29
  function sorted(ys) {
26
30
  const orders = new Map();
@@ -36,17 +40,21 @@ function sorted(ys) {
36
40
  return s;
37
41
  if (!xs.has(s.x))
38
42
  xs.set(s.x, Float64Array.from(o, i => s.x[i]));
39
- return { ...s, x: xs.get(s.x), y: Float64Array.from(o, i => s.y[i]) };
43
+ return { ...s, x: xs.get(s.x), ...columns(s, c => Float64Array.from(o, i => c[i])) };
40
44
  });
41
45
  }
42
- /** Each series' y at the slot of its x in order, NaN where it has no row, the last row winning. */
46
+ /** Each series' values at the slot of its x in order, NaN where it has no row, the last row winning. */
43
47
  function laid(ys, order, x) {
44
48
  const at = new Map(Array.from(order, (v, i) => [v, i]));
45
49
  return ys.map(s => {
46
- const y = new Float64Array(order.length).fill(Number.NaN);
47
- for (let i = 0; i < s.x.length; i++)
48
- y[at.get(s.x[i])] = s.y[i];
49
- return { ...s, x, y };
50
+ const slots = Array.from(s.x, v => at.get(v));
51
+ const lay = (c) => {
52
+ const out = new Float64Array(order.length).fill(Number.NaN);
53
+ for (let i = 0; i < slots.length; i++)
54
+ out[slots[i]] = c[i];
55
+ return out;
56
+ };
57
+ return { ...s, x, ...columns(s, lay) };
50
58
  });
51
59
  }
52
60
  /** The core stacks row by row, so long series are laid over the sorted union of their x. */
@@ -56,164 +64,357 @@ function aligned(ys) {
56
64
  }
57
65
  /** Wide data is one category per row; long data one per distinct x in order of first appearance, the last row winning. */
58
66
  function categorical({ x: ax, ys, order: seen }, utc, long) {
59
- const name = ax.kind === 'text'
60
- ? (v) => ax.categories[v]
61
- : ax.kind === 'time'
62
- ? timeTitle(ys.map(s => s.x), utc)
63
- : String;
67
+ const name = namesOf(ax.kind, ax.categories, ys.map(s => s.x), utc);
64
68
  if (!long) {
65
69
  const xs = ys[0]?.x ?? [];
66
70
  const index = Float64Array.from(xs, (_, i) => i);
67
- return { categories: Array.from(xs, name), ys: ys.map(s => ({ ...s, x: index })) };
71
+ return { categories: Array.from(xs, name), ys: ys.map(s => ({ ...s, x: index })), slots: xs };
68
72
  }
69
73
  const order = seen ?? [];
70
74
  return {
75
+ slots: order,
71
76
  categories: order.map(name),
72
77
  ys: laid(ys, order, Float64Array.from(order, (_, i) => i)),
73
78
  };
74
79
  }
80
+ /** A series with the rows left out put back as missing, so that its rows are those of the data again. */
81
+ function whole(s, rows, length) {
82
+ if (!rows)
83
+ return s;
84
+ // A row without a y draws nothing; its x stays finite, as bars on WebGL measure from the first one.
85
+ const x = new Float64Array(length).fill(s.x[0] ?? Number.NaN);
86
+ const y = new Float64Array(length).fill(Number.NaN);
87
+ rows.forEach((row, i) => {
88
+ x[row] = s.x[i];
89
+ y[row] = s.y[i];
90
+ });
91
+ return { x, y };
92
+ }
93
+ function overlays(p, name, theme, y, xAt, onBand) {
94
+ const neither = (what) => {
95
+ throw new Error(`${name}: ${what} takes x or y`);
96
+ };
97
+ const yAt = (v) => (y.to ? y.to(v, y) : v);
98
+ const edge = (v) => (y.to && v <= 0 ? -Infinity : yAt(v));
99
+ return {
100
+ under: (p.zones ?? []).map((z, i) => {
101
+ const o = { key: `zone:${i}`, text: z.text, color: z.color ?? theme.muted };
102
+ if (z.x) {
103
+ const [a, b] = [xAt(z.x[0]), xAt(z.x[1])];
104
+ const half = onBand ? 0.5 : 0;
105
+ return zone(defined({ ...o, x1: Math.min(a, b) - half, x2: Math.max(a, b) + half }));
106
+ }
107
+ if (z.y)
108
+ return zone(defined({ ...o, y1: edge(z.y[0]), y2: edge(z.y[1]) }));
109
+ return neither(`zones[${i}]`);
110
+ }),
111
+ over: (p.rules ?? []).map((r, i) => {
112
+ const o = { key: `rule:${i}`, text: r.text, dashed: r.dashed, color: r.color ?? theme.text };
113
+ if (r.x !== undefined)
114
+ return rule(defined({ ...o, x: xAt(r.x) }));
115
+ if (r.y !== undefined)
116
+ return rule(defined({ ...o, y: yAt(r.y) }));
117
+ return neither(`rules[${i}]`);
118
+ }),
119
+ };
120
+ }
121
+ /** Error bars that stand where bar() puts the dodged bars of the same series. */
122
+ const dodged = (o) => ({
123
+ ...errorBars(o),
124
+ arrange: {
125
+ key: 'errorBars:dodge',
126
+ lay: members => members.map(({ options }, slot) => {
127
+ const own = options;
128
+ const [from, to] = bands(own.x, { slot, of: members.length });
129
+ return errorBars({ ...own, x: from.map((v, i) => (v + to[i]) / 2) });
130
+ }),
131
+ },
132
+ });
133
+ /** The row whose x is nearest, the last of equal ones; -1 where there is none. x ascends. */
134
+ function nearest(x, v) {
135
+ const after = upTo(x, v);
136
+ const next = x[after];
137
+ if (next === undefined)
138
+ return after - 1;
139
+ return after && v - x[after - 1] <= next - v ? after - 1 : upTo(x, next) - 1;
140
+ }
141
+ /** Bars that answer an x with the value of their nearest row; the columns are theirs with x ascending. */
142
+ function sampled(m, { x, y }) {
143
+ const { arrange } = m;
144
+ return {
145
+ ...m,
146
+ sampleAtX: v => {
147
+ const at = y[nearest(x, v)];
148
+ return Number.isFinite(at) ? at : undefined;
149
+ },
150
+ ...(arrange && {
151
+ arrange: {
152
+ ...arrange,
153
+ lay: members => arrange.lay(members).map((d, i) => ({ ...d, sampleAtX: v => members[i].sampleAtX(v) })),
154
+ },
155
+ }),
156
+ };
157
+ }
75
158
  export function xy(name, kind = 'line') {
76
159
  return (p, { source: s, theme, memo }) => {
77
160
  const utc = kind === 'bar' || (p.xAxis?.utc ?? true);
78
161
  const scatter = kind === 'scatter';
79
162
  const rField = typeof p.r === 'number' ? undefined : p.r;
80
- const assigned = memo('fields', [s, p.x, ...[p.y ?? []].flat(), p.series, rField, utc], () => assign(s, { ...p, xAxis: { utc } }, scatter ? 'scatter' : 'xy', name, kind === 'bar'));
163
+ const ticked = scatter && p.shape === 'tick';
164
+ for (const [prop, on] of [
165
+ ['a field of r', rField !== undefined],
166
+ ['ring', p.ring !== undefined],
167
+ ])
168
+ if (ticked && on)
169
+ throw new Error(`${name}: ${prop} does not apply to shape 'tick'`);
170
+ const barred = (i) => kind === 'bar' || !!p.barred?.[i];
171
+ const combo = kind === 'combo';
172
+ const spread = kind === 'area' ? undefined : p.errorBars;
173
+ const assigned = memo('fields', [s, p.x, ...list(p.y), p.series, rField, utc, spread?.low, spread?.high, spread?.axis, ...list(p.y2)], () => assign(s, { ...p, errorBars: spread, xAxis: { utc } }, scatter ? 'scatter' : 'xy', name, kind === 'bar'));
81
174
  const stacked = kind !== 'line' && !scatter && !!p.stack;
82
- const bars = kind === 'bar'
175
+ if (spread && stacked && assigned.ys.length > 1)
176
+ throw new Error(`${name}: errorBars do not apply to stacked bars. Leave out stack or errorBars.`);
177
+ if (stacked && new Set(assigned.ys.filter((_, i) => barred(i)).map(r => r.yAxis)).size > 1)
178
+ throw new Error(`${name}: stack does not apply to bars on both y and y2. Leave out stack or ${kind === 'bar' ? 'y2' : 'y2Bars'}.`);
179
+ const bars = kind === 'bar' || (combo && assigned.x.kind === 'text')
83
180
  ? memo('bars', [assigned], () => categorical(assigned, utc, p.series !== undefined))
84
181
  : undefined;
85
- const ys = bars?.ys ??
182
+ const placed = bars?.ys ??
86
183
  (scatter ? assigned.ys : undefined) ??
87
184
  memo('sorted', [assigned, stacked], () => stacked && p.series !== undefined ? aligned(assigned.ys) : sorted(assigned.ys));
88
185
  const { x: ax, y: ay } = assigned;
89
- const xa = p.xAxis ?? {};
186
+ const room = p.barred?.includes(true) && !bars
187
+ ? memo('spacing', [placed], () => spacing(placed[0]?.x ?? [], ax.kind === 'time' ? DAY : 1))
188
+ : undefined;
189
+ const given = p.xAxis ?? {};
190
+ const xa = room?.lone && !Array.isArray(given.domain) ? { ...given, domain: room.lone } : given;
90
191
  const ya = p.yAxis ?? {};
91
192
  const label = xa.label ?? ax.label;
92
- const categories = ax.categories ?? [];
93
- const x = bars
94
- ? band({ label, categories: bars.categories })
95
- : ax.kind === 'text'
96
- ? band({ label, categories })
97
- : ax.kind === 'time'
98
- ? time({
99
- label,
100
- utc,
101
- format: xa.format,
102
- fit: xa.fit,
103
- ...(Array.isArray(xa.domain) && { domain: xa.domain }),
104
- ...(xa.unit && { unit: xa.unit, every: xa.every }),
105
- })
106
- : defined({ domain: xa.domain ?? 'nice', label, step: xa.step, format: xa.format, fit: xa.fit });
107
- const y = defined({
108
- domain: ya.domain ?? 'nice',
109
- label: ya.label ?? ay.label,
110
- step: ya.step,
111
- format: ya.format,
112
- fit: ya.fit,
113
- });
193
+ const categories = bars?.categories ?? ax.categories ?? [];
194
+ const banded = !!bars || ax.kind === 'text';
195
+ const x = banded
196
+ ? band({ label, categories })
197
+ : ax.kind === 'time'
198
+ ? dates(xa, ax.label, utc)
199
+ : linear(xa, ax.label);
200
+ const scaled = (role, own) => {
201
+ const a = p[role];
202
+ if (a?.scale !== 'log')
203
+ return linear(a, own);
204
+ const owner = kind === 'area' ? 'area' : 'bar';
205
+ const onY = list(p.y).length;
206
+ const barsOn = role === 'yAxis' ? p.barred?.slice(0, onY) : p.barred?.slice(onY);
207
+ if (kind === 'area' || kind === 'bar' || barsOn?.includes(true))
208
+ throw new Error(`${name}: ${role}.scale 'log' does not apply, as ${owner}s start at zero, which it cannot show`);
209
+ if (a.step !== undefined)
210
+ throw new Error(`${name}: ${role}.step does not apply to a log scale`);
211
+ if (role === 'yAxis' && ay.categories)
212
+ throw new Error(`${name}: yAxis.scale 'log' does not apply to a text y`);
213
+ const { domain } = a;
214
+ if (Array.isArray(domain) && !domain.every(v => v > 0 && v < Infinity))
215
+ throw new Error(`${name}: ${role}.domain must be above zero and finite on a log scale`);
216
+ return log(defined({ label: a.label ?? own, domain, format: a.format, fit: a.fit }));
217
+ };
218
+ const numeric = scaled('yAxis', ay.label);
219
+ const y = ay.categories
220
+ ? band({ label: ya.label ?? ay.label, categories: ay.categories })
221
+ : numeric;
222
+ const y2 = assigned.y2 && scaled('y2Axis', assigned.y2.label);
223
+ const ys = memo('ys', [placed, !!y.col, !!y2?.col], () => placed.map(r => {
224
+ const a = r.yAxis ? y2 : y;
225
+ if (!a.col)
226
+ return r;
227
+ return assigned.lying ? { ...r, y: a.col(r.y) } : { ...r, ...columns(r, c => a.col(c)) };
228
+ }));
229
+ const xAt = (v) => {
230
+ const bySlot = (n, slots) => {
231
+ const i = Array.prototype.indexOf.call(slots, n);
232
+ return i < 0 ? Number.NaN : i;
233
+ };
234
+ if (typeof v === 'string' && ax.kind === 'text')
235
+ return bySlot(v, categories);
236
+ const c = source([{ v }]).column('v', { utc });
237
+ const at = c.kind === 'text' ? Number.NaN : c.values[0];
238
+ return bars ? bySlot(at, bars.slots) : at;
239
+ };
240
+ const { under, over } = overlays(p, name, theme, y, xAt, banded);
114
241
  const colors = colorsFor(theme, p.colors, ys.length);
115
242
  const radius = typeof p.r === 'number' ? p.r : 4;
116
- const radii = scatter
243
+ const radii = scatter && !ticked
117
244
  ? memo('radii', [ys, radius], () => ys.map(r => r.r ?? new Float64Array(r.x.length).fill(radius)))
118
245
  : undefined;
119
- const marks = memo('marks', [ys, stacked, p.curve, p.join, radii, ...colors], () => ys.map((r, i) => {
120
- if (scatter)
121
- return dots({ key: r.name, label: r.name, x: r.x, y: r.y, r: radii[i], color: colors[i] });
122
- const o = {
123
- key: r.name,
124
- label: r.name,
125
- x: r.x,
126
- y: r.y,
127
- color: colors[i],
128
- curve: p.curve,
129
- join: p.join,
130
- };
131
- if (kind === 'line')
132
- return line(o);
133
- if (kind === 'bar')
134
- return bar({
135
- key: r.name,
246
+ const { cap, width } = spread ?? {};
247
+ const deps = [
248
+ ys,
249
+ stacked,
250
+ p.curve,
251
+ p.join,
252
+ p.fill,
253
+ ticked ? radius : radii,
254
+ p.alpha,
255
+ p.ring,
256
+ p.shape,
257
+ cap,
258
+ width,
259
+ bars && theme.text,
260
+ room?.width,
261
+ ...colors,
262
+ ...ys.map((_, i) => barred(i)),
263
+ ];
264
+ const marks = memo('marks', deps, () => {
265
+ const drawn = ys.map((r, i) => {
266
+ if (scatter) {
267
+ const at = {
268
+ key: `series:${r.name}`,
269
+ label: r.name,
270
+ x: r.x,
271
+ y: r.y,
272
+ yAxis: r.yAxis,
273
+ color: colors[i],
274
+ alpha: p.alpha,
275
+ };
276
+ return ticked
277
+ ? ticks(defined({ ...at, size: radius }))
278
+ : dots(defined({ ...at, r: radii[i], ring: p.ring }));
279
+ }
280
+ const o = {
281
+ key: `series:${r.name}`,
136
282
  label: r.name,
137
283
  x: r.x,
138
284
  y: r.y,
139
285
  color: colors[i],
140
- ...(stacked ? { stack: 'stack' } : { dodge: 'dodge' }),
286
+ curve: p.curve,
287
+ join: p.join,
288
+ ...(r.yAxis && { yAxis: r.yAxis }),
289
+ };
290
+ if (barred(i)) {
291
+ // Clicks and `selected` number a bar by its row in the data.
292
+ const own = combo ? whole(bars ? r : assigned.ys[i], assigned.rows, s.length) : r;
293
+ const drawn = bar({
294
+ key: `series:${r.name}`,
295
+ label: r.name,
296
+ x: own.x,
297
+ y: own.y,
298
+ color: colors[i],
299
+ ...(r.yAxis && { yAxis: r.yAxis }),
300
+ ...(room && { width: room.width }),
301
+ ...(stacked ? { stack: 'stack' } : { dodge: 'dodge' }),
302
+ });
303
+ return combo ? sampled(drawn, r) : drawn;
304
+ }
305
+ if (combo || kind === 'line')
306
+ return line(defined({ ...o, fill: p.fill }));
307
+ return area(defined({
308
+ ...o,
309
+ stack: stacked ? 'stack' : undefined,
310
+ alpha: (!stacked || assigned.y2) && ys.length >= 2 ? 0.5 : undefined,
311
+ }));
312
+ });
313
+ const errors = ys.flatMap((r, i) => {
314
+ if (!r.low || !r.high)
315
+ return [];
316
+ const common = defined({
317
+ key: `errorBars:${r.name}`,
318
+ group: r.name,
319
+ color: bars ? theme.text : colors[i],
320
+ cap,
321
+ width,
141
322
  });
142
- return area(defined({
143
- ...o,
144
- stack: stacked ? 'stack' : undefined,
145
- alpha: !stacked && ys.length >= 2 ? 0.5 : undefined,
146
- }));
147
- }));
323
+ if (assigned.lying)
324
+ return [errorBars({ ...common, y: r.y, x1: r.low, x2: r.high })];
325
+ const o = { ...common, x: r.x, y1: r.low, y2: r.high };
326
+ return [bars && ys.length > 1 ? dodged(o) : errorBars(o)];
327
+ });
328
+ if (combo)
329
+ drawn.sort((a, b) => +(b.type === 'bar') - +(a.type === 'bar'));
330
+ return bars ? [...drawn, ...errors] : [...errors, ...drawn];
331
+ });
332
+ const titled = !bars && ax.kind === 'time' && p.tooltip !== false
333
+ ? memo('timeTitle', [ys, utc], () => timeTitle([...new Set(ys.map(r => r.x))], utc))
334
+ : formatNumber;
148
335
  const text = {
149
- x: (v) => (!bars && ax.kind !== 'text' && xa.format ? xa.format : text.title)(v),
150
- title: bars
151
- ? v => bandTitle(bars.categories, v)
152
- : ax.kind === 'text'
153
- ? v => bandTitle(categories, v)
154
- : ax.kind === 'time' && p.tooltip !== false
155
- ? memo('timeTitle', [ys, utc], () => timeTitle([...new Set(ys.map(r => r.x))], utc))
156
- : formatNumber,
157
- value: ya.format ?? formatNumber,
336
+ x: (v) => (!banded && xa.format ? xa.format : text.title)(v),
337
+ title: banded ? v => bandTitle(categories, v) : titled,
338
+ snap: v => {
339
+ const x = ys[0]?.x ?? [];
340
+ return x[nearest(x, v)] ?? v;
341
+ },
342
+ value: (v, axis, observed) => {
343
+ if (axis === 'y' && ay.categories)
344
+ return bandTitle(ay.categories, v);
345
+ const a = axis === 'y2' ? p.y2Axis : ya;
346
+ const format = a?.format ?? formatNumber;
347
+ if (a?.scale !== 'log')
348
+ return format(v);
349
+ const on = axis === 'y2' ? y2 : y;
350
+ // A value back from its logarithm is off by a few ulps, so a row's own value is looked up.
351
+ let best;
352
+ let least = Math.abs(v) * 1e-12;
353
+ for (const own of observed()) {
354
+ const off = Math.abs(on.from(on.to(own, on), on) - v);
355
+ if (off < least)
356
+ [best, least] = [own, off];
357
+ }
358
+ return format(best ?? +v.toPrecision(13));
359
+ },
360
+ around: (x, axis) => placed.flatMap(r => {
361
+ if ((r.yAxis ?? 'y') !== axis)
362
+ return [];
363
+ const after = upTo(r.x, x);
364
+ const rows = r.x[after - 1] === x ? [after - 1] : [after - 1, after];
365
+ return rows.flatMap(i => r.y[i] ?? []);
366
+ }),
367
+ at: (label, row) => {
368
+ const own = placed.find(r => r.name === label)?.y[row ?? -1];
369
+ return own === undefined ? [] : [own];
370
+ },
371
+ axis: label => ys.find(r => r.name === label)?.yAxis ?? 'y',
372
+ onBrush: p.onBrush,
158
373
  };
159
374
  const ref = memo('tooltip', [], () => ({}));
160
- const showLegend = p.legend !== false && ys.length >= 2;
161
- const features = {
162
- tooltip: p.tooltip !== false,
163
- legend: showLegend && (typeof p.legend === 'object' ? p.legend : {}),
164
- zoom: on(p.zoom),
165
- animate: on(p.animate),
166
- };
375
+ const features = { ...featuresOf(p, ys.length), brush: on(p.brush) };
167
376
  ref.current = text;
377
+ let shownX = Number.NaN;
378
+ const own = (label, v, row) => ref.current.value(v, ref.current.axis(label), () => ref.current.at(label, row));
168
379
  return {
169
380
  options: {
170
- ...defined({ width: p.width, height: p.height, margin: p.margin, description: p.description }),
381
+ ...sizeOf(p),
171
382
  theme,
172
383
  x,
173
384
  y,
174
- marks,
385
+ ...(y2 && { y2 }),
386
+ marks: under.length || over.length ? [...under, ...marks, ...over] : marks,
175
387
  },
176
388
  features,
177
389
  use: () => {
178
390
  ref.current = text;
179
- return [
180
- features.tooltip &&
181
- tooltip(scatter
182
- ? {
183
- mode: 'nearest',
184
- text: (label, x, y) => `${label}: ${ref.current.x(x)}, ${ref.current.value(y)}`,
185
- }
186
- : bars
187
- ? {
188
- mode: 'nearest',
189
- text: (label, _x, v, row) => `${ref.current.title(row)} · ${label}: ${ref.current.value(v)}`,
190
- }
191
- : { mode: 'x', title: v => ref.current.title(v), value: v => ref.current.value(v) }),
192
- features.legend && legend(features.legend),
193
- features.zoom && zoom(features.zoom),
194
- features.animate && animate(features.animate),
195
- ].filter((f) => !!f);
391
+ const drawn = install(features, scatter
392
+ ? {
393
+ mode: 'nearest',
394
+ text: (label, x, y, row) => `${label}: ${ref.current.x(x)}, ${own(label, y, row)}`,
395
+ }
396
+ : kind === 'bar'
397
+ ? {
398
+ mode: 'nearest',
399
+ text: (label, _x, v, row) => `${ref.current.title(row)} · ${label}: ${own(label, v)}`,
400
+ }
401
+ : {
402
+ mode: 'x',
403
+ ...(combo && { snap: (v) => ref.current.snap(v) }),
404
+ title: v => ref.current.title((shownX = v)),
405
+ value: (v, axis) => ref.current.value(v, axis, () => ref.current.around(shownX, axis)),
406
+ });
407
+ if (features.brush)
408
+ drawn.push(brush({
409
+ ...features.brush,
410
+ zoom: !!features.zoom,
411
+ onSelect: range => ref.current.onBrush?.(range),
412
+ }));
413
+ return drawn;
196
414
  },
197
415
  };
198
416
  };
199
417
  }
200
- const themeFor = (t) => t === 'light' ? light : t === 'dark' ? dark : t === 'auto' ? undefined : t;
201
- /** The options plot() would get, without an element: a theme of 'auto' gives no theme and the light palette. */
202
- function specOf(build, p) {
203
- const context = {
204
- source: source(p.data),
205
- theme: themeFor(p.theme),
206
- memo: (_name, _deps, make) => make(),
207
- };
208
- const b = build(p, context);
209
- const passed = Object.fromEntries([...PASSED].filter(k => p[k] !== undefined).map(k => [k, p[k]]));
210
- return defined({ ...b.options, ...passed, use: b.use() });
211
- }
212
- function easyChart(build) {
213
- return Object.assign((el, props) => create(el, props, build), {
214
- spec: (props) => specOf(build, props),
215
- });
216
- }
217
418
  export const lineChart = easyChart(xy('lineChart'));
218
419
  export const areaChart = easyChart(xy('areaChart', 'area'));
219
420
  export const barChart = easyChart(xy('barChart', 'bar'));
@@ -1,6 +1,6 @@
1
1
  import type { Feature } from '../types.js';
2
2
  export type AnimateOptions = {
3
- /** Milliseconds; nothing animates when it is 0 or not finite. */
3
+ /** Milliseconds; nothing animates when it is 0 or not finite. @default 300 */
4
4
  duration?: number;
5
5
  /**
6
6
  * How marks appear on the first paint: uncovered (the default), from the left, from the top where a
@@ -8,4 +8,13 @@ export type AnimateOptions = {
8
8
  */
9
9
  enter?: 'reveal' | 'fade';
10
10
  };
11
+ /**
12
+ * Marks are uncovered (or fade in) on the first paint. When the data changes they
13
+ * move to their new shape if every changed mark can (bars, row for row) and cross-fade otherwise.
14
+ * The entrance and the cross-fade blend two pictures of the chart, so a frame costs the same
15
+ * whatever the data size; a move repaints the chart each frame.
16
+ * Nothing animates for a resize or a focus change, with reduced motion, in a hidden tab, or
17
+ * while updates arrive less than `duration` ms apart.
18
+ * ponytail: marks on WebGL take part in the entrance, but swap at once when the data changes.
19
+ */
11
20
  export declare function animate({ duration, enter }?: AnimateOptions): Feature;