apexsankey 1.9.0 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -21,8 +21,16 @@ jobs:
21
21
 
22
22
  - name: Check commit message and extract version
23
23
  id: check
24
+ env:
25
+ # Passed as an environment variable, never interpolated into the
26
+ # script. `${{ }}` is substituted textually before bash parses, so a
27
+ # commit message containing a double quote breaks the script, and one
28
+ # containing $(...) or backticks would RUN in this job, which holds the
29
+ # npm publishing token. Merge commit messages include the PR title,
30
+ # which any outside contributor controls. This is not theoretical: it
31
+ # broke a run in apexcharts-js on 2026-07-27.
32
+ MSG: ${{ github.event.head_commit.message }}
24
33
  run: |
25
- MSG="${{ github.event.head_commit.message }}"
26
34
  if echo "$MSG" | grep -qE '^release: [0-9]+\.[0-9]+\.[0-9]+'; then
27
35
  VERSION=$(echo "$MSG" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+[^ ]*' | head -1)
28
36
  echo "version=$VERSION" >> $GITHUB_OUTPUT
@@ -46,10 +54,15 @@ jobs:
46
54
  fi
47
55
  echo "✅ Version $PKG_VERSION confirmed"
48
56
 
57
+ # Must stay recent enough for the npm the next step installs. npm@12
58
+ # requires node ^22.22.2 || ^24.15.0 || >=26.0.0, so node 20 now fails at
59
+ # `npm install -g npm@latest` before anything is published.
49
60
  - uses: actions/setup-node@v4
50
61
  with:
51
- node-version: "20"
62
+ node-version: "24"
52
63
 
64
+ # npm@latest, not the bundled npm: trusted publishing (OIDC, no token)
65
+ # needs npm >= 11.5.1.
53
66
  - run: npm install -g npm@latest
54
67
  - run: npm install
55
68
 
package/README.md CHANGED
@@ -61,6 +61,23 @@ const sankey = new ApexSankey(document.getElementById('sankey-container'), optio
61
61
  const graph = sankey.render(data);
62
62
  ```
63
63
 
64
+ ## Methods
65
+
66
+ Methods available on an `ApexSankey` instance:
67
+
68
+ | Method | Description |
69
+ | --- | --- |
70
+ | `render(data)` | Build the diagram from `data` (`{ nodes, edges }`) and write the SVG into the container. Returns the internal graph renderer, which exposes `exportToSvg()`. |
71
+ | `update(data)` | Transition an already-rendered instance to new `data`. When the new layout shares the current topology (same nodes and flows, only different values or positions), the nodes and ribbons spring smoothly to their new places. When the topology differs, it morphs through the change: entering flows grow out of their source node, survivors slide to their new places, and removed flows retract and dissolve. When animation is disabled or the user prefers reduced motion, it redraws instantly. |
72
+ | `ApexSankey.setLicense(key)` | Static. Set the commercial license key before creating any chart instances. |
73
+ | `ApexSankey.registerTheme(name, theme)` | Static. Register (or override) a named theme (a `SankeyTheme`), then reference it by name via the `theme` option. Use for brand presets. |
74
+ | `ApexSankey.collapseGroups(data, groups, collapsed)` | Static. Project a detailed `{ nodes, edges }` to an aggregated one by collapsing the listed groups into super-nodes (re-routing and merging their flows). The pure transform behind the `drillDown` plugin; use it to seed the initial collapsed render. |
75
+ | `ApexSankey.compare(element, config)` | Static. Render two linked diagrams (a "before" and an "after") side by side, outlining each flow by how it changed and highlighting the twin node or flow across both panels on hover. Returns a `SankeyComparison` handle (`before` / `after` / `diff` / `destroy()`). See [Comparison split-view](#comparison-split-view). |
76
+ | `on(event, handler)` | Subscribe to an instance event (see [Plugins & Events](#plugins--events)). Returns an unsubscribe function. |
77
+ | `off(event, handler)` | Remove a handler previously registered with `on`. |
78
+ | `use(plugin)` | Install a `SankeyPlugin`. Its `install` runs immediately; any teardown it returns runs on `destroy()`. Returns the instance. |
79
+ | `destroy()` | Tear down the chart: run plugin teardowns, emit `destroyed`, drop all handlers, and remove injected DOM (tooltip container). |
80
+
64
81
  ## ApexSankey Options
65
82
 
66
83
  The layout can be configured by passing a second argument to `ApexSankey` with the properties listed below.
@@ -70,18 +87,26 @@ The layout can be configured by passing a second argument to `ApexSankey` with t
70
87
  | `width` | `number \| string` | `'100%'` | Width of the canvas. Accepts a pixel number or CSS percentage string. |
71
88
  | `height` | `number \| string` | `'auto'` | Height of the canvas. `'auto'` derives height from width at a 1.6:1 ratio. |
72
89
  | `canvasStyle` | `string` | built-in border | Arbitrary CSS injected onto the SVG root container element. |
90
+ | `type` | `'sankey' \| 'chord'` | `'sankey'` | Which projection of the flow model to draw. `'chord'` renders a radial diagram (nodes as arcs on a ring, flows as ribbons across the interior) for dense many-to-many relationships. See [Chord](#chord). |
91
+ | `arcCornerRadius` | `number` | `6` | Chord only. Corner radius (px) for the rounded outer corners of each node arc (the inner edge, where ribbons meet, stays flush). `0` gives sharp corners; clamped to the ring band width. |
92
+ | `theme` | `string \| SankeyTheme` | `undefined` | A named built-in theme (`'light'`, `'dark'`, `'midnight'`, `'mint'`, `'sunset'`), a name registered via `ApexSankey.registerTheme`, or an inline `SankeyTheme`. Seeds coordinated visual defaults (palette, colors, background); options you set explicitly still win. See [Themes](#themes). |
73
93
  | `spacing` | `number` | `20` | Horizontal spacing between node columns in pixels. |
74
94
  | `nodeWidth` | `number` | `20` | Width of each node rectangle in pixels. |
75
95
  | `nodeBorderWidth` | `number` | `1` | Border width of each node in pixels. |
76
96
  | `nodeBorderColor` | `string \| null` | `null` | CSS color for the node border. `null` disables the border. |
97
+ | `nodePalette` | `string[]` | `undefined` | Ordered fill colors cycled across nodes that do not set their own `color`. Overrides the built-in palette; a `theme` sets this for you. |
98
+ | `draggableNodes` | `boolean` | `false` | Allow nodes to be repositioned by dragging with a pointer (mouse, touch, or pen). Connected flows follow the node live; the manual position holds until the next `render()`/`update()` recomputes the layout. |
77
99
  | `onNodeClick` | `(node: SankeyNode) => void` | `undefined` | Callback fired when the user clicks a node. |
78
100
  | `edgeOpacity` | `number` | `0.4` | Opacity of edges (0–1). |
79
101
  | `edgeGradientFill` | `boolean` | `true` | Fill edges with a gradient between source and target node colors. |
102
+ | `particleFlow` | `boolean` | `false` | Animate particles drifting along each flow ribbon, with density proportional to the ribbon's value. Purely decorative; skipped under `prefers-reduced-motion`. |
80
103
  | `edgeGap` | `number` | `0` | Gap in pixels between adjacent edges at node connection points. |
81
104
  | `whitespace` | `number` | `0.18` | Fraction of vertical space used as margins between nodes (0–1). Lower = taller nodes. |
105
+ | `orientation` | `'horizontal' \| 'vertical'` | `'horizontal'` | Flow direction. `'horizontal'` lays ranks out in columns (flows left→right); `'vertical'` lays them in rows (flows top→bottom). |
106
+ | `axisTitles` | `string[]` | `undefined` | Titles drawn above each column (or beside each row when vertical), one per rank — the axis/dimension labels of an alluvial diagram. Index `i` labels rank `i`. See [Alluvial](#alluvial). |
82
107
  | `viewPortWidth` | `number` | `800` | Internal SVG viewport width in pixels. |
83
108
  | `viewPortHeight` | `number` | `500` | Internal SVG viewport height in pixels. |
84
- | `highlightConnectedPath` | `boolean` | `true` | Highlight the connected flow path when hovering a node or edge. |
109
+ | `highlightConnectedPath` | `boolean` | `true` | Highlight connected flows on interaction. Hovering a node or flow gives a one-hop preview; clicking a node or flow pins an isolate of its full upstream/downstream path (click again, or click another, to change/release). |
85
110
  | `dimOpacity` | `number` | `0.2` | Opacity for dimmed (unrelated) elements when path highlighting is active. |
86
111
  | `animation` | `{ enabled: boolean, duration: number }` | `{ enabled: true, duration: 800 }` | Entrance animation. Automatically disabled when `prefers-reduced-motion` is set. |
87
112
  | `enableTooltip` | `boolean` | `true` | Show edge tooltips on hover. |
@@ -100,6 +125,191 @@ The layout can be configured by passing a second argument to `ApexSankey` with t
100
125
  | `a11y` | `{ enabled?: boolean, diagramLabel?: string, description?: string }` | `{ enabled: true }` | WCAG 2.1 AA accessibility options. |
101
126
  | `locale` | `{ direction?: 'ltr' \| 'rtl' \| 'auto', messages?: Partial<SankeyMessages> }` | `{ direction: 'ltr' }` | Localization and text-direction. `direction: 'rtl'` mirrors the diagram horizontally (flows read right-to-left) and sets `dir="rtl"` on the container (`'auto'` defers to the document). `messages` overrides the screen-reader strings the diagram generates. |
102
127
 
128
+ ### Chord
129
+
130
+ Set `type: 'chord'` to draw the radial projection of the same `{ nodes, edges }` model: each node becomes an arc on a ring (its span proportional to total incident flow) and each edge a ribbon crossing the interior. It suits dense many-to-many or symmetric relationships (migration, co-occurrence, adjacency) where a layered Sankey turns into spaghetti. Hovering an arc or ribbon focuses its connections and dims the rest. The arcs' outer corners are rounded by default (`arcCornerRadius`); set it to `0` for sharp corners.
131
+
132
+ ```js
133
+ const sankey = new ApexSankey(el, {type: 'chord'});
134
+ sankey.render({
135
+ nodes: [
136
+ {id: 'A', title: 'A'},
137
+ {id: 'B', title: 'B'},
138
+ {id: 'C', title: 'C'},
139
+ ],
140
+ edges: [
141
+ {source: 'A', target: 'B', value: 12, type: 'x'},
142
+ {source: 'B', target: 'C', value: 8, type: 'x'},
143
+ {source: 'C', target: 'A', value: 5, type: 'x'},
144
+ ],
145
+ });
146
+ ```
147
+
148
+ Chord mode reuses the tooltip, node/edge click events, and color palette. Sankey-only features (multi-orientation, RTL mirror, animated relayout, node dragging, particle flow) do not apply to it.
149
+
150
+ ### Alluvial
151
+
152
+ An alluvial diagram is the same engine as a Sankey, reached through the same `{ nodes, edges }` model. `ApexSankey.buildAlluvialData` (also exported as `buildAlluvialData`) turns categorical records-across-dimensions into that model so you do not hand-build it: it creates one node per (dimension, category) and one edge per adjacent-dimension transition, with each category keeping the same color across every dimension so a cohort reads as one continuous stream. Pair it with `axisTitles` for the dimension labels.
153
+
154
+ ```js
155
+ const input = {
156
+ dimensions: ['2019', '2022', '2025'],
157
+ records: [
158
+ {values: {2019: 'Free', 2022: 'Pro', 2025: 'Pro'}},
159
+ {values: {2019: 'Free', 2022: 'Free', 2025: 'Churned'}},
160
+ {values: {2019: 'Pro', 2022: 'Pro', 2025: 'Team'}, value: 3},
161
+ ],
162
+ };
163
+
164
+ const sankey = new ApexSankey(el, {axisTitles: input.dimensions});
165
+ sankey.render({...ApexSankey.buildAlluvialData(input), options: sankey.options});
166
+ ```
167
+
168
+ `AlluvialInput` fields:
169
+
170
+ | Field | Type | Description |
171
+ | ------------ | ------------------ | -------------------------------------------------------------- |
172
+ | `dimensions` | `string[]` | Ordered dimension (axis) ids, left → right. |
173
+ | `records` | `AlluvialRecord[]` | The subjects flowing across the dimensions. |
174
+ | `palette` | `string[]` | Optional category color palette, cycled per distinct category. |
175
+
176
+ Each `AlluvialRecord` is `{ values: Record<string, string>, value?: number }` — the category at each dimension (keyed by dimension id), and the weight it contributes (default `1`). A record missing a category at some dimension simply skips that adjacency.
177
+
178
+ ### Plugins & Events
179
+
180
+ Subscribe to instance events with `on` (it returns an unsubscribe function), or package reusable behaviour as a `SankeyPlugin` and install it with `use`.
181
+
182
+ ```js
183
+ // events
184
+ const off = sankey.on('node:click', ({id, node, originalEvent}) => {
185
+ console.log('clicked', id);
186
+ });
187
+ // ...later
188
+ off();
189
+
190
+ // a reusable plugin: log every clicked node, cleaned up on destroy()
191
+ sankey.use({
192
+ name: 'click-logger',
193
+ install: ({chart, on}) => on('node:click', ({id}) => console.log('clicked', id)),
194
+ });
195
+ ```
196
+
197
+ Emitted events and their payloads:
198
+
199
+ | Event | Payload | When |
200
+ | --- | --- | --- |
201
+ | `node:click` | `{ id, node, originalEvent }` | A node is clicked. |
202
+ | `node:mouseenter` | `{ id, node, originalEvent }` | The pointer enters a node. |
203
+ | `node:mouseleave` | `{ id, node, originalEvent }` | The pointer leaves a node. |
204
+ | `edge:click` | `{ source, target, value, originalEvent }` | A flow (edge) is clicked. |
205
+ | `edge:mouseenter` | `{ source, target, value, originalEvent }` | The pointer enters a flow. |
206
+ | `edge:mouseleave` | `{ source, target, value, originalEvent }` | The pointer leaves a flow. |
207
+ | `rendered` | none | After the initial render and after each `update()` settles. |
208
+ | `destroyed` | none | On `destroy()`. |
209
+
210
+ A `SankeyPlugin` is `{ name, install(ctx) }`. `install` receives `{ chart, on }` and may return a teardown function that runs on `destroy()`. Every subscription made through `ctx.on` is also released automatically on `destroy()`.
211
+
212
+ #### Built-in plugins
213
+
214
+ `pathTrace` ships with the library (importable as `pathTrace`, or `ApexSankey.plugins.pathTrace`). Installing it makes a bright pulse cascade along the connected flow path when a node is picked, ribbon by ribbon, cueing the eye to where the flow goes. It is skipped under `prefers-reduced-motion` and applies to the Sankey projection (not chord).
215
+
216
+ ```js
217
+ sankey.use(pathTrace({direction: 'downstream'}));
218
+ ```
219
+
220
+ | `PathTraceOptions` | Type | Default | Description |
221
+ | --- | --- | --- | --- |
222
+ | `trigger` | `'click' \| 'hover'` | `'click'` | What starts a trace. |
223
+ | `direction` | `'downstream' \| 'upstream' \| 'both'` | `'downstream'` | Which way flow is traced from the picked node. |
224
+ | `color` | `string` | `'#ffffff'` | Pulse color. |
225
+ | `duration` | `number` | `700` | Milliseconds for a pulse to cross one ribbon. |
226
+ | `stagger` | `number` | `220` | Milliseconds added per hop, so the trace cascades outward. |
227
+
228
+ `timePlayback` steps the diagram through a sequence of data frames, driven by the chart's own `update()` so topology-stable frames spring smoothly from one to the next. It ships a small control bar (play/pause + a scrubber). Importable as `timePlayback` or `ApexSankey.plugins.timePlayback`.
229
+
230
+ ```js
231
+ sankey.render({...frames[0], options: sankey.options});
232
+ sankey.use(timePlayback({frames, interval: 1500, loop: true}));
233
+ ```
234
+
235
+ | `TimePlaybackOptions` | Type | Default | Description |
236
+ | --- | --- | --- | --- |
237
+ | `frames` | `TimePlaybackFrame[]` | required | Ordered frames (`{ nodes, edges, label? }`). Share topology across frames for a smooth morph. |
238
+ | `interval` | `number` | `1600` | Milliseconds each frame is shown before advancing. |
239
+ | `autoplay` | `boolean` | `false` | Start playing on install. |
240
+ | `loop` | `boolean` | `false` | Loop back to the first frame after the last. |
241
+ | `controls` | `boolean` | `true` | Render the built-in control bar. |
242
+ | `mount` | `HTMLElement` | after the chart | Where to render the control bar. |
243
+
244
+ `drillDown` turns a large diagram into a set of super-nodes you expand on demand: click a super-node to reveal its constituent flows, click any of its children to collapse it back. The drillable nodes get a `pointer` cursor so they read as clickable. Expanding animates the children **growing out of the super-node** (and shrinking back into it on collapse) with their ribbons — driven through the chart's own `update()` (which accepts an optional `SankeyTransition` hint for this). It is built on the pure `ApexSankey.collapseGroups` transform (also exported as `collapseGroups`), which re-routes and merges the flows of a collapsed group. Importable as `drillDown` or `ApexSankey.plugins.drillDown`; applies to the Sankey projection (not chord). Seed the initial collapsed render with `ApexSankey.collapseGroups` so there is no load-time morph.
245
+
246
+ ```js
247
+ const detail = {nodes, edges};
248
+ const groups = [{id: 'Fossil', title: 'Fossil', children: ['Coal', 'Gas', 'Oil']}];
249
+ sankey.render({...ApexSankey.collapseGroups(detail, groups, ['Fossil']), options: sankey.options});
250
+ sankey.use(drillDown({...detail, groups}));
251
+ ```
252
+
253
+ | `DrillDownOptions` | Type | Default | Description |
254
+ | --- | --- | --- | --- |
255
+ | `nodes` | `SankeyGraphNode[]` | required | The full, detailed leaf nodes before any collapsing. |
256
+ | `edges` | `SankeyGraphEdge[]` | required | The full, detailed flows between the leaf nodes. |
257
+ | `groups` | `DrillDownGroup[]` | required | Group definitions (`{ id, title, color?, children }`); each collapses its children into one super-node. |
258
+ | `expanded` | `string[]` | `[]` | Group ids expanded on install; every other group starts collapsed. |
259
+
260
+ ### Comparison split-view
261
+
262
+ `ApexSankey.compare(element, config)` renders two diagrams of the same flow model side by side — a "before" and an "after". It outlines each flow by how it changed between them (added, removed, or changed, from the pure `diffGraphs` transform, also exported), draws a legend, and links the panels so hovering a node or flow highlights its twin in the other. It is built on the public surface only (two ordinary `ApexSankey` instances plus their `node:*` and `edge:*` events) and returns a `SankeyComparison` handle exposing `before`, `after`, the computed `diff`, and `destroy()`.
263
+
264
+ ```js
265
+ const cmp = ApexSankey.compare(el, {
266
+ before: {nodes, edges: edges2024, title: '2024'},
267
+ after: {nodes, edges: edges2025, title: '2025'},
268
+ });
269
+ // later: cmp.destroy();
270
+ ```
271
+
272
+ | `ComparisonConfig` | Type | Default | Description |
273
+ | --- | --- | --- | --- |
274
+ | `before` | `{ nodes, edges, title? }` | required | The left panel's flow graph and optional heading. |
275
+ | `after` | `{ nodes, edges, title? }` | required | The right panel's flow graph and optional heading. |
276
+ | `options` | `Partial<SankeyOptions>` | `{}` | Base options shared by both panels (each manages its own width). |
277
+ | `syncHighlight` | `boolean` | `true` | Highlight the twin node or flow in the other panel on hover (a cursor lands on a ribbon at least as readily as on a node). |
278
+ | `showDiff` | `boolean` | `true` | Outline added / removed / changed flows in each panel. |
279
+ | `showLegend` | `boolean` | `true` | Render the diff color legend below the panels. |
280
+ | `diffColors` | `{ added?, removed?, changed? }` | greens/reds/ambers | Override the diff outline colors. |
281
+
282
+ ### Themes
283
+
284
+ Pass `theme` to seed a coordinated set of visual defaults in one shot. Built-in themes: `'light'` (the default look), `'dark'`, `'midnight'`, `'mint'`, and `'sunset'`. A theme sits between the built-in defaults and your explicit options, so anything you set yourself still wins.
285
+
286
+ ```js
287
+ const sankey = new ApexSankey(el, {theme: 'dark'});
288
+ ```
289
+
290
+ Register a brand preset once, then reference it by name:
291
+
292
+ ```js
293
+ ApexSankey.registerTheme('acme', {
294
+ nodePalette: ['#ff5a5f', '#087f8c', '#5d2e8c'],
295
+ fontColor: '#1a1a1a',
296
+ canvasStyle: 'background: #faf7f2; box-sizing: border-box;',
297
+ });
298
+ const sankey = new ApexSankey(el, {theme: 'acme'});
299
+ ```
300
+
301
+ You can also pass an inline `SankeyTheme` object directly as `theme`. A `SankeyTheme` may set any subset of the following (each maps to the option of the same name; omitted fields keep their default):
302
+
303
+ | `SankeyTheme` field | Type | Description |
304
+ | ------------------- | ------------------- | ------------------------------------------------------------------------ |
305
+ | `nodePalette` | `string[]` | Ordered node fill colors, cycled across nodes without their own `color`. |
306
+ | `fontColor` | `string` | CSS color for node labels. |
307
+ | `edgeOpacity` | `number` | Opacity of the flow ribbons (0–1). |
308
+ | `edgeGradientFill` | `boolean` | Fill ribbons with a source→target gradient. |
309
+ | `nodeBorderColor` | `string \| null` | CSS color for the node border (`null` disables). |
310
+ | `canvasStyle` | `string` | CSS on the SVG root container, typically the background and border. |
311
+ | `tooltipTheme` | `'light' \| 'dark'` | Tooltip color preset. |
312
+
103
313
  ### Localization & RTL
104
314
 
105
315
  The diagram's screen-reader strings live in `SankeyMessages`; pass a `Partial<SankeyMessages>` via `locale.messages` to translate any subset (unset keys keep their English defaults, exported as `DEFAULT_SANKEY_MESSAGES`). Visible tooltips are localized separately via `tooltipTemplate` / `nodeTooltipTemplate`.