swiftplot 0.3.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 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.
@@ -60,28 +60,29 @@ chart.destroy();
60
60
 
61
61
  - **Defaults:**
62
62
 
63
- | Thing | Default | Override |
64
- | ------------------- | ------------------------------------------------------------------------- | -------------------------------------- |
65
- | Axis labels | the field's name; none for the row index, an accessor or several y fields | `xAxis.label`, `yAxis.label` |
66
- | Colours | `palette` in order, `paletteDark` on the dark theme | `colors` |
67
- | Tooltip | on; text in the y axis format, else two decimals at most | `tooltip: false` |
68
- | Legend | on with two or more series or named parts; a heatmap's strip of colours | `legend: false` or `legend()` options |
69
- | Zoom | off | `zoom: true` or `zoom()` options |
70
- | Animation | off | `animate: true` or `animate()` options |
71
- | Theme | follows the page | `theme: 'light' \| 'dark' \| Theme` |
72
- | Size | follows the container | `width`, `height`, `margin` |
73
- | Several y on areas | overlapping, half transparent | `stack: true` |
74
- | Several y on bars | side by side | `stack: true` |
75
- | Line and area shape | straight, with gaps | `curve`, `join` |
76
- | Scatter radius | 4 px | `r`: a number or a field |
63
+ | Thing | Default | Override |
64
+ | ------------------- | ------------------------------------------------------------------------- | --------------------------------------- |
65
+ | Axis labels | the field's name; none for the row index, an accessor or several y fields | `xAxis.label`, `yAxis.label` |
66
+ | Colours | `palette` in order, `paletteDark` on the dark theme | `colors` |
67
+ | Tooltip | on; text in the y axis format, else two decimals at most | `tooltip: false` |
68
+ | Legend | on with two or more series or named parts; a heatmap's strip of colours | `legend: false` or `legend()` options |
69
+ | Zoom | off | `zoom: true` or `zoom()` options |
70
+ | Animation | on: a reveal on the first paint, a move or a cross-fade on new data | `animate: false` or `animate()` options |
71
+ | Hover | everything else fades to 0.3 while one series or part is pointed at | `dim: false` or another opacity |
72
+ | Theme | follows the page | `theme: 'light' \| 'dark' \| Theme` |
73
+ | Size | follows the container | `width`, `height`, `margin` |
74
+ | Several y on areas | overlapping, half transparent | `stack: true` |
75
+ | Several y on bars | side by side | `stack: true` |
76
+ | Line and area shape | straight, with gaps | `curve`, `join` |
77
+ | Scatter radius | 4 px | `r`: a number or a field |
77
78
 
78
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'`.
79
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.
80
- - **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.
81
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 })`.
82
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.
83
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.
84
- - **`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.
85
86
 
86
87
  ## React and Vue
87
88
 
@@ -115,7 +116,23 @@ import { LineChart } from '@swiftplot/vue';
115
116
  <LineChart data={rows} x="date" y={['api', 'web']} zoom view={view} onViewChange={setView} />;
116
117
  ```
117
118
 
118
- 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
+ ```
119
136
 
120
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.
121
138
 
@@ -132,7 +149,7 @@ import { LineChart } from '@swiftplot/vue';
132
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.
133
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.
134
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.
135
- - **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`.
136
153
 
137
154
  ## Use
138
155
 
@@ -169,6 +186,7 @@ chart.destroy();
169
186
  - **Error bars** are `errorBars({ x, y1, y2 })`, or `{ y, x1, x2 }` lying down.
170
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.
171
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.
172
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.
173
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) })`.
174
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.
@@ -193,6 +211,7 @@ chart.destroy();
193
211
  );
194
212
  ```
195
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.
196
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.
197
216
 
198
217
  ```ts
