@aliens-syndicate/chart 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +100 -2
- package/elements/ui-chart/ui-chart.markup +13 -0
- package/elements/ui-chart/ui-chart.style +107 -0
- package/index.mjs +17 -0
- package/package.json +25 -4
- package/runtime.mjs +583 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Aliens Syndicate
|
|
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
|
|
13
|
+
all 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
|
|
21
|
+
THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,101 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @aliens-syndicate/chart
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An independent chart dependency for Aliens. 28 chart types drawn as SVG from a plain table, theme-aware Space styles, tooltips and legend. The table stays in the page, visually hidden, as the accessible version of the chart. MIT licensed, ES modules, no runtime dependencies. Neither `@aliens-syndicate/elements` nor `@aliens-syndicate/utilities` is required.
|
|
4
|
+
|
|
5
|
+
## Install in Aliens
|
|
6
|
+
|
|
7
|
+
Use the compiler/tools from this repository with support for the `chart:` extension. Add this entry alongside your existing dependencies in `.config`, then run `aliens install`:
|
|
8
|
+
|
|
9
|
+
```text
|
|
10
|
+
dependencies:
|
|
11
|
+
chart:
|
|
12
|
+
@aliens-syndicate/chart: 0.1.0
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
The updated CLI also offers `aliens new my-project --chart`. The compiler validates the installed version, indexes the package in `ai/.map`, and emits its CSS and runtime only when the page renders `ui-chart`.
|
|
16
|
+
|
|
17
|
+
## Space example
|
|
18
|
+
|
|
19
|
+
```text
|
|
20
|
+
Markup Sales
|
|
21
|
+
ui-chart type="column" caption="Sales" height="240" unit="" legend="true"
|
|
22
|
+
thead
|
|
23
|
+
tr
|
|
24
|
+
th={Month} scope="col"
|
|
25
|
+
th={Online} scope="col"
|
|
26
|
+
th={Store} scope="col"
|
|
27
|
+
tbody
|
|
28
|
+
tr
|
|
29
|
+
td={Jan}
|
|
30
|
+
td={24}
|
|
31
|
+
td={18}
|
|
32
|
+
tr
|
|
33
|
+
td={Feb}
|
|
34
|
+
td={30}
|
|
35
|
+
td={12}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Project lists work inside `tbody`: use `for row in rows` and cells such as `td={$row.month}`. Only the properties that differ from the defaults need to be written. `caption` accepts translation references such as `caption={@sales.title}`.
|
|
39
|
+
|
|
40
|
+
| Property | Purpose |
|
|
41
|
+
| --- | --- |
|
|
42
|
+
| `type` | One of the chart types below. Unknown values draw `column`. |
|
|
43
|
+
| `caption` | Visible title and caption of the data table. |
|
|
44
|
+
| `height` | Height in pixels (minimum 40). The width follows the container. |
|
|
45
|
+
| `unit` | Text after each value, such as `%` or ` km`. Empty for none. |
|
|
46
|
+
| `legend` | `true` shows the legend, `false` hides it. |
|
|
47
|
+
|
|
48
|
+
## Chart types and data
|
|
49
|
+
|
|
50
|
+
The first column names each category; every other header is a series. Cells must be machine-readable numbers; for formatted cells set `data-value="1234.5"`.
|
|
51
|
+
|
|
52
|
+
| Types | Data |
|
|
53
|
+
| --- | --- |
|
|
54
|
+
| `column`, `column-stacked`, `bar`, `bar-stacked` | One or more series. `bar` is horizontal. |
|
|
55
|
+
| `line`, `spline`, `step`, `area`, `area-spline`, `area-stacked` | One or more series. |
|
|
56
|
+
| `combo` | First series as columns, the others as lines. |
|
|
57
|
+
| `lollipop`, `waterfall`, `pie`, `doughnut`, `polar`, `funnel`, `treemap`, `sparkline` | First series. `waterfall` reads each value as a change. |
|
|
58
|
+
| `range` | Two series: low and high. |
|
|
59
|
+
| `candlestick` | Four series: open, high, low and close. |
|
|
60
|
+
| `scatter` | The first column is the numeric x; each series is a y. |
|
|
61
|
+
| `bubble` | Numeric x in the first column, then y and size. |
|
|
62
|
+
| `heatmap` | Every cell; color strength follows the value. |
|
|
63
|
+
| `radial`, `progress`, `gauge` | Value and, optionally, its maximum (100 by default). `radial` draws one ring per row; `progress` and `gauge` use the first row. |
|
|
64
|
+
| `radar` | Each row is an axis; each series is a shape. |
|
|
65
|
+
|
|
66
|
+
### Style properties
|
|
67
|
+
|
|
68
|
+
Every property has a default in the catalog, so a chart only needs what differs. `color-1` to `color-8` color the series and default to the theme tokens `--color-chart-1` to `--color-chart-8` (a lime and green palette starting at `#dfff88` when the theme has none); falls in waterfall and candlestick use `--color-danger`; `background`, `text-color`, `border-size`, `border-color`, `radius` and `padding` set the card; `grid-color`, `label-color` and `label-size` the axes; `line-width`, `bar-radius` and `area-opacity` the marks; `tooltip-background` and `tooltip-color` the tooltip. The framework's `#chart-docs` page is a Storybook with every chart type, its stories, live Controls and editable code.
|
|
69
|
+
|
|
70
|
+
Colors come from `--ui-chart-color-1` to `--ui-chart-color-8`. Override them, `--ui-chart-background`, `--ui-chart-color`, `--ui-chart-border-color`, `--ui-chart-radius` and `--ui-chart-padding` on the container to customize the chart. Labels and grid use the `--color-*` theme tokens.
|
|
71
|
+
|
|
72
|
+
## Browser API
|
|
73
|
+
|
|
74
|
+
```js
|
|
75
|
+
import { mountCharts } from '@aliens-syndicate/chart/browser';
|
|
76
|
+
|
|
77
|
+
const controllers = mountCharts(document);
|
|
78
|
+
controllers[0].refresh(); // Redraws now.
|
|
79
|
+
console.log(controllers[0].state); // { type, rows, series }
|
|
80
|
+
controllers[0].destroy(); // Removes the drawing, the tooltip and the listeners.
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Aliens calls `mountCharts` automatically. Calling it again returns the existing controller. Charts redraw by themselves when the table cells, the `data-*` attributes, the page language or the container width change. You can also dispatch `chart:refresh` on the container. Outside Aliens, provide a `[data-chart]` container with `data-type`, `data-height`, `data-unit` and `data-legend`, a `[data-chart-canvas]`, a `[data-chart-legend]` list and a table inside `[data-chart-data]`. The shipped Space files are the reference structure and styles.
|
|
84
|
+
|
|
85
|
+
## Development and publishing
|
|
86
|
+
|
|
87
|
+
```sh
|
|
88
|
+
npm ci
|
|
89
|
+
npm test
|
|
90
|
+
npm pack --dry-run
|
|
91
|
+
npm publish --access public
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
`prepublishOnly` runs the tests before publication. The published files contain only the runtime, package metadata, Space Element, README and license.
|
|
95
|
+
|
|
96
|
+
The framework repository includes a working example at `#chart-docs` and a package integration check:
|
|
97
|
+
|
|
98
|
+
```sh
|
|
99
|
+
node tools/chart-integration.test.mjs
|
|
100
|
+
node tools/build.mjs
|
|
101
|
+
```
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Markup UiChart
|
|
2
|
+
# A chart drawn as SVG from the table in the slot: the first column names the categories and every other header is a
|
|
3
|
+
# series. type picks one of the 28 charts (column, line, area, pie, radar…); height is in pixels and the width follows
|
|
4
|
+
# the container; unit goes after every value; legend shows or hides the legend. color-1 to color-8 color the series,
|
|
5
|
+
# and the other properties set the frame, the grid, the labels, the lines, the bars and the tooltip.
|
|
6
|
+
figure variant="ui-chart" data-chart data-type={$type} data-height={$height} data-unit={$unit} data-legend={$legend} style="--ui-chart-color-1: {$color-1}; --ui-chart-color-2: {$color-2}; --ui-chart-color-3: {$color-3}; --ui-chart-color-4: {$color-4}; --ui-chart-color-5: {$color-5}; --ui-chart-color-6: {$color-6}; --ui-chart-color-7: {$color-7}; --ui-chart-color-8: {$color-8}; --ui-chart-background: {$background}; --ui-chart-text-color: {$text-color}; --ui-chart-border-size: {$border-size}; --ui-chart-border-color: {$border-color}; --ui-chart-radius: {$radius}; --ui-chart-padding: {$padding}; --ui-chart-grid-color: {$grid-color}; --ui-chart-label-color: {$label-color}; --ui-chart-label-size: {$label-size}; --ui-chart-line-width: {$line-width}; --ui-chart-bar-radius: {$bar-radius}; --ui-chart-area-opacity: {$area-opacity}; --ui-chart-tooltip-background: {$tooltip-background}; --ui-chart-tooltip-color: {$tooltip-color}"
|
|
7
|
+
figcaption={$caption} variant="ui-chart-caption"
|
|
8
|
+
div variant="ui-chart-canvas" data-chart-canvas aria-hidden="true"
|
|
9
|
+
ul variant="ui-chart-legend" data-chart-legend aria-hidden="true"
|
|
10
|
+
div variant="ui-chart-data" data-chart-data
|
|
11
|
+
table
|
|
12
|
+
caption={$caption}
|
|
13
|
+
slot
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
Style UiChart
|
|
2
|
+
ui-chart
|
|
3
|
+
position: relative
|
|
4
|
+
display: grid
|
|
5
|
+
gap: var(--space-3, 0.75rem)
|
|
6
|
+
min-width: 0
|
|
7
|
+
margin: 0
|
|
8
|
+
color: var(--ui-chart-text-color, var(--color-text, #171717))
|
|
9
|
+
background: var(--ui-chart-background, var(--color-canvas, #ffffff))
|
|
10
|
+
border: var(--ui-chart-border-size, 1px) solid var(--ui-chart-border-color, var(--color-outline, #e5e5e5))
|
|
11
|
+
border-radius: var(--ui-chart-radius, var(--radius-lg, 0.75rem))
|
|
12
|
+
padding: var(--ui-chart-padding, 1rem)
|
|
13
|
+
ui-chart-caption
|
|
14
|
+
font-weight: 700
|
|
15
|
+
ui-chart-canvas
|
|
16
|
+
min-width: 0
|
|
17
|
+
ui-chart-svg
|
|
18
|
+
display: block
|
|
19
|
+
overflow: visible
|
|
20
|
+
ui-chart-label
|
|
21
|
+
fill: var(--ui-chart-label-color, var(--color-muted, #525252))
|
|
22
|
+
font-size: var(--ui-chart-label-size, 11px)
|
|
23
|
+
ui-chart-value
|
|
24
|
+
fill: currentColor
|
|
25
|
+
font-size: 22px
|
|
26
|
+
font-weight: 700
|
|
27
|
+
ui-chart-inside
|
|
28
|
+
fill: var(--ui-chart-inside-color, #17210d)
|
|
29
|
+
font-weight: 600
|
|
30
|
+
ui-chart-grid *
|
|
31
|
+
fill: none
|
|
32
|
+
stroke: var(--ui-chart-grid-color, var(--color-outline, #e5e5e5))
|
|
33
|
+
stroke-dasharray: 3 4
|
|
34
|
+
ui-chart-axis, ui-chart-connector
|
|
35
|
+
stroke: var(--color-outline-strong, #a3a3a3)
|
|
36
|
+
ui-chart-connector
|
|
37
|
+
stroke-dasharray: 2 3
|
|
38
|
+
ui-chart-line
|
|
39
|
+
fill: none
|
|
40
|
+
stroke-width: var(--ui-chart-line-width, 2.5)
|
|
41
|
+
stroke-linecap: round
|
|
42
|
+
stroke-linejoin: round
|
|
43
|
+
ui-chart-area
|
|
44
|
+
fill-opacity: var(--ui-chart-area-opacity, 0.22)
|
|
45
|
+
stroke: none
|
|
46
|
+
ui-chart-outline
|
|
47
|
+
stroke-width: 2
|
|
48
|
+
ui-chart-dot
|
|
49
|
+
fill: var(--ui-chart-background, var(--color-canvas, #ffffff))
|
|
50
|
+
stroke-width: 2
|
|
51
|
+
ui-chart-stem
|
|
52
|
+
stroke-width: 2
|
|
53
|
+
ui-chart-track
|
|
54
|
+
fill: none
|
|
55
|
+
stroke: var(--color-surface, #f0f0f0)
|
|
56
|
+
ui-chart-ring
|
|
57
|
+
fill: none
|
|
58
|
+
stroke-linecap: round
|
|
59
|
+
ui-chart-slice
|
|
60
|
+
stroke: var(--ui-chart-background, var(--color-canvas, #ffffff))
|
|
61
|
+
stroke-width: 2
|
|
62
|
+
ui-chart-translucent, ui-chart-bubble
|
|
63
|
+
fill-opacity: 0.7
|
|
64
|
+
ui-chart-mark, ui-chart-dot, ui-chart-ring
|
|
65
|
+
transition: opacity 0.15s
|
|
66
|
+
ui-chart-mark:hover, ui-chart-dot:hover, ui-chart-ring:hover
|
|
67
|
+
opacity: 0.75
|
|
68
|
+
ui-chart-legend
|
|
69
|
+
display: flex
|
|
70
|
+
flex-wrap: wrap
|
|
71
|
+
gap: 0.5rem 1rem
|
|
72
|
+
margin: 0
|
|
73
|
+
padding: 0
|
|
74
|
+
list-style: none
|
|
75
|
+
font-size: 0.8125rem
|
|
76
|
+
color: var(--ui-chart-label-color, var(--color-muted, #525252))
|
|
77
|
+
ui-chart-legend li
|
|
78
|
+
display: inline-flex
|
|
79
|
+
align-items: center
|
|
80
|
+
gap: 0.4rem
|
|
81
|
+
ui-chart-legend[hidden], ui-chart-tooltip[hidden]
|
|
82
|
+
display: none
|
|
83
|
+
ui-chart-swatch
|
|
84
|
+
width: 0.75rem
|
|
85
|
+
height: 0.75rem
|
|
86
|
+
border-radius: 999px
|
|
87
|
+
ui-chart-bar
|
|
88
|
+
rx: var(--ui-chart-bar-radius, 4px)
|
|
89
|
+
ui-chart-tooltip
|
|
90
|
+
position: absolute
|
|
91
|
+
z-index: 2
|
|
92
|
+
max-width: 16rem
|
|
93
|
+
padding: 0.4rem 0.6rem
|
|
94
|
+
border-radius: var(--radius-md, 0.5rem)
|
|
95
|
+
background: var(--ui-chart-tooltip-background, var(--color-text, #171717))
|
|
96
|
+
color: var(--ui-chart-tooltip-color, var(--color-canvas, #ffffff))
|
|
97
|
+
font-size: 0.75rem
|
|
98
|
+
pointer-events: none
|
|
99
|
+
transform: translate(-50%, calc(-100% - 12px))
|
|
100
|
+
white-space: nowrap
|
|
101
|
+
ui-chart-data
|
|
102
|
+
position: absolute
|
|
103
|
+
width: 1px
|
|
104
|
+
height: 1px
|
|
105
|
+
overflow: hidden
|
|
106
|
+
clip-path: inset(50%)
|
|
107
|
+
white-space: nowrap
|
package/index.mjs
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { fileURLToPath } from 'node:url';
|
|
2
|
+
|
|
3
|
+
export { mountCharts } from './runtime.mjs';
|
|
4
|
+
export const elementsDirectory = fileURLToPath(new URL('./elements/', import.meta.url));
|
|
5
|
+
// Every value ui-chart accepts in type; an unknown type draws a column chart.
|
|
6
|
+
export const chartTypes = ['column', 'column-stacked', 'bar', 'bar-stacked', 'line', 'spline', 'step', 'area', 'area-spline', 'area-stacked',
|
|
7
|
+
'combo', 'lollipop', 'range', 'candlestick', 'waterfall', 'scatter', 'bubble', 'heatmap', 'pie', 'doughnut', 'polar', 'radial',
|
|
8
|
+
'progress', 'gauge', 'radar', 'funnel', 'treemap', 'sparkline'];
|
|
9
|
+
// Every property has a default, so a chart needs only what differs: ui-chart type="pie" caption="Share".
|
|
10
|
+
export const catalog = [
|
|
11
|
+
{
|
|
12
|
+
name: 'ui-chart',
|
|
13
|
+
properties: ['type', 'caption', 'height', 'unit', 'legend', 'color-1', 'color-2', 'color-3', 'color-4', 'color-5', 'color-6', 'color-7', 'color-8', 'background', 'text-color', 'border-size', 'border-color', 'radius', 'padding', 'grid-color', 'label-color', 'label-size', 'line-width', 'bar-radius', 'area-opacity', 'tooltip-background', 'tooltip-color'],
|
|
14
|
+
variants: ['ui-chart'],
|
|
15
|
+
defaults: { 'type': 'column', 'caption': 'Chart', 'height': '240', 'unit': '', 'legend': 'true', 'color-1': 'var(--color-chart-1, #dfff88)', 'color-2': 'var(--color-chart-2, #8ae4ae)', 'color-3': 'var(--color-chart-3, #5fa84a)', 'color-4': 'var(--color-chart-4, #f2e27a)', 'color-5': 'var(--color-chart-5, #4fc1b0)', 'color-6': 'var(--color-chart-6, #b8c4b3)', 'color-7': 'var(--color-chart-7, #2f7a46)', 'color-8': 'var(--color-chart-8, #effccb)', 'background': 'var(--color-canvas, #ffffff)', 'text-color': 'var(--color-text, #171717)', 'border-size': '1px', 'border-color': 'var(--color-outline, #e5e5e5)', 'radius': 'var(--radius-lg, 0.75rem)', 'padding': 'var(--space-4, 1rem)', 'grid-color': 'var(--color-outline, #e5e5e5)', 'label-color': 'var(--color-muted, #525252)', 'label-size': '11px', 'line-width': '2.5', 'bar-radius': '4px', 'area-opacity': '0.22', 'tooltip-background': 'var(--color-text, #171717)', 'tooltip-color': 'var(--color-canvas, #ffffff)' }
|
|
16
|
+
}
|
|
17
|
+
];
|
package/package.json
CHANGED
|
@@ -1,6 +1,27 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aliens-syndicate/chart",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Charts for Aliens: 28 SVG chart types drawn from an accessible table, with Space markup and theme-aware styles.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Aliens Syndicate",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./index.mjs",
|
|
10
|
+
"./browser": "./runtime.mjs"
|
|
11
|
+
},
|
|
12
|
+
"files": ["index.mjs", "runtime.mjs", "elements/"],
|
|
13
|
+
"scripts": {
|
|
14
|
+
"test": "node --test test.mjs",
|
|
15
|
+
"prepublishOnly": "npm test"
|
|
16
|
+
},
|
|
17
|
+
"devDependencies": { "linkedom": "0.18.15" },
|
|
18
|
+
"engines": { "node": ">=22.13" },
|
|
19
|
+
"keywords": ["aliens", "space", "chart", "charts", "svg", "graph", "visualization", "components"],
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "git+https://github.com/AliensSyndicate/aliens-syndicate-framework.git",
|
|
23
|
+
"directory": "packages/chart"
|
|
24
|
+
},
|
|
25
|
+
"homepage": "https://github.com/AliensSyndicate/aliens-syndicate-framework/tree/main/packages/chart#readme",
|
|
26
|
+
"publishConfig": { "access": "public" }
|
|
27
|
+
}
|
package/runtime.mjs
ADDED
|
@@ -0,0 +1,583 @@
|
|
|
1
|
+
// Self-contained so the Aliens compiler can include it only when ui-chart is rendered: the build inlines this function
|
|
2
|
+
// as text, so every helper lives inside it. The data comes from the table in the slot, which stays in the page as the
|
|
3
|
+
// accessible version of the chart. No cell content is evaluated as HTML.
|
|
4
|
+
export function mountCharts(container = document) {
|
|
5
|
+
const marker = Symbol.for('@aliens-syndicate/chart');
|
|
6
|
+
const types = ['column', 'column-stacked', 'bar', 'bar-stacked', 'line', 'spline', 'step', 'area', 'area-spline', 'area-stacked',
|
|
7
|
+
'combo', 'lollipop', 'range', 'candlestick', 'waterfall', 'scatter', 'bubble', 'heatmap', 'pie', 'doughnut', 'polar', 'radial',
|
|
8
|
+
'progress', 'gauge', 'radar', 'funnel', 'treemap', 'sparkline'];
|
|
9
|
+
const roots = [...container.querySelectorAll('[data-chart]')];
|
|
10
|
+
if (container.matches?.('[data-chart]')) roots.unshift(container);
|
|
11
|
+
return roots.map(root => {
|
|
12
|
+
if (root[marker]) return root[marker];
|
|
13
|
+
const table = root.querySelector('[data-chart-data] table') ?? root.querySelector('table');
|
|
14
|
+
const canvas = root.querySelector('[data-chart-canvas]');
|
|
15
|
+
const legend = root.querySelector('[data-chart-legend]');
|
|
16
|
+
if (!table?.querySelector('tbody') || !canvas || !legend) throw new Error('ui-chart needs a canvas, a legend and a table with thead and tbody.');
|
|
17
|
+
const document = root.ownerDocument;
|
|
18
|
+
const window = document.defaultView;
|
|
19
|
+
const svgNamespace = 'http://www.w3.org/2000/svg';
|
|
20
|
+
const round = value => Math.round(value * 100) / 100;
|
|
21
|
+
// -1 is the color of a fall (waterfall, candlestick); the others cycle through the eight series colors.
|
|
22
|
+
const color = index => index < 0 ? 'var(--ui-chart-negative, var(--color-danger, #e5484d))' : `var(--ui-chart-color-${index % 8 + 1})`;
|
|
23
|
+
const listeners = [];
|
|
24
|
+
const listen = (node, event, handler) => {
|
|
25
|
+
node.addEventListener(event, handler);
|
|
26
|
+
listeners.push(() => node.removeEventListener(event, handler));
|
|
27
|
+
};
|
|
28
|
+
let destroyed = false;
|
|
29
|
+
let lastWidth = 0;
|
|
30
|
+
let scheduled = false;
|
|
31
|
+
let state = { type: 'column', rows: 0, series: 0 };
|
|
32
|
+
const tooltip = document.createElement('div');
|
|
33
|
+
tooltip.className = 'ui-chart-tooltip';
|
|
34
|
+
tooltip.hidden = true;
|
|
35
|
+
root.append(tooltip);
|
|
36
|
+
|
|
37
|
+
function node(tag, attributes = {}, parent) {
|
|
38
|
+
const element = document.createElementNS(svgNamespace, tag);
|
|
39
|
+
for (const [key, value] of Object.entries(attributes)) if (value !== undefined && value !== null) element.setAttribute(key, String(value));
|
|
40
|
+
parent?.append(element);
|
|
41
|
+
return element;
|
|
42
|
+
}
|
|
43
|
+
function text(parent, x, y, content, attributes = {}) {
|
|
44
|
+
const element = node('text', { x: round(x), y: round(y), class: 'ui-chart-label', ...attributes }, parent);
|
|
45
|
+
element.textContent = content;
|
|
46
|
+
return element;
|
|
47
|
+
}
|
|
48
|
+
const paint = (index, property = 'fill', extra = '') => `${property}: ${color(index)};${extra}`;
|
|
49
|
+
|
|
50
|
+
// Reads the slot: the first header names the categories and each other header is a series; every row is a category.
|
|
51
|
+
function read() {
|
|
52
|
+
const head = [...(table.querySelector('thead tr')?.children ?? [])].map(cell => cell.textContent.trim());
|
|
53
|
+
const rows = [...table.querySelectorAll('tbody tr')].filter(row => row.closest('table') === table).map(row => {
|
|
54
|
+
const cells = [...row.children];
|
|
55
|
+
return {
|
|
56
|
+
label: (cells[0]?.textContent ?? '').trim(),
|
|
57
|
+
x: Number(cells[0]?.getAttribute('data-value') ?? cells[0]?.textContent.trim()),
|
|
58
|
+
values: cells.slice(1).map(cell => {
|
|
59
|
+
const raw = (cell.getAttribute('data-value') ?? cell.textContent).trim();
|
|
60
|
+
return raw === '' ? NaN : Number(raw);
|
|
61
|
+
})
|
|
62
|
+
};
|
|
63
|
+
});
|
|
64
|
+
const count = Math.max(head.length - 1, ...rows.map(row => row.values.length), 0);
|
|
65
|
+
const series = Array.from({ length: count }, (_, index) => ({ name: head[index + 1] ?? '', values: rows.map(row => row.values[index]) }));
|
|
66
|
+
return { rows, series, labels: rows.map(row => row.label) };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function niceTicks(min, max, count = 5) {
|
|
70
|
+
if (!Number.isFinite(min) || !Number.isFinite(max)) [min, max] = [0, 1];
|
|
71
|
+
if (min === max) max = min + 1;
|
|
72
|
+
const raw = (max - min) / count;
|
|
73
|
+
const magnitude = 10 ** Math.floor(Math.log10(raw));
|
|
74
|
+
const normalized = raw / magnitude;
|
|
75
|
+
const step = (normalized < 1.5 ? 1 : normalized < 3 ? 2 : normalized < 7 ? 5 : 10) * magnitude;
|
|
76
|
+
const ticks = [];
|
|
77
|
+
for (let value = Math.floor(min / step) * step; value <= Math.ceil(max / step) * step + step / 2; value += step) ticks.push(round(value));
|
|
78
|
+
return ticks;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Draws the grid, the value labels and the category labels. horizontal puts the categories on the left;
|
|
82
|
+
// xRange makes the category axis numeric too (scatter and bubble).
|
|
83
|
+
function axes(svg, labels, min, max, { width, height, horizontal = false, xRange = null, format }) {
|
|
84
|
+
const ticks = niceTicks(min, max);
|
|
85
|
+
const low = ticks[0], high = ticks.at(-1);
|
|
86
|
+
const xTicks = xRange ? niceTicks(...xRange) : null;
|
|
87
|
+
const valueWidth = Math.max(...ticks.map(value => format(value).length)) * 6.5 + 14;
|
|
88
|
+
const labelWidth = Math.min(120, Math.max(0, ...labels.map(label => label.length)) * 6.5 + 16);
|
|
89
|
+
const box = { left: horizontal ? labelWidth : valueWidth, right: width - 14, top: 12, bottom: height - 28 };
|
|
90
|
+
const along = horizontal ? box.right - box.left : box.bottom - box.top;
|
|
91
|
+
const pos = value => horizontal ? box.left + (value - low) / (high - low) * along : box.bottom - (value - low) / (high - low) * along;
|
|
92
|
+
const across = horizontal ? box.bottom - box.top : box.right - box.left;
|
|
93
|
+
const band = across / Math.max(labels.length, 1);
|
|
94
|
+
const center = index => (horizontal ? box.top : box.left) + band * (index + 0.5);
|
|
95
|
+
const xPos = xTicks ? value => box.left + (value - xTicks[0]) / (xTicks.at(-1) - xTicks[0]) * (box.right - box.left) : null;
|
|
96
|
+
const grid = node('g', { class: 'ui-chart-grid' }, svg);
|
|
97
|
+
for (const value of ticks) {
|
|
98
|
+
const at = pos(value);
|
|
99
|
+
if (horizontal) {
|
|
100
|
+
node('line', { x1: round(at), x2: round(at), y1: box.top, y2: box.bottom }, grid);
|
|
101
|
+
text(svg, at, box.bottom + 18, format(value), { 'text-anchor': 'middle' });
|
|
102
|
+
} else {
|
|
103
|
+
node('line', { x1: box.left, x2: box.right, y1: round(at), y2: round(at) }, grid);
|
|
104
|
+
text(svg, box.left - 8, at + 4, format(value), { 'text-anchor': 'end' });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
if (xTicks) {
|
|
108
|
+
for (const value of xTicks) text(svg, xPos(value), box.bottom + 18, format(value, false), { 'text-anchor': 'middle' });
|
|
109
|
+
} else {
|
|
110
|
+
const room = horizontal ? 18 : Math.max(...labels.map(label => label.length), 1) * 6.5 + 8;
|
|
111
|
+
const every = Math.max(1, Math.ceil(room / band));
|
|
112
|
+
labels.forEach((label, index) => {
|
|
113
|
+
if (index % every) return;
|
|
114
|
+
if (horizontal) text(svg, box.left - 8, center(index) + 4, label, { 'text-anchor': 'end' });
|
|
115
|
+
else text(svg, center(index), box.bottom + 18, label, { 'text-anchor': 'middle' });
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
const base = pos(Math.min(Math.max(0, low), high));
|
|
119
|
+
node('line', horizontal ? { x1: round(base), x2: round(base), y1: box.top, y2: box.bottom, class: 'ui-chart-axis' }
|
|
120
|
+
: { x1: box.left, x2: box.right, y1: round(base), y2: round(base), class: 'ui-chart-axis' }, svg);
|
|
121
|
+
return { box, pos, band, center, base, horizontal, xPos };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const finite = values => values.filter(Number.isFinite);
|
|
125
|
+
function extent(data, indexes, stacked) {
|
|
126
|
+
if (!stacked) {
|
|
127
|
+
const values = finite(indexes.flatMap(index => data.series[index]?.values ?? []));
|
|
128
|
+
return [Math.min(0, ...values), Math.max(0, ...values)];
|
|
129
|
+
}
|
|
130
|
+
const sums = data.rows.map((_, row) => indexes.reduce(([negative, positive], index) => {
|
|
131
|
+
const value = data.series[index]?.values[row];
|
|
132
|
+
return !Number.isFinite(value) ? [negative, positive] : value < 0 ? [negative + value, positive] : [negative, positive + value];
|
|
133
|
+
}, [0, 0]));
|
|
134
|
+
return [Math.min(0, ...sums.map(sum => sum[0])), Math.max(0, ...sums.map(sum => sum[1]))];
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function rect(parent, horizontal, start, size, from, to, attributes) {
|
|
138
|
+
const low = Math.min(from, to), length = Math.max(Math.abs(to - from), 0.5);
|
|
139
|
+
const radius = Math.min(4, size / 2);
|
|
140
|
+
attributes = { ...attributes, class: `${attributes.class ?? ''} ui-chart-bar`.trim() };
|
|
141
|
+
return node('rect', horizontal
|
|
142
|
+
? { x: round(low), y: round(start), width: round(length), height: round(size), rx: round(radius), ...attributes }
|
|
143
|
+
: { x: round(start), y: round(low), width: round(size), height: round(length), rx: round(radius), ...attributes }, parent);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function barsOn(svg, axis, data, indexes, { stacked, format }) {
|
|
147
|
+
const inner = axis.band * 0.68;
|
|
148
|
+
const size = stacked ? inner : inner / Math.max(indexes.length, 1);
|
|
149
|
+
const gap = !stacked && indexes.length > 1 ? Math.min(3, size * 0.2) : 0;
|
|
150
|
+
data.rows.forEach((row, rowIndex) => {
|
|
151
|
+
let positive = 0, negative = 0;
|
|
152
|
+
indexes.forEach((seriesIndex, position) => {
|
|
153
|
+
const value = data.series[seriesIndex].values[rowIndex];
|
|
154
|
+
if (!Number.isFinite(value)) return;
|
|
155
|
+
let from = 0, to = value;
|
|
156
|
+
if (stacked) [from, to] = value < 0 ? [negative, negative += value] : [positive, positive += value];
|
|
157
|
+
const start = axis.center(rowIndex) - inner / 2 + (stacked ? 0 : position * size) + gap / 2;
|
|
158
|
+
rect(svg, axis.horizontal, start, Math.max(size - gap, 1), axis.pos(from), axis.pos(to), {
|
|
159
|
+
class: 'ui-chart-mark', style: paint(seriesIndex),
|
|
160
|
+
'data-tip': `${row.label} · ${data.series[seriesIndex].name}: ${format(value)}`
|
|
161
|
+
});
|
|
162
|
+
});
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function curvePath(points, curve) {
|
|
167
|
+
if (!points.length) return '';
|
|
168
|
+
if (curve === 'step') {
|
|
169
|
+
return points.map((point, index) => index ? `H${round((points[index - 1][0] + point[0]) / 2)}V${point[1]}H${point[0]}` : `M${point}`).join('');
|
|
170
|
+
}
|
|
171
|
+
if (curve === 'smooth') {
|
|
172
|
+
return points.map((point, index) => {
|
|
173
|
+
if (!index) return `M${point}`;
|
|
174
|
+
const previous = points[index - 2] ?? points[index - 1], from = points[index - 1], next = points[index + 1] ?? point;
|
|
175
|
+
const first = [round(from[0] + (point[0] - previous[0]) / 6), round(from[1] + (point[1] - previous[1]) / 6)];
|
|
176
|
+
const second = [round(point[0] - (next[0] - from[0]) / 6), round(point[1] - (next[1] - from[1]) / 6)];
|
|
177
|
+
return `C${first} ${second} ${point}`;
|
|
178
|
+
}).join('');
|
|
179
|
+
}
|
|
180
|
+
return points.map((point, index) => `${index ? 'L' : 'M'}${point}`).join('');
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function linesOn(svg, axis, data, indexes, { curve = 'linear', area = false, stacked = false, dots = true, format }) {
|
|
184
|
+
const totals = data.rows.map(() => 0);
|
|
185
|
+
const layers = indexes.map(seriesIndex => {
|
|
186
|
+
const lower = data.rows.map((_, row) => totals[row]);
|
|
187
|
+
const upper = data.rows.map((_, row) => {
|
|
188
|
+
const value = data.series[seriesIndex].values[row];
|
|
189
|
+
return Number.isFinite(value) ? (stacked ? totals[row] += value : value) : NaN;
|
|
190
|
+
});
|
|
191
|
+
return { seriesIndex, lower, upper };
|
|
192
|
+
});
|
|
193
|
+
const point = (value, row) => [round(axis.center(row)), round(axis.pos(value))];
|
|
194
|
+
for (const { seriesIndex, lower, upper } of [...layers].reverse()) {
|
|
195
|
+
const rows = upper.map((value, row) => [value, row]).filter(([value]) => Number.isFinite(value));
|
|
196
|
+
const top = rows.map(([value, row]) => point(value, row));
|
|
197
|
+
if (!top.length) continue;
|
|
198
|
+
if (area) {
|
|
199
|
+
const bottom = stacked ? rows.map(([, row]) => point(lower[row], row)).reverse() : [[top.at(-1)[0], round(axis.base)], [top[0][0], round(axis.base)]];
|
|
200
|
+
const back = stacked ? curvePath(bottom, curve).replace(/^M/, 'L') : bottom.map(position => `L${position}`).join('');
|
|
201
|
+
node('path', { d: `${curvePath(top, curve)}${back}Z`, class: 'ui-chart-area', style: paint(seriesIndex) }, svg);
|
|
202
|
+
}
|
|
203
|
+
node('path', { d: curvePath(top, curve), class: 'ui-chart-line', style: paint(seriesIndex, 'stroke') }, svg);
|
|
204
|
+
if (dots) {
|
|
205
|
+
rows.forEach(([, row], index) => node('circle', {
|
|
206
|
+
cx: top[index][0], cy: top[index][1], r: 3.5, class: 'ui-chart-dot', style: paint(seriesIndex, 'stroke'),
|
|
207
|
+
'data-tip': `${data.rows[row].label} · ${data.series[seriesIndex].name}: ${format(data.series[seriesIndex].values[row])}`
|
|
208
|
+
}, svg));
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// A circular arc; angles in radians, 0 at the top, clockwise. With inner > 0 it is a ring sector.
|
|
214
|
+
function sector(cx, cy, outer, inner, start, end) {
|
|
215
|
+
if (end - start >= Math.PI * 2 - 1e-6) end = start + Math.PI * 2 - 1e-4;
|
|
216
|
+
const at = (radius, angle) => [round(cx + radius * Math.sin(angle)), round(cy - radius * Math.cos(angle))];
|
|
217
|
+
const large = end - start > Math.PI ? 1 : 0;
|
|
218
|
+
if (!inner) return `M${cx},${cy}L${at(outer, start)}A${outer},${outer} 0 ${large} 1 ${at(outer, end)}Z`;
|
|
219
|
+
return `M${at(outer, start)}A${outer},${outer} 0 ${large} 1 ${at(outer, end)}L${at(inner, end)}A${inner},${inner} 0 ${large} 0 ${at(inner, start)}Z`;
|
|
220
|
+
}
|
|
221
|
+
function arc(cx, cy, radius, start, end) {
|
|
222
|
+
if (end - start >= Math.PI * 2 - 1e-6) end = start + Math.PI * 2 - 1e-4;
|
|
223
|
+
const at = angle => [round(cx + radius * Math.sin(angle)), round(cy - radius * Math.cos(angle))];
|
|
224
|
+
return `M${at(start)}A${radius},${radius} 0 ${end - start > Math.PI ? 1 : 0} 1 ${at(end)}`;
|
|
225
|
+
}
|
|
226
|
+
function centerText(svg, x, y, big, small) {
|
|
227
|
+
text(svg, x, y + (small ? 2 : 8), big, { 'text-anchor': 'middle', class: 'ui-chart-value' });
|
|
228
|
+
if (small) text(svg, x, y + 22, small, { 'text-anchor': 'middle' });
|
|
229
|
+
}
|
|
230
|
+
const rowItems = data => data.rows.map((row, index) => ({ name: row.label, index }));
|
|
231
|
+
const seriesItems = (data, indexes = data.series.map((_, index) => index)) => indexes.map(index => ({ name: data.series[index].name, index }));
|
|
232
|
+
const share = (value, total) => `${new Intl.NumberFormat(document.documentElement.lang || undefined, { maximumFractionDigits: 1 }).format(total ? value / total * 100 : 0)}%`;
|
|
233
|
+
|
|
234
|
+
const renderers = {
|
|
235
|
+
column: (svg, data, size, format, stacked = false, horizontal = false) => {
|
|
236
|
+
const all = data.series.map((_, index) => index);
|
|
237
|
+
const axis = axes(svg, data.labels, ...extent(data, all, stacked), { ...size, horizontal, format });
|
|
238
|
+
barsOn(svg, axis, data, all, { stacked, format });
|
|
239
|
+
return seriesItems(data);
|
|
240
|
+
},
|
|
241
|
+
'column-stacked': (svg, data, size, format) => renderers.column(svg, data, size, format, true),
|
|
242
|
+
bar: (svg, data, size, format) => renderers.column(svg, data, size, format, false, true),
|
|
243
|
+
'bar-stacked': (svg, data, size, format) => renderers.column(svg, data, size, format, true, true),
|
|
244
|
+
line: (svg, data, size, format, options = {}) => {
|
|
245
|
+
const all = data.series.map((_, index) => index);
|
|
246
|
+
const axis = axes(svg, data.labels, ...extent(data, all, options.stacked), { ...size, format });
|
|
247
|
+
linesOn(svg, axis, data, all, { ...options, format });
|
|
248
|
+
return seriesItems(data);
|
|
249
|
+
},
|
|
250
|
+
spline: (svg, data, size, format) => renderers.line(svg, data, size, format, { curve: 'smooth' }),
|
|
251
|
+
step: (svg, data, size, format) => renderers.line(svg, data, size, format, { curve: 'step' }),
|
|
252
|
+
area: (svg, data, size, format) => renderers.line(svg, data, size, format, { area: true }),
|
|
253
|
+
'area-spline': (svg, data, size, format) => renderers.line(svg, data, size, format, { area: true, curve: 'smooth' }),
|
|
254
|
+
'area-stacked': (svg, data, size, format) => renderers.line(svg, data, size, format, { area: true, stacked: true, curve: 'smooth' }),
|
|
255
|
+
combo: (svg, data, size, format) => {
|
|
256
|
+
const all = data.series.map((_, index) => index);
|
|
257
|
+
const axis = axes(svg, data.labels, ...extent(data, all), { ...size, format });
|
|
258
|
+
barsOn(svg, axis, data, [0], { format });
|
|
259
|
+
linesOn(svg, axis, data, all.slice(1), { curve: 'smooth', format });
|
|
260
|
+
return seriesItems(data);
|
|
261
|
+
},
|
|
262
|
+
lollipop: (svg, data, size, format) => {
|
|
263
|
+
const axis = axes(svg, data.labels, ...extent(data, [0]), { ...size, format });
|
|
264
|
+
data.rows.forEach((row, index) => {
|
|
265
|
+
const value = data.series[0]?.values[index];
|
|
266
|
+
if (!Number.isFinite(value)) return;
|
|
267
|
+
const x = round(axis.center(index)), y = round(axis.pos(value));
|
|
268
|
+
node('line', { x1: x, x2: x, y1: round(axis.base), y2: y, class: 'ui-chart-stem', style: paint(index % 8, 'stroke') }, svg);
|
|
269
|
+
node('circle', { cx: x, cy: y, r: 6, class: 'ui-chart-mark', style: paint(index % 8), 'data-tip': `${row.label}: ${format(value)}` }, svg);
|
|
270
|
+
});
|
|
271
|
+
return rowItems(data);
|
|
272
|
+
},
|
|
273
|
+
range: (svg, data, size, format) => {
|
|
274
|
+
const values = finite(data.series.slice(0, 2).flatMap(series => series.values));
|
|
275
|
+
const axis = axes(svg, data.labels, Math.min(...values), Math.max(...values), { ...size, format });
|
|
276
|
+
const width = Math.min(axis.band * 0.4, 18);
|
|
277
|
+
data.rows.forEach((row, index) => {
|
|
278
|
+
const [low, high] = row.values;
|
|
279
|
+
if (!Number.isFinite(low) || !Number.isFinite(high)) return;
|
|
280
|
+
rect(svg, false, axis.center(index) - width / 2, width, axis.pos(low), axis.pos(high), {
|
|
281
|
+
class: 'ui-chart-mark', style: paint(index % 8), 'data-tip': `${row.label}: ${format(low)} – ${format(high)}`
|
|
282
|
+
});
|
|
283
|
+
});
|
|
284
|
+
return rowItems(data);
|
|
285
|
+
},
|
|
286
|
+
candlestick: (svg, data, size, format) => {
|
|
287
|
+
const values = finite(data.series.slice(0, 4).flatMap(series => series.values));
|
|
288
|
+
const axis = axes(svg, data.labels, Math.min(...values), Math.max(...values), { ...size, format });
|
|
289
|
+
const width = Math.min(axis.band * 0.5, 22);
|
|
290
|
+
data.rows.forEach((row, index) => {
|
|
291
|
+
const [open, high, low, close] = row.values;
|
|
292
|
+
if (![open, high, low, close].every(Number.isFinite)) return;
|
|
293
|
+
const tone = close >= open ? 0 : -1;
|
|
294
|
+
const x = round(axis.center(index));
|
|
295
|
+
node('line', { x1: x, x2: x, y1: round(axis.pos(high)), y2: round(axis.pos(low)), class: 'ui-chart-stem', style: paint(tone, 'stroke') }, svg);
|
|
296
|
+
rect(svg, false, x - width / 2, width, axis.pos(open), axis.pos(close), {
|
|
297
|
+
class: 'ui-chart-mark', style: paint(tone),
|
|
298
|
+
'data-tip': `${row.label} · ${data.series.slice(0, 4).map((series, position) => `${series.name} ${format(row.values[position])}`).join(' · ')}`
|
|
299
|
+
});
|
|
300
|
+
});
|
|
301
|
+
return [{ name: '▲', index: 0 }, { name: '▼', index: -1 }];
|
|
302
|
+
},
|
|
303
|
+
waterfall: (svg, data, size, format) => {
|
|
304
|
+
let total = 0;
|
|
305
|
+
const steps = data.rows.map((row, index) => {
|
|
306
|
+
const value = data.series[0]?.values[index];
|
|
307
|
+
const from = total;
|
|
308
|
+
if (Number.isFinite(value)) total += value;
|
|
309
|
+
return { row, value, from, to: total };
|
|
310
|
+
});
|
|
311
|
+
const ends = steps.flatMap(step => [step.from, step.to]);
|
|
312
|
+
const axis = axes(svg, data.labels, Math.min(0, ...ends), Math.max(0, ...ends), { ...size, format });
|
|
313
|
+
const width = axis.band * 0.6;
|
|
314
|
+
steps.forEach((step, index) => {
|
|
315
|
+
if (!Number.isFinite(step.value)) return;
|
|
316
|
+
const start = axis.center(index) - width / 2;
|
|
317
|
+
rect(svg, false, start, width, axis.pos(step.from), axis.pos(step.to), {
|
|
318
|
+
class: 'ui-chart-mark', style: paint(step.value >= 0 ? 0 : -1), 'data-tip': `${step.row.label}: ${step.value >= 0 ? '+' : ''}${format(step.value)} → ${format(step.to)}`
|
|
319
|
+
});
|
|
320
|
+
if (index < steps.length - 1) {
|
|
321
|
+
node('line', { x1: round(start + width), x2: round(start + axis.band), y1: round(axis.pos(step.to)), y2: round(axis.pos(step.to)), class: 'ui-chart-connector' }, svg);
|
|
322
|
+
}
|
|
323
|
+
});
|
|
324
|
+
return [{ name: '+', index: 0 }, { name: '−', index: -1 }];
|
|
325
|
+
},
|
|
326
|
+
scatter: (svg, data, size, format) => {
|
|
327
|
+
const xs = finite(data.rows.map(row => row.x));
|
|
328
|
+
const ys = finite(data.series.flatMap(series => series.values));
|
|
329
|
+
const axis = axes(svg, [], Math.min(...ys), Math.max(...ys), { ...size, format, xRange: [Math.min(...xs), Math.max(...xs)] });
|
|
330
|
+
data.series.forEach((series, seriesIndex) => data.rows.forEach((row, index) => {
|
|
331
|
+
const value = series.values[index];
|
|
332
|
+
if (!Number.isFinite(value) || !Number.isFinite(row.x)) return;
|
|
333
|
+
node('circle', { cx: round(axis.xPos(row.x)), cy: round(axis.pos(value)), r: 5, class: 'ui-chart-mark', style: paint(seriesIndex),
|
|
334
|
+
'data-tip': `${series.name}: ${format(row.x, false)}, ${format(value)}` }, svg);
|
|
335
|
+
}));
|
|
336
|
+
return seriesItems(data);
|
|
337
|
+
},
|
|
338
|
+
bubble: (svg, data, size, format) => {
|
|
339
|
+
const xs = finite(data.rows.map(row => row.x));
|
|
340
|
+
const ys = finite(data.series[0]?.values ?? []);
|
|
341
|
+
const sizes = finite(data.series[1]?.values ?? []);
|
|
342
|
+
const largest = Math.max(...sizes, 1);
|
|
343
|
+
const axis = axes(svg, [], Math.min(...ys), Math.max(...ys), { ...size, format, xRange: [Math.min(...xs), Math.max(...xs)] });
|
|
344
|
+
const maxRadius = Math.min(size.height / 8, 28);
|
|
345
|
+
data.rows.forEach((row, index) => {
|
|
346
|
+
const [value, weight = 1] = row.values;
|
|
347
|
+
if (!Number.isFinite(value) || !Number.isFinite(row.x)) return;
|
|
348
|
+
node('circle', { cx: round(axis.xPos(row.x)), cy: round(axis.pos(value)), r: round(Math.max(3, Math.sqrt(Math.abs(weight) / largest) * maxRadius)),
|
|
349
|
+
class: 'ui-chart-mark ui-chart-bubble', style: paint(index % 8),
|
|
350
|
+
'data-tip': `${format(row.x, false)} · ${data.series[0]?.name}: ${format(value)} · ${data.series[1]?.name ?? ''}: ${format(weight, false)}` }, svg);
|
|
351
|
+
});
|
|
352
|
+
return seriesItems(data, [0]);
|
|
353
|
+
},
|
|
354
|
+
heatmap: (svg, data, size, format) => {
|
|
355
|
+
const values = finite(data.series.flatMap(series => series.values));
|
|
356
|
+
const low = Math.min(...values), high = Math.max(...values);
|
|
357
|
+
const left = Math.min(120, Math.max(0, ...data.labels.map(label => label.length)) * 6.5 + 16);
|
|
358
|
+
const cellWidth = (size.width - left - 8) / Math.max(data.series.length, 1);
|
|
359
|
+
const cellHeight = (size.height - 28) / Math.max(data.rows.length, 1);
|
|
360
|
+
data.rows.forEach((row, rowIndex) => {
|
|
361
|
+
text(svg, left - 8, rowIndex * cellHeight + cellHeight / 2 + 4, row.label, { 'text-anchor': 'end' });
|
|
362
|
+
data.series.forEach((series, seriesIndex) => {
|
|
363
|
+
const value = series.values[rowIndex];
|
|
364
|
+
const x = left + seriesIndex * cellWidth, y = rowIndex * cellHeight;
|
|
365
|
+
const strength = Number.isFinite(value) ? 0.12 + 0.88 * (high === low ? 1 : (value - low) / (high - low)) : 0;
|
|
366
|
+
node('rect', { x: round(x + 1.5), y: round(y + 1.5), width: round(cellWidth - 3), height: round(cellHeight - 3), rx: 4,
|
|
367
|
+
class: 'ui-chart-mark', style: paint(0, 'fill', ` fill-opacity: ${round(strength)};`),
|
|
368
|
+
'data-tip': `${row.label} · ${series.name}: ${Number.isFinite(value) ? format(value) : '—'}` }, svg);
|
|
369
|
+
});
|
|
370
|
+
});
|
|
371
|
+
data.series.forEach((series, index) => text(svg, left + index * cellWidth + cellWidth / 2, size.height - 8, series.name, { 'text-anchor': 'middle' }));
|
|
372
|
+
return [];
|
|
373
|
+
},
|
|
374
|
+
pie: (svg, data, size, format, inner = 0) => {
|
|
375
|
+
const values = data.rows.map((_, index) => Math.max(0, data.series[0]?.values[index] || 0));
|
|
376
|
+
const total = values.reduce((sum, value) => sum + value, 0);
|
|
377
|
+
const cx = size.width / 2, cy = size.height / 2, radius = Math.min(cx, cy) - 8;
|
|
378
|
+
let angle = 0;
|
|
379
|
+
values.forEach((value, index) => {
|
|
380
|
+
if (!value) return;
|
|
381
|
+
const end = angle + value / total * Math.PI * 2;
|
|
382
|
+
node('path', { d: sector(round(cx), round(cy), round(radius), round(radius * inner), angle, end), class: 'ui-chart-mark ui-chart-slice', style: paint(index),
|
|
383
|
+
'data-tip': `${data.rows[index].label}: ${format(value)} (${share(value, total)})` }, svg);
|
|
384
|
+
angle = end;
|
|
385
|
+
});
|
|
386
|
+
if (inner && values.length) centerText(svg, cx, cy, share(values[0], total), data.rows[0].label);
|
|
387
|
+
return rowItems(data);
|
|
388
|
+
},
|
|
389
|
+
doughnut: (svg, data, size, format) => renderers.pie(svg, data, size, format, 0.62),
|
|
390
|
+
polar: (svg, data, size, format) => {
|
|
391
|
+
const values = data.rows.map((_, index) => Math.max(0, data.series[0]?.values[index] || 0));
|
|
392
|
+
const largest = Math.max(...values, 1);
|
|
393
|
+
const cx = size.width / 2, cy = size.height / 2, radius = Math.min(cx, cy) - 8;
|
|
394
|
+
const grid = node('g', { class: 'ui-chart-grid' }, svg);
|
|
395
|
+
for (const level of [0.25, 0.5, 0.75, 1]) node('circle', { cx: round(cx), cy: round(cy), r: round(radius * level) }, grid);
|
|
396
|
+
const slice = Math.PI * 2 / Math.max(values.length, 1);
|
|
397
|
+
values.forEach((value, index) => node('path', {
|
|
398
|
+
d: sector(round(cx), round(cy), round(Math.sqrt(value / largest) * radius), 0, index * slice, (index + 1) * slice),
|
|
399
|
+
class: 'ui-chart-mark ui-chart-slice ui-chart-translucent', style: paint(index), 'data-tip': `${data.rows[index].label}: ${format(value)}`
|
|
400
|
+
}, svg));
|
|
401
|
+
return rowItems(data);
|
|
402
|
+
},
|
|
403
|
+
// Concentric rings: each row against the second column (its maximum), or 100.
|
|
404
|
+
radial: (svg, data, size, format, rows = data.rows) => {
|
|
405
|
+
const cx = size.width / 2, cy = size.height / 2, outer = Math.min(cx, cy) - 8;
|
|
406
|
+
const thickness = Math.min(outer / (rows.length * 1.6 + 1.2), rows.length === 1 ? outer * 0.22 : 16);
|
|
407
|
+
rows.forEach((row, index) => {
|
|
408
|
+
const [value = 0, maximum = 100] = row.values;
|
|
409
|
+
const radius = round(outer - thickness / 2 - index * thickness * 1.6);
|
|
410
|
+
const ratio = Math.min(Math.max(value / (maximum || 100), 0), 1);
|
|
411
|
+
node('circle', { cx: round(cx), cy: round(cy), r: radius, class: 'ui-chart-track', style: `stroke-width: ${round(thickness)}` }, svg);
|
|
412
|
+
if (ratio) node('path', { d: arc(round(cx), round(cy), radius, 0, ratio * Math.PI * 2), class: 'ui-chart-ring', style: paint(index, 'stroke', ` stroke-width: ${round(thickness)};`),
|
|
413
|
+
'data-tip': `${row.label}: ${format(value)} (${share(value, maximum || 100)})` }, svg);
|
|
414
|
+
});
|
|
415
|
+
const [first = 0, maximum = 100] = rows[0]?.values ?? [];
|
|
416
|
+
centerText(svg, cx, cy, share(first, maximum || 100), rows.length === 1 ? rows[0].label : undefined);
|
|
417
|
+
return rows.map((row, index) => ({ name: row.label, index }));
|
|
418
|
+
},
|
|
419
|
+
progress: (svg, data, size, format) => renderers.radial(svg, data, size, format, data.rows.slice(0, 1)),
|
|
420
|
+
gauge: (svg, data, size, format) => {
|
|
421
|
+
const row = data.rows[0];
|
|
422
|
+
const [value = 0, maximum = 100] = row?.values ?? [];
|
|
423
|
+
const ratio = Math.min(Math.max(value / (maximum || 100), 0), 1);
|
|
424
|
+
const cx = size.width / 2, radius = Math.min(size.width / 2 - 16, size.height - 40), cy = round(size.height / 2 + radius / 2);
|
|
425
|
+
const thickness = round(radius * 0.2);
|
|
426
|
+
node('path', { d: arc(round(cx), cy, round(radius), -Math.PI / 2, Math.PI / 2), class: 'ui-chart-track', style: `stroke-width: ${thickness}` }, svg);
|
|
427
|
+
if (ratio) node('path', { d: arc(round(cx), cy, round(radius), -Math.PI / 2, -Math.PI / 2 + ratio * Math.PI), class: 'ui-chart-ring',
|
|
428
|
+
style: paint(0, 'stroke', ` stroke-width: ${thickness};`), 'data-tip': `${row.label}: ${format(value)}` }, svg);
|
|
429
|
+
centerText(svg, cx, cy - 18, share(value, maximum || 100), row?.label);
|
|
430
|
+
return [];
|
|
431
|
+
},
|
|
432
|
+
radar: (svg, data, size, format) => {
|
|
433
|
+
const count = data.rows.length;
|
|
434
|
+
const largest = Math.max(...finite(data.series.flatMap(series => series.values)), 1);
|
|
435
|
+
const ticks = niceTicks(0, largest, 4);
|
|
436
|
+
const top = ticks.at(-1);
|
|
437
|
+
const cx = size.width / 2, cy = size.height / 2, radius = Math.min(cx - 60, cy - 22);
|
|
438
|
+
const at = (index, ratio) => [round(cx + radius * ratio * Math.sin(index / count * Math.PI * 2)), round(cy - radius * ratio * Math.cos(index / count * Math.PI * 2))];
|
|
439
|
+
const grid = node('g', { class: 'ui-chart-grid' }, svg);
|
|
440
|
+
for (const tick of ticks.slice(1)) node('polygon', { points: data.rows.map((_, index) => at(index, tick / top)).join(' ') }, grid);
|
|
441
|
+
data.rows.forEach((row, index) => {
|
|
442
|
+
node('line', { x1: round(cx), y1: round(cy), x2: at(index, 1)[0], y2: at(index, 1)[1] }, grid);
|
|
443
|
+
const [x, y] = at(index, 1.14);
|
|
444
|
+
text(svg, x, y + 4, row.label, { 'text-anchor': Math.abs(x - cx) < 4 ? 'middle' : x > cx ? 'start' : 'end' });
|
|
445
|
+
});
|
|
446
|
+
data.series.forEach((series, seriesIndex) => {
|
|
447
|
+
const points = series.values.map((value, index) => at(index, Math.max(0, value || 0) / top));
|
|
448
|
+
node('polygon', { points: points.join(' '), class: 'ui-chart-area ui-chart-outline', style: `${paint(seriesIndex)} ${paint(seriesIndex, 'stroke')}` }, svg);
|
|
449
|
+
points.forEach((point, index) => node('circle', { cx: point[0], cy: point[1], r: 3.5, class: 'ui-chart-dot', style: paint(seriesIndex, 'stroke'),
|
|
450
|
+
'data-tip': `${data.rows[index].label} · ${series.name}: ${format(series.values[index])}` }, svg));
|
|
451
|
+
});
|
|
452
|
+
return seriesItems(data);
|
|
453
|
+
},
|
|
454
|
+
funnel: (svg, data, size, format) => {
|
|
455
|
+
const values = data.rows.map((_, index) => Math.max(0, data.series[0]?.values[index] || 0));
|
|
456
|
+
const largest = Math.max(...values, 1);
|
|
457
|
+
const step = size.height / Math.max(values.length, 1);
|
|
458
|
+
values.forEach((value, index) => {
|
|
459
|
+
const caption = `${data.rows[index].label} · ${format(value)}`;
|
|
460
|
+
// Narrow stages keep the room their label needs.
|
|
461
|
+
const width = Math.min(Math.max(value / largest * (size.width - 16), caption.length * 6.5 + 20), size.width - 16);
|
|
462
|
+
rect(svg, true, index * step + 2, step - 4, (size.width - width) / 2, (size.width + width) / 2, {
|
|
463
|
+
class: 'ui-chart-mark', style: paint(index), 'data-tip': `${data.rows[index].label}: ${format(value)} (${share(value, values[0])})`
|
|
464
|
+
});
|
|
465
|
+
text(svg, size.width / 2, index * step + step / 2 + 4, caption, { 'text-anchor': 'middle', class: 'ui-chart-label ui-chart-inside' });
|
|
466
|
+
});
|
|
467
|
+
return [];
|
|
468
|
+
},
|
|
469
|
+
treemap: (svg, data, size, format) => {
|
|
470
|
+
const items = data.rows.map((row, index) => ({ row, index, value: Math.max(0, data.series[0]?.values[index] || 0) }))
|
|
471
|
+
.filter(item => item.value).sort((a, b) => b.value - a.value);
|
|
472
|
+
const total = items.reduce((sum, item) => sum + item.value, 0);
|
|
473
|
+
// Splits the list in two halves of similar weight along the longer side, recursively.
|
|
474
|
+
const layout = (list, x, y, width, height) => {
|
|
475
|
+
if (list.length <= 1) return list.map(item => ({ ...item, x, y, width, height }));
|
|
476
|
+
const sum = list.reduce((acc, item) => acc + item.value, 0);
|
|
477
|
+
let split = 1, acc = list[0].value;
|
|
478
|
+
while (split < list.length - 1 && acc + list[split].value <= sum / 2) acc += list[split++].value;
|
|
479
|
+
const ratio = acc / sum;
|
|
480
|
+
return width >= height
|
|
481
|
+
? [...layout(list.slice(0, split), x, y, width * ratio, height), ...layout(list.slice(split), x + width * ratio, y, width * (1 - ratio), height)]
|
|
482
|
+
: [...layout(list.slice(0, split), x, y, width, height * ratio), ...layout(list.slice(split), x, y + height * ratio, width, height * (1 - ratio))];
|
|
483
|
+
};
|
|
484
|
+
for (const item of layout(items, 0, 0, size.width, size.height)) {
|
|
485
|
+
node('rect', { x: round(item.x + 1.5), y: round(item.y + 1.5), width: round(Math.max(item.width - 3, 1)), height: round(Math.max(item.height - 3, 1)), rx: 6,
|
|
486
|
+
class: 'ui-chart-mark', style: paint(item.index), 'data-tip': `${item.row.label}: ${format(item.value)} (${share(item.value, total)})` }, svg);
|
|
487
|
+
if (item.width > item.row.label.length * 7 + 16 && item.height > 26) text(svg, item.x + 10, item.y + 20, item.row.label, { class: 'ui-chart-label ui-chart-inside' });
|
|
488
|
+
}
|
|
489
|
+
return rowItems(data);
|
|
490
|
+
},
|
|
491
|
+
sparkline: (svg, data, size, format) => {
|
|
492
|
+
const values = finite(data.series[0]?.values ?? []);
|
|
493
|
+
const low = Math.min(...values), high = Math.max(...values);
|
|
494
|
+
const axis = { center: index => 4 + index * (size.width - 8) / Math.max(data.rows.length - 1, 1),
|
|
495
|
+
pos: value => size.height - 4 - (value - low) / ((high - low) || 1) * (size.height - 8), base: size.height - 2 };
|
|
496
|
+
linesOn(svg, axis, data, [0], { curve: 'smooth', area: true, dots: false, format });
|
|
497
|
+
return [];
|
|
498
|
+
}
|
|
499
|
+
};
|
|
500
|
+
|
|
501
|
+
function draw() {
|
|
502
|
+
scheduled = false;
|
|
503
|
+
if (destroyed) return;
|
|
504
|
+
const requested = root.dataset.type;
|
|
505
|
+
const type = types.includes(requested) ? requested : 'column';
|
|
506
|
+
const data = read();
|
|
507
|
+
const locale = document.documentElement.lang || undefined;
|
|
508
|
+
const unit = root.dataset.unit ?? '';
|
|
509
|
+
const numbers = new Intl.NumberFormat(locale, { maximumFractionDigits: 2 });
|
|
510
|
+
const format = (value, withUnit = true) => Number.isFinite(value) ? `${numbers.format(value)}${withUnit ? unit : ''}` : '—';
|
|
511
|
+
const measured = Math.round(canvas.getBoundingClientRect?.().width || 0);
|
|
512
|
+
const width = Math.max(measured || 560, 200);
|
|
513
|
+
const configured = Number(root.dataset.height);
|
|
514
|
+
const height = Number.isFinite(configured) && configured >= 40 ? configured : 240;
|
|
515
|
+
lastWidth = measured;
|
|
516
|
+
canvas.replaceChildren();
|
|
517
|
+
legend.replaceChildren();
|
|
518
|
+
const svg = node('svg', { viewBox: `0 0 ${width} ${height}`, width: '100%', height, class: 'ui-chart-svg', focusable: 'false' }, canvas);
|
|
519
|
+
const items = data.rows.length ? renderers[type](svg, data, { width, height }, format) : [];
|
|
520
|
+
for (const item of root.dataset.legend === 'false' ? [] : items) {
|
|
521
|
+
const entry = document.createElement('li');
|
|
522
|
+
const swatch = document.createElement('span');
|
|
523
|
+
swatch.className = 'ui-chart-swatch';
|
|
524
|
+
swatch.setAttribute('style', `background: ${color(item.index)}`);
|
|
525
|
+
entry.append(swatch, document.createTextNode(item.name));
|
|
526
|
+
legend.append(entry);
|
|
527
|
+
}
|
|
528
|
+
legend.hidden = !legend.children.length;
|
|
529
|
+
state = { type, rows: data.rows.length, series: data.series.length };
|
|
530
|
+
}
|
|
531
|
+
function schedule() {
|
|
532
|
+
if (scheduled || destroyed) return;
|
|
533
|
+
scheduled = true;
|
|
534
|
+
(window?.requestAnimationFrame ?? queueMicrotask)(() => draw());
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
listen(canvas, 'pointermove', event => {
|
|
538
|
+
const mark = event.target?.closest?.('[data-tip]');
|
|
539
|
+
if (!mark) { tooltip.hidden = true; return; }
|
|
540
|
+
const box = root.getBoundingClientRect();
|
|
541
|
+
tooltip.textContent = mark.getAttribute('data-tip');
|
|
542
|
+
tooltip.style.left = `${Math.round(event.clientX - box.left)}px`;
|
|
543
|
+
tooltip.style.top = `${Math.round(event.clientY - box.top)}px`;
|
|
544
|
+
tooltip.hidden = false;
|
|
545
|
+
});
|
|
546
|
+
listen(canvas, 'pointerleave', () => { tooltip.hidden = true; });
|
|
547
|
+
listen(root, 'chart:refresh', draw);
|
|
548
|
+
// Translations and data changes rewrite the table cells; a new width redraws so text keeps its size.
|
|
549
|
+
const Observer = window?.MutationObserver;
|
|
550
|
+
const mutations = Observer ? new Observer(schedule) : null;
|
|
551
|
+
mutations?.observe(table, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ['data-value'] });
|
|
552
|
+
mutations?.observe(root, { attributes: true, attributeFilter: ['data-type', 'data-height', 'data-unit', 'data-legend'] });
|
|
553
|
+
const language = Observer ? new Observer(schedule) : null;
|
|
554
|
+
language?.observe(document.documentElement, { attributes: true, attributeFilter: ['lang'] });
|
|
555
|
+
const Resize = window?.ResizeObserver;
|
|
556
|
+
const resize = Resize ? new Resize(() => {
|
|
557
|
+
const width = Math.round(canvas.getBoundingClientRect().width);
|
|
558
|
+
if (width && width !== lastWidth) schedule();
|
|
559
|
+
}) : null;
|
|
560
|
+
resize?.observe(canvas);
|
|
561
|
+
|
|
562
|
+
const controller = {
|
|
563
|
+
element: root,
|
|
564
|
+
refresh: draw,
|
|
565
|
+
get state() { return { ...state }; },
|
|
566
|
+
destroy() {
|
|
567
|
+
if (destroyed) return;
|
|
568
|
+
destroyed = true;
|
|
569
|
+
listeners.forEach(remove => remove());
|
|
570
|
+
mutations?.disconnect();
|
|
571
|
+
language?.disconnect();
|
|
572
|
+
resize?.disconnect();
|
|
573
|
+
canvas.replaceChildren();
|
|
574
|
+
legend.replaceChildren();
|
|
575
|
+
tooltip.remove();
|
|
576
|
+
delete root[marker];
|
|
577
|
+
}
|
|
578
|
+
};
|
|
579
|
+
root[marker] = controller;
|
|
580
|
+
draw();
|
|
581
|
+
return controller;
|
|
582
|
+
});
|
|
583
|
+
}
|