swiftplot 0.5.0 → 0.5.2

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
@@ -9,87 +9,30 @@
9
9
 
10
10
  Small, fast charts on Canvas 2D and WebGL2. MIT, TypeScript, ESM only, no dependencies.
11
11
 
12
- **Status: prototype.** It draws lines and areas (straight or stepped), bars, box plots, error bars, heatmaps, tick marks and scatter dots on linear, time and category axes, and pies, donuts, radars, radial bars, funnels, sankey diagrams, treemaps and sunbursts, with a hover tooltip, dim-the-others on hover and optional animation. A chart can be updated and follows its container when no size is given. `swiftplot/charts` builds each of these charts from the data alone, and bars and lines together, and `@swiftplot/react` and `@swiftplot/vue` make React and Vue components of them. There is a legend that hides and shows series, zoom and pan, a brush, a click event, the pointer from code for linked charts, light and dark themes, reference lines and zones, log axes, and tick steps and formats. The repository is a pnpm workspace with the core in `packages/core` and the wrappers in `packages/react` and `packages/vue`.
12
+ Examples, guides and the reference for every chart and option are at [swiftplot.dev](https://swiftplot.dev). Where the
13
+ project stands, what it lacks and what 1.0 needs: [swiftplot.dev/status](https://swiftplot.dev/status). Questions go to
14
+ [Discussions](https://github.com/GusevP/swiftplot/discussions).
13
15
 
14
- **For AI coding assistants:** [`llms-full.txt`](llms-full.txt) is a guide to writing code with swiftplot, and [`llms.txt`](llms.txt) its index.
16
+ **For AI coding assistants:** [`llms-full.txt`](https://swiftplot.dev/llms-full.txt) is a guide to writing code with
17
+ swiftplot, and [`llms.txt`](https://swiftplot.dev/llms.txt) its index.
15
18
 
16
- ## Charts from data
19
+ <img src="https://raw.githubusercontent.com/GusevP/swiftplot/main/assets/pan.gif" alt="Panning and zooming a line of a million points" width="640" />
17
20
 
18
- `swiftplot/charts` draws a chart from the data alone and lets every default be overridden. It is a second entry of the same package, built on the API under "Use", which it leaves unchanged.
21
+ ```sh
22
+ npm install swiftplot # plain JavaScript
23
+ npm install swiftplot @swiftplot/react # React 18.3 or 19
24
+ npm install swiftplot @swiftplot/vue # Vue 3.4 or later
25
+ ```
19
26
 
20
27
  ```ts
28
+ // <div id="chart" style="height: 320px"></div>
21
29
  import { lineChart } from 'swiftplot/charts';
22
30
 
23
- const chart = lineChart(el, { data: rows }); // fields guessed; axes, colours, tooltip and legend by default
24
- chart.update({ data: next }); // only what changed reaches the chart
25
- chart.destroy();
26
- ```
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(), 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
- - **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
- - **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
- - **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.
32
- - **Fields** of the line, area, bar and scatter charts are named by `x`, `y` (one field or a list) and `series`, by name or, on row objects only, by an accessor `(row, index) => value`. A named field is never second-guessed. What is not named is guessed, in field order (the keys of the first 100 rows, or of the columns object): `x` is the first date field, else the first text field, else the first number field when a `y` is named or another number field is left, else the row index; `y` is every number field left, one series each. A scatter chart takes the first date field, else the first number field, as `x` and the next number field as its one `y`; a named `y` may be text, for a band per category. `y2` names number fields drawn against an axis on the right, set by `y2Axis`; it is never guessed, and goes with neither `series` nor `errorBars`.
33
- - **The other charts** name their fields by what they have, by name or, on row objects, by an accessor. A single field of numbers is guessed only when one is left, and otherwise the error says what to pass:
34
-
35
- | Chart | Fields | Guessed | Other props |
36
- | ------------------------------- | --------------------------------------------------------------------- | ----------------------------------------------------------------------- | ------------------------------------------- |
37
- | `comboChart` | `x`, and `lines`, `bars`, `y2Lines`, `y2Bars`: a field or a list each | `x` as on a line chart; the rest never, and one is needed | `y2Axis`, `stack` |
38
- | `pieChart` | `label`, `value` | the first text field; the only number field | `inner` (above 0, a donut), `text`, `sweep` |
39
- | `funnelChart` | `label`, `value` | as a pie | `text`, `fill` |
40
- | `radialBarChart` | `label`, `value` | as a pie | `max`, `sweep`, `inner` |
41
- | `radarChart` | `x` (spokes), `y` (a shape each) | the first text field; every number field left | `max`, `fill` |
42
- | `heatmapChart` | `x`, `y`, `value` | the first two text or date fields; the only number field left | `color` |
43
- | `histogramChart` | `x` | the only number field | `bins` |
44
- | `boxPlotChart` | `x` (groups, or `null` for one box), `y` | the only text field, when its values repeat; the only number field | `fill` |
45
- | `candlestickChart` | `x`, `open`, `high`, `low`, `close` | the first date field, else text; the fields of those names, in any case | `up`, `down` |
46
- | `sankeyChart` | `source`, `target`, `value` | the first two text fields; the only number field left | `blend`, `text` |
47
- | `treemapChart`, `sunburstChart` | none | | `shade`, `text` |
48
-
49
- - **Errors** name the chart; an error about fields also names the fields with their kinds and the prop to pass. On the line, area, bar and scatter charts guessing throws when no number field is left for `y` (naming any field of numbers held as text), on all but the scatter when a text field is left over without `series` or `y2` (the rows look like long data, even with `x` and `y` named), for a named field that does not exist or is not numbers where numbers are needed, and for a scatter chart without two usable fields or with more than one `y`. An update that throws leaves the chart as it was.
50
- - **Rows:** line and area charts, and combos on dates or numbers, sort rows by x (stably); bar and scatter charts, and combos on text, keep the given order. On these a row with a missing x (or, on a scatter, a missing `r`) is dropped; a missing y is a gap. Pies, funnels, radial bars and radars keep a row with no name, unnamed; heatmaps, box plots and sankeys drop a row with no cell, group or node. A heatmap puts text in order of first appearance and dates and numbers ascending.
51
- - **Axes:** settings go under `xAxis` and `yAxis`. Which x settings apply depends on the x field:
52
-
53
- | x | axis | settings |
54
- | ----------------------------------------------- | -------- | -------------------------------------------------------------------------------------------------- |
55
- | numbers, row index | linear | `label`, `domain` (`'nice'` by default), `step`, `format`, `fit` |
56
- | dates | time | `label`, `utc`, `unit` and `every`, `format`, `fit`, `domain` as `[from, to]` in milliseconds only |
57
- | text, and every bar chart, box plot and heatmap | category | `label` only |
58
-
59
- `yAxis` takes `label`, `domain`, `step`, `format` and `fit` (a heatmap's `label` only), `y2Axis` the same, and on line, scatter and combo charts `scale: 'log'`, where a value at or below zero is a gap, `step` does not apply and bars cannot share the axis. A combo or a candlestick chart puts text in categories; on dates and numbers a bar or a candle takes 0.6 of the smallest gap between x values. Pies, donuts, radars, radial bars, funnels, sankeys, treemaps and sunbursts have no axes, and only the charts that have them zoom, box plots and heatmaps excepted. The bars of `barChart` put each row (or, with `series`, each distinct x in order of first appearance) in a category of its own, dates included, labelled in UTC whatever `utc` says.
60
-
61
- - **Defaults:**
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 | 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 |
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'`.
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, 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
- - **`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
- - **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
- - **`.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(), 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
-
87
- ## React and Vue
88
-
89
- `@swiftplot/react` (React 18.3 or 19) and `@swiftplot/vue` (Vue 3.4 or later) make a component of each chart above, named as its function with a capital: `LineChart`, `AreaChart`, `BarChart`, `ScatterChart`, `ComboChart`, `PieChart`, `FunnelChart`, `RadialBarChart`, `RadarChart`, `HeatmapChart`, `HistogramChart`, `BoxPlotChart`, `CandlestickChart`, `SankeyChart`, `TreemapChart` and `SunburstChart`, and `Plot` for the explicit API. Each takes the props of its function, renders one `div`, creates the chart after mount, sends it only what changed on each render and destroys it on unmount. Install `swiftplot` beside the wrapper, which has it as a peer dependency:
90
-
91
- ```sh
92
- pnpm add swiftplot @swiftplot/react # or @swiftplot/vue
31
+ const rows = [
32
+ { date: '2026-11-01', api: 120, web: 80 },
33
+ { date: '2026-11-02', api: 132, web: 95 },
34
+ ];
35
+ lineChart(document.getElementById('chart')!, { data: rows });
93
36
  ```
94
37
 
95
38
  ```tsx
@@ -108,143 +51,9 @@ import { LineChart } from '@swiftplot/vue';
108
51
  </template>
109
52
  ```
110
53
 
111
- - **Props** are the chart function's, checked against the data's type in JSX and in Vue templates (`y="nope"` on rows without that field is a type error). `createElement` and `h()` do not infer the data's type: give it, `h(LineChart<Row[]>, props)`, and the field names are checked as in a template. `className` (React) or `class` (Vue), `style` and `id` go to the `div`.
112
- - **State** (`view`, `hidden`, `selected`, `pointer`) is kept by the chart unless the prop is given. To control the zoom window, pass `view` and set it from the change:
113
-
114
- ```tsx
115
- const [view, setView] = useState<{ x?: [number, number]; y?: [number, number] }>();
116
- <LineChart data={rows} x="date" y={['api', 'web']} zoom view={view} onViewChange={setView} />;
117
- ```
118
-
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
- ```
136
-
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.
138
-
139
- ```tsx
140
- import { band, bands, bar } from 'swiftplot';
141
- import { Plot } from '@swiftplot/react';
142
-
143
- const days = ['Mon', 'Tue', 'Wed'];
144
- const [y1, y2] = bands(days.length);
145
- const marks = [bar({ y1, y2, x: [12, 19, 7], color: '#2563eb', label: 'Orders' })];
146
- <Plot x={{ domain: 'nice', label: 'Orders' }} y={band({ label: 'Day', categories: days })} marks={marks} />;
147
- ```
148
-
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.
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.
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.
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`.
153
-
154
- ## Use
155
-
156
- ```ts
157
- import { dots, plot, tooltip } from 'swiftplot';
158
-
159
- const chart = plot(document.getElementById('chart')!, {
160
- width: 900,
161
- height: 600,
162
- x: { domain: 'nice', label: 'X' },
163
- y: { domain: 'nice', label: 'Y' },
164
- marks: [dots({ x, y, r, color: '#2563eb', alpha: 0.7, label: 'Group 1' })],
165
- use: [tooltip({ mode: 'nearest', text: (label, x, y) => `${label}: (${x.toFixed(1)}, ${y.toFixed(1)})` })],
166
- dim: 0.3,
167
- });
168
-
169
- chart.update({ marks: [dots({ x, y: y2, r, color: '#2563eb', label: 'Group 1' })] });
170
- chart.destroy();
171
- ```
172
-
173
- - **Marks** are imported functions: `line`, `area`, `bar`, `box`, `candlestick`, `errorBars`, `heatmap`, `ticks`, `dots`, `arcs`, `radar`, `radialBars`, `funnel`, `sankey`, `treemap`, `sunburst`. Only the ones you import are bundled.
174
- - **Lines and areas** are straight between points unless `curve: 'step'` or `curve: 'smooth'`, which curves through the points without overshooting them. `area({ x, y })` fills from zero; `area({ x, y1, y2 })` is a band. A `y` that is `NaN` or infinite leaves a gap: nothing is joined across it, and a lone point between two gaps draws nothing; `join: true` draws a line or fills an area straight across instead. `x` must be finite and ascending.
175
- - **Bars** have explicit bounds, `bar({ x1, x2, y1, y2 })`, so vertical, horizontal, grouped and stacked bars are the same mark. A single `y` (or `x`) starts at zero. On a category axis `const [x1, x2] = bands(7)` gives the bounds. Grouped bars are `bar({ x, y, dodge: 'years' })` for each series, `x` being the category's place: the chart gives the shown series of that id a slot each, in the order listed, so hiding one widens the others. With `dodge` or `stack`, `width` is how much of x the bars of one place take together, 0.8 by default. `bands(7, { slot: 0, of: 2 })` gives one series' bounds for a chart that never hides it.
176
- - **Box plots** take the five numbers as columns: `box({ x, ...fiveNumbers(groups), color })`. The whiskers go to the minimum and maximum; leave outliers out and draw them with `dots`.
177
- - **Heatmaps** are `heatmap({ values, columns, color: sequential({ stops }) })`, with cell (c, r) centred on x = c, y = r so it sits on band axes; `x` and `y` give the grid's outer edges instead. Create the colour scale once, outside the update, or every update repaints the grid.
178
- - **Pies and donuts** are `plot(el, { frame: 'polar', marks: [arcs({ values, colors, labels, inner: 0.6, text: true })] })`. A polar frame has no axes; slices start at twelve o'clock and run clockwise. `labels` give the legend one entry per slice, and `text` writes each slice's share on it where there is room. With `animate()` a pie is revealed by a sweep round the clock.
179
- - **Radars** are `plot(el, { frame: 'polar', marks: radar({ axes, series: [{ values, color, label }] }) })`. `radar()` returns several marks: the rings and spokes, then one per series, so series are named in a legend and dimmed like lines, and a hit's row is the spoke. The rim is `max`, or the largest value rounded up.
180
- - **Radial bars** are `plot(el, { frame: 'polar', marks: [radialBars({ values, max, colors, labels })] })`: one bar per value on its own ring, from twelve o'clock clockwise. Three quarters of a turn stand for `max`; the last quarter holds the names.
181
- - **Treemaps and sunbursts** take a tree in columns, `{ nodes, parent, value }`, or `fromTree()` of nested `{ name, value, children }` objects: `plot(el, { frame: 'blank', marks: [treemap({ ...fromTree(tree), colors })] })` and `plot(el, { frame: 'polar', marks: [sunburst({ ...fromTree(tree), colors })] })`. Only the values of nodes without children count. Each root gets a colour, or each child of a single root. A treemap draws the leaves; a sunburst draws every node, a single root as a disc in the middle.
182
- - **Funnels** are `plot(el, { frame: 'blank', marks: [funnel({ values, colors, labels, text: true })] })`: equally tall stages, each as wide as its value against the largest.
183
- - **Sankey diagrams** are `sankey({ ...fromLinks(links), colors })` in a blank frame, where `links` is a list of `{ source, target, value }`. A cycle, a link to itself or a link to an unknown node throws. A hit's row is the node, or `nodes.length` plus the link.
184
- - **Labels on shapes** (slices, stages, nodes) are drawn where they fit and left out where they would overlap or run off the chart.
185
- - **A colour legend** for a heatmap comes with `legend()`: a strip of its colours between the ends of its domain.
186
- - **Error bars** are `errorBars({ x, y1, y2 })`, or `{ y, x1, x2 }` lying down.
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.
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.
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.
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) })`.
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
- - **No axes:** `x: bare()` and `y: bare([0, 100])` place the marks and draw no ticks, grid or label, for a chart inside a card.
194
- - **Rows** need no helper: `Float64Array.from(rows, r => r.value)` makes a column and `Map.groupBy(rows, r => r.series)` splits rows into series.
195
- - **Ticks** thin out to fit the axis, so a narrow chart shows fewer labels, not overlapping ones.
196
- - **Accessibility:** the chart is exposed as an image with a label built from the axis labels and series names; set `description` to say what it shows. The data itself is not exposed yet.
197
- - **Margins** are sized from the tick labels; pass `margin: { left: 80 }` to set a side yourself.
198
- - **Legend** is a feature you import: `use: [legend()]` lists each labelled series above the plot, highlights it on hover, and hides or shows it on a click, a tap, Enter or Space (`legend({ toggle: false })` turns that off). A label wider than the plot ends in an ellipsis. Rows are capped at what fits in a third of the chart's height, or at `legend({ rows: 2 })`, and the entries left over go behind "+N more".
199
- - **Zoom and pan** is a feature you import: `use: [zoom()]`. Ctrl or cmd and the wheel (a trackpad pinch) zoom about the pointer, a drag pans, and a double click or double tap shows the whole domain again; on a touch screen two fingers pinch and pan and one scrolls the page. `zoom({ axes: 'xy', wheel: 'plain', drag: 'shift' })` zooms both axes, zooms on a plain wheel and pans only with shift held. A mouse drag along both axes pans x alone until it has moved 8 px up or down, so panning level keeps an axis with `fit: 'window'` fitting; panning up or down, or zooming y, gives both y axes a window of their own, which stops the fitting. Two fingers on a touch screen have no such threshold. Over the plot a ctrl or cmd wheel never reaches the page unless `wheel: false`, and with `wheel: 'plain'` a plain one reaches it only when the view cannot move further. The window is the `view` option, `{ x?: [lo, hi], y?: [lo, hi] }` in axis values, shown clamped to the domain; `onViewChange` reports it after a gesture, never for `update()`. `y: { domain: 'nice', label, fit: 'window' }` fits y to what the x window shows.
200
- - **A brush** reports a range: `use: [brush({ onSelect: range => ... })]`. A drag draws a rectangle and `onSelect` gets `{ x, y }` in axis values on release, then `null` once it is cleared; `brush({ zoom: true })` shows the range brushed. With a brush beside `zoom()`, a plain drag brushes and shift and a drag pans. Mouse and pen only.
201
- - **Hidden series:** `hidden: ['Group 1']` leaves out the series a legend lists under that id (a mark's `group`, or its `label`), from the start or from code, and `onHiddenChange(hidden)` reports a change the legend made. An automatic domain fits what is shown; `fit: 'all'` on an axis holds it still. The chart restacks layers given a `stack` id and re-dodges bars given a `dodge` id; the layers `stack()` returns are computed by the app, so it restacks in `onHiddenChange`.
202
- - **Clicks and the pointer:** `onClick(hit, at)` gets what is within 20 px of a click on the plot, or `null`, and the axis values at the click; a click that ends a drag is not one. `selected: [{ id: 'Group 1', rows: [3] }]` picks rows out. `pointer: { x, y }` shows a tooltip as if the user's pointer were there, and `onPointerChange` reports the user's, with `null` as it leaves, so two charts can follow each other:
203
-
204
- ```ts
205
- const charts = [a, b].map((el, i) =>
206
- plot(el, {
207
- ...options,
208
- onPointerChange: p => charts[1 - i]!.update({ pointer: p }),
209
- use: [tooltip(tip)],
210
- }),
211
- );
212
- ```
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.
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.
216
-
217
- ```ts
218
- const scheme = matchMedia('(prefers-color-scheme: dark)');
219
- const chart = plot(el, { ...options, theme: scheme.matches ? dark : light });
220
- scheme.addEventListener('change', e => chart.update({ theme: e.matches ? dark : light }));
221
- ```
222
-
223
- - **Reference lines and zones:** `rule({ y: 50, color: '#dc2626', dashed: true, text: 'Target' })` draws a line across the plot at each value, and `zone({ x1, x2, color, text })` a band between two values. A rule is always above the data and a zone under it, wherever they are in `marks`; neither widens a domain or counts as a series.
224
- - **Tick step and format:** an axis's `step` puts ticks on multiples of it, thinned when their labels do not fit, and `format` labels them; `time({ label, every: 3, unit: 'month', format })` does the same on a time axis. Define `format` once, outside the update: a new function each time counts as a changed axis, so its ticks are worked out again and the data is repainted, which `animate()` shows as a cross-fade.
225
-
226
- ```ts
227
- const percent = (v: number) => `${v * 100}%`;
228
- chart.update({ y: { domain: 'nice', label: 'Share', step: 0.25, format: percent } });
229
- ```
230
-
231
- - **Log axes:** `const y = log({ label: 'Count' })` (`base` defaults to 10, `domain` takes real values above zero). Marks take their columns through it, `line({ x, y: y.col(counts), color })`, and a value at or below zero becomes a gap. Everything the app is given or gives (`view`, `pointer`, callbacks, tooltip text) is a real value; a rule or zone takes `y.to(v, y)`. Bars need both ends given, `bar({ x1, x2, y1: y.col(lows), y2: y.col(highs), color })` with `[x1, x2]` from `bands()`, since zero has no place on a log axis, and nothing is stacked on one.
232
- - **Histograms and stacks** are plain functions feeding the marks: `bar({ ...bin(values, 20), color })`, and `area({ x, y, stack: 'traffic' })` or `bar({ x, y, stack: 'traffic' })` for each series stacks the shown series of that id in the order listed, negative values downwards, so hiding one closes the gap; a tooltip and `onClick` report a layer's own value. `stack([a, b, c])` gives each series the `y1` and `y2` of its layer once, for a chart that never hides one. A `NaN` in a layer counts as zero: that layer has no thickness there.
233
- - **Hover** highlights the series under the pointer and dims the others (`dim`). Where a chart has only one series, the hovered bar is picked out from the other bars instead.
234
- - **Tooltips** are `tooltip({ mode: 'nearest', text })`, for what is nearest the pointer, or `tooltip({ mode: 'x', title, value })`, for every labelled line and area at its x; there `snap: x => other` reads them at another x, such as the nearest row's.
235
- - **Touch:** a tap shows the tooltip, and it stays after the finger lifts until a tap elsewhere or the next update or resize of the chart, which lets it go. A pen behaves as a mouse. Without `zoom()` the chart adds no listener that blocks the page from scrolling; with it the chart takes `touch-action: pan-x pan-y`, so one finger still scrolls the page.
236
- - **Animation** is a feature you import: `use: [animate({ duration: 300 })]`. Marks are revealed from the left on the first paint (`enter: 'fade'` fades them in instead). When the data changes, bars move to their new values, row for row, and everything else cross-fades. It is skipped for a resize, with reduced motion, and while updates arrive faster than the duration.
237
- - **A second y axis:** `y2: { domain, label }` draws an axis on the right, and a mark given `yAxis: 'y2'` is drawn against it: `marks: [bar({ x, y: revenue, color }), line({ x, y: margin, color, yAxis: 'y2' })]`. Each axis takes its extent from its own marks, grid lines come from `y` only, and there are exactly two. A zoom or a pan on y moves `y2` through the same pixels; `view`, `onViewChange`, the click's `at`, `pointer`, `onPointerChange` and a brush's range carry `y2`, and an `x` tooltip's `value(v, axis)` is told which axis a value is on. A y `rule` or `zone` takes `yAxis` too. Bars or areas stacked under one name on the two axes are two stacks; dodged bars share their slots whichever axis they are on.
238
- - **Axes** are linear by default: `{ domain: 'nice' | 'data' | [lo, hi], label }`. `time({ label })` takes millisecond timestamps and puts ticks on calendar boundaries, in UTC unless `utc: false`. `log({ label })` is a log axis. `step` and `format` set the ticks, and `fit` which marks an automatic domain is fitted to. `band({ label, categories })` puts category `i` at `x = i`, owning `i - 0.5` to `i + 0.5`.
239
- - **Columns** (`x`, `y`, `r`) are typed arrays or plain number arrays, one set per mark.
240
- - **Size**: leave out `width` or `height` and the chart follows its container, which must then have a size of its own (a container with no height gives an empty chart, which draws once the container gets a height).
241
- - **Updates**: a mark whose options are unchanged keeps its geometry, so passing a fresh `marks` array is cheap. Columns are compared by identity: after writing new values into the same array, pass a new array or view of it (`x.subarray(0)`).
242
- - **Without a DOM:** the package imports in Node, and marks and transforms such as `bin` and `stack` run there; `plot()` needs a browser.
243
- - **Your own mark** is an object with the `Mark` shape from the package's types.
244
-
245
54
  ## Why it is fast
246
55
 
247
- Each point comes from profiling uPlot, the fastest of thirteen libraries in [chart-bench](https://github.com/gusevp/chart-bench), and timing the alternative.
56
+ Each point comes from profiling uPlot, the fastest of the other twelve libraries in [chart-bench](https://github.com/gusevp/chart-bench) with the CPU slowed 4×, and timing the alternative.
248
57
 
249
58
  - **Axis text is DOM, not canvas text.** uPlot's axis drawing cost 17–21 ms at 4× CPU slowdown at every data size.
250
59
  - **Each mark has its own x column.** No aligned table, so no join step.
@@ -255,33 +64,47 @@ Each point comes from profiling uPlot, the fastest of thirteen libraries in [cha
255
64
 
256
65
  ## Measured
257
66
 
258
- Mount time in chart-bench, median ms, 2026-11-24, Apple M3 Pro that was not idle. Each cell is the mean of two runs of nine loads, each load a new page, with the two libraries taking turns to go first. 4× is Chrome's CPU slowdown. At native speed the two smaller sizes sit at the empty-page floor (about 27 ms), so only the other rows and columns separate the libraries.
67
+ Mount time in chart-bench, median ms, 2026-11-26, Apple M3 Pro that was not idle. Each cell is one run of nine loads, each load a new page; the tables of 2026-11-24 were the mean of two runs with the libraries taking turns to go first. The 3 × 200, 6 × 1,000, 500 and 10,000 rows come from the run of all fourteen arms, whose [full table](https://github.com/gusevp/chart-bench#results) has the other libraries; the 10 × 10,000 and 100,000 rows from a [separate run of the two libraries](https://github.com/gusevp/chart-bench#large-data-swiftplot-and-uplot) on the same day. 4× is Chrome's CPU slowdown.
259
68
 
260
69
  | case | swiftplot | uPlot | swiftplot, 4× | uPlot, 4× |
261
70
  | ------------------------ | --------: | ----: | ------------: | --------: |
262
- | survival, 3 × 200 points | 26.8 | 28.8 | 47.9 | 58.3 |
263
- | survival, 6 × 1,000 | 29.4 | 22.1 | 49.6 | 71.1 |
264
- | survival, 10 × 10,000 | 33.1 | 55.2 | 86.0 | 218.2 |
265
- | scatter, 500 | 26.2 | 26.1 | 37.7 | 60.0 |
266
- | scatter, 10,000 | 25.3 | 25.8 | 52.0 | 66.5 |
267
- | scatter, 100,000 | 32.2 | 34.9 | 68.0 | 137.5 |
71
+ | survival, 3 × 200 points | 31.0 | 23.5 | 41.6 | 55.3 |
72
+ | survival, 6 × 1,000 | 26.1 | 28.4 | 50.7 | 69.0 |
73
+ | survival, 10 × 10,000 | 30.4 | 53.9 | 85.0 | 202.1 |
74
+ | scatter, 500 | 27.9 | 27.4 | 37.0 | 57.9 |
75
+ | scatter, 10,000 | 26.3 | 30.4 | 45.6 | 76.3 |
76
+ | scatter, 100,000 | 26.2 | 35.1 | 68.7 | 135.2 |
77
+
78
+ An empty page measured 20.6–25.4 ms at native speed and 15.0–23.2 ms at 4×, and the clock stops two frames after the chart is done, so a gap under one frame (16.7 ms) is a tie, and so, as chart-bench reads it, is a gap under 20% on a heavy chart. At native speed the two tie on every case but the 10 × 10,000 survival chart, where swiftplot is ahead. At 4× swiftplot is ahead on every case but the 3 × 200 survival chart, a tie.
268
79
 
269
80
  Time until the chart's own code has finished, which leaves out the wait for the next frame:
270
81
 
271
82
  | case | swiftplot | uPlot | swiftplot, 4× | uPlot, 4× |
272
83
  | ------------------------ | --------: | ----: | ------------: | --------: |
273
- | survival, 3 × 200 points | 5.1 | 9.4 | 25.5 | 45.1 |
274
- | survival, 6 × 1,000 | 8.0 | 13.2 | 30.9 | 58.7 |
275
- | survival, 10 × 10,000 | 19.6 | 51.3 | 66.9 | 200.9 |
276
- | scatter, 500 | 4.3 | 8.3 | 19.2 | 45.9 |
277
- | scatter, 10,000 | 6.8 | 11.8 | 31.4 | 51.9 |
278
- | scatter, 100,000 | 14.2 | 29.3 | 48.8 | 119.1 |
279
-
280
- - Every load is the first chart on a new page, so each cell includes the browser parsing the library's code for the first time. A second chart on the same page does not pay that.
84
+ | survival, 3 × 200 points | 6.3 | 10.6 | 24.1 | 43.4 |
85
+ | survival, 6 × 1,000 | 9.1 | 13.8 | 31.2 | 56.2 |
86
+ | survival, 10 × 10,000 | 18.5 | 49.3 | 65.6 | 186.8 |
87
+ | scatter, 500 | 4.7 | 9.1 | 19.4 | 45.2 |
88
+ | scatter, 10,000 | 7.7 | 12.3 | 28.7 | 60.9 |
89
+ | scatter, 100,000 | 15.6 | 30.4 | 48.7 | 118.4 |
90
+
91
+ - Every load is the first chart on a new page. The clock starts when the harness asks the loaded page to mount the chart, so loading and evaluating the library's code is not counted: these are first-mount times, not page startup.
281
92
  - The 100k scatter runs on WebGL, where the draw call returns before the GPU finishes, so its numbers flatter swiftplot.
282
93
  - uPlot has no built-in scatter, so its scatter numbers include circle-drawing code written for the benchmark.
283
94
  - Only these two chart types are in the benchmark. Bars, areas, the time axis, the legend and animation are not measured against uPlot.
284
- - uPlot ships far more features in the 23.9 KB gzip it adds to the benchmark page (plus a stylesheet); swiftplot adds 15.8 KB, with its tooltip and animation.
95
+
96
+ Gzip size of the minified bundle of each entry in `site/scripts/size/`, built from the packages' `dist` with Vite and measured by `pnpm size` into `site/scripts/size/sizes.json`, in KB. Each entry uses what it imports, so nothing it names is shaken out.
97
+
98
+ | entry | imports | KB |
99
+ | ------------------ | ------------------------------------------------------- | ---: |
100
+ | plot-line | `plot` and `line` from `swiftplot` | 14.4 |
101
+ | plot-line-features | the same with `tooltip`, `legend`, `zoom` and `animate` | 19.1 |
102
+ | line-chart | `lineChart` from `swiftplot/charts` | 37.6 |
103
+ | all-charts | every chart of `swiftplot/charts` | 54.7 |
104
+ | react-line-chart | `LineChart` from `@swiftplot/react`, React not counted | 39.3 |
105
+ | vue-line-chart | `LineChart` from `@swiftplot/vue`, Vue not counted | 39.8 |
106
+
107
+ On chart-bench's page, which bundles `plot`, `line`, `area`, `ticks`, `dots`, `tooltip` and `animate`, swiftplot 0.5.0 adds 19.3 KB and uPlot 23.9 KB (`results/bundle.json`: the arm's page less the same page with no chart). uPlot ships more in its size: it is one module that comes whole, with its legend, cursor, selection and series types whether a page uses them or not.
285
108
 
286
109
  Script time of one pan step, `propose()` of a window moved by a hundredth of its width (at the whole domain, one narrowed by a thousandth), median ms of 50, on an 800 × 400 chart, 2026-11-22, Apple M3 Pro, Chrome on Metal. Before → after is the remedy of the same date: a line or an area reads only the rows its window shows, and points on the canvas skip those that cannot reach the plot.
287
110
 
@@ -328,44 +151,6 @@ The same step at 1,000,000 points with `fit: 'window'` on the y axis, 2026-11-22
328
151
 
329
152
  - A line or an area finds the rows in its window by binary search, so the fit costs the rows the window holds. Bars and points need not be in x order, so the fit reads every row.
330
153
 
331
- ## Develop
332
-
333
- From the repository root. `build`, `test` and `typecheck` run in every package under `packages/` and in the site (`site/`), `test:import` in the packages only. GitHub runs these checks, then packs the packages and checks the tarballs, on every push to `main` and every pull request (`.github/workflows/ci.yml`, read-only):
334
-
335
- ```sh
336
- pnpm install
337
- pnpm --filter swiftplot exec playwright install chromium # once, for the tests
338
- pnpm build
339
- pnpm test:import # imports each package's dist/ in Node, after pnpm build
340
- pnpm test:smoke # Playwright on the built site, after pnpm build
341
- pnpm test # Vitest (in a real browser for the packages), one package at a time, then node --test on scripts/
342
- pnpm typecheck
343
- pnpm --filter swiftplot run test # one package
344
- pnpm lint # oxlint, type-aware
345
- pnpm format # oxfmt
346
- ```
347
-
348
- The site is the Astro project in `site/`. `pnpm --filter swiftplot-site dev` serves it while you edit; `pnpm --filter swiftplot-site build`, then `pnpm --filter swiftplot-site exec astro preview`, serves the build, with search. `pnpm test:smoke` needs that build in `site/dist` and the Chromium installed above, and starts the preview itself. The site's other commands and its Cloudflare Pages settings are in [site/README.md](site/README.md).
349
-
350
- ## Releasing
351
-
352
- Every package has the same version, and one release is one tag `vX.Y.Z` and one GitHub Release with the three tarballs and `SHA256SUMS`. The changelog is `CHANGELOG.md`: work adds its entries under `## Unreleased`, written by hand. Two commands, run on your machine with your own `git`, `gh` and `npm` logins:
353
-
354
- ```sh
355
- pnpm release:prepare <version | patch | minor | major> # one local commit: versions and changelog
356
- pnpm release [--npm] [--dry-run] # releases the commit on main
357
- ```
358
-
359
- `release:prepare` needs a clean tree, a version higher than the current one and than every `v` tag on `origin`, and entries under `## Unreleased`. It sets the version in every package, turns `## Unreleased` into `## X.Y.Z - date` and commits `release: vX.Y.Z`. It does not push or tag: get the commit onto `main` as usual and let its checks run. A version with a hyphen (`0.1.0-rc.0`) is a pre-release.
360
-
361
- `pnpm release` takes the version from the packages and, when the tag does not exist yet, requires a clean tree, `HEAD` equal to `main` on `origin`, a version higher than every tag and changelog entries for it. It waits for the `ci.yml` push run on `main` for that commit and requires it and its `check` and `pack` jobs to have passed (a pull-request run does not count). It builds the tarballs from a clean export of the commit, checks them and keeps them in `.release/<version>/`. It then shows the commit, each file with its size and SHA-256, and the notes (the changelog section), and asks you to type the version. Only then does it push the tag to `origin` and create, upload to and publish the GitHub Release. A published release is never changed: one that differs from what was confirmed stops the command, naming what differs.
362
-
363
- If it stops, fix the cause and run it again: each step checks what is already done. Once the tag exists, a run continues that release on the tag's commit, even when `main` has moved on, and asks again before writing. A `.release/<version>/` that no longer matches stops the command with a message to remove it. `--dry-run` builds and shows the same preview, lists every reason a real run would stop, and writes nothing. It looks at the `ci.yml` run once, so it also lists a run still queued or in progress, which a real run waits up to 30 minutes for.
364
-
365
- `--npm` then publishes the published release's own files to npm in the order `swiftplot`, `@swiftplot/react`, `@swiftplot/vue`, a pre-release under the dist-tag `next`. npm refuses a `private` package, and every package is `"private": true` for now, so `--npm` stops before anything is written. To publish, remove `private` from the three packages before `release:prepare`: the check reads the packages at the release commit. A release made without `--npm` can go to npm later with `pnpm release --npm`.
366
-
367
- npm's staged publishing holds a new version for approval on npmjs.com, and a waiting version does not show in `npm view`. So the command keeps a receipt per package in `.release/<version>/npm.json` on your machine and never publishes a package twice. At the end it says for each package whether it is public, waiting, unconfirmed (sent, but npm did not answer; check npmjs.com), not published or not checked. A waiting version is approved on npmjs.com. If npmjs.com shows no publish of a package, because it was rejected or never arrived, remove that package's entry from `npm.json` and run again. `.release/<version>/npm.lock` stops a second publish of the same version; if a run was killed and none is running, remove `npm.lock`, not `npm.json`.
368
-
369
154
  ## Licence
370
155
 
371
156
  The code is MIT. The swiftplot name and logo are not covered by that licence.
package/dist/chart.js CHANGED
@@ -1,4 +1,4 @@
1
- import { extend, resolver } from './color.js';
1
+ import { extend, resolver, windowOf } from './color.js';
2
2
  import { copied, keep, sameData } from './equal.js';
3
3
  import { owns, position, presses, released, strayed } from './features/pointer.js';
4
4
  import { upTo } from './marks/common.js';
@@ -65,12 +65,14 @@ const clamp = (want, [p, q]) => {
65
65
  */
66
66
  export function plot(el, options) {
67
67
  let o = options;
68
- let dpr = devicePixelRatio;
69
- const root = document.createElement('div');
68
+ const doc = el.ownerDocument;
69
+ const win = windowOf(el);
70
+ let dpr = win.devicePixelRatio;
71
+ const root = doc.createElement('div');
70
72
  root.style.cssText = `position:relative;font:${FONT};pointer-events:auto`;
71
73
  let overlay;
72
74
  const layer = (tag, css = '') => {
73
- const e = document.createElement(tag);
75
+ const e = doc.createElement(tag);
74
76
  e.style.cssText = `position:absolute;pointer-events:none;${css}`;
75
77
  return root.insertBefore(e, overlay?.parentNode === root ? overlay : null);
76
78
  };
@@ -305,7 +307,7 @@ export function plot(el, options) {
305
307
  return;
306
308
  noted = key;
307
309
  boxes = kept.map(k => {
308
- const el = document.createElement('div');
310
+ const el = doc.createElement('div');
309
311
  el.textContent = k.text;
310
312
  el.style.cssText = `position:absolute;white-space:nowrap;line-height:16px;left:${k.l}px;top:${k.t}px;width:${k.r - k.l}px;text-align:center`;
311
313
  if (k.color)
@@ -333,7 +335,7 @@ export function plot(el, options) {
333
335
  clipped = '';
334
336
  }
335
337
  lines.replaceChildren(...wanted.map(r => {
336
- const e = document.createElement('div');
338
+ const e = doc.createElement('div');
337
339
  const w = Number(r.width) / dpr;
338
340
  const along = (at, lo, size) => Math.min(Math.max(Math.round(at - r.width / 2) / dpr, lo / dpr), (lo + size) / dpr - w);
339
341
  e.style.cssText =
@@ -657,9 +659,9 @@ export function plot(el, options) {
657
659
  if (key !== axesKey) {
658
660
  axesKey = key;
659
661
  // Axis text is DOM, not fillText: the first text drawn on a canvas cost ~20 ms at 4x CPU slowdown.
660
- const labels = document.createDocumentFragment();
662
+ const labels = doc.createDocumentFragment();
661
663
  const text = (s, x, y, transform) => {
662
- const e = document.createElement('div');
664
+ const e = doc.createElement('div');
663
665
  e.textContent = s;
664
666
  e.style.cssText = `position:absolute;white-space:nowrap;left:${x}px;top:${y}px;transform:${transform}`;
665
667
  labels.appendChild(e);
@@ -1048,6 +1050,8 @@ export function plot(el, options) {
1048
1050
  return next;
1049
1051
  };
1050
1052
  const internals = {
1053
+ doc,
1054
+ win,
1051
1055
  root,
1052
1056
  canvas,
1053
1057
  get overlay() {
@@ -1289,9 +1293,9 @@ export function plot(el, options) {
1289
1293
  tracking = on;
1290
1294
  for (const type of RELEASES)
1291
1295
  if (on)
1292
- document.addEventListener(type, release, true);
1296
+ doc.addEventListener(type, release, true);
1293
1297
  else
1294
- document.removeEventListener(type, release, true);
1298
+ doc.removeEventListener(type, release, true);
1295
1299
  };
1296
1300
  const adopt = (e) => {
1297
1301
  const changed = () => {
@@ -1407,7 +1411,7 @@ export function plot(el, options) {
1407
1411
  // A density query matches one value only, so each change is listened for once and asked for again.
1408
1412
  let density;
1409
1413
  const redensify = () => {
1410
- dpr = devicePixelRatio;
1414
+ dpr = win.devicePixelRatio;
1411
1415
  fit(canvas);
1412
1416
  if (glCanvas)
1413
1417
  fit(glCanvas);
@@ -1418,7 +1422,7 @@ export function plot(el, options) {
1418
1422
  report();
1419
1423
  };
1420
1424
  const watch = () => {
1421
- density = matchMedia(`(resolution: ${dpr}dppx)`);
1425
+ density = win.matchMedia(`(resolution: ${dpr}dppx)`);
1422
1426
  density.addEventListener('change', redensify, { once: true });
1423
1427
  };
1424
1428
  const teardown = () => {
@@ -1456,7 +1460,7 @@ export function plot(el, options) {
1456
1460
  root.addEventListener('pointermove', point, true);
1457
1461
  if (refresh(true))
1458
1462
  sync();
1459
- observer = new ResizeObserver(() => {
1463
+ observer = new win.ResizeObserver(() => {
1460
1464
  letGo();
1461
1465
  if (refresh(false, measure() ? 'size' : undefined))
1462
1466
  sync();
@@ -1,3 +1,4 @@
1
+ import { windowOf } from '../color.js';
1
2
  import { palette, paletteDark } from '../paint.js';
2
3
  import { dark, light } from '../theme.js';
3
4
  export const DAY = 864e5;
@@ -94,6 +95,7 @@ export function spacing(x, fallback) {
94
95
  /** 'auto' reads the element's computed color-scheme; onChange fires when a 'light dark' page flips. */
95
96
  export function themeOf(el, prop, onChange) {
96
97
  const none = () => { };
98
+ const win = windowOf(el);
97
99
  if (prop === 'light')
98
100
  return { theme: light, dispose: none };
99
101
  if (prop === 'dark')
@@ -101,7 +103,7 @@ export function themeOf(el, prop, onChange) {
101
103
  if (prop !== undefined && prop !== 'auto')
102
104
  return { theme: prop, dispose: none };
103
105
  const fixed = () => {
104
- const words = getComputedStyle(el).colorScheme.split(/\s+/);
106
+ const words = win.getComputedStyle(el).colorScheme.split(/\s+/);
105
107
  if (!words.includes('dark'))
106
108
  return light;
107
109
  return words.includes('light') ? undefined : dark;
@@ -109,7 +111,7 @@ export function themeOf(el, prop, onChange) {
109
111
  const theme = fixed();
110
112
  if (theme)
111
113
  return { theme, dispose: none };
112
- const mq = matchMedia('(prefers-color-scheme: dark)');
114
+ const mq = win.matchMedia('(prefers-color-scheme: dark)');
113
115
  const resolve = () => fixed() ?? (mq.matches ? dark : light);
114
116
  const listen = () => onChange(resolve());
115
117
  mq.addEventListener('change', listen);
package/dist/color.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ /** The window an element is in, or this one for an element of a document that has none. */
2
+ export declare const windowOf: (el: Node) => Window & typeof globalThis;
1
3
  /**
2
4
  * CSS variables in a colour, resolved where the chart stands: anything but a string naming one comes
3
5
  * back as it is. A colour with no value becomes `muted`, with one warning. What was read is kept
package/dist/color.js CHANGED
@@ -1,4 +1,6 @@
1
1
  import { light } from './theme.js';
2
+ /** The window an element is in, or this one for an element of a document that has none. */
3
+ export const windowOf = (el) => (el.ownerDocument?.defaultView ?? globalThis);
2
4
  /**
3
5
  * CSS variables in a colour, resolved where the chart stands: anything but a string naming one comes
4
6
  * back as it is. A colour with no value becomes `muted`, with one warning. What was read is kept
@@ -8,7 +10,7 @@ export function resolver(root, muted) {
8
10
  const known = new Map();
9
11
  const warned = new Set();
10
12
  const read = (css) => {
11
- const probe = document.createElement('div');
13
+ const probe = root.ownerDocument.createElement('div');
12
14
  // The root's own values, against a page's rules for its children and properties that do not inherit.
13
15
  // Every word is taken, as CSS escapes can spell even a name's dashes.
14
16
  const names = css.match(/(?:\\[\da-f]{1,6}(?:\r\n|\s)?|\\.|[\w-]|[^\0-\x7f])+/gi) ?? [];
@@ -18,8 +20,8 @@ export function resolver(root, muted) {
18
20
  // value each keeps its own, so they differ.
19
21
  probe.style.setProperty('flood-color', css, 'important');
20
22
  probe.style.setProperty('lighting-color', css, 'important');
21
- (root.isConnected ? root : document.body).append(probe);
22
- const { floodColor, lightingColor } = getComputedStyle(probe);
23
+ (root.isConnected ? root : root.ownerDocument.body).append(probe);
24
+ const { floodColor, lightingColor } = windowOf(root).getComputedStyle(probe);
23
25
  probe.remove();
24
26
  return floodColor === lightingColor ? floodColor : undefined;
25
27
  };
@@ -13,8 +13,8 @@ export function animate({ duration = 300, enter = 'reveal' } = {}) {
13
13
  if (!Number.isFinite(duration) || duration <= 0)
14
14
  return () => ({ destroy() { } });
15
15
  return chart => {
16
- const { canvas } = chart;
17
- const motion = matchMedia('(prefers-reduced-motion: reduce)');
16
+ const { canvas, win } = chart;
17
+ const motion = win.matchMedia('(prefers-reduced-motion: reduce)');
18
18
  const ctx = canvas.getContext('2d');
19
19
  const from = new OffscreenCanvas(0, 0);
20
20
  const to = new OffscreenCanvas(0, 0);
@@ -29,7 +29,7 @@ export function animate({ duration = 300, enter = 'reveal' } = {}) {
29
29
  picture.getContext('2d').drawImage(canvas, 0, 0);
30
30
  };
31
31
  const stop = () => {
32
- cancelAnimationFrame(frame);
32
+ win.cancelAnimationFrame(frame);
33
33
  frame = 0;
34
34
  entering = false;
35
35
  shown = undefined;
@@ -37,7 +37,7 @@ export function animate({ duration = 300, enter = 'reveal' } = {}) {
37
37
  chart.morph(1);
38
38
  };
39
39
  const run = (step, drawn = false) => {
40
- const start = performance.now();
40
+ const start = win.performance.now();
41
41
  const show = (e) => {
42
42
  step(e);
43
43
  shown = () => step(e);
@@ -46,13 +46,13 @@ export function animate({ duration = 300, enter = 'reveal' } = {}) {
46
46
  const t = motion.matches ? 1 : Math.min(1, Math.max(0, (now - start) / duration));
47
47
  show(1 - (1 - t) ** 3);
48
48
  if (t < 1)
49
- frame = requestAnimationFrame(tick);
49
+ frame = win.requestAnimationFrame(tick);
50
50
  else
51
51
  stop();
52
52
  };
53
53
  if (!drawn)
54
54
  show(0);
55
- frame = requestAnimationFrame(tick);
55
+ frame = win.requestAnimationFrame(tick);
56
56
  };
57
57
  // 'copy' replaces the canvas with what is drawn, so the pictures need no clearing first.
58
58
  const blend = (mix) => (t) => {
@@ -89,7 +89,7 @@ export function animate({ duration = 300, enter = 'reveal' } = {}) {
89
89
  return shown();
90
90
  }
91
91
  const now = performance.now();
92
- const still = why !== 'data' || frame !== 0 || now - last < duration || document.hidden || motion.matches;
92
+ const still = why !== 'data' || frame !== 0 || now - last < duration || chart.doc.hidden || motion.matches;
93
93
  stop();
94
94
  if (why === 'data')
95
95
  last = now;
@@ -2,7 +2,7 @@ import { locate, settle, SLOP_PX, unselect } from './pointer.js';
2
2
  export function brush(b = {}) {
3
3
  const [bx, by] = ['x', 'y'].map(k => (b.axes ?? 'x').includes(k));
4
4
  return chart => {
5
- const { drag } = chart;
5
+ const { drag, doc } = chart;
6
6
  drag.brush = true;
7
7
  const shade = chart.layer('div', 'display:none;opacity:0.2');
8
8
  let reported = false;
@@ -28,11 +28,11 @@ export function brush(b = {}) {
28
28
  if (!over)
29
29
  return;
30
30
  from = { id: e.pointerId, x: px, y: py };
31
- document.addEventListener('pointermove', move, true);
32
- document.addEventListener('pointerup', up, true);
33
- document.addEventListener('pointercancel', cancel, true);
34
- document.addEventListener('keydown', key, true);
35
- document.addEventListener('selectstart', unselect, true);
31
+ doc.addEventListener('pointermove', move, true);
32
+ doc.addEventListener('pointerup', up, true);
33
+ doc.addEventListener('pointercancel', cancel, true);
34
+ doc.addEventListener('keydown', key, true);
35
+ doc.addEventListener('selectstart', unselect, true);
36
36
  clear();
37
37
  };
38
38
  const move = (e) => {
@@ -74,11 +74,11 @@ export function brush(b = {}) {
74
74
  };
75
75
  const end = () => {
76
76
  from = undefined;
77
- document.removeEventListener('pointermove', move, true);
78
- document.removeEventListener('pointerup', up, true);
79
- document.removeEventListener('pointercancel', cancel, true);
80
- document.removeEventListener('keydown', key, true);
81
- document.removeEventListener('selectstart', unselect, true);
77
+ doc.removeEventListener('pointermove', move, true);
78
+ doc.removeEventListener('pointerup', up, true);
79
+ doc.removeEventListener('pointercancel', cancel, true);
80
+ doc.removeEventListener('keydown', key, true);
81
+ doc.removeEventListener('selectstart', unselect, true);
82
82
  if (drag.active)
83
83
  settling = settle(chart);
84
84
  };
@@ -118,7 +118,7 @@ export function brush(b = {}) {
118
118
  gone = true;
119
119
  from = undefined;
120
120
  end();
121
- clearTimeout(settling);
121
+ chart.win.clearTimeout(settling);
122
122
  drag.brush = drag.active = false;
123
123
  chart.root.removeEventListener('pointerdown', down);
124
124
  shade.remove();
@@ -17,12 +17,12 @@ function ends(lo, hi) {
17
17
  */
18
18
  export function legend({ toggle = true, rows: cap } = {}) {
19
19
  return chart => {
20
- const { root } = chart;
20
+ const { root, doc } = chart;
21
21
  const toggles = (e) => toggle && !e.part;
22
22
  const off = (e) => e.id !== undefined && chart.hidden().includes(e.id);
23
23
  const box = chart.layer('div', `color:${chart.theme().text}`);
24
24
  const shown = new Map();
25
- const cut = new ResizeObserver(seen => {
25
+ const cut = new chart.win.ResizeObserver(seen => {
26
26
  for (const { target: t } of seen) {
27
27
  if (t.scrollWidth > t.clientWidth)
28
28
  t.setAttribute('title', t.textContent);
@@ -103,19 +103,19 @@ export function legend({ toggle = true, rows: cap } = {}) {
103
103
  const key = JSON.stringify([rows, unlisted, strips]);
104
104
  if (key !== built) {
105
105
  built = key;
106
- const doc = root.getRootNode();
107
- const focused = [...shown].find(([item]) => item.contains(doc.activeElement))?.[1].id;
106
+ const tree = root.getRootNode();
107
+ const focused = [...shown].find(([item]) => item.contains(tree.activeElement))?.[1].id;
108
108
  shown.clear();
109
109
  cut.disconnect();
110
110
  box.replaceChildren(...rows.map((row, r) => {
111
- const line = document.createElement('div');
111
+ const line = doc.createElement('div');
112
112
  line.style.cssText = `display:flex;gap:${GAP}px;height:${ROW}px;align-items:center;white-space:nowrap;overflow:hidden`;
113
113
  const capped = r === rows.length - 1 && unlisted.length > 0;
114
114
  for (const e of row) {
115
- const item = line.appendChild(document.createElement('span'));
115
+ const item = line.appendChild(doc.createElement('span'));
116
116
  // Only the entries take the pointer: the rest of the strip stays the chart's.
117
117
  item.style.cssText = `pointer-events:auto;${capped ? 'flex:0 1 auto;min-width:0' : 'flex:none;max-width:100%'};overflow:hidden;text-overflow:ellipsis`;
118
- const swatch = item.appendChild(document.createElement('span'));
118
+ const swatch = item.appendChild(doc.createElement('span'));
119
119
  swatch.style.cssText =
120
120
  'display:inline-block;width:10px;height:10px;margin-right:6px;border-radius:2px';
121
121
  swatch.style.backgroundColor = e.color;
@@ -129,16 +129,16 @@ export function legend({ toggle = true, rows: cap } = {}) {
129
129
  shown.set(item, e);
130
130
  }
131
131
  if (capped) {
132
- const item = line.appendChild(document.createElement('span'));
132
+ const item = line.appendChild(doc.createElement('span'));
133
133
  item.style.cssText = 'pointer-events:auto;flex:none';
134
134
  item.textContent = more(unlisted.length);
135
135
  item.title = unlisted.join(', ');
136
136
  }
137
137
  return line;
138
138
  }), ...strips.map(s => {
139
- const line = document.createElement('div');
139
+ const line = doc.createElement('div');
140
140
  line.style.cssText = `display:flex;gap:6px;height:${ROW}px;align-items:center;white-space:nowrap;overflow:hidden`;
141
- const strip = document.createElement('span');
141
+ const strip = doc.createElement('span');
142
142
  strip.style.cssText = 'display:inline-block;width:120px;height:10px;border-radius:2px';
143
143
  strip.style.backgroundImage = `linear-gradient(to right,${s.colors.join()})`;
144
144
  line.append(...(s.label ? [s.label, ' '] : []), s.ends[0], strip, s.ends[1]);
@@ -213,13 +213,13 @@ export function legend({ toggle = true, rows: cap } = {}) {
213
213
  host.addEventListener('pointermove', move, true);
214
214
  root.addEventListener('pointerleave', lift);
215
215
  root.addEventListener('pointercancel', leave);
216
- document.addEventListener('pointerdown', leave, true);
216
+ doc.addEventListener('pointerdown', leave, true);
217
217
  return {
218
218
  // The entries may have moved under a pointer at rest, so what it is over is looked up again.
219
219
  update() {
220
220
  box.style.color = chart.theme().text;
221
- const doc = root.isConnected && root.getRootNode();
222
- if (at && !over(doc ? doc.elementFromPoint(...at) : null))
221
+ const tree = root.isConnected && root.getRootNode();
222
+ if (at && !over(tree ? tree.elementFromPoint(...at) : null))
223
223
  at = undefined;
224
224
  },
225
225
  letGo: () => held && leave(),
@@ -228,7 +228,7 @@ export function legend({ toggle = true, rows: cap } = {}) {
228
228
  host.removeEventListener('pointermove', move, true);
229
229
  root.removeEventListener('pointerleave', lift);
230
230
  root.removeEventListener('pointercancel', leave);
231
- document.removeEventListener('pointerdown', leave, true);
231
+ doc.removeEventListener('pointerdown', leave, true);
232
232
  cut.disconnect();
233
233
  box.remove();
234
234
  },
@@ -1,7 +1,7 @@
1
1
  export const SLOP_PX = 4;
2
2
  export const unselect = (e) => e.preventDefault();
3
3
  /** Clears `drag.active` after the click the browser sends for this release, which a drag must not count as one. */
4
- export const settle = (chart) => setTimeout(() => {
4
+ export const settle = (chart) => chart.win.setTimeout(() => {
5
5
  chart.drag.active = false;
6
6
  chart.sync();
7
7
  }, 0);
@@ -30,7 +30,8 @@ export const released = ({ overlay }, e) => e.pointerType !== 'touch' && !!overl
30
30
  export const strayed = ({ overlay }, e) => {
31
31
  const held = overlay && presses.get(overlay)?.held;
32
32
  // Some browsers send a click as a MouseEvent, which does not name its pointer, and so are double clicks.
33
- return !!held && (e instanceof PointerEvent ? held.has(e.pointerId) : held.size > 0);
33
+ const id = e.pointerId;
34
+ return !!held && (id === undefined ? held.size > 0 : held.has(id));
34
35
  };
35
36
  /** Whether a hover is the chart's own: on it or on the app's DOM over it, and not on a control such as a legend's. */
36
37
  export const owns = (chart, target) => target === chart.root || !!chart.overlay?.contains(target);
@@ -3,7 +3,7 @@ import { owns, position, released } from './pointer.js';
3
3
  const FOCUS_PX = 30;
4
4
  export function tooltip(t) {
5
5
  return chart => {
6
- const { root } = chart;
6
+ const { root, doc } = chart;
7
7
  const cross = chart.layer('div', 'display:none;border-left:1px dashed');
8
8
  const tip = chart.layer('div', 'display:none;left:0;top:0;border:1px solid;padding:4px 8px;box-sizing:border-box;width:max-content;max-width:100%;max-height:100%;overflow:hidden;white-space:normal;overflow-wrap:anywhere;z-index:100');
9
9
  const restyle = () => {
@@ -24,7 +24,7 @@ export function tooltip(t) {
24
24
  const show = (x, y, rows) => {
25
25
  const { width, height } = chart.size();
26
26
  tip.replaceChildren(...rows.map(r => {
27
- const e = document.createElement('div');
27
+ const e = doc.createElement('div');
28
28
  e.textContent = r.text;
29
29
  if (r.color)
30
30
  e.style.color = chart.color(r.color);
@@ -179,7 +179,7 @@ export function tooltip(t) {
179
179
  root.addEventListener('pointerup', release, true);
180
180
  root.addEventListener('pointerleave', lift);
181
181
  root.addEventListener('pointercancel', out);
182
- document.addEventListener('pointerdown', away, true);
182
+ doc.addEventListener('pointerdown', away, true);
183
183
  return {
184
184
  update() {
185
185
  restyle();
@@ -193,7 +193,7 @@ export function tooltip(t) {
193
193
  root.removeEventListener('pointerup', release, true);
194
194
  root.removeEventListener('pointerleave', lift);
195
195
  root.removeEventListener('pointercancel', out);
196
- document.removeEventListener('pointerdown', away, true);
196
+ doc.removeEventListener('pointerdown', away, true);
197
197
  cross.remove();
198
198
  tip.remove();
199
199
  },
@@ -7,7 +7,7 @@ const TAP_MS = 500;
7
7
  export function zoom(z = {}) {
8
8
  const sides = ['x', 'y'].filter(k => (z.axes ?? 'x').includes(k));
9
9
  return chart => {
10
- const { root, drag } = chart;
10
+ const { root, drag, doc, win } = chart;
11
11
  const locate = (e) => where(chart, e);
12
12
  if (z.drag !== false)
13
13
  drag.pan = z.drag === 'pan' ? 'plain' : 'shift';
@@ -23,7 +23,7 @@ export function zoom(z = {}) {
23
23
  };
24
24
  const ask = (want) => {
25
25
  pending = want;
26
- frame ||= requestAnimationFrame(flush);
26
+ frame ||= win.requestAnimationFrame(flush);
27
27
  };
28
28
  const wheel = (e) => {
29
29
  if (z.wheel === false)
@@ -69,10 +69,10 @@ export function zoom(z = {}) {
69
69
  if (!over)
70
70
  return;
71
71
  from = { id: e.pointerId, x: px, y: py, view: shown(), w, h };
72
- document.addEventListener('pointermove', move, true);
73
- document.addEventListener('pointerup', up, true);
74
- document.addEventListener('pointercancel', up, true);
75
- document.addEventListener('selectstart', unselect, true);
72
+ doc.addEventListener('pointermove', move, true);
73
+ doc.addEventListener('pointerup', up, true);
74
+ doc.addEventListener('pointercancel', up, true);
75
+ doc.addEventListener('selectstart', unselect, true);
76
76
  };
77
77
  const move = (e) => {
78
78
  if (!from || e.pointerId !== from.id)
@@ -107,10 +107,10 @@ export function zoom(z = {}) {
107
107
  };
108
108
  const end = () => {
109
109
  from = undefined;
110
- document.removeEventListener('pointermove', move, true);
111
- document.removeEventListener('pointerup', up, true);
112
- document.removeEventListener('pointercancel', up, true);
113
- document.removeEventListener('selectstart', unselect, true);
110
+ doc.removeEventListener('pointermove', move, true);
111
+ doc.removeEventListener('pointerup', up, true);
112
+ doc.removeEventListener('pointercancel', up, true);
113
+ doc.removeEventListener('selectstart', unselect, true);
114
114
  };
115
115
  const up = (e) => {
116
116
  if (e.pointerId !== from?.id)
@@ -121,7 +121,7 @@ export function zoom(z = {}) {
121
121
  };
122
122
  const settle = () => (settling = release(chart));
123
123
  const engage = () => {
124
- clearTimeout(settling);
124
+ win.clearTimeout(settling);
125
125
  drag.active = true;
126
126
  };
127
127
  const whole = () => ask(sides.length === 2 ? null : { [sides[0]]: undefined });
@@ -145,9 +145,9 @@ export function zoom(z = {}) {
145
145
  if (!over || touches.size >= 2)
146
146
  return;
147
147
  if (!touches.size) {
148
- document.addEventListener('pointermove', touchMove, true);
149
- document.addEventListener('pointerup', touchUp, true);
150
- document.addEventListener('pointercancel', touchCancel, true);
148
+ doc.addEventListener('pointermove', touchMove, true);
149
+ doc.addEventListener('pointerup', touchUp, true);
150
+ doc.addEventListener('pointercancel', touchCancel, true);
151
151
  }
152
152
  touches.set(e.pointerId, { px, py, at });
153
153
  if (touches.size === 2) {
@@ -194,9 +194,9 @@ export function zoom(z = {}) {
194
194
  touches.clear();
195
195
  pinch = tap = undefined;
196
196
  again = false;
197
- document.removeEventListener('pointermove', touchMove, true);
198
- document.removeEventListener('pointerup', touchUp, true);
199
- document.removeEventListener('pointercancel', touchCancel, true);
197
+ doc.removeEventListener('pointermove', touchMove, true);
198
+ doc.removeEventListener('pointerup', touchUp, true);
199
+ doc.removeEventListener('pointercancel', touchCancel, true);
200
200
  if (drag.active)
201
201
  settle();
202
202
  };
@@ -234,8 +234,8 @@ export function zoom(z = {}) {
234
234
  touchEnd();
235
235
  root.style.touchAction = touchAction;
236
236
  root.removeEventListener('pointerdown', touchDown, true);
237
- cancelAnimationFrame(frame);
238
- clearTimeout(settling);
237
+ win.cancelAnimationFrame(frame);
238
+ win.clearTimeout(settling);
239
239
  drag.pan = drag.active = false;
240
240
  root.removeEventListener('wheel', wheel);
241
241
  root.removeEventListener('pointerdown', down);
package/dist/text.js CHANGED
@@ -14,6 +14,7 @@ export function textWidth(s) {
14
14
  if (w !== undefined)
15
15
  return w;
16
16
  if (pen === undefined) {
17
+ // oxlint-disable-next-line no-restricted-globals -- one canvas for every window: FONT is the same in all of them
17
18
  pen = typeof document === 'undefined' ? null : document.createElement('canvas').getContext('2d');
18
19
  if (pen)
19
20
  pen.font = FONT;
package/dist/types.d.ts CHANGED
@@ -388,6 +388,13 @@ export type Painter = (draw: (reveal?: number) => void, why: 'data' | 'size' | '
388
388
  * work from that paint on.
389
389
  */
390
390
  export type Internals = {
391
+ /** The document of the element the chart was made in, which creates its nodes and takes its listeners. */
392
+ doc: Document;
393
+ /**
394
+ * That document's window, or this one when it has none: frames, timers, observers, media queries and
395
+ * styles are asked of it.
396
+ */
397
+ win: Window & typeof globalThis;
391
398
  root: HTMLElement;
392
399
  /** The 2D canvas holding the grid and every mark that is not on WebGL. */
393
400
  canvas: HTMLCanvasElement;
package/package.json CHANGED
@@ -1,14 +1,25 @@
1
1
  {
2
2
  "name": "swiftplot",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "Small, fast charts on Canvas 2D and WebGL2",
5
+ "keywords": [
6
+ "chart",
7
+ "charts",
8
+ "plot",
9
+ "canvas",
10
+ "webgl",
11
+ "visualization",
12
+ "dataviz",
13
+ "timeseries",
14
+ "typescript"
15
+ ],
5
16
  "license": "MIT",
6
17
  "repository": {
7
18
  "type": "git",
8
19
  "url": "git+https://github.com/GusevP/swiftplot.git",
9
20
  "directory": "packages/core"
10
21
  },
11
- "homepage": "https://github.com/GusevP/swiftplot#readme",
22
+ "homepage": "https://swiftplot.dev",
12
23
  "bugs": {
13
24
  "url": "https://github.com/GusevP/swiftplot/issues"
14
25
  },