@swiftplot/react 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/bind.d.ts +6 -1
- package/dist/bind.js +66 -4
- package/package.json +4 -3
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/bind.d.ts
CHANGED
|
@@ -1,14 +1,19 @@
|
|
|
1
|
-
import { type CSSProperties, type FunctionComponent } from 'react';
|
|
1
|
+
import { type CSSProperties, type FunctionComponent, type ReactNode } from 'react';
|
|
2
|
+
import type { Hover, Layout } from 'swiftplot';
|
|
2
3
|
export type Mount<P> = (el: HTMLElement, props: P) => {
|
|
3
4
|
update(partial: Partial<P>): void;
|
|
4
5
|
destroy(): void;
|
|
6
|
+
readonly overlay: HTMLElement;
|
|
5
7
|
};
|
|
8
|
+
type Children = (layout: Layout, hover: Hover | null) => ReactNode;
|
|
6
9
|
export type HostProps = {
|
|
7
10
|
className?: string;
|
|
8
11
|
style?: CSSProperties;
|
|
9
12
|
id?: string;
|
|
10
13
|
/** Without it, a failed render throws to the nearest error boundary. */
|
|
11
14
|
onError?: (error: unknown) => void;
|
|
15
|
+
/** Rendered over the chart, in its overlay, from its layout and what the pointer is over. */
|
|
16
|
+
children?: Children;
|
|
12
17
|
};
|
|
13
18
|
type Sized = {
|
|
14
19
|
width?: number;
|
package/dist/bind.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { createElement, useEffect, useLayoutEffect, useRef, } from 'react';
|
|
1
|
+
import { createElement, Fragment, memo, useCallback, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, } from 'react';
|
|
2
|
+
import { createPortal } from 'react-dom';
|
|
2
3
|
import { equal, plain } from 'swiftplot/charts';
|
|
3
4
|
const list = (v) => typeof v === 'object' && v !== null && typeof v.length === 'number';
|
|
4
5
|
function strip(v, seen) {
|
|
@@ -101,15 +102,57 @@ function sheet(el) {
|
|
|
101
102
|
});
|
|
102
103
|
first.observe(parent, { childList: true });
|
|
103
104
|
}
|
|
105
|
+
const NOTHING = { hover: null };
|
|
106
|
+
// A store, as React commits a change of one before the frame the chart painted is shown: zoom() reports from
|
|
107
|
+
// requestAnimationFrame, where a state update would land a frame after the canvas.
|
|
108
|
+
function storeOf() {
|
|
109
|
+
let shown = NOTHING;
|
|
110
|
+
const listeners = new Set();
|
|
111
|
+
return {
|
|
112
|
+
get: () => shown,
|
|
113
|
+
set(next) {
|
|
114
|
+
shown = { ...shown, ...next };
|
|
115
|
+
for (const l of listeners)
|
|
116
|
+
l();
|
|
117
|
+
},
|
|
118
|
+
clear(key) {
|
|
119
|
+
shown = { ...shown, [key]: NOTHING[key] };
|
|
120
|
+
},
|
|
121
|
+
subscribe: (l) => {
|
|
122
|
+
listeners.add(l);
|
|
123
|
+
return () => void listeners.delete(l);
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
const Overlay = memo(({ store }) => {
|
|
128
|
+
const { layout, hover, children } = useSyncExternalStore(store.subscribe, store.get);
|
|
129
|
+
return layout && children ? children(layout, hover) : null;
|
|
130
|
+
});
|
|
104
131
|
export function bind(chart) {
|
|
105
132
|
return function Chart(all) {
|
|
106
133
|
// width and height size the host only: the core measures it on both axes, so its ResizeObserver
|
|
107
134
|
// follows whatever else resizes the host (min-/max-, !important, a parent, a media query).
|
|
108
|
-
const { className, style, id, onError, ref: _, width, height, ...rest } = all;
|
|
135
|
+
const { className, style, id, onError, children, onLayout, onHover, ref: _, width, height, ...rest } = all;
|
|
109
136
|
const props = rest;
|
|
110
137
|
const host = useRef(null);
|
|
111
138
|
const bound = useRef({});
|
|
112
139
|
const reported = useRef(undefined);
|
|
140
|
+
const [store] = useState(storeOf);
|
|
141
|
+
const [overlay, setOverlay] = useState();
|
|
142
|
+
const layoutTo = useCallback((layout) => {
|
|
143
|
+
// With the children of the last props the chart took: they may have waited for this layout.
|
|
144
|
+
store.set({ layout, children: bound.current.children });
|
|
145
|
+
onLayout?.(layout);
|
|
146
|
+
}, [store, onLayout]);
|
|
147
|
+
const hoverTo = useCallback((hover) => {
|
|
148
|
+
store.set({ hover });
|
|
149
|
+
onHover?.(hover);
|
|
150
|
+
}, [store, onHover]);
|
|
151
|
+
// With a listener of the app's alone too: the chart reports nothing anew when children then appear.
|
|
152
|
+
if (children || onLayout)
|
|
153
|
+
props.onLayout = layoutTo;
|
|
154
|
+
if (children || onHover)
|
|
155
|
+
props.onHover = hoverTo;
|
|
113
156
|
useLayout(() => {
|
|
114
157
|
const el = host.current;
|
|
115
158
|
const sizing = [width, height, className, id, style];
|
|
@@ -170,13 +213,32 @@ export function bind(chart) {
|
|
|
170
213
|
detached?.unobserve(el);
|
|
171
214
|
bound.current.chart?.destroy();
|
|
172
215
|
bound.current = {};
|
|
216
|
+
store.clear('layout');
|
|
217
|
+
store.clear('hover');
|
|
173
218
|
};
|
|
174
|
-
}, []);
|
|
175
|
-
|
|
219
|
+
}, [store]);
|
|
220
|
+
useLayout(() => {
|
|
221
|
+
if (!children && !onLayout)
|
|
222
|
+
store.clear('layout');
|
|
223
|
+
if (!children && !onHover)
|
|
224
|
+
store.clear('hover');
|
|
225
|
+
// Not from the render, which comes before the chart has the props: its hover can name a row the new data lacks.
|
|
226
|
+
const b = bound.current;
|
|
227
|
+
if (!children || b.applied === props)
|
|
228
|
+
b.children = children;
|
|
229
|
+
const layer = children && b.chart?.overlay;
|
|
230
|
+
// A chart with no room takes props without reporting their layout, and the core hides its root for as long.
|
|
231
|
+
const hidden = layer?.parentElement?.style.visibility === 'hidden';
|
|
232
|
+
if (!hidden && store.get().children !== b.children)
|
|
233
|
+
store.set({ children: b.children });
|
|
234
|
+
setOverlay(layer);
|
|
235
|
+
});
|
|
236
|
+
const div = createElement('div', {
|
|
176
237
|
ref: host,
|
|
177
238
|
className,
|
|
178
239
|
id,
|
|
179
240
|
style: { ...style, width: style?.width ?? width, height: style?.height ?? height },
|
|
180
241
|
});
|
|
242
|
+
return createElement(Fragment, null, div, children && overlay && createPortal(createElement(Overlay, { store }), overlay));
|
|
181
243
|
};
|
|
182
244
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@swiftplot/react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "React components for swiftplot charts",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -21,7 +21,8 @@
|
|
|
21
21
|
],
|
|
22
22
|
"peerDependencies": {
|
|
23
23
|
"react": "^18.3 || ^19",
|
|
24
|
-
"
|
|
24
|
+
"react-dom": "^18.3 || ^19",
|
|
25
|
+
"swiftplot": "^0.5.0"
|
|
25
26
|
},
|
|
26
27
|
"devDependencies": {
|
|
27
28
|
"@types/node": "^24.19.2",
|
|
@@ -33,7 +34,7 @@
|
|
|
33
34
|
"react-dom": "^19.3.1",
|
|
34
35
|
"typescript": "^7.0.2",
|
|
35
36
|
"vitest": "^5.1.1",
|
|
36
|
-
"swiftplot": "0.
|
|
37
|
+
"swiftplot": "0.5.0"
|
|
37
38
|
},
|
|
38
39
|
"scripts": {
|
|
39
40
|
"build": "tsc -p tsconfig.build.json",
|