@tabler/charts-bootstrap 0.0.0-stage → 0.0.1-alpha.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 +106 -2
- package/dist/bootstrap.css +2 -0
- package/dist/index.cjs +188 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +24 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.js +183 -0
- package/dist/index.js.map +1 -0
- package/dist/tabler-charts-bootstrap.min.js +3 -0
- package/dist/tabler-charts-bootstrap.min.js.map +1 -0
- package/dist/tabler.css +2 -0
- package/package.json +76 -3
- package/scss/_charts.scss +88 -0
- package/scss/_tabler.scss +22 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 The Tabler Authors
|
|
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,107 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<picture>
|
|
3
|
+
<source media="(prefers-color-scheme: dark)" srcset="../../docs/images/logo-white.svg">
|
|
4
|
+
<img src="../../docs/images/logo.svg" alt="Tabler Charts" width="280">
|
|
5
|
+
</picture>
|
|
6
|
+
</p>
|
|
2
7
|
|
|
3
|
-
|
|
8
|
+
# @tabler/charts-bootstrap
|
|
9
|
+
|
|
10
|
+
[`@tabler/charts`](../core) for Bootstrap 5.3 and Tabler: a theme mapping (CSS and SCSS) and a data API, so charts can be declared in HTML.
|
|
11
|
+
|
|
12
|
+
> 🚧 **Pre-release.** Not on npm yet; the API may still change.
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm install @tabler/charts @tabler/charts-bootstrap
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Theme
|
|
19
|
+
|
|
20
|
+
Load the mapping after the chart stylesheet:
|
|
21
|
+
|
|
22
|
+
```js
|
|
23
|
+
import '@tabler/charts/style.css'
|
|
24
|
+
import '@tabler/charts-bootstrap/bootstrap.css' // or tabler.css
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
What the mapping gives you:
|
|
28
|
+
- **Theme values:** charts use your theme's body font and colors, border colors, radius and shadow.
|
|
29
|
+
- **First series:** it takes `primary`. Series 2–8 keep the chart palette, which is checked for colorblind separation next to a blue primary; Bootstrap's own orange, yellow and pink are not.
|
|
30
|
+
- **Dark mode:** `data-bs-theme="dark"` switches the charts along with the rest of the page, on `<html>` or on any element.
|
|
31
|
+
|
|
32
|
+
The Tabler preset, `tabler.css`, uses Tabler's `--tblr-*` variables:
|
|
33
|
+
- charts sit on the card surface and use Tabler's muted gray;
|
|
34
|
+
- the first series follows the theme's primary color, so `data-bs-theme-primary` works too.
|
|
35
|
+
|
|
36
|
+
### SCSS
|
|
37
|
+
|
|
38
|
+
```scss
|
|
39
|
+
@use "@tabler/charts-bootstrap/scss/charts" with (
|
|
40
|
+
$tc-series-1: var(--bs-success)
|
|
41
|
+
);
|
|
42
|
+
// Tabler:
|
|
43
|
+
@use "@tabler/charts-bootstrap/scss/tabler";
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
| Variable | Default | |
|
|
47
|
+
| --- | --- | --- |
|
|
48
|
+
| `$tc-prefix` | `"bs-"` | Bootstrap's CSS variable prefix (`$prefix`) |
|
|
49
|
+
| `$tc-theme-attribute` | `"data-bs-theme"` | The color mode attribute |
|
|
50
|
+
| `$tc-theme-scopes` | `:root, [data-bs-theme]` | Where the mapping is repeated |
|
|
51
|
+
| `$tc-series-1` | `var(--bs-primary)` | The first series' color |
|
|
52
|
+
| `$tc-palette-light`, `$tc-palette-dark` | the chart palette | Series 2–8, per mode |
|
|
53
|
+
|
|
54
|
+
The mapped variables are `$tc-surface`, `$tc-text-color`, `$tc-text-muted`, `$tc-grid-color`, `$tc-baseline-color`, `$tc-hover-color`, `$tc-font-family` and `$tc-tooltip-bg`, `-border`, `-shadow` and `-radius`.
|
|
55
|
+
|
|
56
|
+
## Data API
|
|
57
|
+
|
|
58
|
+
```html
|
|
59
|
+
<div data-tc-chart="line" data-tc-src="/api/sales.json" data-tc-aspect-ratio="3" data-tc-title="Sales"></div>
|
|
60
|
+
|
|
61
|
+
<div data-tc-chart="bar" data-tc-stacked="true" data-tc-legend="bottom">
|
|
62
|
+
<script type="application/json">
|
|
63
|
+
{ "labels": ["Q1", "Q2"], "series": [{ "name": "North", "values": [3, 5] }] }
|
|
64
|
+
</script>
|
|
65
|
+
</div>
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
```js
|
|
69
|
+
import { init } from '@tabler/charts-bootstrap'
|
|
70
|
+
|
|
71
|
+
await init() // every [data-tc-chart] on the page
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
- **Type:** `data-tc-chart` names the chart type.
|
|
75
|
+
- **Data:** it comes from `data-tc-src` (a JSON URL), an inline `<script type="application/json">`, or `data-tc-data`.
|
|
76
|
+
- **Options:** every other `data-tc-*` attribute is an option in camelCase (`data-tc-aspect-ratio="3"` becomes `aspectRatio: 3`).
|
|
77
|
+
- Values are parsed: `true` and `false`, numbers, and JSON objects or arrays.
|
|
78
|
+
- `data-tc-legend="bottom"` moves the legend.
|
|
79
|
+
- `data-tc-download="true"` adds a download menu (PNG and SVG); `data-tc-download="svg png"` picks the formats.
|
|
80
|
+
- `data-tc-options` takes a JSON object for the rest.
|
|
81
|
+
- **Loading:** while `data-tc-src` loads, the element has `aria-busy="true"`. A failed load or broken markup is reported without stopping the other charts.
|
|
82
|
+
|
|
83
|
+
| Function | |
|
|
84
|
+
| --- | --- |
|
|
85
|
+
| `init(root?, { types? })` | Create charts in `root` (default `document`) that do not have one yet. Resolves once the `data-tc-src` charts have loaded |
|
|
86
|
+
| `observe(root?, { types? })` | Also initialize charts added later and destroy removed ones; returns a function that stops |
|
|
87
|
+
| `getChart(element)` | The [`Chart`](../core#the-chart-instance) of an element |
|
|
88
|
+
| `dispose(element)` | Destroy an element's chart |
|
|
89
|
+
|
|
90
|
+
Chart events bubble out of the element as DOM events (`tc-hover`, `tc-click`, `tc-legend-toggle`, `tc-render`), with the payload in `detail`.
|
|
91
|
+
|
|
92
|
+
## CDN
|
|
93
|
+
|
|
94
|
+
One classic script with the library, the chart stylesheet with the Bootstrap mapping, and the data API:
|
|
95
|
+
|
|
96
|
+
```html
|
|
97
|
+
<script src="https://cdn.jsdelivr.net/npm/@tabler/charts-bootstrap/dist/tabler-charts-bootstrap.min.js"></script>
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
It injects the styles and initializes every `[data-tc-chart]` on load; everything is also on the `TablerCharts` global. On the script tag:
|
|
101
|
+
- `data-observe` also handles charts added later;
|
|
102
|
+
- `data-no-styles` skips the styles, so you can load them yourself;
|
|
103
|
+
- `nonce` (under a strict CSP) is passed on to the injected styles.
|
|
104
|
+
|
|
105
|
+
## License
|
|
106
|
+
|
|
107
|
+
MIT
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! @tabler/charts-bootstrap | MIT */
|
|
2
|
+
:where(:root,[data-bs-theme]){--tc-color-1:var(--bs-primary,#2a78d6);--tc-focus-color:var(--bs-primary,#2a78d6);--tc-surface:var(--bs-body-bg,#fff);--tc-text-color:var(--bs-body-color,#0b0b0b);--tc-tooltip-color:var(--bs-body-color,#0b0b0b);--tc-text-muted:var(--bs-secondary-color,#6f6e69);--tc-grid-color:var(--bs-border-color-translucent,#e1e0d9);--tc-baseline-color:var(--bs-border-color,#c3c2b7);--tc-hover-color:rgba(var(--bs-emphasis-color-rgb,11, 11, 11), .05);--tc-tooltip-bg:var(--bs-body-bg,#fff);--tc-tooltip-border:var(--bs-border-color-translucent,#0b0b0b1a);--tc-tooltip-shadow:var(--bs-box-shadow,0 4px 16px #0b0b0b1f);--tc-tooltip-radius:var(--bs-border-radius,6px);--tc-font-family:var(--bs-body-font-family,inherit)}:where(:root,[data-bs-theme=light]){--tc-color-2:#eb6834;--tc-color-3:#1baf7a;--tc-color-4:#eda100;--tc-color-5:#e87ba4;--tc-color-6:#008300;--tc-color-7:#4a3aa7;--tc-color-8:#e34948}:where([data-bs-theme=dark]){--tc-color-2:#d95926;--tc-color-3:#199e70;--tc-color-4:#c98500;--tc-color-5:#d55181;--tc-color-6:#008300;--tc-color-7:#9085e9;--tc-color-8:#e66767}
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let _tabler_charts = require("@tabler/charts");
|
|
3
|
+
//#region src/index.ts
|
|
4
|
+
/**
|
|
5
|
+
* `@tabler/charts-bootstrap`: a data API in the Bootstrap style. Charts are
|
|
6
|
+
* declared in HTML and `init()` (or the CDN script, on its own) turns them
|
|
7
|
+
* into charts.
|
|
8
|
+
*
|
|
9
|
+
* ```html
|
|
10
|
+
* <div data-tc-chart="line" data-tc-src="/api/sales.json" data-tc-aspect-ratio="3"></div>
|
|
11
|
+
* <div data-tc-chart="bar" data-tc-stacked="true">
|
|
12
|
+
* <script type="application/json">{ "labels": [...], "series": [...] }<\/script>
|
|
13
|
+
* </div>
|
|
14
|
+
* ```
|
|
15
|
+
*
|
|
16
|
+
* `data-tc-chart` names the type; data comes from `data-tc-src` (a JSON URL),
|
|
17
|
+
* an inline `<script type="application/json">` or `data-tc-data`; every other
|
|
18
|
+
* `data-tc-*` attribute is an option (`data-tc-aspect-ratio="3"`), and
|
|
19
|
+
* `data-tc-options` takes a JSON object for the rest.
|
|
20
|
+
*/
|
|
21
|
+
const SELECTOR = "[data-tc-chart]";
|
|
22
|
+
/** Attributes that are not chart options. */
|
|
23
|
+
const RESERVED = /* @__PURE__ */ new Set([
|
|
24
|
+
"chart",
|
|
25
|
+
"src",
|
|
26
|
+
"data",
|
|
27
|
+
"options"
|
|
28
|
+
]);
|
|
29
|
+
/** Options that are text, whatever it spells: a title "2024" is not a number. */
|
|
30
|
+
const TEXT = /* @__PURE__ */ new Set([
|
|
31
|
+
"title",
|
|
32
|
+
"description",
|
|
33
|
+
"locale",
|
|
34
|
+
"sync",
|
|
35
|
+
"id",
|
|
36
|
+
"class"
|
|
37
|
+
]);
|
|
38
|
+
const charts = /* @__PURE__ */ new WeakMap();
|
|
39
|
+
/** Elements whose data is still loading, so a second init() does not fetch twice. */
|
|
40
|
+
const pending = /* @__PURE__ */ new WeakSet();
|
|
41
|
+
/** The chart created for an element by `init()`, if any; `O` types its options (e.g. `LineOptions`). */
|
|
42
|
+
function getChart(element) {
|
|
43
|
+
return charts.get(element);
|
|
44
|
+
}
|
|
45
|
+
/** Destroy the chart of an element (it can be initialized again later). */
|
|
46
|
+
function dispose(element) {
|
|
47
|
+
charts.get(element)?.destroy();
|
|
48
|
+
charts.delete(element);
|
|
49
|
+
}
|
|
50
|
+
/** `"true"`, `"3"`, `'{"a":1}'` or plain text, as the value it spells. */
|
|
51
|
+
function parseValue(text) {
|
|
52
|
+
if (text === "true" || text === "") return true;
|
|
53
|
+
if (text === "false") return false;
|
|
54
|
+
if (text !== "" && Number.isFinite(Number(text))) return Number(text);
|
|
55
|
+
if (/^\s*[[{]/.test(text)) return parseJson(text, "a data-tc-* attribute");
|
|
56
|
+
return text;
|
|
57
|
+
}
|
|
58
|
+
function parseJson(text, what) {
|
|
59
|
+
try {
|
|
60
|
+
return JSON.parse(text);
|
|
61
|
+
} catch (error) {
|
|
62
|
+
throw new SyntaxError(`@tabler/charts-bootstrap: invalid JSON in ${what}: ${error.message}`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/** Options from the element's `data-tc-*` attributes. */
|
|
66
|
+
function optionsOf(element) {
|
|
67
|
+
const out = {};
|
|
68
|
+
const json = element.dataset.tcOptions;
|
|
69
|
+
if (json) Object.assign(out, parseJson(json, "data-tc-options"));
|
|
70
|
+
for (const [key, value] of Object.entries(element.dataset)) {
|
|
71
|
+
if (!key.startsWith("tc") || value === void 0) continue;
|
|
72
|
+
const name = key.charAt(2).toLowerCase() + key.slice(3);
|
|
73
|
+
if (RESERVED.has(name)) continue;
|
|
74
|
+
out[name] = name === "legend" && value === "bottom" ? { position: "bottom" } : name === "download" && /^[a-z]/i.test(value) && !/^(true|false)$/.test(value) ? value.split(/[\s,]+/).filter(Boolean) : TEXT.has(name) ? value : parseValue(value);
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
/** Inline data: `data-tc-data` or a `<script type="application/json">` child. */
|
|
79
|
+
function inlineData(element) {
|
|
80
|
+
const attr = element.dataset.tcData;
|
|
81
|
+
if (attr) return parseJson(attr, "data-tc-data");
|
|
82
|
+
const text = element.querySelector(":scope > script[type=\"application/json\"]")?.textContent?.trim();
|
|
83
|
+
return text ? parseJson(text, "the inline <script type=\"application/json\">") : void 0;
|
|
84
|
+
}
|
|
85
|
+
function emit(element, name, detail) {
|
|
86
|
+
element.dispatchEvent(new CustomEvent(`tc-${name}`, {
|
|
87
|
+
detail,
|
|
88
|
+
bubbles: true
|
|
89
|
+
}));
|
|
90
|
+
}
|
|
91
|
+
function create(element, type, data) {
|
|
92
|
+
const config = {
|
|
93
|
+
...optionsOf(element),
|
|
94
|
+
type,
|
|
95
|
+
data
|
|
96
|
+
};
|
|
97
|
+
const chart = new _tabler_charts.Chart(element, config);
|
|
98
|
+
for (const name of _tabler_charts.chartEvents) chart.on(name, (detail) => emit(element, name, detail));
|
|
99
|
+
charts.set(element, chart);
|
|
100
|
+
emit(element, "render", { size: chart.size });
|
|
101
|
+
return chart;
|
|
102
|
+
}
|
|
103
|
+
/** Set up one element; returns its chart, or a promise while `data-tc-src` loads. */
|
|
104
|
+
function setup(element, known) {
|
|
105
|
+
const existing = charts.get(element);
|
|
106
|
+
if (existing || pending.has(element)) return existing;
|
|
107
|
+
const name = element.dataset.tcChart ?? "";
|
|
108
|
+
const type = known[name];
|
|
109
|
+
if (!type) {
|
|
110
|
+
const list = Object.keys(known).join(", ");
|
|
111
|
+
throw new Error(`@tabler/charts-bootstrap: unknown chart type "${name}". Known types: ${list}.`);
|
|
112
|
+
}
|
|
113
|
+
const src = element.dataset.tcSrc;
|
|
114
|
+
if (!src) return create(element, type, inlineData(element) ?? []);
|
|
115
|
+
pending.add(element);
|
|
116
|
+
element.setAttribute("aria-busy", "true");
|
|
117
|
+
return fetch(src).then((response) => {
|
|
118
|
+
if (!response.ok) throw new Error(`${response.status} ${response.statusText}`.trim());
|
|
119
|
+
return response.json();
|
|
120
|
+
}).then((data) => element.isConnected ? create(element, type, data) : void 0, (error) => {
|
|
121
|
+
emit(element, "error", {
|
|
122
|
+
error,
|
|
123
|
+
src
|
|
124
|
+
});
|
|
125
|
+
console.error(`@tabler/charts-bootstrap: could not load ${src}:`, error);
|
|
126
|
+
}).finally(() => {
|
|
127
|
+
pending.delete(element);
|
|
128
|
+
element.removeAttribute("aria-busy");
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Create a chart for every `[data-tc-chart]` in `root` (and `root` itself)
|
|
133
|
+
* that does not have one yet. Resolves once charts with `data-tc-src` have
|
|
134
|
+
* loaded; the ones with inline data exist as soon as `init()` returns.
|
|
135
|
+
*/
|
|
136
|
+
function init(root = document, options = {}) {
|
|
137
|
+
const known = {
|
|
138
|
+
..._tabler_charts.types,
|
|
139
|
+
...options.types
|
|
140
|
+
};
|
|
141
|
+
const elements = [...root.querySelectorAll(SELECTOR)];
|
|
142
|
+
if (root instanceof Element && root.matches(SELECTOR)) elements.unshift(root);
|
|
143
|
+
const made = elements.map((element) => {
|
|
144
|
+
try {
|
|
145
|
+
return setup(element, known);
|
|
146
|
+
} catch (error) {
|
|
147
|
+
emit(element, "error", { error });
|
|
148
|
+
console.error(error);
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
return Promise.all(made).then((list) => list.filter((c) => c !== void 0));
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Keep `root` in sync: charts added later are initialized, charts removed
|
|
156
|
+
* are destroyed. Returns a function that stops observing.
|
|
157
|
+
*/
|
|
158
|
+
function observe(root = document.body, options = {}) {
|
|
159
|
+
init(root, options);
|
|
160
|
+
const observer = new MutationObserver((records) => {
|
|
161
|
+
for (const record of records) {
|
|
162
|
+
const owner = record.target.closest?.(SELECTOR);
|
|
163
|
+
if (owner && charts.has(owner)) continue;
|
|
164
|
+
for (const node of record.removedNodes) {
|
|
165
|
+
if (!(node instanceof Element)) continue;
|
|
166
|
+
if (charts.has(node)) dispose(node);
|
|
167
|
+
for (const inner of node.querySelectorAll(SELECTOR)) dispose(inner);
|
|
168
|
+
}
|
|
169
|
+
for (const node of record.addedNodes) {
|
|
170
|
+
if (node instanceof Element && !node.isConnected) continue;
|
|
171
|
+
if (node instanceof Element) init(node, options);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
observer.observe(root, {
|
|
176
|
+
childList: true,
|
|
177
|
+
subtree: true
|
|
178
|
+
});
|
|
179
|
+
return () => observer.disconnect();
|
|
180
|
+
}
|
|
181
|
+
//#endregion
|
|
182
|
+
exports.dispose = dispose;
|
|
183
|
+
exports.getChart = getChart;
|
|
184
|
+
exports.init = init;
|
|
185
|
+
exports.observe = observe;
|
|
186
|
+
exports.types = _tabler_charts.types;
|
|
187
|
+
|
|
188
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["Chart","chartEvents","types"],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `@tabler/charts-bootstrap`: a data API in the Bootstrap style. Charts are\n * declared in HTML and `init()` (or the CDN script, on its own) turns them\n * into charts.\n *\n * ```html\n * <div data-tc-chart=\"line\" data-tc-src=\"/api/sales.json\" data-tc-aspect-ratio=\"3\"></div>\n * <div data-tc-chart=\"bar\" data-tc-stacked=\"true\">\n * <script type=\"application/json\">{ \"labels\": [...], \"series\": [...] }</script>\n * </div>\n * ```\n *\n * `data-tc-chart` names the type; data comes from `data-tc-src` (a JSON URL),\n * an inline `<script type=\"application/json\">` or `data-tc-data`; every other\n * `data-tc-*` attribute is an option (`data-tc-aspect-ratio=\"3\"`), and\n * `data-tc-options` takes a JSON object for the rest.\n */\nimport { Chart, type ChartConfig, type ChartType, chartEvents, types } from '@tabler/charts'\n\n/** Every built-in chart type, by its `data-tc-chart` name. */\nexport { types }\n\nexport interface InitOptions {\n /** Extra or replacement chart types, merged over the built-in ones. */\n types?: Readonly<Record<string, ChartType<never>>>\n}\n\nconst SELECTOR = '[data-tc-chart]'\n/** Attributes that are not chart options. */\nconst RESERVED = new Set(['chart', 'src', 'data', 'options'])\n/** Options that are text, whatever it spells: a title \"2024\" is not a number. */\nconst TEXT = new Set(['title', 'description', 'locale', 'sync', 'id', 'class'])\n\nconst charts = new WeakMap<Element, Chart<object>>()\n/** Elements whose data is still loading, so a second init() does not fetch twice. */\nconst pending = new WeakSet<Element>()\n\n/** The chart created for an element by `init()`, if any; `O` types its options (e.g. `LineOptions`). */\nexport function getChart<O extends object = object>(element: Element): Chart<O> | undefined {\n return charts.get(element) as Chart<O> | undefined\n}\n\n/** Destroy the chart of an element (it can be initialized again later). */\nexport function dispose(element: Element): void {\n charts.get(element)?.destroy()\n charts.delete(element)\n}\n\n/** `\"true\"`, `\"3\"`, `'{\"a\":1}'` or plain text, as the value it spells. */\nfunction parseValue(text: string): unknown {\n if (text === 'true' || text === '') return true\n if (text === 'false') return false\n if (text !== '' && Number.isFinite(Number(text))) return Number(text)\n if (/^\\s*[[{]/.test(text)) return parseJson(text, 'a data-tc-* attribute')\n return text\n}\n\nfunction parseJson(text: string, what: string): unknown {\n try {\n return JSON.parse(text)\n } catch (error) {\n throw new SyntaxError(\n `@tabler/charts-bootstrap: invalid JSON in ${what}: ${(error as Error).message}`,\n )\n }\n}\n\n/** Options from the element's `data-tc-*` attributes. */\nfunction optionsOf(element: HTMLElement): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n const json = element.dataset.tcOptions\n if (json) Object.assign(out, parseJson(json, 'data-tc-options'))\n for (const [key, value] of Object.entries(element.dataset)) {\n if (!key.startsWith('tc') || value === undefined) continue\n // dataset turns data-tc-aspect-ratio into tcAspectRatio.\n const name = key.charAt(2).toLowerCase() + key.slice(3)\n if (RESERVED.has(name)) continue\n out[name] =\n name === 'legend' && value === 'bottom'\n ? { position: 'bottom' }\n : name === 'download' && /^[a-z]/i.test(value) && !/^(true|false)$/.test(value)\n ? value.split(/[\\s,]+/).filter(Boolean)\n : TEXT.has(name)\n ? value\n : parseValue(value)\n }\n return out\n}\n\n/** Inline data: `data-tc-data` or a `<script type=\"application/json\">` child. */\nfunction inlineData(element: HTMLElement): unknown {\n const attr = element.dataset.tcData\n if (attr) return parseJson(attr, 'data-tc-data')\n const script = element.querySelector(':scope > script[type=\"application/json\"]')\n const text = script?.textContent?.trim()\n return text ? parseJson(text, 'the inline <script type=\"application/json\">') : undefined\n}\n\nfunction emit(element: Element, name: string, detail: unknown): void {\n element.dispatchEvent(new CustomEvent(`tc-${name}`, { detail, bubbles: true }))\n}\n\nfunction create(element: HTMLElement, type: ChartType<object>, data: unknown): Chart<object> {\n const config = { ...optionsOf(element), type, data } as ChartConfig<object>\n const chart = new Chart(element, config)\n for (const name of chartEvents) chart.on(name, (detail) => emit(element, name, detail))\n charts.set(element, chart)\n // The first render ran in the constructor, before anyone could listen.\n emit(element, 'render', { size: chart.size })\n return chart\n}\n\n/** Set up one element; returns its chart, or a promise while `data-tc-src` loads. */\nfunction setup(\n element: HTMLElement,\n known: Readonly<Record<string, ChartType<never>>>,\n): Chart<object> | Promise<Chart<object> | undefined> | undefined {\n const existing = charts.get(element)\n if (existing || pending.has(element)) return existing\n const name = element.dataset.tcChart ?? ''\n const type = known[name] as ChartType<object> | undefined\n if (!type) {\n const list = Object.keys(known).join(', ')\n throw new Error(`@tabler/charts-bootstrap: unknown chart type \"${name}\". Known types: ${list}.`)\n }\n const src = element.dataset.tcSrc\n if (!src) return create(element, type, inlineData(element) ?? [])\n\n pending.add(element)\n element.setAttribute('aria-busy', 'true')\n return fetch(src)\n .then((response) => {\n if (!response.ok) throw new Error(`${response.status} ${response.statusText}`.trim())\n return response.json()\n })\n .then(\n (data) => (element.isConnected ? create(element, type, data) : undefined),\n (error: unknown) => {\n emit(element, 'error', { error, src })\n console.error(`@tabler/charts-bootstrap: could not load ${src}:`, error)\n return undefined\n },\n )\n .finally(() => {\n pending.delete(element)\n element.removeAttribute('aria-busy')\n })\n}\n\n/**\n * Create a chart for every `[data-tc-chart]` in `root` (and `root` itself)\n * that does not have one yet. Resolves once charts with `data-tc-src` have\n * loaded; the ones with inline data exist as soon as `init()` returns.\n */\nexport function init(\n root: ParentNode = document,\n options: InitOptions = {},\n): Promise<Chart<object>[]> {\n const known = { ...types, ...options.types }\n const elements = [...root.querySelectorAll<HTMLElement>(SELECTOR)]\n if (root instanceof Element && root.matches(SELECTOR)) elements.unshift(root as HTMLElement)\n const made = elements.map((element) => {\n // One broken declaration (unknown type, bad JSON) must not stop the others.\n try {\n return setup(element, known)\n } catch (error) {\n emit(element, 'error', { error })\n console.error(error)\n return undefined\n }\n })\n return Promise.all(made).then((list) => list.filter((c): c is Chart<object> => c !== undefined))\n}\n\n/**\n * Keep `root` in sync: charts added later are initialized, charts removed\n * are destroyed. Returns a function that stops observing.\n */\nexport function observe(root: Element = document.body, options: InitOptions = {}): () => void {\n void init(root, options)\n const observer = new MutationObserver((records) => {\n for (const record of records) {\n // A chart changing its own content (every hover, every update) adds no charts.\n const owner = (record.target as Element).closest?.(SELECTOR)\n if (owner && charts.has(owner)) continue\n for (const node of record.removedNodes) {\n if (!(node instanceof Element)) continue\n if (charts.has(node)) dispose(node)\n for (const inner of node.querySelectorAll(SELECTOR)) dispose(inner)\n }\n for (const node of record.addedNodes) {\n if (node instanceof Element && !node.isConnected) continue\n if (node instanceof Element) void init(node, options)\n }\n }\n })\n observer.observe(root, { childList: true, subtree: true })\n return () => observer.disconnect()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA2BA,MAAM,WAAW;;AAEjB,MAAM,2BAAW,IAAI,IAAI;CAAC;CAAS;CAAO;CAAQ;AAAS,CAAC;;AAE5D,MAAM,uBAAO,IAAI,IAAI;CAAC;CAAS;CAAe;CAAU;CAAQ;CAAM;AAAO,CAAC;AAE9E,MAAM,yBAAS,IAAI,QAAgC;;AAEnD,MAAM,0BAAU,IAAI,QAAiB;;AAGrC,SAAgB,SAAoC,SAAwC;CAC1F,OAAO,OAAO,IAAI,OAAO;AAC3B;;AAGA,SAAgB,QAAQ,SAAwB;CAC9C,OAAO,IAAI,OAAO,CAAC,EAAE,QAAQ;CAC7B,OAAO,OAAO,OAAO;AACvB;;AAGA,SAAS,WAAW,MAAuB;CACzC,IAAI,SA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B,WAAW,CAAC,KAAK,aAAa;IAClD,IAAI,gBAAgB,SAAS,KAAU,MAAM,OAAO;GACtD;EACF;CACF,CAAC;CACD,SAAS,QAAQ,MAAM;EAAE,WAAW;EAAM,SAAS;CAAK,CAAC;CACzD,aAAa,SAAS,WAAW;AACnC"}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { Chart, ChartType, types } from "@tabler/charts";
|
|
2
|
+
//#region src/index.d.ts
|
|
3
|
+
export interface InitOptions {
|
|
4
|
+
/** Extra or replacement chart types, merged over the built-in ones. */
|
|
5
|
+
types?: Readonly<Record<string, ChartType<never>>>;
|
|
6
|
+
}
|
|
7
|
+
/** The chart created for an element by `init()`, if any; `O` types its options (e.g. `LineOptions`). */
|
|
8
|
+
export declare function getChart<O extends object = object>(element: Element): Chart<O> | undefined;
|
|
9
|
+
/** Destroy the chart of an element (it can be initialized again later). */
|
|
10
|
+
export declare function dispose(element: Element): void;
|
|
11
|
+
/**
|
|
12
|
+
* Create a chart for every `[data-tc-chart]` in `root` (and `root` itself)
|
|
13
|
+
* that does not have one yet. Resolves once charts with `data-tc-src` have
|
|
14
|
+
* loaded; the ones with inline data exist as soon as `init()` returns.
|
|
15
|
+
*/
|
|
16
|
+
export declare function init(root?: ParentNode, options?: InitOptions): Promise<Chart<object>[]>;
|
|
17
|
+
/**
|
|
18
|
+
* Keep `root` in sync: charts added later are initialized, charts removed
|
|
19
|
+
* are destroyed. Returns a function that stops observing.
|
|
20
|
+
*/
|
|
21
|
+
export declare function observe(root?: Element, options?: InitOptions): () => void;
|
|
22
|
+
//#endregion
|
|
23
|
+
export { types };
|
|
24
|
+
//# sourceMappingURL=index.d.cts.map
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { Chart, ChartType, types } from "@tabler/charts";
|
|
2
|
+
//#region src/index.d.ts
|
|
3
|
+
export interface InitOptions {
|
|
4
|
+
/** Extra or replacement chart types, merged over the built-in ones. */
|
|
5
|
+
types?: Readonly<Record<string, ChartType<never>>>;
|
|
6
|
+
}
|
|
7
|
+
/** The chart created for an element by `init()`, if any; `O` types its options (e.g. `LineOptions`). */
|
|
8
|
+
export declare function getChart<O extends object = object>(element: Element): Chart<O> | undefined;
|
|
9
|
+
/** Destroy the chart of an element (it can be initialized again later). */
|
|
10
|
+
export declare function dispose(element: Element): void;
|
|
11
|
+
/**
|
|
12
|
+
* Create a chart for every `[data-tc-chart]` in `root` (and `root` itself)
|
|
13
|
+
* that does not have one yet. Resolves once charts with `data-tc-src` have
|
|
14
|
+
* loaded; the ones with inline data exist as soon as `init()` returns.
|
|
15
|
+
*/
|
|
16
|
+
export declare function init(root?: ParentNode, options?: InitOptions): Promise<Chart<object>[]>;
|
|
17
|
+
/**
|
|
18
|
+
* Keep `root` in sync: charts added later are initialized, charts removed
|
|
19
|
+
* are destroyed. Returns a function that stops observing.
|
|
20
|
+
*/
|
|
21
|
+
export declare function observe(root?: Element, options?: InitOptions): () => void;
|
|
22
|
+
//#endregion
|
|
23
|
+
export { types };
|
|
24
|
+
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { Chart, chartEvents, types } from "@tabler/charts";
|
|
2
|
+
//#region src/index.ts
|
|
3
|
+
/**
|
|
4
|
+
* `@tabler/charts-bootstrap`: a data API in the Bootstrap style. Charts are
|
|
5
|
+
* declared in HTML and `init()` (or the CDN script, on its own) turns them
|
|
6
|
+
* into charts.
|
|
7
|
+
*
|
|
8
|
+
* ```html
|
|
9
|
+
* <div data-tc-chart="line" data-tc-src="/api/sales.json" data-tc-aspect-ratio="3"></div>
|
|
10
|
+
* <div data-tc-chart="bar" data-tc-stacked="true">
|
|
11
|
+
* <script type="application/json">{ "labels": [...], "series": [...] }<\/script>
|
|
12
|
+
* </div>
|
|
13
|
+
* ```
|
|
14
|
+
*
|
|
15
|
+
* `data-tc-chart` names the type; data comes from `data-tc-src` (a JSON URL),
|
|
16
|
+
* an inline `<script type="application/json">` or `data-tc-data`; every other
|
|
17
|
+
* `data-tc-*` attribute is an option (`data-tc-aspect-ratio="3"`), and
|
|
18
|
+
* `data-tc-options` takes a JSON object for the rest.
|
|
19
|
+
*/
|
|
20
|
+
const SELECTOR = "[data-tc-chart]";
|
|
21
|
+
/** Attributes that are not chart options. */
|
|
22
|
+
const RESERVED = /* @__PURE__ */ new Set([
|
|
23
|
+
"chart",
|
|
24
|
+
"src",
|
|
25
|
+
"data",
|
|
26
|
+
"options"
|
|
27
|
+
]);
|
|
28
|
+
/** Options that are text, whatever it spells: a title "2024" is not a number. */
|
|
29
|
+
const TEXT = /* @__PURE__ */ new Set([
|
|
30
|
+
"title",
|
|
31
|
+
"description",
|
|
32
|
+
"locale",
|
|
33
|
+
"sync",
|
|
34
|
+
"id",
|
|
35
|
+
"class"
|
|
36
|
+
]);
|
|
37
|
+
const charts = /* @__PURE__ */ new WeakMap();
|
|
38
|
+
/** Elements whose data is still loading, so a second init() does not fetch twice. */
|
|
39
|
+
const pending = /* @__PURE__ */ new WeakSet();
|
|
40
|
+
/** The chart created for an element by `init()`, if any; `O` types its options (e.g. `LineOptions`). */
|
|
41
|
+
function getChart(element) {
|
|
42
|
+
return charts.get(element);
|
|
43
|
+
}
|
|
44
|
+
/** Destroy the chart of an element (it can be initialized again later). */
|
|
45
|
+
function dispose(element) {
|
|
46
|
+
charts.get(element)?.destroy();
|
|
47
|
+
charts.delete(element);
|
|
48
|
+
}
|
|
49
|
+
/** `"true"`, `"3"`, `'{"a":1}'` or plain text, as the value it spells. */
|
|
50
|
+
function parseValue(text) {
|
|
51
|
+
if (text === "true" || text === "") return true;
|
|
52
|
+
if (text === "false") return false;
|
|
53
|
+
if (text !== "" && Number.isFinite(Number(text))) return Number(text);
|
|
54
|
+
if (/^\s*[[{]/.test(text)) return parseJson(text, "a data-tc-* attribute");
|
|
55
|
+
return text;
|
|
56
|
+
}
|
|
57
|
+
function parseJson(text, what) {
|
|
58
|
+
try {
|
|
59
|
+
return JSON.parse(text);
|
|
60
|
+
} catch (error) {
|
|
61
|
+
throw new SyntaxError(`@tabler/charts-bootstrap: invalid JSON in ${what}: ${error.message}`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/** Options from the element's `data-tc-*` attributes. */
|
|
65
|
+
function optionsOf(element) {
|
|
66
|
+
const out = {};
|
|
67
|
+
const json = element.dataset.tcOptions;
|
|
68
|
+
if (json) Object.assign(out, parseJson(json, "data-tc-options"));
|
|
69
|
+
for (const [key, value] of Object.entries(element.dataset)) {
|
|
70
|
+
if (!key.startsWith("tc") || value === void 0) continue;
|
|
71
|
+
const name = key.charAt(2).toLowerCase() + key.slice(3);
|
|
72
|
+
if (RESERVED.has(name)) continue;
|
|
73
|
+
out[name] = name === "legend" && value === "bottom" ? { position: "bottom" } : name === "download" && /^[a-z]/i.test(value) && !/^(true|false)$/.test(value) ? value.split(/[\s,]+/).filter(Boolean) : TEXT.has(name) ? value : parseValue(value);
|
|
74
|
+
}
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
/** Inline data: `data-tc-data` or a `<script type="application/json">` child. */
|
|
78
|
+
function inlineData(element) {
|
|
79
|
+
const attr = element.dataset.tcData;
|
|
80
|
+
if (attr) return parseJson(attr, "data-tc-data");
|
|
81
|
+
const text = element.querySelector(":scope > script[type=\"application/json\"]")?.textContent?.trim();
|
|
82
|
+
return text ? parseJson(text, "the inline <script type=\"application/json\">") : void 0;
|
|
83
|
+
}
|
|
84
|
+
function emit(element, name, detail) {
|
|
85
|
+
element.dispatchEvent(new CustomEvent(`tc-${name}`, {
|
|
86
|
+
detail,
|
|
87
|
+
bubbles: true
|
|
88
|
+
}));
|
|
89
|
+
}
|
|
90
|
+
function create(element, type, data) {
|
|
91
|
+
const config = {
|
|
92
|
+
...optionsOf(element),
|
|
93
|
+
type,
|
|
94
|
+
data
|
|
95
|
+
};
|
|
96
|
+
const chart = new Chart(element, config);
|
|
97
|
+
for (const name of chartEvents) chart.on(name, (detail) => emit(element, name, detail));
|
|
98
|
+
charts.set(element, chart);
|
|
99
|
+
emit(element, "render", { size: chart.size });
|
|
100
|
+
return chart;
|
|
101
|
+
}
|
|
102
|
+
/** Set up one element; returns its chart, or a promise while `data-tc-src` loads. */
|
|
103
|
+
function setup(element, known) {
|
|
104
|
+
const existing = charts.get(element);
|
|
105
|
+
if (existing || pending.has(element)) return existing;
|
|
106
|
+
const name = element.dataset.tcChart ?? "";
|
|
107
|
+
const type = known[name];
|
|
108
|
+
if (!type) {
|
|
109
|
+
const list = Object.keys(known).join(", ");
|
|
110
|
+
throw new Error(`@tabler/charts-bootstrap: unknown chart type "${name}". Known types: ${list}.`);
|
|
111
|
+
}
|
|
112
|
+
const src = element.dataset.tcSrc;
|
|
113
|
+
if (!src) return create(element, type, inlineData(element) ?? []);
|
|
114
|
+
pending.add(element);
|
|
115
|
+
element.setAttribute("aria-busy", "true");
|
|
116
|
+
return fetch(src).then((response) => {
|
|
117
|
+
if (!response.ok) throw new Error(`${response.status} ${response.statusText}`.trim());
|
|
118
|
+
return response.json();
|
|
119
|
+
}).then((data) => element.isConnected ? create(element, type, data) : void 0, (error) => {
|
|
120
|
+
emit(element, "error", {
|
|
121
|
+
error,
|
|
122
|
+
src
|
|
123
|
+
});
|
|
124
|
+
console.error(`@tabler/charts-bootstrap: could not load ${src}:`, error);
|
|
125
|
+
}).finally(() => {
|
|
126
|
+
pending.delete(element);
|
|
127
|
+
element.removeAttribute("aria-busy");
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Create a chart for every `[data-tc-chart]` in `root` (and `root` itself)
|
|
132
|
+
* that does not have one yet. Resolves once charts with `data-tc-src` have
|
|
133
|
+
* loaded; the ones with inline data exist as soon as `init()` returns.
|
|
134
|
+
*/
|
|
135
|
+
function init(root = document, options = {}) {
|
|
136
|
+
const known = {
|
|
137
|
+
...types,
|
|
138
|
+
...options.types
|
|
139
|
+
};
|
|
140
|
+
const elements = [...root.querySelectorAll(SELECTOR)];
|
|
141
|
+
if (root instanceof Element && root.matches(SELECTOR)) elements.unshift(root);
|
|
142
|
+
const made = elements.map((element) => {
|
|
143
|
+
try {
|
|
144
|
+
return setup(element, known);
|
|
145
|
+
} catch (error) {
|
|
146
|
+
emit(element, "error", { error });
|
|
147
|
+
console.error(error);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
return Promise.all(made).then((list) => list.filter((c) => c !== void 0));
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Keep `root` in sync: charts added later are initialized, charts removed
|
|
155
|
+
* are destroyed. Returns a function that stops observing.
|
|
156
|
+
*/
|
|
157
|
+
function observe(root = document.body, options = {}) {
|
|
158
|
+
init(root, options);
|
|
159
|
+
const observer = new MutationObserver((records) => {
|
|
160
|
+
for (const record of records) {
|
|
161
|
+
const owner = record.target.closest?.(SELECTOR);
|
|
162
|
+
if (owner && charts.has(owner)) continue;
|
|
163
|
+
for (const node of record.removedNodes) {
|
|
164
|
+
if (!(node instanceof Element)) continue;
|
|
165
|
+
if (charts.has(node)) dispose(node);
|
|
166
|
+
for (const inner of node.querySelectorAll(SELECTOR)) dispose(inner);
|
|
167
|
+
}
|
|
168
|
+
for (const node of record.addedNodes) {
|
|
169
|
+
if (node instanceof Element && !node.isConnected) continue;
|
|
170
|
+
if (node instanceof Element) init(node, options);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
});
|
|
174
|
+
observer.observe(root, {
|
|
175
|
+
childList: true,
|
|
176
|
+
subtree: true
|
|
177
|
+
});
|
|
178
|
+
return () => observer.disconnect();
|
|
179
|
+
}
|
|
180
|
+
//#endregion
|
|
181
|
+
export { dispose, getChart, init, observe, types };
|
|
182
|
+
|
|
183
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `@tabler/charts-bootstrap`: a data API in the Bootstrap style. Charts are\n * declared in HTML and `init()` (or the CDN script, on its own) turns them\n * into charts.\n *\n * ```html\n * <div data-tc-chart=\"line\" data-tc-src=\"/api/sales.json\" data-tc-aspect-ratio=\"3\"></div>\n * <div data-tc-chart=\"bar\" data-tc-stacked=\"true\">\n * <script type=\"application/json\">{ \"labels\": [...], \"series\": [...] }</script>\n * </div>\n * ```\n *\n * `data-tc-chart` names the type; data comes from `data-tc-src` (a JSON URL),\n * an inline `<script type=\"application/json\">` or `data-tc-data`; every other\n * `data-tc-*` attribute is an option (`data-tc-aspect-ratio=\"3\"`), and\n * `data-tc-options` takes a JSON object for the rest.\n */\nimport { Chart, type ChartConfig, type ChartType, chartEvents, types } from '@tabler/charts'\n\n/** Every built-in chart type, by its `data-tc-chart` name. */\nexport { types }\n\nexport interface InitOptions {\n /** Extra or replacement chart types, merged over the built-in ones. */\n types?: Readonly<Record<string, ChartType<never>>>\n}\n\nconst SELECTOR = '[data-tc-chart]'\n/** Attributes that are not chart options. */\nconst RESERVED = new Set(['chart', 'src', 'data', 'options'])\n/** Options that are text, whatever it spells: a title \"2024\" is not a number. */\nconst TEXT = new Set(['title', 'description', 'locale', 'sync', 'id', 'class'])\n\nconst charts = new WeakMap<Element, Chart<object>>()\n/** Elements whose data is still loading, so a second init() does not fetch twice. */\nconst pending = new WeakSet<Element>()\n\n/** The chart created for an element by `init()`, if any; `O` types its options (e.g. `LineOptions`). */\nexport function getChart<O extends object = object>(element: Element): Chart<O> | undefined {\n return charts.get(element) as Chart<O> | undefined\n}\n\n/** Destroy the chart of an element (it can be initialized again later). */\nexport function dispose(element: Element): void {\n charts.get(element)?.destroy()\n charts.delete(element)\n}\n\n/** `\"true\"`, `\"3\"`, `'{\"a\":1}'` or plain text, as the value it spells. */\nfunction parseValue(text: string): unknown {\n if (text === 'true' || text === '') return true\n if (text === 'false') return false\n if (text !== '' && Number.isFinite(Number(text))) return Number(text)\n if (/^\\s*[[{]/.test(text)) return parseJson(text, 'a data-tc-* attribute')\n return text\n}\n\nfunction parseJson(text: string, what: string): unknown {\n try {\n return JSON.parse(text)\n } catch (error) {\n throw new SyntaxError(\n `@tabler/charts-bootstrap: invalid JSON in ${what}: ${(error as Error).message}`,\n )\n }\n}\n\n/** Options from the element's `data-tc-*` attributes. */\nfunction optionsOf(element: HTMLElement): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n const json = element.dataset.tcOptions\n if (json) Object.assign(out, parseJson(json, 'data-tc-options'))\n for (const [key, value] of Object.entries(element.dataset)) {\n if (!key.startsWith('tc') || value === undefined) continue\n // dataset turns data-tc-aspect-ratio into tcAspectRatio.\n const name = key.charAt(2).toLowerCase() + key.slice(3)\n if (RESERVED.has(name)) continue\n out[name] =\n name === 'legend' && value === 'bottom'\n ? { position: 'bottom' }\n : name === 'download' && /^[a-z]/i.test(value) && !/^(true|false)$/.test(value)\n ? value.split(/[\\s,]+/).filter(Boolean)\n : TEXT.has(name)\n ? value\n : parseValue(value)\n }\n return out\n}\n\n/** Inline data: `data-tc-data` or a `<script type=\"application/json\">` child. */\nfunction inlineData(element: HTMLElement): unknown {\n const attr = element.dataset.tcData\n if (attr) return parseJson(attr, 'data-tc-data')\n const script = element.querySelector(':scope > script[type=\"application/json\"]')\n const text = script?.textContent?.trim()\n return text ? parseJson(text, 'the inline <script type=\"application/json\">') : undefined\n}\n\nfunction emit(element: Element, name: string, detail: unknown): void {\n element.dispatchEvent(new CustomEvent(`tc-${name}`, { detail, bubbles: true }))\n}\n\nfunction create(element: HTMLElement, type: ChartType<object>, data: unknown): Chart<object> {\n const config = { ...optionsOf(element), type, data } as ChartConfig<object>\n const chart = new Chart(element, config)\n for (const name of chartEvents) chart.on(name, (detail) => emit(element, name, detail))\n charts.set(element, chart)\n // The first render ran in the constructor, before anyone could listen.\n emit(element, 'render', { size: chart.size })\n return chart\n}\n\n/** Set up one element; returns its chart, or a promise while `data-tc-src` loads. */\nfunction setup(\n element: HTMLElement,\n known: Readonly<Record<string, ChartType<never>>>,\n): Chart<object> | Promise<Chart<object> | undefined> | undefined {\n const existing = charts.get(element)\n if (existing || pending.has(element)) return existing\n const name = element.dataset.tcChart ?? ''\n const type = known[name] as ChartType<object> | undefined\n if (!type) {\n const list = Object.keys(known).join(', ')\n throw new Error(`@tabler/charts-bootstrap: unknown chart type \"${name}\". Known types: ${list}.`)\n }\n const src = element.dataset.tcSrc\n if (!src) return create(element, type, inlineData(element) ?? [])\n\n pending.add(element)\n element.setAttribute('aria-busy', 'true')\n return fetch(src)\n .then((response) => {\n if (!response.ok) throw new Error(`${response.status} ${response.statusText}`.trim())\n return response.json()\n })\n .then(\n (data) => (element.isConnected ? create(element, type, data) : undefined),\n (error: unknown) => {\n emit(element, 'error', { error, src })\n console.error(`@tabler/charts-bootstrap: could not load ${src}:`, error)\n return undefined\n },\n )\n .finally(() => {\n pending.delete(element)\n element.removeAttribute('aria-busy')\n })\n}\n\n/**\n * Create a chart for every `[data-tc-chart]` in `root` (and `root` itself)\n * that does not have one yet. Resolves once charts with `data-tc-src` have\n * loaded; the ones with inline data exist as soon as `init()` returns.\n */\nexport function init(\n root: ParentNode = document,\n options: InitOptions = {},\n): Promise<Chart<object>[]> {\n const known = { ...types, ...options.types }\n const elements = [...root.querySelectorAll<HTMLElement>(SELECTOR)]\n if (root instanceof Element && root.matches(SELECTOR)) elements.unshift(root as HTMLElement)\n const made = elements.map((element) => {\n // One broken declaration (unknown type, bad JSON) must not stop the others.\n try {\n return setup(element, known)\n } catch (error) {\n emit(element, 'error', { error })\n console.error(error)\n return undefined\n }\n })\n return Promise.all(made).then((list) => list.filter((c): c is Chart<object> => c !== undefined))\n}\n\n/**\n * Keep `root` in sync: charts added later are initialized, charts removed\n * are destroyed. Returns a function that stops observing.\n */\nexport function observe(root: Element = document.body, options: InitOptions = {}): () => void {\n void init(root, options)\n const observer = new MutationObserver((records) => {\n for (const record of records) {\n // A chart changing its own content (every hover, every update) adds no charts.\n const owner = (record.target as Element).closest?.(SELECTOR)\n if (owner && charts.has(owner)) continue\n for (const node of record.removedNodes) {\n if (!(node instanceof Element)) continue\n if (charts.has(node)) dispose(node)\n for (const inner of node.querySelectorAll(SELECTOR)) dispose(inner)\n }\n for (const node of record.addedNodes) {\n if (node instanceof Element && !node.isConnected) continue\n if (node instanceof Element) void init(node, options)\n }\n }\n })\n observer.observe(root, { childList: true, subtree: true })\n return () => observer.disconnect()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA2BA,MAAM,WAAW;;AAEjB,MAAM,2BAAW,IAAI,IAAI;CAAC;CAAS;CAAO;CAAQ;AAAS,CAAC;;AAE5D,MAAM,uBAAO,IAAI,IAAI;CAAC;CAAS;CAAe;CAAU;CAAQ;CAAM;AAAO,CAAC;AAE9E,MAAM,yBAAS,IAAI,QAAgC;;AAEnD,MAAM,0BAAU,IAAI,QAAiB;;AAGrC,SAAgB,SAAoC,SAAwC;CAC1F,OAAO,OAAO,IAAI,OAAO;AAC3B;;AAGA,SAAgB,QAAQ,SAAwB;CAC9C,OAAO,IAAI,OAAO,CAAC,EAAE,QAAQ;CAC7B,OAAO,OAAO,OAAO;AACvB;;AAGA,SAAS,WAAW,MAAuB;CACzC,IAAI,SAAS,UAAU,SAAS,IAAI,OAAO;CAC3C,IAAI,SAAS,SAAS,OAAO;CAC7B,IAAI,SAAS,MAAM,OAAO,SAAS,OAAO,IAAI,CAAC,GAAG,OAAO,OAAO,IAAI;CACpE,IAAI,WAAW,KAAK,IAAI,GAAG,OAAO,UAAU,MAAM,uBAAuB;CACzE,OAAO;AACT;AAEA,SAAS,UAAU,MAAc,MAAuB;CACtD,IAAI;EACF,OAAO,KAAK,MAAM,IAAI;CACxB,SAAS,OAAO;EACd,MAAM,IAAI,YACR,6CAA6C,KAAK,IAAK,MAAgB,SACzE;CACF;AACF;;AAGA,SAAS,UAAU,SAA+C;CAChE,MAAM,MAA+B,CAAC;CACtC,MAAM,OAAO,QAAQ,QAAQ;CAC7B,IAAI,MAAM,OAAO,O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