package/dist/chart.js CHANGED
@@ -1,17 +1,29 @@
1
- import { locate, position } from './features/pointer.js';
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(['pointer', 'onClick', 'onPointerChange', 'onViewChange', 'onHiddenChange']);
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) && a[k] === 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.appendChild(e);
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)].flatMap(k => cache.get(k)?.p.rules ?? []);
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
- const theme = () => o.theme ?? light;
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;
@@ -778,9 +805,7 @@ export function plot(el, options) {
778
805
  let several = false;
779
806
  // One row is picked out where there is no other series to set the hovered one against, or where
780
807
  // the row is a named part of its mark, such as a slice, which is then the thing pointed at.
781
- const drawnRow = () => (o.dim ?? 1) !== 1 && focusedRow && !focusedRow.mark.rowsAlike && (!several || focusedRow.mark.entries)
782
- ? focusedRow
783
- : undefined;
808
+ const drawnRow = () => (o.dim ?? 1) !== 1 && focusedRow && (!several || focusedRow.mark.entries) ? focusedRow : undefined;
784
809
  const chosen = () => {
785
810
  if (!o.selected?.length)
786
811
  return undefined;
@@ -866,6 +891,62 @@ export function plot(el, options) {
866
891
  };
867
892
  let painter;
868
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
+ };
869
950
  const refresh = (data, also, restyled = false, asked = false) => {
870
951
  const before = viewKey;
871
952
  const shown = () => [xs.lo, xs.hi, ys.lo, ys.hi, ys2?.lo, ys2?.hi].join();
@@ -885,6 +966,7 @@ export function plot(el, options) {
885
966
  root.style.visibility = drawable ? '' : 'hidden';
886
967
  // Growing back always changes the view, so marks replaced while hidden are prepared then.
887
968
  if (!drawable) {
969
+ reported = undefined;
888
970
  flat = [];
889
971
  onGl = [];
890
972
  cache.clear();
@@ -968,6 +1050,16 @@ export function plot(el, options) {
968
1050
  const internals = {
969
1051
  root,
970
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
+ },
971
1063
  layer,
972
1064
  onPaint(p) {
973
1065
  painter = p;
@@ -995,10 +1087,12 @@ export function plot(el, options) {
995
1087
  if (refresh(true, relaid ? undefined : 'size'))
996
1088
  sync();
997
1089
  o.onHiddenChange?.(ids);
1090
+ report();
998
1091
  },
999
1092
  size: () => ({ width: W, height: H }),
1000
1093
  margin: () => m,
1001
1094
  theme,
1095
+ color,
1002
1096
  xPx,
1003
1097
  yPx,
1004
1098
  xValue: px => (px * dpr - view.ox) / view.kx,
@@ -1047,12 +1141,23 @@ export function plot(el, options) {
1047
1141
  ...(!fits.y.fitted && { y: [real('y', ys.lo), real('y', ys.hi)] }),
1048
1142
  ...(ys2 && !fits.y2.fitted && { y2: [real('y2', ys2.lo), real('y2', ys2.hi)] }),
1049
1143
  });
1144
+ report();
1050
1145
  return true;
1051
1146
  },
1052
1147
  real,
1053
1148
  frame: () => o.frame ?? 'axes',
1054
- drag: { brush: false, pan: false, active: false },
1055
- sync: () => sync(),
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
+ },
1056
1161
  // Topmost first, the reverse of render(): a hit that is no nearer never replaces one above it.
1057
1162
  hit(px, py, max) {
1058
1163
  const lit = drawnFocus();
@@ -1095,16 +1200,144 @@ export function plot(el, options) {
1095
1200
  o.onPointerChange?.(p);
1096
1201
  };
1097
1202
  let at;
1203
+ let under;
1098
1204
  const aim = () => {
1099
- root.style.cursor = o.onClick && at && clicked(at)?.hit ? 'pointer' : '';
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);
1100
1331
  };
1101
1332
  const point = (e) => {
1102
- at = e;
1333
+ if (destroyed || internals.drag.child)
1334
+ return;
1335
+ at = pointOf(e);
1103
1336
  aim();
1104
- if (internals.drag.active)
1105
- return tell(null);
1106
- const { px, py, over } = locate(internals, e);
1107
- tell(over ? valuesAt(px, py) : null);
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();
1108
1341
  };
1109
1342
  const valuesAt = (px, py) => ({
1110
1343
  x: real('x', internals.xValue(px)),
@@ -1113,34 +1346,40 @@ export function plot(el, options) {
1113
1346
  });
1114
1347
  const unpoint = () => {
1115
1348
  at = undefined;
1116
- root.style.cursor = '';
1349
+ aim();
1117
1350
  tell(null);
1351
+ reportHover();
1118
1352
  };
1119
- root.addEventListener('pointerdown', point);
1120
- root.addEventListener('pointermove', point);
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);
1121
1355
  root.addEventListener('pointerleave', unpoint);
1122
1356
  root.addEventListener('pointercancel', unpoint);
1123
1357
  const clicked = (e) => {
1124
- if (internals.drag.active || e.target !== root)
1358
+ if (internals.drag.active || !e.own)
1125
1359
  return undefined;
1126
1360
  const { px, py, inside } = position(internals, e.clientX, e.clientY);
1127
1361
  if (!inside)
1128
1362
  return undefined;
1129
1363
  return { px, py, hit: internals.hit(px, py, NEAREST_PX) };
1130
1364
  };
1131
- root.addEventListener('click', e => {
1132
- const c = o.onClick && clicked(e);
1133
- if (!c)
1134
- return;
1135
- const { px, py, hit } = c;
1136
- const on = hit ? onAxis(hit.mark) : 'y';
1137
- o.onClick(hit && {
1365
+ const shaped = (hit) => {
1366
+ const on = onAxis(hit.mark);
1367
+ return {
1138
1368
  ...hit,
1139
1369
  mark: declared.get(hit.mark) ?? hit.mark,
1140
1370
  x: real('x', hit.x),
1141
1371
  y: real(on, hit.y),
1142
1372
  ...(hit.value !== undefined && { value: real(on, hit.value) }),
1143
- }, valuesAt(px, py));
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));
1144
1383
  });
1145
1384
  showing();
1146
1385
  const features = [];
@@ -1176,12 +1415,14 @@ export function plot(el, options) {
1176
1415
  letGo();
1177
1416
  if (refresh(false, 'size'))
1178
1417
  sync();
1418
+ report();
1179
1419
  };
1180
1420
  const watch = () => {
1181
1421
  density = matchMedia(`(resolution: ${dpr}dppx)`);
1182
1422
  density.addEventListener('change', redensify, { once: true });
1183
1423
  };
1184
1424
  const teardown = () => {
1425
+ destroyed = true;
1185
1426
  let failed;
1186
1427
  const run = (f) => {
1187
1428
  try {
@@ -1193,6 +1434,7 @@ export function plot(el, options) {
1193
1434
  };
1194
1435
  run(() => observer?.disconnect());
1195
1436
  run(() => density?.removeEventListener('change', redensify));
1437
+ track();
1196
1438
  for (const f of features)
1197
1439
  run(() => f.destroy());
1198
1440
  for (const k of new Set([...marks, ...declared.keys()]))
@@ -1208,15 +1450,21 @@ export function plot(el, options) {
1208
1450
  measure();
1209
1451
  for (const feature of o.use ?? [])
1210
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);
1211
1457
  if (refresh(true))
1212
1458
  sync();
1213
1459
  observer = new ResizeObserver(() => {
1214
1460
  letGo();
1215
1461
  if (refresh(false, measure() ? 'size' : undefined))
1216
1462
  sync();
1463
+ report();
1217
1464
  });
1218
1465
  observe();
1219
1466
  watch();
1467
+ report();
1220
1468
  }
1221
1469
  catch (e) {
1222
1470
  try {
@@ -1227,7 +1475,13 @@ export function plot(el, options) {
1227
1475
  }
1228
1476
  return {
1229
1477
  update(partial) {
1230
- const keys = Object.keys(partial);
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
+ }
1231
1485
  if (!keys.length || !keys.every(k => LIGHT.has(k)))
1232
1486
  letGo();
1233
1487
  const prev = o;
@@ -1294,7 +1548,11 @@ export function plot(el, options) {
1294
1548
  const lost = unfocusGone();
1295
1549
  observe();
1296
1550
  const resized = measure();
1297
- const restyled = theme() !== (prev.theme ?? light);
1551
+ if (restyled) {
1552
+ taken = { ...given };
1553
+ styled = undefined;
1554
+ forget();
1555
+ }
1298
1556
  // Ticks are DOM and change at once, so a new window must not cross-fade with new marks.
1299
1557
  const moved = ['x', 'y', 'y2'].some(k => String(o.view?.[k]) !== String(prev.view?.[k]));
1300
1558
  if (refresh(data, resized || restyled || (hid && !relaid)
@@ -1305,7 +1563,13 @@ export function plot(el, options) {
1305
1563
  sync();
1306
1564
  else
1307
1565
  aim();
1566
+ report();
1308
1567
  },
1309
1568
  destroy: teardown,
1569
+ get overlay() {
1570
+ if (!overlay)
1571
+ adopt((overlay = layer('div', 'inset:0;isolation:isolate')));
1572
+ return overlay;
1573
+ },
1310
1574
  };
1311
1575
  }
@@ -9,6 +9,7 @@ export declare const sizeOf: (p: Base) => {
9
9
  height: number | undefined;
10
10
  margin: Partial<import("../types.js").Margin> | undefined;
11
11
  description: string | undefined;
12
+ dim: number;
12
13
  };
13
14
  export declare const featuresOf: (p: Base & Pick<Axes, 'zoom'>, listed: number) => {
14
15
  tooltip: boolean;