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,46 @@
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> & {
5
+ data?: unknown;
6
+ curve?: LineProps<undefined>['curve'];
7
+ join?: boolean;
8
+ fill?: LineProps<undefined>['fill'];
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[];
16
+ };
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
+ }): 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;
24
+ };
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;
31
+ };
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;
38
+ };
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;
45
+ };
46
+ export {};
@@ -0,0 +1,421 @@
1
+ import { brush } from '../features/brush.js';
2
+ import { area } from '../marks/area.js';
3
+ import { bar } from '../marks/bar.js';
4
+ import { upTo } from '../marks/common.js';
5
+ import { dots } from '../marks/dots.js';
6
+ import { errorBars } from '../marks/errorBars.js';
7
+ import { line } from '../marks/line.js';
8
+ import { rule, zone } from '../marks/rule.js';
9
+ import { ticks } from '../marks/ticks.js';
10
+ import { band } from '../scales/band.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';
16
+ import { source } from './source.js';
17
+ const ascending = (x) => {
18
+ for (let i = 1; i < x.length; i++)
19
+ if (x[i] < x[i - 1])
20
+ return false;
21
+ return true;
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
+ });
28
+ /** Line and area need ascending x; equal x keep their order. */
29
+ function sorted(ys) {
30
+ const orders = new Map();
31
+ const order = (x) => {
32
+ if (!orders.has(x))
33
+ orders.set(x, ascending(x) ? undefined : Array.from(x, (_, i) => i).sort((a, b) => x[a] - x[b] || a - b));
34
+ return orders.get(x);
35
+ };
36
+ const xs = new Map();
37
+ return ys.map(s => {
38
+ const o = order(s.x);
39
+ if (!o)
40
+ return s;
41
+ if (!xs.has(s.x))
42
+ xs.set(s.x, Float64Array.from(o, i => s.x[i]));
43
+ return { ...s, x: xs.get(s.x), ...columns(s, c => Float64Array.from(o, i => c[i])) };
44
+ });
45
+ }
46
+ /** Each series' values at the slot of its x in order, NaN where it has no row, the last row winning. */
47
+ function laid(ys, order, x) {
48
+ const at = new Map(Array.from(order, (v, i) => [v, i]));
49
+ return ys.map(s => {
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) };
58
+ });
59
+ }
60
+ /** The core stacks row by row, so long series are laid over the sorted union of their x. */
61
+ function aligned(ys) {
62
+ const x = Float64Array.from(new Set(ys.flatMap(s => Array.from(s.x)))).sort();
63
+ return laid(ys, x, x);
64
+ }
65
+ /** Wide data is one category per row; long data one per distinct x in order of first appearance, the last row winning. */
66
+ function categorical({ x: ax, ys, order: seen }, utc, long) {
67
+ const name = namesOf(ax.kind, ax.categories, ys.map(s => s.x), utc);
68
+ if (!long) {
69
+ const xs = ys[0]?.x ?? [];
70
+ const index = Float64Array.from(xs, (_, i) => i);
71
+ return { categories: Array.from(xs, name), ys: ys.map(s => ({ ...s, x: index })), slots: xs };
72
+ }
73
+ const order = seen ?? [];
74
+ return {
75
+ slots: order,
76
+ categories: order.map(name),
77
+ ys: laid(ys, order, Float64Array.from(order, (_, i) => i)),
78
+ };
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
+ }
158
+ export function xy(name, kind = 'line') {
159
+ return (p, { source: s, theme, memo }) => {
160
+ const utc = kind === 'bar' || (p.xAxis?.utc ?? true);
161
+ const scatter = kind === 'scatter';
162
+ const rField = typeof p.r === 'number' ? undefined : p.r;
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'));
174
+ const stacked = kind !== 'line' && !scatter && !!p.stack;
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')
180
+ ? memo('bars', [assigned], () => categorical(assigned, utc, p.series !== undefined))
181
+ : undefined;
182
+ const placed = bars?.ys ??
183
+ (scatter ? assigned.ys : undefined) ??
184
+ memo('sorted', [assigned, stacked], () => stacked && p.series !== undefined ? aligned(assigned.ys) : sorted(assigned.ys));
185
+ const { x: ax, y: ay } = assigned;
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;
191
+ const ya = p.yAxis ?? {};
192
+ const label = xa.label ?? ax.label;
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);
241
+ const colors = colorsFor(theme, p.colors, ys.length);
242
+ const radius = typeof p.r === 'number' ? p.r : 4;
243
+ const radii = scatter && !ticked
244
+ ? memo('radii', [ys, radius], () => ys.map(r => r.r ?? new Float64Array(r.x.length).fill(radius)))
245
+ : undefined;
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}`,
282
+ label: r.name,
283
+ x: r.x,
284
+ y: r.y,
285
+ color: colors[i],
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,
322
+ });
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;
335
+ const text = {
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,
373
+ };
374
+ const ref = memo('tooltip', [], () => ({}));
375
+ const features = { ...featuresOf(p, ys.length), brush: on(p.brush) };
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));
379
+ return {
380
+ options: {
381
+ ...sizeOf(p),
382
+ theme,
383
+ x,
384
+ y,
385
+ ...(y2 && { y2 }),
386
+ marks: under.length || over.length ? [...under, ...marks, ...over] : marks,
387
+ },
388
+ features,
389
+ use: () => {
390
+ ref.current = text;
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;
414
+ },
415
+ };
416
+ };
417
+ }
418
+ export const lineChart = easyChart(xy('lineChart'));
419
+ export const areaChart = easyChart(xy('areaChart', 'area'));
420
+ export const barChart = easyChart(xy('barChart', 'bar'));
421
+ export const scatterChart = easyChart(xy('scatterChart', 'scatter'));
@@ -0,0 +1,20 @@
1
+ import type { Feature } from '../types.js';
2
+ export type AnimateOptions = {
3
+ /** Milliseconds; nothing animates when it is 0 or not finite. @default 300 */
4
+ duration?: number;
5
+ /**
6
+ * How marks appear on the first paint: uncovered (the default), from the left, from the top where a
7
+ * mark asks for it, or round the clock in a polar frame; or all at once from transparent.
8
+ */
9
+ enter?: 'reveal' | 'fade';
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
+ */
20
+ export declare function animate({ duration, enter }?: AnimateOptions): Feature;
@@ -0,0 +1,118 @@
1
+ // A move falls back to the cross-fade when one repaint of the chart takes longer than this, in ms.
2
+ const REPAINT_BUDGET = 6;
3
+ /**
4
+ * Marks are uncovered (or fade in) on the first paint. When the data changes they
5
+ * move to their new shape if every changed mark can (bars, row for row) and cross-fade otherwise.
6
+ * The entrance and the cross-fade blend two pictures of the chart, so a frame costs the same
7
+ * whatever the data size; a move repaints the chart each frame.
8
+ * Nothing animates for a resize or a focus change, with reduced motion, in a hidden tab, or
9
+ * while updates arrive less than `duration` ms apart.
10
+ * ponytail: marks on WebGL take part in the entrance, but swap at once when the data changes.
11
+ */
12
+ export function animate({ duration = 300, enter = 'reveal' } = {}) {
13
+ if (!Number.isFinite(duration) || duration <= 0)
14
+ return () => ({ destroy() { } });
15
+ return chart => {
16
+ const { canvas } = chart;
17
+ const motion = matchMedia('(prefers-reduced-motion: reduce)');
18
+ const ctx = canvas.getContext('2d');
19
+ const from = new OffscreenCanvas(0, 0);
20
+ const to = new OffscreenCanvas(0, 0);
21
+ let frame = 0;
22
+ let last = -Infinity;
23
+ let entered = false;
24
+ let entering = false;
25
+ let shown;
26
+ const keep = (picture) => {
27
+ picture.width = canvas.width;
28
+ picture.height = canvas.height;
29
+ picture.getContext('2d').drawImage(canvas, 0, 0);
30
+ };
31
+ const stop = () => {
32
+ cancelAnimationFrame(frame);
33
+ frame = 0;
34
+ entering = false;
35
+ shown = undefined;
36
+ from.width = to.width = 0;
37
+ chart.morph(1);
38
+ };
39
+ const run = (step, drawn = false) => {
40
+ const start = performance.now();
41
+ const show = (e) => {
42
+ step(e);
43
+ shown = () => step(e);
44
+ };
45
+ const tick = (now) => {
46
+ const t = motion.matches ? 1 : Math.min(1, Math.max(0, (now - start) / duration));
47
+ show(1 - (1 - t) ** 3);
48
+ if (t < 1)
49
+ frame = requestAnimationFrame(tick);
50
+ else
51
+ stop();
52
+ };
53
+ if (!drawn)
54
+ show(0);
55
+ frame = requestAnimationFrame(tick);
56
+ };
57
+ // 'copy' replaces the canvas with what is drawn, so the pictures need no clearing first.
58
+ const blend = (mix) => (t) => {
59
+ ctx.save();
60
+ ctx.globalCompositeOperation = 'copy';
61
+ mix(t);
62
+ ctx.restore();
63
+ };
64
+ // Additive, so a pixel that is the same in both pictures keeps its value throughout.
65
+ const fade = blend(t => {
66
+ ctx.globalAlpha = 1 - t;
67
+ ctx.drawImage(from, 0, 0);
68
+ ctx.globalCompositeOperation = 'lighter';
69
+ ctx.globalAlpha = t;
70
+ ctx.drawImage(to, 0, 0);
71
+ });
72
+ // The chart says what a reveal has uncovered; here it becomes the clip for the canvas.
73
+ const reveal = blend(t => {
74
+ const scale = canvas.width / chart.size().width;
75
+ ctx.drawImage(from, 0, 0);
76
+ ctx.beginPath();
77
+ for (const [x, y] of chart.revealed(t))
78
+ ctx.lineTo(x * scale, y * scale);
79
+ ctx.clip();
80
+ ctx.drawImage(to, 0, 0);
81
+ });
82
+ chart.onPaint((draw, why) => {
83
+ // A focus change lands while the entrance runs: it goes into both pictures, which may have a new layout.
84
+ if (why === 'focus' && entering && shown) {
85
+ draw(0);
86
+ keep(from);
87
+ draw();
88
+ keep(to);
89
+ return shown();
90
+ }
91
+ const now = performance.now();
92
+ const still = why !== 'data' || frame !== 0 || now - last < duration || document.hidden || motion.matches;
93
+ stop();
94
+ if (why === 'data')
95
+ last = now;
96
+ const first = !entered;
97
+ entered = true;
98
+ if (still)
99
+ return draw();
100
+ if (first)
101
+ draw(0);
102
+ keep(from);
103
+ if (!first && chart.morph(0)) {
104
+ draw();
105
+ if (performance.now() - now < REPAINT_BUDGET)
106
+ return run(t => (chart.morph(t), draw()), true);
107
+ chart.morph(1);
108
+ }
109
+ draw();
110
+ keep(to);
111
+ if (!first)
112
+ return run(fade);
113
+ entering = true;
114
+ run(enter === 'fade' ? t => (chart.reveal(1, t), fade(t)) : t => (chart.reveal(t), reveal(t)));
115
+ });
116
+ return { destroy: stop };
117
+ };
118
+ }
@@ -0,0 +1,15 @@
1
+ import type { Feature, Span } from '../types.js';
2
+ /** A drag over the plot marks out a range on x, y or both, which is reported on release and, with `zoom`, shown. */
3
+ export type BrushOptions = {
4
+ /** 'x' when left out: the rectangle spans the plot's height and the range its whole y window. */
5
+ axes?: 'x' | 'y' | 'xy';
6
+ /** Show the range brushed once it is reported, on the brushed axes, and drop the rectangle. */
7
+ zoom?: boolean;
8
+ /** The range brushed, in axis values, on release, with y2 when the chart has a second axis; null once a range reported is cleared. */
9
+ onSelect?(range: {
10
+ x: Span;
11
+ y: Span;
12
+ y2?: Span;
13
+ } | null): void;
14
+ };
15
+ export declare function brush(b?: BrushOptions): Feature;