swiftplot 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -5
- package/dist/chart.js +295 -29
- package/dist/charts/controller.d.ts +3 -4
- package/dist/charts/controller.js +74 -24
- package/dist/charts/index.d.ts +1 -1
- package/dist/charts/index.js +1 -1
- package/dist/charts/mount.js +3 -0
- package/dist/charts/types.d.ts +4 -0
- package/dist/color.d.ts +12 -0
- package/dist/color.js +61 -0
- package/dist/equal.d.ts +20 -0
- package/dist/equal.js +106 -0
- package/dist/features/legend.js +8 -7
- package/dist/features/pointer.d.ts +18 -1
- package/dist/features/pointer.js +19 -1
- package/dist/features/tooltip.js +14 -7
- package/dist/features/zoom.js +2 -2
- package/dist/gl.d.ts +2 -0
- package/dist/gl.js +8 -1
- package/dist/marks/sankey.js +3 -3
- package/dist/types.d.ts +63 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -25,7 +25,7 @@ chart.update({ data: next }); // only what changed reaches the chart
|
|
|
25
25
|
chart.destroy();
|
|
26
26
|
```
|
|
27
27
|
|
|
28
|
-
- **Charts:** `lineChart`, `areaChart`, `barChart`, `scatterChart`, `comboChart`, `pieChart`, `funnelChart`, `radialBarChart`, `radarChart`, `heatmapChart`, `histogramChart`, `boxPlotChart`, `candlestickChart`, `sankeyChart`, `treemapChart` and `sunburstChart`. Each returns `{ update(props), destroy(), chart }`; `update` takes only the props that change, and `chart` is the underlying chart.
|
|
28
|
+
- **Charts:** `lineChart`, `areaChart`, `barChart`, `scatterChart`, `comboChart`, `pieChart`, `funnelChart`, `radialBarChart`, `radarChart`, `heatmapChart`, `histogramChart`, `boxPlotChart`, `candlestickChart`, `sankeyChart`, `treemapChart` and `sunburstChart`. Each returns `{ update(props), destroy(), overlay, chart }`; `update` takes only the props that change, `overlay` is the element for your own DOM (see "Drawing over the chart" under "Use"), and `chart` is the underlying chart.
|
|
29
29
|
- **Data** is row objects, an object of columns (arrays or typed arrays, all of one length), a plain number array (`y` against its index, as the series `value`), or `[x, y]` pairs (the series `y`; a row of any other length throws), and for `treemapChart` and `sunburstChart` a nested `{ name, value, children }` or a list of them. Pairs are `[label, value]` on a pie, a funnel and radial bars, `[name, value]` on a radar and `[group, value]` on a box plot; a histogram takes no pairs, and a heatmap, candlesticks, a combo and a sankey take neither pairs nor numbers. On the line, area, bar and scatter charts long rows, `{ date, service, value }`, take `series: 'service'` and give one series per distinct value. `data` missing, `null` or empty draws an empty frame and never throws, so a chart can be created before its data arrives.
|
|
30
30
|
- **Values:** a number, a `Date`, an ISO 8601 string (`2026-11-22`, `2026-11-22T10:00` or with a space, optional seconds and fraction, and `Z` or `+02:00` after a time) or other text. A field's first value that is not missing (`null`, `undefined`, `''`, `NaN`, an infinite number) decides its kind; later values of another kind, an invalid `Date` and an impossible date (`2026-13-40`, `T24:00`) are missing. Numbers held as text (`"12.5"`) are text and are not converted. A field of booleans or objects cannot be plotted.
|
|
31
31
|
- **Dates** without a zone are read as UTC, so the same data draws the same chart on every machine; `xAxis: { utc: false }` reads them, and shows the axis, in local time.
|
|
@@ -78,11 +78,11 @@ chart.destroy();
|
|
|
78
78
|
|
|
79
79
|
- **Marks added to a chart:** line, area, bar, scatter and combo charts take `rules` (`{ x }` or `{ y }`, with `text`, `dashed` and `color`), `zones` (`{ x: [from, to] }` or `{ y: [from, to] }`, with `text` and `color`) and `brush` (`true` or `{ axes }`; with `zoom` its release shows the range), whose range goes to `onBrush`. `errorBars: { low, high, cap, width }` on line, bar and scatter charts names two fields that are values on the y axis, not distances from y, for a chart of one unstacked `y`. A line takes `fill` (`true` or a gradient) and a scatter `alpha`, `ring` and `shape: 'tick'`.
|
|
80
80
|
- **Stacking** counts a missing value as zero, so a stacked area has no gap where an unstacked one would. Long series are stacked over the union of their x values.
|
|
81
|
-
- **Interaction state** (`view`, `hidden`, `selected`, `pointer`) is kept by the chart unless the prop is given; `onViewChange`, `onHiddenChange`, `onClick` and `onPointerChange` report it as in the explicit API. Changing `tooltip`, `legend`, `zoom`, `animate` or `brush` creates the chart again and keeps a zoomed window and hidden series.
|
|
81
|
+
- **Interaction state** (`view`, `hidden`, `selected`, `pointer`) is kept by the chart unless the prop is given; `onViewChange`, `onHiddenChange`, `onClick` and `onPointerChange` report it, and `onLayout` and `onHover` the geometry and the hover, as in the explicit API. Changing `tooltip`, `legend`, `zoom`, `animate` or `brush` creates the chart again and keeps a zoomed window and hidden series.
|
|
82
82
|
- **`dataVersion`:** conversion is cached on the data's identity and length (each column's, for an object of columns). Pass new data, or after changing values in place, bump `dataVersion`: `chart.update({ dataVersion: ++version })`.
|
|
83
83
|
- **Theme:** `theme` defaults to `'auto'`, which follows the computed CSS `color-scheme` of the chart's element: `dark` gives the dark theme, `light dark` follows the system setting and switches with it, anything else gives light. It is read when the chart is created, when the system setting changes and when the `theme` prop changes.
|
|
84
84
|
- **`.spec()`** is the way out to the explicit API: `lineChart.spec({ data: rows, x: 'date', y: ['api', 'web'] })` returns the `plot()` options the chart would use. It needs no element and runs in Node; with the `'auto'` theme it gives no theme and the light palette.
|
|
85
|
-
- **`mount(el, options)`** is `plot()` behind the same controller, for the explicit API in plain JavaScript: it takes the `plot()` options and returns `{ update(options), destroy(), chart }`. An update sends the core only the options that changed (marks compared by key, type and options), and leaves `view`, `hidden`, `selected` and `pointer` alone unless given. `use` is read once; `theme` is `light` unless given. `equal(a, b)`, which mount uses for that comparison, compares plain objects and arrays by value (cycles included) and anything else (typed arrays, functions, `Date`s) by identity; `plain(v)` tells whether `v` is a plain object or array.
|
|
85
|
+
- **`mount(el, options)`** is `plot()` behind the same controller, for the explicit API in plain JavaScript: it takes the `plot()` options and returns `{ update(options), destroy(), overlay, chart }`. An update sends the core only the options that changed (marks compared by key, type and options, and `theme` by identity, so a new theme object has the CSS variables read again), and leaves `view`, `hidden`, `selected` and `pointer` alone unless given. `use` is read once; `theme` is `light` unless given. `equal(a, b)`, which mount uses for that comparison, compares plain objects and arrays by value (cycles included) and anything else (typed arrays, functions, `Date`s) by identity; `plain(v)` tells whether `v` is a plain object or array.
|
|
86
86
|
|
|
87
87
|
## React and Vue
|
|
88
88
|
|
|
@@ -116,7 +116,23 @@ import { LineChart } from '@swiftplot/vue';
|
|
|
116
116
|
<LineChart data={rows} x="date" y={['api', 'web']} zoom view={view} onViewChange={setView} />;
|
|
117
117
|
```
|
|
118
118
|
|
|
119
|
-
In Vue the changes are events: `v-model:view`, `v-model:hidden` and `v-model:pointer`, `@click`, `@brush` and `@error` (`<LineChart :data="rows" zoom v-model:view="view" />`). `selected` is a plain prop: the app sets it, from a click for example.
|
|
119
|
+
In Vue the changes are events: `v-model:view`, `v-model:hidden` and `v-model:pointer`, `@click`, `@layout`, `@hover`, `@brush` and `@error` (`<LineChart :data="rows" zoom v-model:view="view" />`). `selected` is a plain prop: the app sets it, from a click for example.
|
|
120
|
+
|
|
121
|
+
- **Your own nodes over the chart:** every component renders them from the layout and the hover, in React from a function given as children, in Vue from the default slot. They are drawn with the layout the chart has taken. While an update fails React keeps the last good children, and Vue hides a slot whose hover or layout changed. `layout.xPx` and `layout.yPx` are there only with axes.
|
|
122
|
+
|
|
123
|
+
```tsx
|
|
124
|
+
<ScatterChart data={rows} tooltip={false}>
|
|
125
|
+
{(layout, hover) =>
|
|
126
|
+
hover?.hit && <Tip style={{ position: 'absolute', left: hover.hit.px, top: hover.hit.py }} />
|
|
127
|
+
}
|
|
128
|
+
</ScatterChart>
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
```vue
|
|
132
|
+
<ScatterChart :data="rows" :tooltip="false" v-slot="{ layout, hover }">
|
|
133
|
+
<Tip v-if="hover?.hit" :hit="hover.hit" />
|
|
134
|
+
</ScatterChart>
|
|
135
|
+
```
|
|
120
136
|
|
|
121
137
|
- **`Plot`** takes every `plot()` option as a prop, to mix marks in a way no easy chart does, for a mark of your own, or to pass large typed arrays straight in. `use` is read when it mounts, as in `plot()`: change the component's `key` to change features. Its theme is `light` unless given; it does not follow the page as the easy charts do.
|
|
122
138
|
|
|
@@ -133,7 +149,7 @@ import { LineChart } from '@swiftplot/vue';
|
|
|
133
149
|
- **Size:** `width` and `height` (px) size the `div`, and `style` wins over them; the chart measures the `div` and follows whatever resizes it (a class, a parent, a media query). With no height from `height`, `style` or CSS, the `div` fills a parent that has a height, else is 300 px tall, so `<LineChart data={rows} />` shows a chart on an ordinary page and a class added later wins, in a cascade layer (Tailwind) or not. The fallback is a `<style>` kept first in the document head (or the shadow root), inserted only for a chart with no height: under a Content Security Policy that blocks inline styles, give every chart a height (`height`, `style` or CSS). A chart mounted in a detached element falls back once the element is attached.
|
|
134
150
|
- **Errors** (a missing field, an accessor or formatter that throws) go to `onError` in React or `@error` in Vue, and the last good chart stays; without a handler they are thrown to the nearest error boundary, or to Vue's error handling (`onErrorCaptured`, `app.config.errorHandler`). A failed render is tried again when a chart prop other than a callback changes; a changed callback still reaches the last good chart. A failure is reported once until its error message, the data's length (each column's, for an object of columns) or another prop that is not a function changes, so inline props, data rebuilt during render and a handler that sets state cannot loop, unless the message itself changes on every attempt. Rows are never read, so new data of the same length that fails with the same message is not reported again.
|
|
135
151
|
- **Server rendering:** the server renders the `div` alone, the client hydrates the same markup and creates the chart after hydration. The React entry is marked `'use client'`. The 300 px fallback is applied in the browser, so give a server-rendered chart a `height` (or a CSS height) to reserve its space before hydration.
|
|
136
|
-
- **Performance:** each render compares props by identity and the chart then by value, so inline objects such as `xAxis={{ label: 'Day' }}` cost little. `data` built during render and inline accessors are converted again on every render, and an inline `xAxis.format` repaints the data: build them outside render, or with `useMemo` and `useCallback`. In Vue keep the data in a `shallowRef` and replace the array: a deep `ref` makes the app wrap every row for nothing the chart uses. Data changed in place with every prop unchanged is not noticed: pass a new array or bump `dataVersion`.
|
|
152
|
+
- **Performance:** each render compares props by identity and the chart then by value, so inline objects such as `xAxis={{ label: 'Day' }}` cost little. `theme` is the exception: replacing it is how a changed CSS variable is seen, so keep a theme object outside the component. `data` built during render and inline accessors are converted again on every render, and an inline `xAxis.format` repaints the data: build them outside render, or with `useMemo` and `useCallback`. In Vue keep the data in a `shallowRef` and replace the array: a deep `ref` makes the app wrap every row for nothing the chart uses. Data changed in place with every prop unchanged is not noticed: pass a new array or bump `dataVersion`.
|
|
137
153
|
|
|
138
154
|
## Use
|
|
139
155
|
|
|
@@ -170,6 +186,7 @@ chart.destroy();
|
|
|
170
186
|
- **Error bars** are `errorBars({ x, y1, y2 })`, or `{ y, x1, x2 }` lying down.
|
|
171
187
|
- **Candlesticks** are `candlestick({ x, open, high, low, close, color, up, down })`: a wick from low to high and a body from open to close, in `up` where the close is not below the open and in `down` where it is. `width` is the body's width in x units, 0.6 by default. A pointer anywhere on a candle hits it; a `nearest` tooltip gets the row, to read the four values from your own columns.
|
|
172
188
|
- **Colours:** `palette` is eight series colours to give out in order, and `brand` the cyan-to-violet blend. `gradient(from, to, 'down' | 'up' | 'right' | 'left')` makes a blend of two colours; a number stands for the mark's own colour at that opacity. `line({ fill: true })` puts a faint fade of the line's colour under it. A blend goes in `area({ fill })`, `bar({ fill })`, `line({ stroke })` and `line({ fill })`, so `area({ x, y, color, fill: gradient(0.4, 0) })` fades an area out towards its baseline. `color` stays the one colour a legend and a tooltip show.
|
|
189
|
+
- **CSS variables:** a colour may be `var(--name)` or `var(--name, fallback)`, in marks, gradient stops, themes and an easy chart's `colors`, read at the chart's element. One with no value draws in the theme's `muted` and warns on the console. A value is kept until `theme` is replaced with another object, even an equal one: that is how a changed variable is seen, and why an inline theme object in React has the variables read on each render. On an easy chart, reading a changed variable needs a theme object, not `'auto'` or `'dark'`, and a copy of `dark` needs `colors: paletteDark` or your own `colors`. `sequential()` takes hex stops only, and a custom mark's own `addColorStop` takes no variable.
|
|
173
190
|
- **Blends on other charts:** `sankey({ blend: true })` runs each ribbon from its source's colour into its target's; `funnel({ fill: gradient(a, b) })` puts one blend down the whole funnel; `arcs({ sweep: 0.8 })` and `radialBars({ sweep: 0.35 })` start each slice or bar at that opacity and bring it to full colour at its end; `treemap({ shade: 0.7 })` starts each branch at that opacity at its top, and `sunburst({ shade: 0.7 })` ends each at that opacity at the rim.
|
|
174
191
|
- **Box plots** take `radius`, `medianWidth`, `whiskers` (their opacity) and `fill`: `box({ ..., radius: 4, medianWidth: 2.5, whiskers: 0.5, fill: gradient(0.4, 0.1) })`.
|
|
175
192
|
- **Rounded bars and ringed points:** `bar({ radius: 6 })` rounds the value end of a bar that starts at zero, or all corners of one that floats, and `bar({ gap: 2 })` sets touching bars such as a histogram's two pixels apart; `dots({ ring: 2 })` draws rings round a white middle.
|
|
@@ -194,6 +211,7 @@ chart.destroy();
|
|
|
194
211
|
);
|
|
195
212
|
```
|
|
196
213
|
|
|
214
|
+
- **Drawing over the chart:** `chart.overlay` is an element over the chart, under its tooltip, for your own DOM. `onLayout(layout)` gives the size, margin, shown domains and ticks, and, with axes, `xPx`, `yPx`, `xValue` and `yValue`, whenever they change; `onHover(hover)` gives the pointer in CSS pixels and the hit `onClick` would get with its anchor, `{ px, py, hit }`, and `null` as it leaves. The first `onLayout` runs inside `plot()`: to use `chart.overlay` in it, set it with `update()`. An axis's `to` and `from` must stay the same functions between updates, or state set from `onLayout` loops; data made anew with equal values does not make `onHover` loop. Data written in place and passed as a new view or array is compared by a copy of the hovered mark's, which of a list over 1000 values is a sample: a write to a row neither hovered nor sampled reports nothing. New data in a new array, not written in place, is compared whole. A child with `pointer-events: auto` passes the hover and the tooltip to the chart; clicks, the wheel and drags on it stay its own.
|
|
197
215
|
- **Themes:** `theme: dark` colours the text, grid, tick marks and tooltip for a dark page; `light` is the default. The core never guesses dark mode: the app switches it, and `paletteDark` gives series colours for a dark surface. The charts of `swiftplot/charts` follow the page's `color-scheme` instead.
|
|
198
216
|
|
|
199
217
|
```ts
|
package/dist/chart.js
CHANGED
|
@@ -1,17 +1,29 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { extend, resolver } from './color.js';
|
|
2
|
+
import { copied, keep, sameData } from './equal.js';
|
|
3
|
+
import { owns, position, presses, released, strayed } from './features/pointer.js';
|
|
2
4
|
import { upTo } from './marks/common.js';
|
|
3
5
|
import { extent, scale } from './scale.js';
|
|
4
6
|
import { FONT, textWidth } from './text.js';
|
|
5
7
|
import { light } from './theme.js';
|
|
6
8
|
export const NEAREST_PX = 20;
|
|
9
|
+
const RELEASES = ['pointermove', 'pointerup', 'pointercancel'];
|
|
7
10
|
// What an update of these alone leaves alone: a tip held by a tap stays.
|
|
8
|
-
const LIGHT = new Set([
|
|
11
|
+
const LIGHT = new Set([
|
|
12
|
+
'pointer',
|
|
13
|
+
'onClick',
|
|
14
|
+
'onPointerChange',
|
|
15
|
+
'onViewChange',
|
|
16
|
+
'onHiddenChange',
|
|
17
|
+
'onLayout',
|
|
18
|
+
'onHover',
|
|
19
|
+
]);
|
|
9
20
|
// ponytail: measured crossover is somewhere between 10k and 100k points; tune per device if it matters.
|
|
10
21
|
const GL_FROM = 10_000;
|
|
11
22
|
const same = (a, b) => {
|
|
12
23
|
const keys = Object.keys(a);
|
|
13
24
|
return (keys.length === Object.keys(b).length &&
|
|
14
|
-
keys.every(k => Object.hasOwn(b, k) &&
|
|
25
|
+
keys.every(k => Object.hasOwn(b, k) &&
|
|
26
|
+
Object.is(a[k], b[k])));
|
|
15
27
|
};
|
|
16
28
|
const resolve = (a, of, room) => {
|
|
17
29
|
if (a.scale)
|
|
@@ -56,13 +68,16 @@ export function plot(el, options) {
|
|
|
56
68
|
let dpr = devicePixelRatio;
|
|
57
69
|
const root = document.createElement('div');
|
|
58
70
|
root.style.cssText = `position:relative;font:${FONT};pointer-events:auto`;
|
|
71
|
+
let overlay;
|
|
59
72
|
const layer = (tag, css = '') => {
|
|
60
73
|
const e = document.createElement(tag);
|
|
61
74
|
e.style.cssText = `position:absolute;pointer-events:none;${css}`;
|
|
62
|
-
return root.
|
|
75
|
+
return root.insertBefore(e, overlay?.parentNode === root ? overlay : null);
|
|
63
76
|
};
|
|
64
77
|
const canvas = layer('canvas', 'left:0;top:0');
|
|
65
78
|
const ctx = canvas.getContext('2d');
|
|
79
|
+
const { color, forget, reread } = resolver(root, () => (o.theme ?? light).muted);
|
|
80
|
+
extend(ctx, color);
|
|
66
81
|
const axes = layer('div', 'inset:0');
|
|
67
82
|
canvas.setAttribute('role', 'img');
|
|
68
83
|
axes.ariaHidden = 'true';
|
|
@@ -278,7 +293,7 @@ export function plot(el, options) {
|
|
|
278
293
|
for (const label of wanted.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0))) {
|
|
279
294
|
const [x, y, w] = [label.x / dpr, label.y / dpr, textWidth(label.text)];
|
|
280
295
|
const l = label.align === 'start' ? x : label.align === 'end' ? x - w : x - w / 2;
|
|
281
|
-
const box = { l, t: y - 8, r: l + w, b: y + 8, text: label.text, color: label.color };
|
|
296
|
+
const box = { l, t: y - 8, r: l + w, b: y + 8, text: label.text, color: color(label.color) };
|
|
282
297
|
if (box.l < 0 || box.t < 0 || box.r > W || box.b > H)
|
|
283
298
|
continue;
|
|
284
299
|
if (kept.some(k => box.l < k.r && k.l < box.r && box.t < k.b && k.t < box.b))
|
|
@@ -306,7 +321,9 @@ export function plot(el, options) {
|
|
|
306
321
|
let ruled = '[]';
|
|
307
322
|
const rule = () => {
|
|
308
323
|
const { left, top, width, height } = view;
|
|
309
|
-
const wanted = [...new Set(visible)]
|
|
324
|
+
const wanted = [...new Set(visible)]
|
|
325
|
+
.flatMap(k => cache.get(k)?.p.rules ?? [])
|
|
326
|
+
.map(r => ({ ...r, color: color(r.color) }));
|
|
310
327
|
const key = JSON.stringify(wanted.length ? [wanted, left, top, width, height] : []);
|
|
311
328
|
if (key === ruled)
|
|
312
329
|
return;
|
|
@@ -525,7 +542,17 @@ export function plot(el, options) {
|
|
|
525
542
|
ys = fitted('y', { length: h, horizontal: false });
|
|
526
543
|
ys2 = has2() ? fitted('y2', { length: h, horizontal: false }) : undefined;
|
|
527
544
|
};
|
|
528
|
-
|
|
545
|
+
// The theme last taken, kept from later writes in place.
|
|
546
|
+
let taken = { ...(o.theme ?? light) };
|
|
547
|
+
// The theme as given unless it names a variable, so a mark or a feature can tell one theme from another.
|
|
548
|
+
let styled;
|
|
549
|
+
const theme = () => {
|
|
550
|
+
if (styled)
|
|
551
|
+
return styled;
|
|
552
|
+
const given = o.theme ?? light;
|
|
553
|
+
const read = Object.fromEntries(Object.entries(given).map(([k, v]) => [k, color(v)]));
|
|
554
|
+
return (styled = same(given, read) ? given : read);
|
|
555
|
+
};
|
|
529
556
|
const real = (k, v) => {
|
|
530
557
|
const a = axisOf(o, k);
|
|
531
558
|
return a.from ? a.from(v, a) : v;
|
|
@@ -864,6 +891,62 @@ export function plot(el, options) {
|
|
|
864
891
|
};
|
|
865
892
|
let painter;
|
|
866
893
|
const paint = (why) => (painter ? painter(render, why) : render());
|
|
894
|
+
// Nothing in it reads the chart later: what is captured are numbers and each axis's own conversions.
|
|
895
|
+
const snapshot = () => {
|
|
896
|
+
const frame = o.frame ?? 'axes';
|
|
897
|
+
const size = { width: W, height: H, margin: Object.freeze({ ...m }), frame };
|
|
898
|
+
if (bare(o))
|
|
899
|
+
return Object.freeze(size);
|
|
900
|
+
const side = (k, { lo, hi, ticks }, at, by) => {
|
|
901
|
+
const a = axisOf(o, k);
|
|
902
|
+
const [to, from, density] = [a.to?.bind(a), a.from?.bind(a), dpr];
|
|
903
|
+
const value = (v) => (from ? from(v, a) : v);
|
|
904
|
+
return {
|
|
905
|
+
px: (v) => (at + (to ? to(v, a) : v) * by) / density,
|
|
906
|
+
value: (px) => value((px * density - at) / by),
|
|
907
|
+
axis: Object.freeze({
|
|
908
|
+
domain: Object.freeze([value(lo), value(hi)]),
|
|
909
|
+
ticks: Object.freeze(ticks.map(t => Object.freeze({ value: value(t.value), label: t.label }))),
|
|
910
|
+
}),
|
|
911
|
+
};
|
|
912
|
+
};
|
|
913
|
+
const x = side('x', xs, view.ox, view.kx);
|
|
914
|
+
const y = side('y', ys, view.oy, -view.ky);
|
|
915
|
+
const y2 = ys2 && side('y2', ys2, view2.oy, -view2.ky);
|
|
916
|
+
const on = (axis) => (axis === 'y2' && y2 ? y2 : y);
|
|
917
|
+
return Object.freeze({
|
|
918
|
+
...size,
|
|
919
|
+
x: x.axis,
|
|
920
|
+
y: y.axis,
|
|
921
|
+
...(y2 && { y2: y2.axis }),
|
|
922
|
+
xPx: x.px,
|
|
923
|
+
yPx: (v, axis) => on(axis).px(v),
|
|
924
|
+
xValue: x.value,
|
|
925
|
+
yValue: (px, axis) => on(axis).value(px),
|
|
926
|
+
});
|
|
927
|
+
};
|
|
928
|
+
let destroyed = false;
|
|
929
|
+
let reported;
|
|
930
|
+
const reportLayout = () => {
|
|
931
|
+
if (!o.onLayout)
|
|
932
|
+
reported = undefined;
|
|
933
|
+
if (!o.onLayout || !drawable || destroyed)
|
|
934
|
+
return;
|
|
935
|
+
const next = snapshot();
|
|
936
|
+
// A conversion may read any field of its axis, such as the base of a log(). Not its scale or format, which
|
|
937
|
+
// an app may give anew in each update: one made from onLayout would then report without end.
|
|
938
|
+
const rule = (a) => (a.to || a.from ? { ...a, domain: String(a.domain), scale: 0, format: 0 } : {});
|
|
939
|
+
const key = [[axesKey, JSON.stringify(next)], ...keys().map(k => rule(axisOf(o, k)))];
|
|
940
|
+
if (reported?.length === key.length && key.every((r, i) => same(r, reported[i])))
|
|
941
|
+
return;
|
|
942
|
+
reported = key;
|
|
943
|
+
o.onLayout(next);
|
|
944
|
+
};
|
|
945
|
+
// It runs the app's code, so each caller calls it last: the app may update or destroy the chart from it.
|
|
946
|
+
const report = () => {
|
|
947
|
+
reportLayout();
|
|
948
|
+
reportHover();
|
|
949
|
+
};
|
|
867
950
|
const refresh = (data, also, restyled = false, asked = false) => {
|
|
868
951
|
const before = viewKey;
|
|
869
952
|
const shown = () => [xs.lo, xs.hi, ys.lo, ys.hi, ys2?.lo, ys2?.hi].join();
|
|
@@ -883,6 +966,7 @@ export function plot(el, options) {
|
|
|
883
966
|
root.style.visibility = drawable ? '' : 'hidden';
|
|
884
967
|
// Growing back always changes the view, so marks replaced while hidden are prepared then.
|
|
885
968
|
if (!drawable) {
|
|
969
|
+
reported = undefined;
|
|
886
970
|
flat = [];
|
|
887
971
|
onGl = [];
|
|
888
972
|
cache.clear();
|
|
@@ -966,6 +1050,16 @@ export function plot(el, options) {
|
|
|
966
1050
|
const internals = {
|
|
967
1051
|
root,
|
|
968
1052
|
canvas,
|
|
1053
|
+
get overlay() {
|
|
1054
|
+
return overlay;
|
|
1055
|
+
},
|
|
1056
|
+
set overlay(e) {
|
|
1057
|
+
overlay = e;
|
|
1058
|
+
if (!e)
|
|
1059
|
+
return;
|
|
1060
|
+
root.append(e);
|
|
1061
|
+
adopt(e);
|
|
1062
|
+
},
|
|
969
1063
|
layer,
|
|
970
1064
|
onPaint(p) {
|
|
971
1065
|
painter = p;
|
|
@@ -993,10 +1087,12 @@ export function plot(el, options) {
|
|
|
993
1087
|
if (refresh(true, relaid ? undefined : 'size'))
|
|
994
1088
|
sync();
|
|
995
1089
|
o.onHiddenChange?.(ids);
|
|
1090
|
+
report();
|
|
996
1091
|
},
|
|
997
1092
|
size: () => ({ width: W, height: H }),
|
|
998
1093
|
margin: () => m,
|
|
999
1094
|
theme,
|
|
1095
|
+
color,
|
|
1000
1096
|
xPx,
|
|
1001
1097
|
yPx,
|
|
1002
1098
|
xValue: px => (px * dpr - view.ox) / view.kx,
|
|
@@ -1045,12 +1141,23 @@ export function plot(el, options) {
|
|
|
1045
1141
|
...(!fits.y.fitted && { y: [real('y', ys.lo), real('y', ys.hi)] }),
|
|
1046
1142
|
...(ys2 && !fits.y2.fitted && { y2: [real('y2', ys2.lo), real('y2', ys2.hi)] }),
|
|
1047
1143
|
});
|
|
1144
|
+
report();
|
|
1048
1145
|
return true;
|
|
1049
1146
|
},
|
|
1050
1147
|
real,
|
|
1051
1148
|
frame: () => o.frame ?? 'axes',
|
|
1052
|
-
drag: {
|
|
1053
|
-
|
|
1149
|
+
drag: {
|
|
1150
|
+
brush: false,
|
|
1151
|
+
pan: false,
|
|
1152
|
+
active: false,
|
|
1153
|
+
get child() {
|
|
1154
|
+
return [...(pressed()?.held.values() ?? [])].includes(true);
|
|
1155
|
+
},
|
|
1156
|
+
},
|
|
1157
|
+
sync() {
|
|
1158
|
+
sync();
|
|
1159
|
+
reportHover();
|
|
1160
|
+
},
|
|
1054
1161
|
// Topmost first, the reverse of render(): a hit that is no nearer never replaces one above it.
|
|
1055
1162
|
hit(px, py, max) {
|
|
1056
1163
|
const lit = drawnFocus();
|
|
@@ -1093,16 +1200,144 @@ export function plot(el, options) {
|
|
|
1093
1200
|
o.onPointerChange?.(p);
|
|
1094
1201
|
};
|
|
1095
1202
|
let at;
|
|
1203
|
+
let under;
|
|
1096
1204
|
const aim = () => {
|
|
1097
|
-
|
|
1205
|
+
under = at && (o.onClick || o.onHover) ? clicked(at) : undefined;
|
|
1206
|
+
root.style.cursor = o.onClick && at?.direct && under?.hit ? 'pointer' : '';
|
|
1207
|
+
};
|
|
1208
|
+
let hoverKey = [];
|
|
1209
|
+
let hoverMark;
|
|
1210
|
+
let hoverRow;
|
|
1211
|
+
let hoverData;
|
|
1212
|
+
// The values themselves against the mark last seen, and the copy for what was written into that mark's since.
|
|
1213
|
+
const unchanged = (k) => k === hoverMark ||
|
|
1214
|
+
(sameData(copied(k.options, hoverRow), hoverData?.data) && sameData(k.options, hoverMark?.options));
|
|
1215
|
+
const reportHover = () => {
|
|
1216
|
+
if (!o.onHover) {
|
|
1217
|
+
hoverKey = [];
|
|
1218
|
+
hoverMark = hoverData = undefined;
|
|
1219
|
+
}
|
|
1220
|
+
if (!o.onHover || destroyed)
|
|
1221
|
+
return;
|
|
1222
|
+
// A press on a child holds the hover, but not over data that no longer has what it names.
|
|
1223
|
+
if (internals.drag.child && at) {
|
|
1224
|
+
const [, , type, id] = hoverKey;
|
|
1225
|
+
const seen = marks.find((k, i) => k.type === type && (k.key ?? i) === id && unchanged(k));
|
|
1226
|
+
if (seen)
|
|
1227
|
+
hoverMark = seen;
|
|
1228
|
+
if (seen || !hoverMark)
|
|
1229
|
+
return;
|
|
1230
|
+
}
|
|
1231
|
+
let next = null;
|
|
1232
|
+
if (under && drawable) {
|
|
1233
|
+
const { px, py, hit } = under;
|
|
1234
|
+
next = {
|
|
1235
|
+
px,
|
|
1236
|
+
py,
|
|
1237
|
+
hit: hit && {
|
|
1238
|
+
...shaped(hit),
|
|
1239
|
+
px: internals.xPx(hit.x),
|
|
1240
|
+
py: internals.yPx(hit.y, onAxis(hit.mark)),
|
|
1241
|
+
},
|
|
1242
|
+
};
|
|
1243
|
+
}
|
|
1244
|
+
const h = next?.hit;
|
|
1245
|
+
const k = h?.mark;
|
|
1246
|
+
// Not the mark itself, which an app may make anew in each update: one made from onHover would report without end.
|
|
1247
|
+
const key = next
|
|
1248
|
+
? [
|
|
1249
|
+
next.px,
|
|
1250
|
+
next.py,
|
|
1251
|
+
k?.type,
|
|
1252
|
+
k && (k.key ?? marks.indexOf(k)),
|
|
1253
|
+
k?.label,
|
|
1254
|
+
k?.color,
|
|
1255
|
+
h?.row,
|
|
1256
|
+
h?.px,
|
|
1257
|
+
h?.py,
|
|
1258
|
+
h?.x,
|
|
1259
|
+
h?.y,
|
|
1260
|
+
h?.value,
|
|
1261
|
+
h?.color,
|
|
1262
|
+
h?.distance,
|
|
1263
|
+
]
|
|
1264
|
+
: [];
|
|
1265
|
+
const repeated = same(hoverKey, key) && (!k || unchanged(k));
|
|
1266
|
+
hoverMark = k;
|
|
1267
|
+
if (repeated)
|
|
1268
|
+
return;
|
|
1269
|
+
hoverRow = h?.row;
|
|
1270
|
+
if (k && hoverData?.of === k.options)
|
|
1271
|
+
hoverData.to(hoverRow);
|
|
1272
|
+
else
|
|
1273
|
+
hoverData = k && keep(k.options, hoverRow);
|
|
1274
|
+
hoverKey = key;
|
|
1275
|
+
o.onHover(next);
|
|
1276
|
+
};
|
|
1277
|
+
const pointOf = (e) => ({
|
|
1278
|
+
clientX: e.clientX,
|
|
1279
|
+
clientY: e.clientY,
|
|
1280
|
+
own: owns(internals, e.target),
|
|
1281
|
+
direct: e.target === root,
|
|
1282
|
+
});
|
|
1283
|
+
const pressed = () => overlay && presses.get(overlay);
|
|
1284
|
+
let tracking = false;
|
|
1285
|
+
const track = () => {
|
|
1286
|
+
const on = internals.drag.child && !destroyed;
|
|
1287
|
+
if (on === tracking)
|
|
1288
|
+
return;
|
|
1289
|
+
tracking = on;
|
|
1290
|
+
for (const type of RELEASES)
|
|
1291
|
+
if (on)
|
|
1292
|
+
document.addEventListener(type, release, true);
|
|
1293
|
+
else
|
|
1294
|
+
document.removeEventListener(type, release, true);
|
|
1295
|
+
};
|
|
1296
|
+
const adopt = (e) => {
|
|
1297
|
+
const changed = () => {
|
|
1298
|
+
track();
|
|
1299
|
+
if (!destroyed)
|
|
1300
|
+
sync();
|
|
1301
|
+
};
|
|
1302
|
+
presses.set(e, { held: presses.get(e)?.held ?? new Map(), changed });
|
|
1303
|
+
track();
|
|
1304
|
+
};
|
|
1305
|
+
const press = (e) => {
|
|
1306
|
+
const p = pressed();
|
|
1307
|
+
if (!p)
|
|
1308
|
+
return;
|
|
1309
|
+
const child = e.target !== root && owns(internals, e.target);
|
|
1310
|
+
for (const [id, held] of p.held)
|
|
1311
|
+
if (!held || id === e.pointerId)
|
|
1312
|
+
p.held.delete(id);
|
|
1313
|
+
if (child)
|
|
1314
|
+
p.held.set(e.pointerId, true);
|
|
1315
|
+
if (child)
|
|
1316
|
+
p.changed();
|
|
1317
|
+
else
|
|
1318
|
+
track();
|
|
1319
|
+
};
|
|
1320
|
+
const release = (e) => {
|
|
1321
|
+
const p = pressed();
|
|
1322
|
+
if (!p?.held.get(e.pointerId) || e.buttons)
|
|
1323
|
+
return;
|
|
1324
|
+
p.held.set(e.pointerId, false);
|
|
1325
|
+
p.changed();
|
|
1326
|
+
};
|
|
1327
|
+
// Apart from release(): an event on the document has lost a target inside a shadow tree.
|
|
1328
|
+
const lifted = (e) => {
|
|
1329
|
+
if (released(internals, e))
|
|
1330
|
+
point(e);
|
|
1098
1331
|
};
|
|
1099
1332
|
const point = (e) => {
|
|
1100
|
-
|
|
1333
|
+
if (destroyed || internals.drag.child)
|
|
1334
|
+
return;
|
|
1335
|
+
at = pointOf(e);
|
|
1101
1336
|
aim();
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1337
|
+
const { px, py, inside } = position(internals, e.clientX, e.clientY);
|
|
1338
|
+
const over = at.own && inside && internals.frame() === 'axes';
|
|
1339
|
+
tell(over && !internals.drag.active ? valuesAt(px, py) : null);
|
|
1340
|
+
reportHover();
|
|
1106
1341
|
};
|
|
1107
1342
|
const valuesAt = (px, py) => ({
|
|
1108
1343
|
x: real('x', internals.xValue(px)),
|
|
@@ -1111,34 +1346,40 @@ export function plot(el, options) {
|
|
|
1111
1346
|
});
|
|
1112
1347
|
const unpoint = () => {
|
|
1113
1348
|
at = undefined;
|
|
1114
|
-
|
|
1349
|
+
aim();
|
|
1115
1350
|
tell(null);
|
|
1351
|
+
reportHover();
|
|
1116
1352
|
};
|
|
1117
|
-
|
|
1118
|
-
root.addEventListener('
|
|
1353
|
+
// Capturing, so a child that stops its own events still holds its press; the release and the moves, too.
|
|
1354
|
+
root.addEventListener('pointerdown', press, true);
|
|
1119
1355
|
root.addEventListener('pointerleave', unpoint);
|
|
1120
1356
|
root.addEventListener('pointercancel', unpoint);
|
|
1121
1357
|
const clicked = (e) => {
|
|
1122
|
-
if (internals.drag.active || e.
|
|
1358
|
+
if (internals.drag.active || !e.own)
|
|
1123
1359
|
return undefined;
|
|
1124
1360
|
const { px, py, inside } = position(internals, e.clientX, e.clientY);
|
|
1125
1361
|
if (!inside)
|
|
1126
1362
|
return undefined;
|
|
1127
1363
|
return { px, py, hit: internals.hit(px, py, NEAREST_PX) };
|
|
1128
1364
|
};
|
|
1129
|
-
|
|
1130
|
-
const
|
|
1131
|
-
|
|
1132
|
-
return;
|
|
1133
|
-
const { px, py, hit } = c;
|
|
1134
|
-
const on = hit ? onAxis(hit.mark) : 'y';
|
|
1135
|
-
o.onClick(hit && {
|
|
1365
|
+
const shaped = (hit) => {
|
|
1366
|
+
const on = onAxis(hit.mark);
|
|
1367
|
+
return {
|
|
1136
1368
|
...hit,
|
|
1137
1369
|
mark: declared.get(hit.mark) ?? hit.mark,
|
|
1138
1370
|
x: real('x', hit.x),
|
|
1139
1371
|
y: real(on, hit.y),
|
|
1140
1372
|
...(hit.value !== undefined && { value: real(on, hit.value) }),
|
|
1141
|
-
}
|
|
1373
|
+
};
|
|
1374
|
+
};
|
|
1375
|
+
root.addEventListener('click', e => {
|
|
1376
|
+
if (e.target !== root || strayed(internals, e))
|
|
1377
|
+
return;
|
|
1378
|
+
const c = o.onClick && clicked(pointOf(e));
|
|
1379
|
+
if (!c)
|
|
1380
|
+
return;
|
|
1381
|
+
const { px, py, hit } = c;
|
|
1382
|
+
o.onClick(hit && shaped(hit), valuesAt(px, py));
|
|
1142
1383
|
});
|
|
1143
1384
|
showing();
|
|
1144
1385
|
const features = [];
|
|
@@ -1174,12 +1415,14 @@ export function plot(el, options) {
|
|
|
1174
1415
|
letGo();
|
|
1175
1416
|
if (refresh(false, 'size'))
|
|
1176
1417
|
sync();
|
|
1418
|
+
report();
|
|
1177
1419
|
};
|
|
1178
1420
|
const watch = () => {
|
|
1179
1421
|
density = matchMedia(`(resolution: ${dpr}dppx)`);
|
|
1180
1422
|
density.addEventListener('change', redensify, { once: true });
|
|
1181
1423
|
};
|
|
1182
1424
|
const teardown = () => {
|
|
1425
|
+
destroyed = true;
|
|
1183
1426
|
let failed;
|
|
1184
1427
|
const run = (f) => {
|
|
1185
1428
|
try {
|
|
@@ -1191,6 +1434,7 @@ export function plot(el, options) {
|
|
|
1191
1434
|
};
|
|
1192
1435
|
run(() => observer?.disconnect());
|
|
1193
1436
|
run(() => density?.removeEventListener('change', redensify));
|
|
1437
|
+
track();
|
|
1194
1438
|
for (const f of features)
|
|
1195
1439
|
run(() => f.destroy());
|
|
1196
1440
|
for (const k of new Set([...marks, ...declared.keys()]))
|
|
@@ -1206,15 +1450,21 @@ export function plot(el, options) {
|
|
|
1206
1450
|
measure();
|
|
1207
1451
|
for (const feature of o.use ?? [])
|
|
1208
1452
|
features.push(feature(internals));
|
|
1453
|
+
// After the features, whose focus decides which of overlapping marks is on top.
|
|
1454
|
+
root.addEventListener('pointerup', lifted, true);
|
|
1455
|
+
root.addEventListener('pointerdown', point);
|
|
1456
|
+
root.addEventListener('pointermove', point, true);
|
|
1209
1457
|
if (refresh(true))
|
|
1210
1458
|
sync();
|
|
1211
1459
|
observer = new ResizeObserver(() => {
|
|
1212
1460
|
letGo();
|
|
1213
1461
|
if (refresh(false, measure() ? 'size' : undefined))
|
|
1214
1462
|
sync();
|
|
1463
|
+
report();
|
|
1215
1464
|
});
|
|
1216
1465
|
observe();
|
|
1217
1466
|
watch();
|
|
1467
|
+
report();
|
|
1218
1468
|
}
|
|
1219
1469
|
catch (e) {
|
|
1220
1470
|
try {
|
|
@@ -1225,7 +1475,13 @@ export function plot(el, options) {
|
|
|
1225
1475
|
}
|
|
1226
1476
|
return {
|
|
1227
1477
|
update(partial) {
|
|
1228
|
-
const
|
|
1478
|
+
const given = partial.theme ?? light;
|
|
1479
|
+
const restyled = 'theme' in partial && given !== (o.theme ?? light) && (!same(given, taken) || reread());
|
|
1480
|
+
const keys = Object.keys(partial).filter(k => k !== 'theme' || restyled);
|
|
1481
|
+
if (!keys.length && 'theme' in partial) {
|
|
1482
|
+
o = { ...o, ...partial };
|
|
1483
|
+
return;
|
|
1484
|
+
}
|
|
1229
1485
|
if (!keys.length || !keys.every(k => LIGHT.has(k)))
|
|
1230
1486
|
letGo();
|
|
1231
1487
|
const prev = o;
|
|
@@ -1292,7 +1548,11 @@ export function plot(el, options) {
|
|
|
1292
1548
|
const lost = unfocusGone();
|
|
1293
1549
|
observe();
|
|
1294
1550
|
const resized = measure();
|
|
1295
|
-
|
|
1551
|
+
if (restyled) {
|
|
1552
|
+
taken = { ...given };
|
|
1553
|
+
styled = undefined;
|
|
1554
|
+
forget();
|
|
1555
|
+
}
|
|
1296
1556
|
// Ticks are DOM and change at once, so a new window must not cross-fade with new marks.
|
|
1297
1557
|
const moved = ['x', 'y', 'y2'].some(k => String(o.view?.[k]) !== String(prev.view?.[k]));
|
|
1298
1558
|
if (refresh(data, resized || restyled || (hid && !relaid)
|
|
@@ -1303,7 +1563,13 @@ export function plot(el, options) {
|
|
|
1303
1563
|
sync();
|
|
1304
1564
|
else
|
|
1305
1565
|
aim();
|
|
1566
|
+
report();
|
|
1306
1567
|
},
|
|
1307
1568
|
destroy: teardown,
|
|
1569
|
+
get overlay() {
|
|
1570
|
+
if (!overlay)
|
|
1571
|
+
adopt((overlay = layer('div', 'inset:0;isolation:isolate')));
|
|
1572
|
+
return overlay;
|
|
1573
|
+
},
|
|
1308
1574
|
};
|
|
1309
1575
|
}
|
|
@@ -11,7 +11,7 @@ export type Context = {
|
|
|
11
11
|
/** make() runs again only when deps differ, element by element, from the last call under this name. */
|
|
12
12
|
memo: <T>(name: string, deps: readonly unknown[], make: () => T) => T;
|
|
13
13
|
};
|
|
14
|
-
type Passed = 'view' | 'hidden' | 'selected' | 'pointer' | 'onViewChange' | 'onHiddenChange' | 'onClick' | 'onPointerChange';
|
|
14
|
+
type Passed = 'view' | 'hidden' | 'selected' | 'pointer' | 'onViewChange' | 'onHiddenChange' | 'onClick' | 'onPointerChange' | 'onLayout' | 'onHover';
|
|
15
15
|
export type Built = {
|
|
16
16
|
options: Omit<Options, 'use' | Passed>;
|
|
17
17
|
/** Compared by value across updates: a change recreates the chart. */
|
|
@@ -23,10 +23,9 @@ export type EasyChart<P> = {
|
|
|
23
23
|
update(props: Partial<P>): void;
|
|
24
24
|
destroy(): void;
|
|
25
25
|
readonly chart: Chart;
|
|
26
|
+
/** The chart's own overlay, the same element with its children when the chart is made again. */
|
|
27
|
+
readonly overlay: HTMLElement;
|
|
26
28
|
};
|
|
27
29
|
export declare const PASSED: Set<string>;
|
|
28
|
-
export declare const plain: (v: unknown) => v is Record<string, unknown>;
|
|
29
|
-
/** Plain objects and arrays by value, anything else (typed arrays, functions, themes) by identity. */
|
|
30
|
-
export declare const equal: (a: unknown, b: unknown) => boolean;
|
|
31
30
|
export declare function create<P extends ControllerProps>(el: HTMLElement, initial: P, build: Build<P>): EasyChart<P>;
|
|
32
31
|
export {};
|