swiftplot 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +327 -2
  3. package/dist/chart.d.ts +3 -0
  4. package/dist/chart.js +1226 -0
  5. package/dist/charts/controller.d.ts +32 -0
  6. package/dist/charts/controller.js +231 -0
  7. package/dist/charts/defaults.d.ts +12 -0
  8. package/dist/charts/defaults.js +60 -0
  9. package/dist/charts/fields.d.ts +34 -0
  10. package/dist/charts/fields.js +167 -0
  11. package/dist/charts/index.d.ts +6 -0
  12. package/dist/charts/index.js +3 -0
  13. package/dist/charts/mount.d.ts +5 -0
  14. package/dist/charts/mount.js +21 -0
  15. package/dist/charts/source.d.ts +24 -0
  16. package/dist/charts/source.js +225 -0
  17. package/dist/charts/types.d.ts +104 -0
  18. package/dist/charts/types.js +1 -0
  19. package/dist/charts/xy.d.ts +36 -0
  20. package/dist/charts/xy.js +220 -0
  21. package/dist/features/animate.d.ts +11 -0
  22. package/dist/features/animate.js +118 -0
  23. package/dist/features/brush.d.ts +13 -0
  24. package/dist/features/brush.js +127 -0
  25. package/dist/features/legend.d.ts +15 -0
  26. package/dist/features/legend.js +237 -0
  27. package/dist/features/pointer.d.ts +29 -0
  28. package/dist/features/pointer.js +23 -0
  29. package/dist/features/tooltip.d.ts +14 -0
  30. package/dist/features/tooltip.js +190 -0
  31. package/dist/features/zoom.d.ts +13 -0
  32. package/dist/features/zoom.js +228 -0
  33. package/dist/gl.d.ts +5 -0
  34. package/dist/gl.js +52 -0
  35. package/dist/index.d.ts +60 -0
  36. package/dist/index.js +31 -0
  37. package/dist/marks/arcs.d.ts +25 -0
  38. package/dist/marks/arcs.js +124 -0
  39. package/dist/marks/area.d.ts +24 -0
  40. package/dist/marks/area.js +106 -0
  41. package/dist/marks/bar.d.ts +44 -0
  42. package/dist/marks/bar.js +243 -0
  43. package/dist/marks/box.d.ts +27 -0
  44. package/dist/marks/box.js +188 -0
  45. package/dist/marks/common.d.ts +84 -0
  46. package/dist/marks/common.js +236 -0
  47. package/dist/marks/dots.d.ts +15 -0
  48. package/dist/marks/dots.js +156 -0
  49. package/dist/marks/errorBars.d.ts +19 -0
  50. package/dist/marks/errorBars.js +79 -0
  51. package/dist/marks/funnel.d.ts +25 -0
  52. package/dist/marks/funnel.js +121 -0
  53. package/dist/marks/heatmap.d.ts +19 -0
  54. package/dist/marks/heatmap.js +139 -0
  55. package/dist/marks/line.d.ts +19 -0
  56. package/dist/marks/line.js +75 -0
  57. package/dist/marks/radar.d.ts +22 -0
  58. package/dist/marks/radar.js +155 -0
  59. package/dist/marks/radialBars.d.ts +27 -0
  60. package/dist/marks/radialBars.js +111 -0
  61. package/dist/marks/rects.d.ts +43 -0
  62. package/dist/marks/rects.js +120 -0
  63. package/dist/marks/rule.d.ts +28 -0
  64. package/dist/marks/rule.js +80 -0
  65. package/dist/marks/sankey.d.ts +41 -0
  66. package/dist/marks/sankey.js +366 -0
  67. package/dist/marks/sunburst.d.ts +26 -0
  68. package/dist/marks/sunburst.js +185 -0
  69. package/dist/marks/ticks.d.ts +9 -0
  70. package/dist/marks/ticks.js +26 -0
  71. package/dist/marks/tree.d.ts +41 -0
  72. package/dist/marks/tree.js +110 -0
  73. package/dist/marks/treemap.d.ts +25 -0
  74. package/dist/marks/treemap.js +159 -0
  75. package/dist/paint.d.ts +30 -0
  76. package/dist/paint.js +66 -0
  77. package/dist/scale.d.ts +16 -0
  78. package/dist/scale.js +96 -0
  79. package/dist/scales/band.d.ts +9 -0
  80. package/dist/scales/band.js +23 -0
  81. package/dist/scales/bare.d.ts +3 -0
  82. package/dist/scales/bare.js +7 -0
  83. package/dist/scales/color.d.ts +18 -0
  84. package/dist/scales/color.js +21 -0
  85. package/dist/scales/log.d.ts +20 -0
  86. package/dist/scales/log.js +97 -0
  87. package/dist/scales/time.d.ts +30 -0
  88. package/dist/scales/time.js +181 -0
  89. package/dist/theme.d.ts +10 -0
  90. package/dist/theme.js +8 -0
  91. package/dist/transforms.d.ts +43 -0
  92. package/dist/transforms.js +118 -0
  93. package/dist/types.d.ts +434 -0
  94. package/dist/types.js +1 -0
  95. package/package.json +39 -3
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Pavel Gusev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,328 @@
1
- # Temporary Holding Version
1
+ # swiftplot
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <p>
4
+ <picture>
5
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/GusevP/swiftplot/main/assets/logo-dark.svg" />
6
+ <img src="https://raw.githubusercontent.com/GusevP/swiftplot/main/assets/logo.svg" alt="swiftplot" height="64" />
7
+ </picture>
8
+ </p>
9
+
10
+ Small, fast charts on Canvas 2D and WebGL2. MIT, TypeScript, ESM only, no dependencies.
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 line, area, bar and scatter charts from the data alone, 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`.
13
+
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.
15
+
16
+ ## Charts from data
17
+
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.
19
+
20
+ ```ts
21
+ import { lineChart } from 'swiftplot/charts';
22
+
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` and `scatterChart`. Each returns `{ update(props), destroy(), chart }`; `update` takes only the props that change, 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). 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** 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`.
33
+ - **Errors** name the chart; an error about fields also names the fields with their kinds and the prop to pass. Guessing throws when no number field is left for `y` (naming any field of numbers held as text), when a text field is left over without `series` (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.
34
+ - **Rows:** line and area charts sort rows by x (stably); bar and scatter charts keep the given order. A row with a missing x (or, on a scatter, a missing `r`) is dropped; a missing y is a gap.
35
+ - **Axes:** settings go under `xAxis` and `yAxis`. Which x settings apply depends on the x field:
36
+
37
+ | x | axis | settings |
38
+ | ------------------- | -------- | -------------------------------------------------------------------------------------------------- |
39
+ | numbers, row index | linear | `label`, `domain` (`'nice'` by default), `step`, `format`, `fit` |
40
+ | dates | time | `label`, `utc`, `unit` and `every`, `format`, `fit`, `domain` as `[from, to]` in milliseconds only |
41
+ | text, and every bar | category | `label` only |
42
+
43
+ `yAxis` takes `label`, `domain`, `step`, `format` and `fit`. Bars 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.
44
+
45
+ - **Defaults:**
46
+
47
+ | Thing | Default | Override |
48
+ | ------------------- | ------------------------------------------------------------------------- | -------------------------------------- |
49
+ | Axis labels | the field's name; none for the row index, an accessor or several y fields | `xAxis.label`, `yAxis.label` |
50
+ | Colours | `palette` in order, `paletteDark` on the dark theme | `colors` |
51
+ | Tooltip | on; text in the y axis format, else two decimals at most | `tooltip: false` |
52
+ | Legend | on with two or more series | `legend: false` or `legend()` options |
53
+ | Zoom | off | `zoom: true` or `zoom()` options |
54
+ | Animation | off | `animate: true` or `animate()` options |
55
+ | Theme | follows the page | `theme: 'light' \| 'dark' \| Theme` |
56
+ | Size | follows the container | `width`, `height`, `margin` |
57
+ | Several y on areas | overlapping, half transparent | `stack: true` |
58
+ | Several y on bars | side by side | `stack: true` |
59
+ | Line and area shape | straight, with gaps | `curve`, `join` |
60
+ | Scatter radius | 4 px | `r`: a number or a field |
61
+
62
+ - **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.
63
+ - **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` or `animate` creates the chart again and keeps a zoomed window and hidden series.
64
+ - **`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 })`.
65
+ - **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.
66
+ - **`.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.
67
+ - **`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.
68
+
69
+ ## React and Vue
70
+
71
+ `@swiftplot/react` (React 18.3 or 19) and `@swiftplot/vue` (Vue 3.4 or later) make components of the charts above: `LineChart`, `AreaChart`, `BarChart`, `ScatterChart`, 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:
72
+
73
+ ```sh
74
+ pnpm add swiftplot @swiftplot/react # or @swiftplot/vue
75
+ ```
76
+
77
+ ```tsx
78
+ import { LineChart } from '@swiftplot/react';
79
+
80
+ <LineChart data={rows} />;
81
+ ```
82
+
83
+ ```vue
84
+ <script setup lang="ts">
85
+ import { LineChart } from '@swiftplot/vue';
86
+ </script>
87
+
88
+ <template>
89
+ <LineChart :data="rows" />
90
+ </template>
91
+ ```
92
+
93
+ - **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`.
94
+ - **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:
95
+
96
+ ```tsx
97
+ const [view, setView] = useState<{ x?: [number, number]; y?: [number, number] }>();
98
+ <LineChart data={rows} x="date" y={['api', 'web']} zoom view={view} onViewChange={setView} />;
99
+ ```
100
+
101
+ In Vue the changes are events: `v-model:view`, `v-model:hidden` and `v-model:pointer`, `@click` and `@error` (`<LineChart :data="rows" zoom v-model:view="view" />`). `selected` is a plain prop: the app sets it, from a click for example.
102
+
103
+ - **`Plot`** takes every `plot()` option as a prop, for a chart type with no easy version yet, for mixing marks and for large typed-array data. `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.
104
+
105
+ ```tsx
106
+ import { arcs, legend } from 'swiftplot';
107
+ import { Plot } from '@swiftplot/react';
108
+
109
+ const marks = [
110
+ arcs({ values: [5, 3, 2], labels: ['A', 'B', 'C'], colors: ['#2563eb', '#16a34a', '#f59e0b'] }),
111
+ ];
112
+ <Plot frame="polar" marks={marks} use={[legend()]} />;
113
+ ```
114
+
115
+ - **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.
116
+ - **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.
117
+ - **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.
118
+ - **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` redraws the axis: 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`.
119
+
120
+ ## Use
121
+
122
+ ```ts
123
+ import { dots, plot, tooltip } from 'swiftplot';
124
+
125
+ const chart = plot(document.getElementById('chart')!, {
126
+ width: 900,
127
+ height: 600,
128
+ x: { domain: 'nice', label: 'X' },
129
+ y: { domain: 'nice', label: 'Y' },
130
+ marks: [dots({ x, y, r, color: '#2563eb', alpha: 0.7, label: 'Group 1' })],
131
+ use: [tooltip({ mode: 'nearest', text: (label, x, y) => `${label}: (${x.toFixed(1)}, ${y.toFixed(1)})` })],
132
+ dim: 0.3,
133
+ });
134
+
135
+ chart.update({ marks: [dots({ x, y: y2, r, color: '#2563eb', label: 'Group 1' })] });
136
+ chart.destroy();
137
+ ```
138
+
139
+ - **Marks** are imported functions: `line`, `area`, `bar`, `box`, `errorBars`, `heatmap`, `ticks`, `dots`, `arcs`, `radar`, `radialBars`, `funnel`, `sankey`, `treemap`, `sunburst`. Only the ones you import are bundled.
140
+ - **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.
141
+ - **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. `bands(7, { slot: 0, of: 2 })` gives one series' bounds for a chart that never hides it.
142
+ - **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`.
143
+ - **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.
144
+ - **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.
145
+ - **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.
146
+ - **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.
147
+ - **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.
148
+ - **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.
149
+ - **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.
150
+ - **Labels on shapes** (slices, stages, nodes) are drawn where they fit and left out where they would overlap or run off the chart.
151
+ - **A colour legend** for a heatmap comes with `legend()`: a strip of its colours between the ends of its domain.
152
+ - **Error bars** are `errorBars({ x, y1, y2 })`, or `{ y, x1, x2 }` lying down.
153
+ - **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.
154
+ - **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.
155
+ - **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) })`.
156
+ - **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.
157
+ - **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.
158
+ - **Rows** need no helper: `Float64Array.from(rows, r => r.value)` makes a column and `Map.groupBy(rows, r => r.series)` splits rows into series.
159
+ - **Ticks** thin out to fit the axis, so a narrow chart shows fewer labels, not overlapping ones.
160
+ - **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.
161
+ - **Margins** are sized from the tick labels; pass `margin: { left: 80 }` to set a side yourself.
162
+ - **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".
163
+ - **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. 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.
164
+ - **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.
165
+ - **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`.
166
+ - **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:
167
+
168
+ ```ts
169
+ const charts = [a, b].map((el, i) =>
170
+ plot(el, {
171
+ ...options,
172
+ onPointerChange: p => charts[1 - i]!.update({ pointer: p }),
173
+ use: [tooltip(tip)],
174
+ }),
175
+ );
176
+ ```
177
+
178
+ - **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.
179
+
180
+ ```ts
181
+ const scheme = matchMedia('(prefers-color-scheme: dark)');
182
+ const chart = plot(el, { ...options, theme: scheme.matches ? dark : light });
183
+ scheme.addEventListener('change', e => chart.update({ theme: e.matches ? dark : light }));
184
+ ```
185
+
186
+ - **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.
187
+ - **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 new axis and prepares every mark again.
188
+
189
+ ```ts
190
+ const percent = (v: number) => `${v * 100}%`;
191
+ chart.update({ y: { domain: 'nice', label: 'Share', step: 0.25, format: percent } });
192
+ ```
193
+
194
+ - **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.
195
+ - **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.
196
+ - **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.
197
+ - **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.
198
+ - **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.
199
+ - **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`.
200
+ - **Columns** (`x`, `y`, `r`) are typed arrays or plain number arrays, one set per mark.
201
+ - **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).
202
+ - **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)`).
203
+ - **Without a DOM:** the package imports in Node, and marks and transforms such as `bin` and `stack` run there; `plot()` needs a browser.
204
+ - **Your own mark** is an object with the `Mark` shape from the package's types.
205
+
206
+ ## Why it is fast
207
+
208
+ Each point comes from profiling uPlot, the fastest of thirteen libraries in [chart-bench](https://github.com/gusevp/chart-bench), and timing the alternative in `experiments/`.
209
+
210
+ - **Axis text is DOM, not canvas text.** uPlot's axis drawing cost 17–21 ms at 4× CPU slowdown at every data size.
211
+ - **Each mark has its own x column.** No aligned table, so no join step.
212
+ - **Step lines and bands are reduced to one min/max per pixel column** before the path is built.
213
+ - **Typed-array columns in, scale maths inlined** in the draw loops.
214
+ - **Scatter, bars, error bars and box plots switch to WebGL2 at 10,000 points, and a sankey at 1,000 nodes and links together.** Raw WebGL2 set-up cost about 5 ms; Canvas 2D wins or ties below roughly 10k points. When the browser takes a WebGL context away, as it does with many WebGL charts on one page, that chart falls back to Canvas 2D.
215
+ - **Paths and GPU buffers are kept,** so a hover repaint never touches the data again.
216
+
217
+ ## Measured
218
+
219
+ Mount time in chart-bench, median ms, 2026-11-20, Apple M3 Pro that was not idle. Each cell is the mean of two runs of nine loads, with the two libraries taking turns to go first. 4× is Chrome's CPU slowdown. At native speed every case but uPlot's largest sits at the empty-page floor (about 27 ms), so only the other columns separate them.
220
+
221
+ | case | swiftplot | uPlot | swiftplot, 4× | uPlot, 4× |
222
+ | ------------------------ | --------: | ----: | ------------: | --------: |
223
+ | survival, 3 × 200 points | 29.3 | 25.9 | 33.5 | 53.3 |
224
+ | survival, 6 × 1,000 | 28.3 | 24.7 | 37.9 | 68.8 |
225
+ | survival, 10 × 10,000 | 31.6 | 55.2 | 67.1 | 196.9 |
226
+ | scatter, 500 | 27.8 | 25.2 | 33.7 | 46.0 |
227
+ | scatter, 10,000 | 25.1 | 26.6 | 38.9 | 55.7 |
228
+ | scatter, 100,000 | 30.6 | 34.3 | 56.8 | 129.0 |
229
+
230
+ Time until the chart's own code has finished, which leaves out the wait for the next frame:
231
+
232
+ | case | swiftplot | uPlot | swiftplot, 4× | uPlot, 4× |
233
+ | ------------------------ | --------: | ----: | ------------: | --------: |
234
+ | survival, 3 × 200 points | 4.0 | 10.7 | 14.4 | 41.7 |
235
+ | survival, 6 × 1,000 | 5.7 | 14.2 | 20.6 | 55.8 |
236
+ | survival, 10 × 10,000 | 14.3 | 50.6 | 48.2 | 181.6 |
237
+ | scatter, 500 | 3.1 | 9.3 | 12.2 | 35.4 |
238
+ | scatter, 10,000 | 5.9 | 12.9 | 21.3 | 44.6 |
239
+ | scatter, 100,000 | 14.5 | 28.6 | 39.6 | 111.2 |
240
+
241
+ - The 100k scatter runs on WebGL, where the draw call returns before the GPU finishes, so its numbers flatter swiftplot.
242
+ - uPlot has no built-in scatter, so its scatter numbers include circle-drawing code written for the benchmark.
243
+ - Only these two chart types are in the benchmark. Bars, areas, the time axis, the legend and animation are not measured against uPlot.
244
+ - uPlot ships far more features in its 23.6 KB gzip (plus a stylesheet); the swiftplot code these two charts pull in is 7.2 KB gzip.
245
+
246
+ 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.
247
+
248
+ | case | 100,000 | 1,000,000 |
249
+ | ------------------ | ---------: | ----------: |
250
+ | line, whole | 0.9 | 5.1 |
251
+ | line, 10× | 0.2 | 0.8 |
252
+ | line, 5000× | 3.5 → 0.1 | 40.0 → 0.1 |
253
+ | area, whole | 0.8 | 5.0 |
254
+ | area, 10× | 0.2 | 0.8 |
255
+ | area, 5000× | 5.0 → 0.0 | 55.8 → 0.1 |
256
+ | filled line, whole | 0.9 | 5.0 |
257
+ | filled line, 10× | 0.2 | 0.9 |
258
+ | filled line, 5000× | 0.1 | 0.1 |
259
+ | filled area, whole | 0.8 | 4.9 |
260
+ | filled area, 10× | 0.2 | 0.8 |
261
+ | filled area, 5000× | 0.0 | 0.1 |
262
+ | bars, whole | 0.1 | 0.0 |
263
+ | bars, 10× | 0.0 | 0.1 |
264
+ | bars, 5000× | 4.9 | 61.0 |
265
+ | points, whole | 0.1 | 0.0 |
266
+ | points, 10× | 0.0 | 0.0 |
267
+ | points, 5000× | 13.3 → 0.2 | 156.9 → 1.9 |
268
+
269
+ - Bars and points of 10,000 rows or more are drawn by WebGL, whose draw call returns before the GPU finishes, so their whole and 10× cells leave the drawing out. Magnified past 4096 times every mark is drawn on the canvas.
270
+ - A million bars at 5000× is over the 16 ms budget: the canvas still walks every bar.
271
+
272
+ The same step at 1,000,000 points with `fit: 'window'` on the y axis, 2026-11-22, beside the step without it in the same run (mean of two runs each). At the whole domain two windows narrowed by a thousandth and by two take turns, since one window repeated would be fitted once and kept.
273
+
274
+ | case | without | with fit |
275
+ | ------------- | ------: | -------: |
276
+ | line, whole | 4.8 | 7.0 |
277
+ | line, 10× | 0.8 | 1.3 |
278
+ | line, 5000× | 0.1 | 0.1 |
279
+ | area, whole | 4.8 | 7.0 |
280
+ | area, 10× | 0.9 | 1.3 |
281
+ | area, 5000× | 0.1 | 0.1 |
282
+ | bars, whole | 0.0 | 8.4 |
283
+ | bars, 10× | 0.0 | 5.2 |
284
+ | bars, 5000× | 55.4 | 63.8 |
285
+ | points, whole | 0.0 | 7.4 |
286
+ | points, 10× | 0.1 | 3.8 |
287
+ | points, 5000× | 1.9 | 5.0 |
288
+
289
+ - 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.
290
+
291
+ ## Develop
292
+
293
+ From the repository root. `build`, `test:import`, `test` and `typecheck` run in every package under `packages/`. 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):
294
+
295
+ ```sh
296
+ pnpm install
297
+ pnpm --filter swiftplot exec playwright install chromium # once, for the tests
298
+ pnpm build
299
+ pnpm test:import # imports each package's dist/ in Node, after pnpm build
300
+ pnpm test # Vitest in a real browser, one package at a time, then node --test on scripts/
301
+ pnpm typecheck
302
+ pnpm --filter swiftplot run test # one package
303
+ pnpm lint # oxlint, type-aware
304
+ pnpm format # oxfmt
305
+ ```
306
+
307
+ ## Releasing
308
+
309
+ 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:
310
+
311
+ ```sh
312
+ pnpm release:prepare <version | patch | minor | major> # one local commit: versions and changelog
313
+ pnpm release [--npm] [--dry-run] # releases the commit on main
314
+ ```
315
+
316
+ `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.
317
+
318
+ `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.
319
+
320
+ 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.
321
+
322
+ `--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`.
323
+
324
+ 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`.
325
+
326
+ ## Licence
327
+
328
+ The code is MIT. The swiftplot name and logo are not covered by that licence.
@@ -0,0 +1,3 @@
1
+ import type { Chart, Options } from './types.js';
2
+ export declare const NEAREST_PX = 20;
3
+ export declare function plot(el: HTMLElement, options: Options): Chart;