@clarity-js/charts 0.0.0-stage → 1.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/README.md +132 -2
- package/index.d.ts +407 -0
- package/maps/index.d.ts +5 -0
- package/maps/turkey.js +3 -0
- package/maps/world.js +3 -0
- package/package.json +21 -4
- package/src/axes.js +281 -0
- package/src/compat.js +414 -0
- package/src/components.js +111 -0
- package/src/controllers.js +321 -0
- package/src/core.js +914 -0
- package/src/depth.js +316 -0
- package/src/features.js +783 -0
- package/src/fills.js +187 -0
- package/src/format.js +42 -0
- package/src/full.js +23 -0
- package/src/graphs.js +342 -0
- package/src/index.js +53 -0
- package/src/layouts.js +272 -0
- package/src/lite.js +40 -0
- package/src/maps.js +227 -0
- package/src/painter.js +162 -0
- package/src/plugins.js +381 -0
- package/src/scale.js +108 -0
- package/src/shape.js +119 -0
- package/src/themes.js +79 -0
- package/src/types.js +1193 -0
package/src/core.js
ADDED
|
@@ -0,0 +1,914 @@
|
|
|
1
|
+
// @clarity-js/charts — the Chart: Chart.js's configuration and API, drawn by Clarity.
|
|
2
|
+
//
|
|
3
|
+
// const chart = new Chart(el, {
|
|
4
|
+
// type: 'bar',
|
|
5
|
+
// data: { labels: ['Mon', 'Tue', 'Wed'], datasets: [{ label: 'Visits', data: [12, 19, 3] }] },
|
|
6
|
+
// options: { plugins: { title: { display: true, text: 'This week' } }, scales: { y: { beginAtZero: true } } },
|
|
7
|
+
// })
|
|
8
|
+
// chart.data.datasets[0].data.push(7); chart.update()
|
|
9
|
+
//
|
|
10
|
+
// `el` is a container (the chart draws as SVG in it: accessible, drawn on a server too, allowed by a
|
|
11
|
+
// strict Content-Security-Policy) or a <canvas> (drawn on it, and `chart.ctx` is there for plugins
|
|
12
|
+
// that draw). Animations run on Clarity's shared clock, so `clock.pause()` / `clock.step()` hold and
|
|
13
|
+
// step them in tests.
|
|
14
|
+
|
|
15
|
+
import { frame } from '@ozsarman/clarityjs/game-loop';
|
|
16
|
+
import { reducedMotion } from '@ozsarman/clarityjs/motion';
|
|
17
|
+
import { svgPainter, canvasPainter, stringPainter, measureText } from './painter.js';
|
|
18
|
+
import { Axis, RadialAxis, toTime, formatTime, TIME_FORMATS } from './axes.js';
|
|
19
|
+
import { CONTROLLERS, parse, inRange, inAxisRange, centerOf, tipPoint, extentOf } from './controllers.js';
|
|
20
|
+
import { formatNumber } from './format.js';
|
|
21
|
+
import { BUILT_IN_PLUGINS, colorize } from './plugins.js';
|
|
22
|
+
import { resolveTheme, themeOptions, registerTheme, THEMES, PALETTES } from './themes.js';
|
|
23
|
+
|
|
24
|
+
export const VERSION = '1.1.0';
|
|
25
|
+
const RADIAL = new Set(['radar', 'polarArea']), ROUND = new Set(['pie', 'doughnut', 'polarArea']);
|
|
26
|
+
|
|
27
|
+
/** Easing by Chart.js's names. */
|
|
28
|
+
export const EASING = {
|
|
29
|
+
linear: (t) => t, easeInQuad: (t) => t * t, easeOutQuad: (t) => t * (2 - t), easeInOutQuad: (t) => (t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t),
|
|
30
|
+
easeInCubic: (t) => t ** 3, easeOutCubic: (t) => 1 - (1 - t) ** 3, easeInOutCubic: (t) => (t < 0.5 ? 4 * t ** 3 : 1 - (-2 * t + 2) ** 3 / 2),
|
|
31
|
+
easeInQuart: (t) => t ** 4, easeOutQuart: (t) => 1 - (1 - t) ** 4, easeInOutQuart: (t) => (t < 0.5 ? 8 * t ** 4 : 1 - (-2 * t + 2) ** 4 / 2),
|
|
32
|
+
easeInQuint: (t) => t ** 5, easeOutQuint: (t) => 1 - (1 - t) ** 5, easeInOutQuint: (t) => (t < 0.5 ? 16 * t ** 5 : 1 - (-2 * t + 2) ** 5 / 2),
|
|
33
|
+
easeInSine: (t) => 1 - Math.cos((t * Math.PI) / 2), easeOutSine: (t) => Math.sin((t * Math.PI) / 2), easeInOutSine: (t) => -(Math.cos(Math.PI * t) - 1) / 2,
|
|
34
|
+
easeInExpo: (t) => (t === 0 ? 0 : 2 ** (10 * t - 10)), easeOutExpo: (t) => (t === 1 ? 1 : 1 - 2 ** (-10 * t)), easeInOutExpo: (t) => (t === 0 || t === 1 ? t : t < 0.5 ? 2 ** (20 * t - 10) / 2 : (2 - 2 ** (-20 * t + 10)) / 2),
|
|
35
|
+
easeInCirc: (t) => 1 - Math.sqrt(1 - t * t), easeOutCirc: (t) => Math.sqrt(1 - (t - 1) ** 2), easeInOutCirc: (t) => (t < 0.5 ? (1 - Math.sqrt(1 - (2 * t) ** 2)) / 2 : (Math.sqrt(1 - (-2 * t + 2) ** 2) + 1) / 2),
|
|
36
|
+
easeInBack: (t) => 2.70158 * t ** 3 - 1.70158 * t * t, easeOutBack: (t) => 1 + 2.70158 * (t - 1) ** 3 + 1.70158 * (t - 1) ** 2, easeInOutBack: (t) => { const c = 2.5949095; return t < 0.5 ? ((2 * t) ** 2 * ((c + 1) * 2 * t - c)) / 2 : ((2 * t - 2) ** 2 * ((c + 1) * (t * 2 - 2) + c) + 2) / 2; },
|
|
37
|
+
easeInElastic: (t) => (t === 0 || t === 1 ? t : -(2 ** (10 * t - 10)) * Math.sin((t * 10 - 10.75) * ((2 * Math.PI) / 3))), easeOutElastic: (t) => (t === 0 || t === 1 ? t : 2 ** (-10 * t) * Math.sin((t * 10 - 0.75) * ((2 * Math.PI) / 3)) + 1),
|
|
38
|
+
easeInOutElastic: (t) => (t === 0 || t === 1 ? t : t < 0.5 ? -(2 ** (20 * t - 10) * Math.sin((20 * t - 11.125) * ((2 * Math.PI) / 4.5))) / 2 : (2 ** (-20 * t + 10) * Math.sin((20 * t - 11.125) * ((2 * Math.PI) / 4.5))) / 2 + 1),
|
|
39
|
+
easeOutBounce: (t) => { const n = 7.5625, d = 2.75; if (t < 1 / d) return n * t * t; if (t < 2 / d) return n * (t -= 1.5 / d) * t + 0.75; if (t < 2.5 / d) return n * (t -= 2.25 / d) * t + 0.9375; return n * (t -= 2.625 / d) * t + 0.984375; },
|
|
40
|
+
};
|
|
41
|
+
EASING.easeInBounce = (t) => 1 - EASING.easeOutBounce(1 - t);
|
|
42
|
+
EASING.easeInOutBounce = (t) => (t < 0.5 ? (1 - EASING.easeOutBounce(1 - 2 * t)) / 2 : (1 + EASING.easeOutBounce(2 * t - 1)) / 2);
|
|
43
|
+
|
|
44
|
+
/** Every chart starts from these (change them for all charts: Chart.defaults.font.size = 13). */
|
|
45
|
+
export const defaults = {
|
|
46
|
+
responsive: true, maintainAspectRatio: true, aspectRatio: 2, resizeDelay: 0, devicePixelRatio: undefined, locale: undefined, renderer: 'svg',
|
|
47
|
+
color: 'var(--clarity-chart-text, #5b6573)', borderColor: 'rgba(0,0,0,0.1)', backgroundColor: 'rgba(0,0,0,0.1)',
|
|
48
|
+
font: { family: 'system-ui, -apple-system, "Segoe UI", sans-serif', size: 12, style: 'normal', weight: 'normal', lineHeight: 1.2 },
|
|
49
|
+
layout: { padding: 0, autoPadding: true },
|
|
50
|
+
animation: { duration: 1000, easing: 'easeOutQuart', delay: 0, loop: false, animateRotate: true, animateScale: false },
|
|
51
|
+
interaction: { mode: 'nearest', intersect: true, axis: 'x', includeInvisible: false },
|
|
52
|
+
hover: {},
|
|
53
|
+
events: ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove'],
|
|
54
|
+
elements: {
|
|
55
|
+
point: { radius: 3, pointStyle: 'circle', borderWidth: 1, hitRadius: 1, hoverRadius: 4, hoverBorderWidth: 1, rotation: 0 },
|
|
56
|
+
line: { tension: 0, borderWidth: 3, borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0, borderJoinStyle: 'miter', cubicInterpolationMode: 'default', fill: false, stepped: false, spanGaps: false, showLine: true },
|
|
57
|
+
bar: { borderWidth: 0, borderRadius: 0, borderSkipped: 'start', minBarLength: 0 },
|
|
58
|
+
arc: { borderWidth: 2, borderColor: 'var(--clarity-chart-bg, #fff)', borderAlign: 'center', offset: 0, hoverOffset: 4, spacing: 0, borderJoinStyle: 'round' },
|
|
59
|
+
},
|
|
60
|
+
datasets: {
|
|
61
|
+
bar: { categoryPercentage: 0.8, barPercentage: 0.9, grouped: true },
|
|
62
|
+
scatter: { showLine: false },
|
|
63
|
+
radar: { tension: 0 },
|
|
64
|
+
},
|
|
65
|
+
scales: {},
|
|
66
|
+
plugins: {},
|
|
67
|
+
};
|
|
68
|
+
// what each type changes in the defaults
|
|
69
|
+
const OVERRIDES = {
|
|
70
|
+
bar: { interaction: { mode: 'index', intersect: false } },
|
|
71
|
+
line: { interaction: { mode: 'index', intersect: false } },
|
|
72
|
+
pie: { aspectRatio: 1, interaction: { mode: 'nearest', intersect: true }, plugins: { legend: { display: true } } },
|
|
73
|
+
doughnut: { aspectRatio: 1, interaction: { mode: 'nearest', intersect: true } },
|
|
74
|
+
polarArea: { aspectRatio: 1, interaction: { mode: 'nearest', intersect: true } },
|
|
75
|
+
radar: { aspectRatio: 1, interaction: { mode: 'nearest', intersect: true } },
|
|
76
|
+
scatter: { interaction: { mode: 'nearest', intersect: true } },
|
|
77
|
+
bubble: { interaction: { mode: 'nearest', intersect: true } },
|
|
78
|
+
};
|
|
79
|
+
// the types and plugins beyond Chart.js, and the functions behind zoom, drilldown, CSV, saved views and sound, come
|
|
80
|
+
// from full.js (what '@clarity-js/charts' loads); '@clarity-js/charts/lite' is Chart.js's own and leaves them out
|
|
81
|
+
const registry = { plugins: [...BUILT_IN_PLUGINS], controllers: { ...CONTROLLERS }, scales: {}, extras: {} };
|
|
82
|
+
const need = (name) => registry.extras[name] ?? (() => { throw new Error(`[clarity-charts] chart.${name.replace(/By$/, '')}() is in the full package: import from '@clarity-js/charts', not '@clarity-js/charts/lite'`); });
|
|
83
|
+
// sparkline: the line alone, as small as a word (ApexCharts's chart.sparkline)
|
|
84
|
+
const SPARKLINE = { layout: { padding: 2 }, plugins: { legend: { display: false }, title: { display: false }, subtitle: { display: false } }, elements: { point: { radius: 0, hoverRadius: 3 } }, interaction: { mode: 'index', intersect: false } };
|
|
85
|
+
const sparkOn = (v) => v === true || !!v?.enabled;
|
|
86
|
+
|
|
87
|
+
const isObj = (v) => v && typeof v === 'object' && !Array.isArray(v) && !(v instanceof Date) && !(typeof Node !== 'undefined' && v instanceof Node);
|
|
88
|
+
export function merge(...objs) {
|
|
89
|
+
const out = {};
|
|
90
|
+
for (const o of objs) if (isObj(o)) for (const k in o) { if (o[k] === undefined) continue; out[k] = isObj(o[k]) && isObj(out[k]) ? merge(out[k], o[k]) : isObj(o[k]) ? merge(o[k]) : o[k]; }
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
// a meta as Chart.js code reads it: meta.data (its elements as drawn), meta.hidden (null: as the dataset says)
|
|
94
|
+
function withAliases(meta) {
|
|
95
|
+
Object.defineProperty(meta, 'data', { get: () => meta.drawn ?? meta.elements, enumerable: false });
|
|
96
|
+
Object.defineProperty(meta, 'hidden', { get: () => meta.hiddenOverride, set: (v) => { meta.hiddenOverride = v == null ? null : !!v; }, enumerable: false });
|
|
97
|
+
return meta;
|
|
98
|
+
}
|
|
99
|
+
const at = (v, i) => (Array.isArray(v) ? v[((i % v.length) + v.length) % v.length] : v);
|
|
100
|
+
let nextId = 0;
|
|
101
|
+
|
|
102
|
+
export class Chart {
|
|
103
|
+
static defaults = defaults;
|
|
104
|
+
static overrides = OVERRIDES;
|
|
105
|
+
static instances = {};
|
|
106
|
+
static version = VERSION;
|
|
107
|
+
static registry = registry;
|
|
108
|
+
static themes = THEMES;
|
|
109
|
+
static palettes = PALETTES;
|
|
110
|
+
/** Add a theme by name: Chart.registerTheme('ocean', { extends: 'dark', palette: [...], grid: '…' }). */
|
|
111
|
+
static registerTheme(name, theme) { return registerTheme(name, theme); }
|
|
112
|
+
/** Add plugins, controllers ({ id, controller }) or axis types ({ id, axis: class }) for every chart. */
|
|
113
|
+
static register(...items) {
|
|
114
|
+
for (const it of items.flat()) {
|
|
115
|
+
if (!it) continue;
|
|
116
|
+
if (it.controller) registry.controllers[it.id] = it.controller;
|
|
117
|
+
else if (it.axis) registry.scales[it.id] = it.axis;
|
|
118
|
+
else if (it.id && !registry.plugins.some((p) => p.id === it.id)) registry.plugins.push(it);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
static unregister(...items) { for (const it of items.flat()) { registry.plugins = registry.plugins.filter((p) => p !== it && p.id !== it?.id); if (it?.controller) delete registry.controllers[it.id]; } }
|
|
122
|
+
/** The chart drawn in an element, a canvas, or by its id. */
|
|
123
|
+
static getChart(key) {
|
|
124
|
+
const el = typeof key === 'string' ? (Chart.instances[key] ? null : globalThis.document?.getElementById(key)) : key;
|
|
125
|
+
if (typeof key === 'string' && Chart.instances[key]) return Chart.instances[key];
|
|
126
|
+
if (!el) return null;
|
|
127
|
+
return Object.values(Chart.instances).find((c) => (c.canvas && (c.canvas === el || c.canvas === el.canvas)) || (c.container === el && !c.canvas) || c.svg === el) ?? null;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
constructor(item, config = {}) {
|
|
131
|
+
let target = typeof item === 'string' ? globalThis.document?.getElementById(item) : item;
|
|
132
|
+
if (target && typeof target.getContext === 'function' && target.canvas) target = target.canvas;
|
|
133
|
+
if (!target) throw new Error('[clarity-charts] new Chart(el, config): el is not an element, a canvas or the id of one');
|
|
134
|
+
if (Chart.getChart(target)) throw new Error('[clarity-charts] this element already has a chart: destroy() it first');
|
|
135
|
+
this.id = String(nextId++);
|
|
136
|
+
this.config = { type: config.type ?? 'bar', data: config.data ?? { datasets: [] }, options: config.options ?? {}, plugins: config.plugins ?? [] };
|
|
137
|
+
const isCanvas = typeof target.getContext === 'function';
|
|
138
|
+
const renderer = isCanvas ? 'canvas' : this.config.options.renderer ?? defaults.renderer;
|
|
139
|
+
if (isCanvas) { this.canvas = target; this.container = target.parentElement ?? target; }
|
|
140
|
+
else {
|
|
141
|
+
this.container = target;
|
|
142
|
+
if (renderer === 'canvas') { this.canvas = document.createElement('canvas'); target.appendChild(this.canvas); }
|
|
143
|
+
else { this.svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); target.appendChild(this.svg); }
|
|
144
|
+
}
|
|
145
|
+
const surface = this.canvas ?? this.svg;
|
|
146
|
+
surface.style.display = 'block'; surface.style.touchAction = 'pan-y';
|
|
147
|
+
if (this.container !== surface && globalThis.getComputedStyle?.(this.container).position === 'static') this.container.style.position = 'relative';
|
|
148
|
+
this.painter = this.canvas ? canvasPainter(this.canvas, { pixelRatio: this.config.options.devicePixelRatio }) : svgPainter(this.svg);
|
|
149
|
+
this.ctx = this.painter.ctx ?? null;
|
|
150
|
+
this.surface = surface;
|
|
151
|
+
this.metas = []; this.scales = {}; this.boxes = []; this._active = []; this._hiddenIndices = new Set(); this._shown = new Map(); this.chartArea = { left: 0, top: 0, right: 0, bottom: 0, width: 0, height: 0 };
|
|
152
|
+
this.width = 0; this.height = 0; this.attached = !!this.container.isConnected;
|
|
153
|
+
Chart.instances[this.id] = this;
|
|
154
|
+
this._plugins = [...registry.plugins, ...this.config.plugins];
|
|
155
|
+
this.notify('install'); this.notify('beforeInit');
|
|
156
|
+
this._listen();
|
|
157
|
+
this._a11y();
|
|
158
|
+
this.notify('afterInit');
|
|
159
|
+
this.update();
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
get type() { return this.config.type; }
|
|
163
|
+
get data() { return this.config.data; }
|
|
164
|
+
set data(v) { this.config.data = v ?? { datasets: [] }; }
|
|
165
|
+
/** The options as given (change them and call update()); the resolved ones are chart.resolved. */
|
|
166
|
+
get options() { return this.config.options; }
|
|
167
|
+
set options(v) { this.config.options = v ?? {}; }
|
|
168
|
+
|
|
169
|
+
// ── options ───────────────────────────────────────────────────────────────
|
|
170
|
+
_resolve(extra) {
|
|
171
|
+
const type = this.type, user = this.config.options, ctl = registry.controllers[type];
|
|
172
|
+
const theme = resolveTheme(extra?.theme ?? user.theme);
|
|
173
|
+
const spark = sparkOn(extra?.sparkline ?? user.sparkline);
|
|
174
|
+
const o = merge(defaults, OVERRIDES[type] ?? ctl?.defaults ?? {}, themeOptions(theme), spark ? SPARKLINE : {}, user, extra ?? {});
|
|
175
|
+
o.theme = theme; o.sparkline = spark;
|
|
176
|
+
// what each type in use sets for its datasets (a streamgraph's fill, a candlestick's colours …)
|
|
177
|
+
for (const ds of this.data?.datasets ?? []) { const t = ds?.type ?? type, c = registry.controllers[t]; if (c?.datasetDefaults) o.datasets[t] = merge(c.datasetDefaults, o.datasets?.[t] ?? {}); }
|
|
178
|
+
for (const p of this._plugins) if (p.defaults) o.plugins[p.id] = merge(p.defaults, o.plugins[p.id] ?? {});
|
|
179
|
+
if (o.plugins.tooltip && !user.plugins?.tooltip?.mode) { o.plugins.tooltip.mode = o.interaction.mode; if (user.plugins?.tooltip?.intersect == null) o.plugins.tooltip.intersect = o.interaction.intersect; }
|
|
180
|
+
o.locale = o.locale ?? (globalThis.navigator?.language || 'en-US');
|
|
181
|
+
this.resolved = o;
|
|
182
|
+
return o;
|
|
183
|
+
}
|
|
184
|
+
/** A dataset's option for a data point: the dataset's own, then options.datasets[type], then options.elements; a function is given the context, an array is read at the point's index. */
|
|
185
|
+
option(meta, name, index, elementKey = null, fallback) {
|
|
186
|
+
const o = this.resolved, ds = meta.dataset;
|
|
187
|
+
let v = ds[name];
|
|
188
|
+
if (v === undefined) v = o.datasets?.[meta.type]?.[name];
|
|
189
|
+
if (v === undefined) v = o[meta.type]?.[name];
|
|
190
|
+
if (v === undefined) v = this.config.options?.[name]; // Chart.js reads dataset options at the root of options too (cutout, rotation …)
|
|
191
|
+
if (v === undefined && elementKey) v = o.elements?.[CONTROLLERS[meta.type]?.element ?? meta.controller.element]?.[elementKey];
|
|
192
|
+
if (v === undefined && elementKey && meta.controller.element === 'point') v = o.elements?.line?.[elementKey];
|
|
193
|
+
if (v === undefined) return fallback;
|
|
194
|
+
if (typeof v === 'function' && !/^on|callback$/.test(name)) v = v(this._ctx(meta, index));
|
|
195
|
+
return at(v, index);
|
|
196
|
+
}
|
|
197
|
+
_ctx(meta, index) { const p = meta.parsed?.[index]; return { chart: this, type: 'data', dataset: meta.dataset, datasetIndex: meta.index, dataIndex: index, index, raw: p?.raw, parsed: p ? { x: p.index, y: p.value, r: p.r } : undefined, active: this.isActive(meta.index, index), mode: this._mode }; }
|
|
198
|
+
_colour(meta, name, index, fallbackIndex) { return this.option(meta, name, index, name) ?? meta.colors?.[name]?.[at(fallbackIndex, index)] ?? at(meta.colors?.[name], index); }
|
|
199
|
+
pointOptions(meta, i) {
|
|
200
|
+
const pick = (n, el, d) => this.option(meta, n, i, el, d);
|
|
201
|
+
const bg = pick('pointBackgroundColor', null) ?? this.option(meta, 'backgroundColor', i, 'backgroundColor') ?? meta.auto?.backgroundColor ?? this.resolved.backgroundColor;
|
|
202
|
+
const bc = pick('pointBorderColor', null) ?? this.option(meta, 'borderColor', i, 'borderColor') ?? meta.auto?.borderColor ?? this.resolved.borderColor;
|
|
203
|
+
const isLine = meta.type === 'line' || meta.type === 'radar';
|
|
204
|
+
return {
|
|
205
|
+
pointStyle: pick('pointStyle', 'pointStyle', 'circle'), rotation: pick('pointRotation', 'rotation', 0),
|
|
206
|
+
backgroundColor: bg, borderColor: bc, borderWidth: pick('pointBorderWidth', null) ?? (isLine ? this.option(meta, 'borderWidth', i, null) ?? 1 : this.option(meta, 'borderWidth', i, 'borderWidth', 1)),
|
|
207
|
+
hoverRadius: pick('pointHoverRadius', null) ?? pick('hoverRadius', 'hoverRadius', 4), hitRadius: pick('pointHitRadius', null) ?? pick('hitRadius', 'hitRadius', 1),
|
|
208
|
+
hoverBackgroundColor: pick('pointHoverBackgroundColor', null) ?? pick('hoverBackgroundColor', null) ?? bg, hoverBorderColor: pick('pointHoverBorderColor', null) ?? pick('hoverBorderColor', null) ?? bc,
|
|
209
|
+
hoverBorderWidth: pick('pointHoverBorderWidth', null) ?? pick('hoverBorderWidth', 'hoverBorderWidth', 1),
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
lineOptions(meta) {
|
|
213
|
+
const pick = (n, d) => this.option(meta, n, 0, n, d);
|
|
214
|
+
return {
|
|
215
|
+
borderColor: this.option(meta, 'borderColor', 0, 'borderColor') ?? meta.auto?.borderColor ?? this.resolved.borderColor, backgroundColor: this.option(meta, 'backgroundColor', 0, 'backgroundColor') ?? meta.auto?.backgroundColor ?? this.resolved.backgroundColor,
|
|
216
|
+
borderWidth: pick('borderWidth', 3), borderDash: pick('borderDash', []), borderDashOffset: pick('borderDashOffset', 0), borderCapStyle: pick('borderCapStyle', 'butt'), borderJoinStyle: pick('borderJoinStyle', 'miter'),
|
|
217
|
+
tension: meta.dataset.lineTension ?? pick('tension', 0), stepped: pick('stepped', false), cubicInterpolationMode: pick('cubicInterpolationMode', 'default'), fill: pick('fill', false),
|
|
218
|
+
spanGaps: meta.dataset.spanGaps ?? this.resolved.spanGaps ?? pick('spanGaps', false), showLine: meta.dataset.showLine ?? this.resolved.datasets?.[meta.type]?.showLine ?? this.resolved.showLine ?? true,
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
barOptions(meta, i) {
|
|
222
|
+
const pick = (n, d) => this.option(meta, n, i, n, d);
|
|
223
|
+
const bg = this.option(meta, 'backgroundColor', i, 'backgroundColor') ?? at(meta.auto?.backgroundColor, i) ?? this.resolved.backgroundColor, bc = this.option(meta, 'borderColor', i, 'borderColor') ?? at(meta.auto?.borderColor, i) ?? this.resolved.borderColor;
|
|
224
|
+
return { backgroundColor: bg, borderColor: bc, borderWidth: pick('borderWidth', 0), borderRadius: pick('borderRadius', 0), borderSkipped: pick('borderSkipped', 'start'), hoverBackgroundColor: pick('hoverBackgroundColor') ?? bg, hoverBorderColor: pick('hoverBorderColor') ?? bc, hoverBorderWidth: pick('hoverBorderWidth') ?? pick('borderWidth', 0) };
|
|
225
|
+
}
|
|
226
|
+
arcOptions(meta, i) {
|
|
227
|
+
const pick = (n, d) => this.option(meta, n, i, n, d);
|
|
228
|
+
const bg = this.option(meta, 'backgroundColor', i, 'backgroundColor') ?? at(meta.auto?.backgroundColor, i) ?? this.resolved.backgroundColor, bc = pick('borderColor', '#fff');
|
|
229
|
+
return { backgroundColor: bg, borderColor: bc, borderWidth: pick('borderWidth', 2), hoverBackgroundColor: pick('hoverBackgroundColor') ?? bg, hoverBorderColor: pick('hoverBorderColor') ?? bc, hoverBorderWidth: pick('hoverBorderWidth') ?? pick('borderWidth', 2), offset: pick('offset', 0), hoverOffset: pick('hoverOffset', 4), spacing: pick('spacing', 0), borderJoinStyle: pick('borderJoinStyle', 'round') };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** A data point's fill and outline, for any type: the dataset's own, else the colour it was given. */
|
|
233
|
+
fillOf(meta, i) { return this.option(meta, 'backgroundColor', i, 'backgroundColor') ?? at(meta.auto?.backgroundColor, i) ?? this.resolved.backgroundColor; }
|
|
234
|
+
strokeOf(meta, i) { return this.option(meta, 'borderColor', i, 'borderColor') ?? at(meta.auto?.borderColor, i) ?? this.resolved.borderColor; }
|
|
235
|
+
|
|
236
|
+
// ── data → metas ─────────────────────────────────────────────────────────────
|
|
237
|
+
_buildMetas() {
|
|
238
|
+
const o = this.resolved, old = this.metas;
|
|
239
|
+
this.metas = (this.data.datasets ?? []).map((ds, index) => {
|
|
240
|
+
const type = ds.type ?? this.type, controller = registry.controllers[type] ?? CONTROLLERS[type];
|
|
241
|
+
if (!controller) throw new Error(`[clarity-charts] no controller for type "${type}"${registry.extras.zoomBy ? '' : ' (the types beyond Chart.js\'s eight are in \'@clarity-js/charts\', not \'/lite\')'}: register one with Chart.register({ id, controller })`);
|
|
242
|
+
const prev = old[index]?.dataset === ds ? old[index] : old[index];
|
|
243
|
+
const indexAxis = controller.indexAxis ?? ds.indexAxis ?? o.datasets?.[type]?.indexAxis ?? o.indexAxis ?? 'x';
|
|
244
|
+
const kind = controller.axes ?? (RADIAL.has(type) ? 'radial' : type === 'pie' || type === 'doughnut' ? 'none' : 'cartesian');
|
|
245
|
+
const radial = kind === 'radial', round = kind === 'none';
|
|
246
|
+
const xId = ds.xAxisID ?? 'x', yId = ds.yAxisID ?? 'y';
|
|
247
|
+
return withAliases({
|
|
248
|
+
index, dataset: ds, type, controller, chart: this, order: ds.order ?? controller.order ?? 0, stackName: ds.stack ?? '__default',
|
|
249
|
+
indexAxis, iAxisID: radial ? 'r' : round ? null : indexAxis === 'y' ? yId : xId, vAxisID: radial ? 'r' : round ? null : indexAxis === 'y' ? xId : yId,
|
|
250
|
+
hiddenOverride: prev?.hiddenOverride ?? null, elements: [], label: ds.label ?? '',
|
|
251
|
+
});
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
isDatasetVisible(i) { const m = this.metas[i]; if (!m) return false; return m.hiddenOverride != null ? !m.hiddenOverride : !m.dataset.hidden; }
|
|
255
|
+
setDatasetVisibility(i, visible) { const m = this.metas[i]; if (m) m.hiddenOverride = !visible; }
|
|
256
|
+
getDatasetMeta(i) { return this.metas[i]; }
|
|
257
|
+
getVisibleDatasetCount() { return this.metas.filter((m, i) => this.isDatasetVisible(i)).length; }
|
|
258
|
+
getSortedVisibleDatasetMetas() { return this.metas.filter((m) => this.isDatasetVisible(m.index)).sort((a, b) => a.order - b.order || a.index - b.index); }
|
|
259
|
+
/** Hide or show one point of the data (a slice of a pie: what its legend toggles). */
|
|
260
|
+
toggleDataVisibility(index) { if (this._hiddenIndices.has(index)) this._hiddenIndices.delete(index); else this._hiddenIndices.add(index); }
|
|
261
|
+
getDataVisibility(index) { return !this._hiddenIndices.has(index); }
|
|
262
|
+
hide(datasetIndex, dataIndex) { if (dataIndex != null) this._hiddenIndices.add(dataIndex); else this.setDatasetVisibility(datasetIndex, false); this.update('hide'); }
|
|
263
|
+
show(datasetIndex, dataIndex) { if (dataIndex != null) this._hiddenIndices.delete(dataIndex); else this.setDatasetVisibility(datasetIndex, true); this.update('show'); }
|
|
264
|
+
|
|
265
|
+
barGroups(meta) {
|
|
266
|
+
const vx = this.scales[meta.vAxisID], stacked = !!vx?.options.stacked;
|
|
267
|
+
const bars = this.getSortedVisibleDatasetMetas().filter((m) => m.type === meta.type && m.iAxisID === meta.iAxisID);
|
|
268
|
+
if (meta.dataset.grouped === false || this.resolved.datasets?.bar?.grouped === false) return { count: 1, at: 0 };
|
|
269
|
+
const keys = [];
|
|
270
|
+
for (const m of bars) { const k = stacked ? m.vAxisID + '|' + m.stackName : m.index; if (!keys.includes(k)) keys.push(k); }
|
|
271
|
+
const k = stacked ? meta.vAxisID + '|' + meta.stackName : meta.index;
|
|
272
|
+
return { count: Math.max(1, keys.length), at: Math.max(0, keys.indexOf(k)) };
|
|
273
|
+
}
|
|
274
|
+
ringOf(meta) {
|
|
275
|
+
const rings = this.getSortedVisibleDatasetMetas().filter((m) => m.type === meta.type).sort((a, b) => a.index - b.index);
|
|
276
|
+
let before = 0, total = 0;
|
|
277
|
+
for (const m of rings) { const w = m.dataset.weight ?? 1; if (m.index < meta.index) before += w; total += w; }
|
|
278
|
+
return { before, weight: meta.dataset.weight ?? 1, total: total || 1 };
|
|
279
|
+
}
|
|
280
|
+
_stack() {
|
|
281
|
+
for (const m of this.metas) { m.stack = null; m.stackMode = null; m.shares = null; }
|
|
282
|
+
const groups = new Map();
|
|
283
|
+
for (const m of this.getSortedVisibleDatasetMetas()) {
|
|
284
|
+
if (ROUND.has(m.type) || m.type === 'radar' || m.type === 'bubble' || m.type === 'scatter' || !m.controller.stack) continue;
|
|
285
|
+
const vx = this.scales[m.vAxisID];
|
|
286
|
+
if (!vx?.options.stacked) continue;
|
|
287
|
+
const key = m.vAxisID + '|' + m.iAxisID + '|' + (m.controller.element === 'point' ? '__line' + (m.dataset.stack ?? '') : m.stackName);
|
|
288
|
+
if (!groups.has(key)) groups.set(key, []);
|
|
289
|
+
groups.get(key).push(m);
|
|
290
|
+
}
|
|
291
|
+
for (const [, list] of groups) {
|
|
292
|
+
const how = this.scales[list[0].vAxisID].options.stacked;
|
|
293
|
+
// percent (Highcharts's stacking: 'percent', ApexCharts's stackType: '100%'), expand (0 … 1),
|
|
294
|
+
// and stream: a streamgraph's layers around a middle line
|
|
295
|
+
if (how === 'percent' || how === '100%' || how === 'expand' || how === 'stream') {
|
|
296
|
+
const totals = new Map(), at = new Map();
|
|
297
|
+
for (const m of list) for (const p of m.parsed) if (Number.isFinite(p.value)) totals.set(p.index, (totals.get(p.index) ?? 0) + Math.abs(p.value));
|
|
298
|
+
for (const m of list.sort((a, b) => a.order - b.order || a.index - b.index)) {
|
|
299
|
+
m.stackMode = how;
|
|
300
|
+
m.shares = m.parsed.map((p) => (Number.isFinite(p.value) ? (Math.abs(p.value) / (totals.get(p.index) || 1)) * 100 : NaN));
|
|
301
|
+
m.stack = m.parsed.map((p, i) => {
|
|
302
|
+
if (!Number.isFinite(p.value)) return null;
|
|
303
|
+
const tot = totals.get(p.index) || 1, a = at.has(p.index) ? at.get(p.index) : how === 'stream' ? -tot / 2 : 0;
|
|
304
|
+
const v = how === 'stream' ? Math.abs(p.value) : how === 'expand' ? m.shares[i] / 100 : m.shares[i];
|
|
305
|
+
at.set(p.index, a + v);
|
|
306
|
+
return [a, a + v];
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
311
|
+
const up = new Map(), down = new Map(), single = list.some((m) => this.scales[m.vAxisID].options.stacked === 'single');
|
|
312
|
+
for (const m of list.sort((a, b) => a.order - b.order || a.index - b.index)) {
|
|
313
|
+
m.stack = m.parsed.map((p) => {
|
|
314
|
+
if (!Number.isFinite(p.value)) return null;
|
|
315
|
+
const map = single || p.value >= 0 ? up : down, a = map.get(p.index) ?? 0, b = a + p.value;
|
|
316
|
+
map.set(p.index, b);
|
|
317
|
+
return [a, b];
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// ── scales ────────────────────────────────────────────────────────────────────
|
|
324
|
+
_buildScales() {
|
|
325
|
+
const o = this.resolved, want = new Map();
|
|
326
|
+
const labels = this.data.labels ?? [];
|
|
327
|
+
for (const m of this.metas) {
|
|
328
|
+
if (m.iAxisID == null) continue;
|
|
329
|
+
if (m.iAxisID === 'r') { want.set('r', { type: 'radialLinear', axis: 'r' }); continue; }
|
|
330
|
+
const indexType = m.type === 'scatter' || m.type === 'bubble' ? 'linear' : labels.length || (m.dataset.data ?? []).some((v) => typeof v === 'number' || v == null) ? 'category' : 'linear';
|
|
331
|
+
const ia = m.indexAxis, va = ia === 'y' ? 'x' : 'y', extra = m.controller.scales?.(m, this) ?? {};
|
|
332
|
+
if (!want.has(m.iAxisID)) want.set(m.iAxisID, { type: indexType, axis: ia, offset: m.type === 'bar' || undefined, ...extra.index });
|
|
333
|
+
else { if (m.type === 'bar') want.get(m.iAxisID).offset = true; if (extra.index) Object.assign(want.get(m.iAxisID), extra.index); }
|
|
334
|
+
if (!want.has(m.vAxisID)) want.set(m.vAxisID, { type: 'linear', axis: va, ...(m.type === 'bar' ? { beginAtZero: true } : {}), ...extra.value });
|
|
335
|
+
else if (extra.value) Object.assign(want.get(m.vAxisID), extra.value);
|
|
336
|
+
}
|
|
337
|
+
for (const id in o.scales ?? {}) if (!want.has(id) && o.scales[id]?.display !== undefined || (!want.has(id) && o.scales[id]?.type)) want.set(id, { type: o.scales[id].type ?? 'linear', axis: o.scales[id].axis ?? (id[0] === 'y' ? 'y' : id[0] === 'r' ? 'r' : 'x') });
|
|
338
|
+
const old = this.scales;
|
|
339
|
+
this.scales = {};
|
|
340
|
+
for (const [id, base] of want) {
|
|
341
|
+
const opts = merge({ ticks: {}, grid: {}, border: {}, title: {} }, base, o.scales?.[id] ?? {});
|
|
342
|
+
if (o.sparkline && o.scales?.[id]?.display == null) opts.display = false;
|
|
343
|
+
// a zoomed or panned range (zoom, pan, the navigator, a range selector, a brush)
|
|
344
|
+
const v = this._view?.[id];
|
|
345
|
+
if (v) { if (v.min != null) opts.min = v.min; if (v.max != null) opts.max = v.max; }
|
|
346
|
+
if (opts.type === 'time' || opts.type === 'timeseries') opts.offset = opts.offset ?? base.offset ?? false;
|
|
347
|
+
if (opts.type === 'category') opts.offset = opts.offset ?? !!base.offset;
|
|
348
|
+
const Cls = registry.scales[opts.type] ?? (opts.type === 'radialLinear' ? RadialAxis : Axis);
|
|
349
|
+
const ax = old[id]?.constructor === Cls && old[id].type === opts.type ? Object.assign(old[id], { options: opts, type: opts.type, axis: opts.axis ?? old[id].axis, position: opts.position ?? old[id].position }) : new Cls(id, opts, this);
|
|
350
|
+
if (opts.position) ax.position = opts.position;
|
|
351
|
+
ax.offset = !!opts.offset;
|
|
352
|
+
this.scales[id] = ax;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// ── layout ────────────────────────────────────────────────────────────────────
|
|
357
|
+
_size() {
|
|
358
|
+
const o = this.resolved;
|
|
359
|
+
const cw = this.container.clientWidth || this._lastWidth || 0;
|
|
360
|
+
let w = this._fixedWidth ?? (o.responsive === false && this.canvas?.getAttribute('width') ? Number(this.canvas.getAttribute('width')) : cw) ?? 0;
|
|
361
|
+
if (!w) w = Number(this.container.getAttribute?.('width')) || 640;
|
|
362
|
+
let h = this._fixedHeight ?? (o.maintainAspectRatio === false ? this.container.clientHeight || 0 : 0);
|
|
363
|
+
if (!h) h = Math.round(w / (o.aspectRatio || 2));
|
|
364
|
+
return [Math.max(1, Math.round(w)), Math.max(1, Math.round(h))];
|
|
365
|
+
}
|
|
366
|
+
addBox(box) { this.boxes.push(box); }
|
|
367
|
+
// the largest point drawn (a bubble's radius, a line's point and its hover size), to keep inside the picture
|
|
368
|
+
_pointEdge() {
|
|
369
|
+
let r = 0;
|
|
370
|
+
for (const m of this.getSortedVisibleDatasetMetas()) {
|
|
371
|
+
if (m.controller.element !== 'point' || m.type === 'radar') continue;
|
|
372
|
+
if (m.type === 'bubble') { for (const p of m.parsed) if (Number.isFinite(p.r)) r = Math.max(r, p.r); continue; }
|
|
373
|
+
const pr = this.option(m, 'pointRadius', 0, 'radius', 3), hr = this.option(m, 'pointHoverRadius', 0, 'hoverRadius', 4);
|
|
374
|
+
r = Math.max(r, Number(pr) || 0, Number(hr) || 0);
|
|
375
|
+
}
|
|
376
|
+
return r ? r + 2 : 0;
|
|
377
|
+
}
|
|
378
|
+
_layout() {
|
|
379
|
+
const o = this.resolved, p = o.layout?.padding ?? 0, pad = typeof p === 'number' ? { left: p, top: p, right: p, bottom: p } : { left: 0, top: 0, right: 0, bottom: 0, ...p };
|
|
380
|
+
// room a type asks for beyond its plot (the depth of 3D columns)
|
|
381
|
+
const room = {};
|
|
382
|
+
for (const m of this.metas) { const r = m.controller.reserve?.(this, m); if (r) for (const k in r) room[k] = Math.max(room[k] ?? 0, r[k] ?? 0); }
|
|
383
|
+
for (const k in room) pad[k] += room[k];
|
|
384
|
+
const area = { left: pad.left, top: pad.top, right: this.width - pad.right, bottom: this.height - pad.bottom };
|
|
385
|
+
// title, subtitle and legend take their room from the edges, heaviest outermost
|
|
386
|
+
for (const b of this.boxes.sort((a, c) => (c.weight ?? 0) - (a.weight ?? 0))) {
|
|
387
|
+
if (b.position === 'chartArea') continue;
|
|
388
|
+
const horizontal = b.position === 'top' || b.position === 'bottom';
|
|
389
|
+
const size = b.size(horizontal ? area.right - area.left : area.bottom - area.top, horizontal);
|
|
390
|
+
if (!size) { b.rect = null; continue; }
|
|
391
|
+
if (b.position === 'top') { b.rect = { left: area.left, top: area.top, right: area.right, bottom: area.top + size }; area.top += size; }
|
|
392
|
+
else if (b.position === 'bottom') { b.rect = { left: area.left, top: area.bottom - size, right: area.right, bottom: area.bottom }; area.bottom -= size; }
|
|
393
|
+
else if (b.position === 'left') { b.rect = { left: area.left, top: area.top, right: area.left + size, bottom: area.bottom }; area.left += size; }
|
|
394
|
+
else { b.rect = { left: area.right - size, top: area.top, right: area.right, bottom: area.bottom }; area.right -= size; }
|
|
395
|
+
}
|
|
396
|
+
const axes = Object.values(this.scales).filter((s) => s.axis !== 'r');
|
|
397
|
+
// the axes: twice, since how high the x axis is changes how wide the y axis must be
|
|
398
|
+
// autoPadding: room for the first and last tick labels and for the biggest point, so nothing is cut at the edge
|
|
399
|
+
const edge = o.layout?.autoPadding === false ? 0 : this._pointEdge();
|
|
400
|
+
for (let pass = 0; pass < 2; pass++) {
|
|
401
|
+
const inner = { ...area };
|
|
402
|
+
let leftAxes = 0, rightAxes = 0;
|
|
403
|
+
// axes in a stack (options.stack, stackWeight) share one slot at their side, each a share of the height
|
|
404
|
+
const stackW = new Map(), weightOf = (key) => axes.filter((a) => !a.isHorizontal() && a.position + '|' + a.options.stack === key).reduce((t, a) => t + (a.options.stackWeight ?? 1), 0);
|
|
405
|
+
for (const ax of axes) if (!ax.isHorizontal()) {
|
|
406
|
+
const key = ax.options.stack != null ? ax.position + '|' + ax.options.stack : null, len = (inner.bottom - inner.top) || 100;
|
|
407
|
+
const s = ax.fit(this.painter, key ? (len * (ax.options.stackWeight ?? 1)) / weightOf(key) : len);
|
|
408
|
+
let add = s;
|
|
409
|
+
if (key) { const had = stackW.get(key) ?? 0; add = Math.max(0, s - had); stackW.set(key, Math.max(had, s)); }
|
|
410
|
+
if (ax.position === 'left') { inner.left += add; leftAxes += add; } else { inner.right -= add; rightAxes += add; }
|
|
411
|
+
}
|
|
412
|
+
for (const ax of axes) if (ax.isHorizontal()) { const s = ax.fit(this.painter, (inner.right - inner.left) || 100); if (ax.position === 'top') inner.top += s; else inner.bottom -= s; }
|
|
413
|
+
if (o.layout?.autoPadding !== false && axes.length) {
|
|
414
|
+
let needL = edge, needR = edge, needT = edge, needB = edge;
|
|
415
|
+
for (const ax of axes) {
|
|
416
|
+
if (ax.options.display === false || ax.options.ticks?.display === false || !ax.ticks.length) continue;
|
|
417
|
+
const f = ax.font();
|
|
418
|
+
if (ax.isHorizontal() && !ax.offset && !ax.rotation) { needR = Math.max(needR, this.painter.measure(ax.ticks.at(-1).label, f) / 2 - rightAxes); needL = Math.max(needL, this.painter.measure(ax.ticks[0].label, f) / 2 - leftAxes); }
|
|
419
|
+
if (!ax.isHorizontal() && !ax.offset) { needT = Math.max(needT, f.size * 0.6); needB = Math.max(needB, ax.position === 'left' || ax.position === 'right' ? f.size * 0.6 - (area.bottom - inner.bottom) : 0); }
|
|
420
|
+
}
|
|
421
|
+
inner.left += Math.max(0, needL); inner.right -= Math.max(0, needR); inner.top += Math.max(0, needT); inner.bottom -= Math.max(0, needB);
|
|
422
|
+
}
|
|
423
|
+
this.chartArea = { ...inner, width: inner.right - inner.left, height: inner.bottom - inner.top };
|
|
424
|
+
}
|
|
425
|
+
// place them, outward from the chart area
|
|
426
|
+
const c = this.chartArea; let l = c.left, r = c.right, t = c.top, bt = c.bottom;
|
|
427
|
+
const stacks = new Map();
|
|
428
|
+
for (const ax of axes) {
|
|
429
|
+
if (!ax.isHorizontal() && ax.options.stack != null) {
|
|
430
|
+
const key = ax.position + '|' + ax.options.stack;
|
|
431
|
+
let g = stacks.get(key);
|
|
432
|
+
if (!g) {
|
|
433
|
+
const members = axes.filter((a) => !a.isHorizontal() && a.position + '|' + a.options.stack === key), size = Math.max(...members.map((a) => a.size ?? 0));
|
|
434
|
+
g = { x: ax.position === 'left' ? l - size : r, size, total: members.reduce((s, a) => s + (a.options.stackWeight ?? 1), 0), placed: c.top };
|
|
435
|
+
if (ax.position === 'left') l -= size; else r += size;
|
|
436
|
+
stacks.set(key, g);
|
|
437
|
+
}
|
|
438
|
+
const gap = ax.options.stackGap ?? Math.max(12, (ax.font().size ?? 12) * 1.2 + 4), n = axes.filter((a) => !a.isHorizontal() && a.position + '|' + a.options.stack === key).length;
|
|
439
|
+
const hgt = ((c.height - gap * (n - 1)) * (ax.options.stackWeight ?? 1)) / g.total;
|
|
440
|
+
ax.setBox(g.x, g.placed, g.x + g.size, g.placed + hgt); g.placed += hgt + gap;
|
|
441
|
+
ax.buildTicks(hgt);
|
|
442
|
+
continue;
|
|
443
|
+
}
|
|
444
|
+
if (ax.position === 'left') { ax.setBox(l - ax.size, c.top, l, c.bottom); l -= ax.size; }
|
|
445
|
+
else if (ax.position === 'right') { ax.setBox(r, c.top, r + ax.size, c.bottom); r += ax.size; }
|
|
446
|
+
else if (ax.position === 'top') { ax.setBox(c.left, t - ax.size, c.right, t); t -= ax.size; }
|
|
447
|
+
else { ax.setBox(c.left, bt, c.right, bt + ax.size); bt += ax.size; }
|
|
448
|
+
ax.buildTicks(ax.isHorizontal() ? c.width : c.height);
|
|
449
|
+
}
|
|
450
|
+
if (this.scales.r) this.scales.r.setCenter(this.chartArea, Math.max(this.data.labels?.length ?? 0, ...this.metas.map((m) => m.parsed?.length ?? 0)));
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// ── update and draw ─────────────────────────────────────────────────────────
|
|
454
|
+
/**
|
|
455
|
+
* Read data and options again and draw. mode: 'none' (no animation), 'active', 'resize',
|
|
456
|
+
* 'reset' (from the starting state), 'show', 'hide', or nothing (animate).
|
|
457
|
+
*/
|
|
458
|
+
update(mode) {
|
|
459
|
+
if (this._destroyed) return;
|
|
460
|
+
this._mode = mode; this._updates = (this._updates ?? 0) + 1;
|
|
461
|
+
let o = this._resolve();
|
|
462
|
+
if (this.notify('beforeUpdate', { mode, cancelable: true }) === false) return;
|
|
463
|
+
let [w, h] = this._size();
|
|
464
|
+
// responsive rules: Highcharts's { rules: [{ condition: { maxWidth }, chartOptions }] } or ApexCharts's [{ breakpoint, options }]
|
|
465
|
+
const rule = responsiveRule(o.responsive, w, h, this);
|
|
466
|
+
if (rule) { o = this._resolve(rule); [w, h] = this._size(); }
|
|
467
|
+
this.activeRule = rule;
|
|
468
|
+
if (w !== this.width || h !== this.height) { this.width = w; this.height = h; this.painter.size(w, h); }
|
|
469
|
+
this._buildMetas();
|
|
470
|
+
this._buildScales();
|
|
471
|
+
colorize(this);
|
|
472
|
+
// a type may read its own data (candles, boxes, cells, flows …); indicators read another dataset's, so come last
|
|
473
|
+
const read = (m) => { m.parsed = m.controller.parse ? m.controller.parse(this, m, parse) : parse(this, m); m.decimated = null; };
|
|
474
|
+
for (const m of this.metas) if (!m.controller.derived) read(m);
|
|
475
|
+
for (const m of this.metas) if (m.controller.derived) read(m);
|
|
476
|
+
this.notify('afterParse');
|
|
477
|
+
this._timeseries();
|
|
478
|
+
this._stack();
|
|
479
|
+
const visible = this.getSortedVisibleDatasetMetas();
|
|
480
|
+
for (const ax of Object.values(this.scales)) ax.determineDataLimits(visible.filter((m) => m.iAxisID === ax.id || m.vAxisID === ax.id));
|
|
481
|
+
this.boxes = [];
|
|
482
|
+
this.notify('beforeLayout');
|
|
483
|
+
this._layout();
|
|
484
|
+
this.notify('afterLayout');
|
|
485
|
+
this.notify('beforeDatasetsUpdate', { mode });
|
|
486
|
+
for (const m of this.metas) {
|
|
487
|
+
this.notify('beforeDatasetUpdate', { meta: m, index: m.index, mode });
|
|
488
|
+
m.controller.update(this, m, mode);
|
|
489
|
+
if (!this.isDatasetVisible(m.index)) for (const e of m.elements) e.skip = e.hidden = true;
|
|
490
|
+
this.notify('afterDatasetUpdate', { meta: m, index: m.index, mode });
|
|
491
|
+
}
|
|
492
|
+
this.notify('afterDatasetsUpdate', { mode });
|
|
493
|
+
this.notify('afterUpdate', { mode });
|
|
494
|
+
this._animate(mode);
|
|
495
|
+
this._a11yUpdate();
|
|
496
|
+
}
|
|
497
|
+
_timeseries() {
|
|
498
|
+
for (const ax of Object.values(this.scales)) if (ax.type === 'timeseries') {
|
|
499
|
+
const all = new Set(); for (const m of this.metas) if (m.iAxisID === ax.id) for (const p of m.parsed) if (Number.isFinite(p.index)) all.add(p.index);
|
|
500
|
+
ax._series = [...all].sort((a, b) => a - b);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
_animate(mode) {
|
|
504
|
+
const o = this.resolved, anim = o.animation;
|
|
505
|
+
const off = anim === false || mode === 'none' || mode === 'active' || mode === 'resize' || !anim || anim.duration === 0 || reducedMotion.peek();
|
|
506
|
+
const keys = ['x', 'y', 'base', 'width', 'height', 'radius', 'startAngle', 'endAngle', 'innerRadius', 'outerRadius', 'cx', 'cy', 'x2', 'y2', 'open', 'high', 'low', 'close', 'q1', 'q3', 'median', 'wlo', 'whi', 'grow', 'angle'];
|
|
507
|
+
const plan = [];
|
|
508
|
+
for (const m of this.metas) for (const target of m.elements) {
|
|
509
|
+
const id = m.index + ':' + target.index, was = this._shown.get(id);
|
|
510
|
+
const from = mode === 'reset' || !was ? m.controller.initial?.(target, m, this) ?? target : was;
|
|
511
|
+
plan.push({ m, target, from, id });
|
|
512
|
+
}
|
|
513
|
+
this._stopAnim?.();
|
|
514
|
+
const commit = (t) => {
|
|
515
|
+
for (const { m, target, from, id } of plan) {
|
|
516
|
+
const e = { ...target };
|
|
517
|
+
if (t < 1) for (const k of keys) if (Number.isFinite(from[k]) && Number.isFinite(target[k])) e[k] = from[k] + (target[k] - from[k]) * t;
|
|
518
|
+
this._shown.set(id, e);
|
|
519
|
+
const list = m._current ?? (m._current = []);
|
|
520
|
+
list.length = m.elements.length;
|
|
521
|
+
list[m.elements.indexOf(target)] = e;
|
|
522
|
+
}
|
|
523
|
+
for (const m of this.metas) { m.drawn = m._current ?? m.elements; m._current = null; }
|
|
524
|
+
};
|
|
525
|
+
if (off) { commit(1); this.draw(); anim?.onComplete?.call(this, { chart: this, initial: !this._drawnOnce, numSteps: 0, currentStep: 0 }); this._drawnOnce = true; return; }
|
|
526
|
+
const duration = Math.max(1, anim.duration ?? 1000) / 1000, ease = typeof anim.easing === 'function' ? anim.easing : EASING[anim.easing] ?? EASING.easeOutQuart;
|
|
527
|
+
const delay = anim.delay ?? 0;
|
|
528
|
+
let elapsed = 0;
|
|
529
|
+
const step = (dt) => {
|
|
530
|
+
elapsed += dt;
|
|
531
|
+
const per = (p) => { const d = (typeof delay === 'function' ? delay({ chart: this, type: 'data', dataIndex: p.target.index, datasetIndex: p.m.index }) : delay) / 1000; return Math.min(1, Math.max(0, (elapsed - d) / duration)); };
|
|
532
|
+
const longest = Math.max(...plan.map((p) => (typeof delay === 'function' ? delay({ chart: this, type: 'data', dataIndex: p.target.index, datasetIndex: p.m.index }) : delay) / 1000), 0) + duration;
|
|
533
|
+
for (const p of plan) p.t = ease(per(p));
|
|
534
|
+
for (const { m, target, from, id, t } of plan) {
|
|
535
|
+
const e = { ...target };
|
|
536
|
+
if (t < 1) for (const k of keys) if (Number.isFinite(from[k]) && Number.isFinite(target[k])) e[k] = from[k] + (target[k] - from[k]) * t;
|
|
537
|
+
this._shown.set(id, e);
|
|
538
|
+
(m._current ?? (m._current = new Array(m.elements.length)))[m.elements.indexOf(target)] = e;
|
|
539
|
+
}
|
|
540
|
+
for (const m of this.metas) { m.drawn = m._current ?? m.elements; m._current = null; }
|
|
541
|
+
this.draw();
|
|
542
|
+
anim.onProgress?.call(this, { chart: this, initial: !this._drawnOnce, currentStep: elapsed, numSteps: longest });
|
|
543
|
+
if (elapsed >= longest) {
|
|
544
|
+
if (anim.loop) { elapsed = 0; return true; }
|
|
545
|
+
this._stopAnim = null; anim.onComplete?.call(this, { chart: this, initial: !this._drawnOnce, numSteps: longest, currentStep: elapsed }); this._drawnOnce = true;
|
|
546
|
+
return false;
|
|
547
|
+
}
|
|
548
|
+
return true;
|
|
549
|
+
};
|
|
550
|
+
step(0);
|
|
551
|
+
const stop = frame((dt) => { if (step(dt) === false) stop(); }, { own: false });
|
|
552
|
+
this._stopAnim = () => { stop(); this._stopAnim = null; };
|
|
553
|
+
}
|
|
554
|
+
/** Stop a running animation where it is. */
|
|
555
|
+
stop() { this._stopAnim?.(); return this; }
|
|
556
|
+
/** Draw again as things stand, without reading data and options. */
|
|
557
|
+
render() { this.draw(); }
|
|
558
|
+
/** Back to the starting state of the animations (bars at their base), then update() grows them again. */
|
|
559
|
+
reset() { this._shown.clear(); this.update('reset'); }
|
|
560
|
+
draw() {
|
|
561
|
+
if (this._destroyed) return;
|
|
562
|
+
const p = this.painter, area = this.chartArea;
|
|
563
|
+
p.clear(); p.size(this.width, this.height);
|
|
564
|
+
if (this.notify('beforeDraw', { cancelable: true }) === false) return;
|
|
565
|
+
for (const name of ['background', 'grid', 'fill', 'datasets', 'axes', 'boxes', 'over']) p.layer(name);
|
|
566
|
+
p.layer('background');
|
|
567
|
+
const bg = this.resolved.background ?? this.resolved.theme?.background;
|
|
568
|
+
if (bg) p.rect(0, 0, this.width, this.height, { fill: bg });
|
|
569
|
+
const plotBg = this.resolved.chartArea?.backgroundColor;
|
|
570
|
+
if (plotBg && area.right > area.left) p.rect(area.left, area.top, area.right - area.left, area.bottom - area.top, { fill: plotBg });
|
|
571
|
+
p.layer('grid');
|
|
572
|
+
for (const ax of Object.values(this.scales)) ax.draw(p, area);
|
|
573
|
+
const margin = 2;
|
|
574
|
+
p.layer('datasets');
|
|
575
|
+
this.clip = this.resolved.clip === false ? null : p.clipRect(area.left - margin, area.top - margin, area.right - area.left + margin * 2, area.bottom - area.top + margin * 2);
|
|
576
|
+
p.layer('fill');
|
|
577
|
+
if (this.notify('beforeDatasetsDraw', { cancelable: true }) !== false) {
|
|
578
|
+
p.layer('datasets');
|
|
579
|
+
// lower `order` is drawn last, on top
|
|
580
|
+
for (const m of this.getSortedVisibleDatasetMetas().slice().reverse()) {
|
|
581
|
+
if (this.notify('beforeDatasetDraw', { meta: m, index: m.index, cancelable: true }) === false) continue;
|
|
582
|
+
const keep = m.elements; m.elements = m.drawn ?? m.elements;
|
|
583
|
+
p.layer('datasets');
|
|
584
|
+
m.controller.draw(p, m, this);
|
|
585
|
+
m.elements = keep;
|
|
586
|
+
this.notify('afterDatasetDraw', { meta: m, index: m.index });
|
|
587
|
+
}
|
|
588
|
+
this.notify('afterDatasetsDraw');
|
|
589
|
+
}
|
|
590
|
+
p.layer('boxes');
|
|
591
|
+
for (const b of this.boxes) if (b.rect || b.position === 'chartArea') b.draw(p, b.rect ?? area);
|
|
592
|
+
p.layer('over');
|
|
593
|
+
this.notify('afterDraw');
|
|
594
|
+
this._shownElements = this.metas.map((m) => m.drawn ?? m.elements);
|
|
595
|
+
}
|
|
596
|
+
/** Change the size by hand (a responsive chart follows its container by itself). */
|
|
597
|
+
resize(width, height) {
|
|
598
|
+
this._fixedWidth = width ?? undefined; this._fixedHeight = height ?? undefined;
|
|
599
|
+
const before = [this.width, this.height];
|
|
600
|
+
this.update('resize');
|
|
601
|
+
if (before[0] !== this.width || before[1] !== this.height) { this.notify('resize', { size: { width: this.width, height: this.height } }); this.resolved.onResize?.(this, { width: this.width, height: this.height }); }
|
|
602
|
+
}
|
|
603
|
+
clear() { this.painter.clear(); return this; }
|
|
604
|
+
destroy() {
|
|
605
|
+
if (this._destroyed) return;
|
|
606
|
+
this.notify('beforeDestroy');
|
|
607
|
+
this._stopAnim?.(); this._ro?.disconnect();
|
|
608
|
+
for (const [t, f] of this._listeners ?? []) this.surface.removeEventListener(t, f);
|
|
609
|
+
this._tipEl?.remove(); this._a11yEl?.remove();
|
|
610
|
+
if (this.svg) this.svg.remove(); else if (this.canvas && this.canvas.parentElement === this.container && this._madeCanvas) this.canvas.remove(); else this.painter.clear();
|
|
611
|
+
delete Chart.instances[this.id];
|
|
612
|
+
this._destroyed = true;
|
|
613
|
+
this.notify('afterDestroy'); this.notify('uninstall');
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
// ── plugins ───────────────────────────────────────────────────────────────────
|
|
617
|
+
/** Call a hook on every plugin; a plugin that returns false from a cancelable hook stops it. */
|
|
618
|
+
notify(hook, args = {}) {
|
|
619
|
+
const off = this.config.options?.plugins ?? {};
|
|
620
|
+
let ok = true;
|
|
621
|
+
for (const p of this._plugins ?? []) {
|
|
622
|
+
if (typeof p[hook] !== 'function') continue;
|
|
623
|
+
if (off[p.id] === false) continue;
|
|
624
|
+
const r = p[hook](this, args, this.resolved?.plugins?.[p.id] ?? {});
|
|
625
|
+
if (r === false && args.cancelable) ok = false;
|
|
626
|
+
}
|
|
627
|
+
return ok;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
// ── interaction ─────────────────────────────────────────────────────────────
|
|
631
|
+
isActive(d, i) { return this._active.some((a) => a.datasetIndex === d && a.index === i); }
|
|
632
|
+
getActiveElements() { return this._active.map((a) => ({ ...a, element: this._elementAt(a.datasetIndex, a.index) })); }
|
|
633
|
+
setActiveElements(list) { this._active = (list ?? []).map((a) => ({ datasetIndex: a.datasetIndex, index: a.index })); this.draw(); this._tip?.(); }
|
|
634
|
+
_elementAt(d, i) { const els = this._shownElements?.[d] ?? this.metas[d]?.elements ?? []; return els.find((e) => e.index === i) ?? null; }
|
|
635
|
+
isPointInArea(p) { const a = this.chartArea; return p.x >= a.left - 0.5 && p.x <= a.right + 0.5 && p.y >= a.top - 0.5 && p.y <= a.bottom + 0.5; }
|
|
636
|
+
/**
|
|
637
|
+
* The elements an event points at, by Chart.js's modes: 'point', 'nearest', 'index', 'dataset',
|
|
638
|
+
* 'x', 'y'. options: { intersect, axis: 'x' | 'y' | 'xy' | 'r', includeInvisible }.
|
|
639
|
+
* → [{ element, datasetIndex, index }]
|
|
640
|
+
*/
|
|
641
|
+
getElementsAtEventForMode(e, mode = 'nearest', options = {}, useFinal = false) {
|
|
642
|
+
const pos = e && 'x' in e && !('clientX' in e && !('native' in e)) ? { x: e.x, y: e.y } : this._pos(e);
|
|
643
|
+
const intersect = options.intersect ?? true, axis = options.axis ?? 'xy';
|
|
644
|
+
const all = [];
|
|
645
|
+
this.metas.forEach((m, d) => { if (!this.isDatasetVisible(d) && !options.includeInvisible) return; for (const el of (useFinal ? m.elements : this._shownElements?.[d] ?? m.elements)) if (!el.skip) all.push({ element: el, datasetIndex: d, index: el.index }); });
|
|
646
|
+
const dist = (el) => { const c = centerOf(el); return axis === 'x' ? Math.abs(c.x - pos.x) : axis === 'y' ? Math.abs(c.y - pos.y) : Math.hypot(c.x - pos.x, c.y - pos.y); };
|
|
647
|
+
const hits = all.filter((h) => inRange(h.element, pos.x, pos.y));
|
|
648
|
+
if (mode === 'point') return hits;
|
|
649
|
+
if (mode === 'x' || mode === 'y') return all.filter((h) => inAxisRange(h.element, mode, mode === 'x' ? pos.x : pos.y));
|
|
650
|
+
let pool = intersect ? hits : all.filter((h) => this.isPointInArea(pos) || h.element.kind === 'arc');
|
|
651
|
+
if (!pool.length) return [];
|
|
652
|
+
if (mode === 'nearest') { const best = Math.min(...pool.map((h) => dist(h.element))); return pool.filter((h) => Math.abs(dist(h.element) - best) < 1e-6).slice(0, axis === 'xy' ? 1 : undefined); }
|
|
653
|
+
const nearest = pool.reduce((a, b) => (dist(b.element) < dist(a.element) ? b : a));
|
|
654
|
+
if (mode === 'dataset') return all.filter((h) => h.datasetIndex === nearest.datasetIndex);
|
|
655
|
+
if (mode === 'index') return all.filter((h) => h.index === nearest.index);
|
|
656
|
+
return [nearest];
|
|
657
|
+
}
|
|
658
|
+
_pos(e) {
|
|
659
|
+
const b = this.surface.getBoundingClientRect?.() ?? { left: 0, top: 0, width: this.width, height: this.height };
|
|
660
|
+
const sx = b.width ? this.width / b.width : 1, sy = b.height ? this.height / b.height : 1;
|
|
661
|
+
return { x: (e.clientX - b.left) * sx, y: (e.clientY - b.top) * sy };
|
|
662
|
+
}
|
|
663
|
+
_listen() {
|
|
664
|
+
const s = this.surface, o = () => this.resolved ?? defaults;
|
|
665
|
+
const handle = (native, type) => {
|
|
666
|
+
if (!(o().events ?? defaults.events).includes(type) && type !== 'keyboard') return;
|
|
667
|
+
const { x, y } = this._pos(native), event = { type, x, y, native, chart: this };
|
|
668
|
+
if (this.notify('beforeEvent', { event, cancelable: true, inChartArea: this.isPointInArea(event) }) === false) return;
|
|
669
|
+
const box = this.boxes.find((b) => b.rect && b.handle && x >= b.rect.left && x <= b.rect.right && y >= b.rect.top && y <= b.rect.bottom);
|
|
670
|
+
if (box?.handle(event)) { this.notify('afterEvent', { event }); return; }
|
|
671
|
+
const hov = o().hover ?? {}, inter = o().interaction ?? {};
|
|
672
|
+
const els = type === 'mouseout' ? [] : this.getElementsAtEventForMode(event, hov.mode ?? inter.mode, { intersect: hov.intersect ?? inter.intersect, axis: hov.axis ?? inter.axis });
|
|
673
|
+
const changed = els.length !== this._active.length || els.some((a, k) => a.datasetIndex !== this._active[k]?.datasetIndex || a.index !== this._active[k]?.index);
|
|
674
|
+
if (changed) { this._active = els.map((a) => ({ datasetIndex: a.datasetIndex, index: a.index })); this._mode = 'active'; this.draw(); }
|
|
675
|
+
this.notify('tooltipEvent', { event, elements: els });
|
|
676
|
+
if (type === 'mousemove') o().onHover?.call(this, event, els, this);
|
|
677
|
+
if (type === 'click') o().onClick?.call(this, event, els, this);
|
|
678
|
+
s.style.cursor = (o().onClick && els.length) || box ? 'pointer' : '';
|
|
679
|
+
this.notify('afterEvent', { event, changed });
|
|
680
|
+
};
|
|
681
|
+
const on = (t, f) => { s.addEventListener(t, f); (this._listeners ??= []).push([t, f]); };
|
|
682
|
+
on('pointermove', (e) => handle(e, e.pointerType === 'touch' ? 'touchmove' : 'mousemove'));
|
|
683
|
+
on('pointerdown', (e) => { if (e.pointerType === 'touch') handle(e, 'touchstart'); });
|
|
684
|
+
on('pointerleave', (e) => handle(e, 'mouseout'));
|
|
685
|
+
on('click', (e) => handle(e, 'click'));
|
|
686
|
+
// the keyboard: arrows go along the points, Enter is a click
|
|
687
|
+
on('keydown', (e) => {
|
|
688
|
+
const flat = this._keyOrder();
|
|
689
|
+
if (!flat.length) return;
|
|
690
|
+
let k = this._key ?? -1;
|
|
691
|
+
if (e.key === 'ArrowRight' || e.key === 'ArrowDown') k = Math.min(flat.length - 1, k + 1);
|
|
692
|
+
else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') k = k < 0 ? flat.length - 1 : Math.max(0, k - 1);
|
|
693
|
+
else if (e.key === 'Home') k = 0; else if (e.key === 'End') k = flat.length - 1;
|
|
694
|
+
else if (e.key === 'Escape') { this._key = -1; this.setActiveElements([]); return; }
|
|
695
|
+
else if (e.key === 'Enter' && k >= 0) { const els = this.getActiveElements(); o().onClick?.call(this, { type: 'click', native: e, chart: this, x: 0, y: 0 }, els, this); return; }
|
|
696
|
+
else return;
|
|
697
|
+
e.preventDefault();
|
|
698
|
+
this._key = k;
|
|
699
|
+
const mode = o().interaction?.mode;
|
|
700
|
+
const pick = flat[k];
|
|
701
|
+
this.setActiveElements(mode === 'index' ? this.metas.filter((m, d) => this.isDatasetVisible(d)).map((m) => ({ datasetIndex: m.index, index: pick.index })).filter((a) => this._elementAt(a.datasetIndex, a.index) && !this._elementAt(a.datasetIndex, a.index).skip) : [pick]);
|
|
702
|
+
});
|
|
703
|
+
on('blur', () => { this._key = -1; if (this._active.length) this.setActiveElements([]); });
|
|
704
|
+
if (typeof ResizeObserver === 'function' && (this.config.options.responsive ?? true)) {
|
|
705
|
+
let t = 0;
|
|
706
|
+
this._ro = new ResizeObserver((entries) => {
|
|
707
|
+
const w = Math.round(entries[0].contentRect.width);
|
|
708
|
+
if (!w || w === this._lastWidth) return;
|
|
709
|
+
this._lastWidth = w;
|
|
710
|
+
const delay = this.resolved?.resizeDelay ?? 0, go = () => this.resize();
|
|
711
|
+
if (delay) { clearTimeout(t); t = setTimeout(go, delay); } else go();
|
|
712
|
+
});
|
|
713
|
+
this._ro.observe(this.container);
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
_keyOrder() {
|
|
717
|
+
const mode = this.resolved?.interaction?.mode;
|
|
718
|
+
const metas = this.getSortedVisibleDatasetMetas();
|
|
719
|
+
if (mode === 'index' && metas.length) { const first = metas[0]; return (this._shownElements?.[first.index] ?? first.elements).filter((e) => !e.skip).map((e) => ({ datasetIndex: first.index, index: e.index })); }
|
|
720
|
+
return metas.flatMap((m) => (this._shownElements?.[m.index] ?? m.elements).filter((e) => !e.skip).map((e) => ({ datasetIndex: m.index, index: e.index })));
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
// ── for screen readers: a sentence on the picture, the numbers as a table ────────
|
|
724
|
+
_a11y() {
|
|
725
|
+
const s = this.surface;
|
|
726
|
+
s.setAttribute('role', 'img'); s.setAttribute('tabindex', '0');
|
|
727
|
+
if (this.canvas && !this.canvas.textContent) this.canvas.textContent = '';
|
|
728
|
+
const box = document.createElement('div');
|
|
729
|
+
const hide = { position: 'absolute', width: '1px', height: '1px', padding: '0', margin: '-1px', overflow: 'hidden', clip: 'rect(0 0 0 0)', whiteSpace: 'nowrap', border: '0' };
|
|
730
|
+
for (const k in hide) box.style[k] = hide[k];
|
|
731
|
+
box.className = 'clarity-chart-a11y';
|
|
732
|
+
this.container.appendChild(box);
|
|
733
|
+
this._a11yEl = box;
|
|
734
|
+
}
|
|
735
|
+
_a11yUpdate() {
|
|
736
|
+
if (!this._a11yEl) return;
|
|
737
|
+
const title = [this.resolved.plugins?.title?.text].flat().filter(Boolean).join(' ');
|
|
738
|
+
this.surface.setAttribute('aria-label', describe(this, title));
|
|
739
|
+
const t = document.createElement('table'), cap = document.createElement('caption');
|
|
740
|
+
cap.textContent = title || 'Chart data'; t.appendChild(cap);
|
|
741
|
+
const head = document.createElement('tr'), labels = this.data.labels ?? [];
|
|
742
|
+
const cell = (tag, text, row) => { const c = document.createElement(tag); c.textContent = text; row.appendChild(c); };
|
|
743
|
+
cell('th', '', head);
|
|
744
|
+
for (const m of this.metas) cell('th', m.label || `Dataset ${m.index + 1}`, head);
|
|
745
|
+
t.appendChild(head);
|
|
746
|
+
const n = Math.min(500, Math.max(labels.length, ...this.metas.map((m) => m.parsed.length)));
|
|
747
|
+
for (let i = 0; i < n; i++) {
|
|
748
|
+
const row = document.createElement('tr');
|
|
749
|
+
cell('th', String(labels[i] ?? this.metas[0]?.parsed[i]?.name ?? this.metas[0]?.parsed[i]?.raw?.x ?? i + 1), row);
|
|
750
|
+
for (const m of this.metas) { const p = m.parsed[i]; cell('td', p && Number.isFinite(p.value) ? formatNumber(p.value, { locale: this.resolved.locale }) : '', row); }
|
|
751
|
+
t.appendChild(row);
|
|
752
|
+
}
|
|
753
|
+
let holder = this._a11yEl.querySelector('.clarity-chart-table');
|
|
754
|
+
if (!holder) { holder = document.createElement('div'); holder.className = 'clarity-chart-table'; this._a11yEl.appendChild(holder); }
|
|
755
|
+
holder.replaceChildren(t);
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
// ── views: zoom, pan, the navigator, a range selector and a brush all set these ─────
|
|
759
|
+
/** Show part of an axis: setView('x', min, max), values as the axis reads them (null leaves that end free). */
|
|
760
|
+
setView(id, min, max, { mode = 'none', silent = false } = {}) {
|
|
761
|
+
(this._view ??= {})[id] = { min: min ?? null, max: max ?? null };
|
|
762
|
+
this.update(mode);
|
|
763
|
+
if (!silent) this.notify('viewChanged', { id });
|
|
764
|
+
return this;
|
|
765
|
+
}
|
|
766
|
+
/** What an axis shows ({ min, max }) and the whole range of its data ({ dataMin, dataMax }). */
|
|
767
|
+
getView(id) { const ax = this.scales[id]; return ax ? { min: ax.min, max: ax.max, dataMin: ax.dataMin, dataMax: ax.dataMax } : null; }
|
|
768
|
+
/** Every axis back to its whole range. */
|
|
769
|
+
resetView(mode = 'none') { this._view = null; this._mapView = null; this._mapRotate = null; this.update(mode); this.notify('viewChanged', {}); return this; }
|
|
770
|
+
isZoomedOrPanned() { return (!!this._view && Object.keys(this._view).length > 0) || !!this._mapView; }
|
|
771
|
+
/** Zoom in (> 1) or out (< 1) about the middle, or to { x: [min, max], y: [min, max] }; mode 'x' | 'y' | 'xy'. */
|
|
772
|
+
zoom(amount, mode) { need('zoomBy')(this, amount, mode); return this; }
|
|
773
|
+
/** Move the view by pixels: pan({ x: -40 }). */
|
|
774
|
+
pan(delta, mode) { need('panBy')(this, delta, mode); return this; }
|
|
775
|
+
resetZoom(mode) { return this.resetView(mode); }
|
|
776
|
+
zoomScale(id, range, mode) { return this.setView(id, range?.min, range?.max, { mode: mode ?? 'none' }); }
|
|
777
|
+
/** How far in the view is: the whole range over what is shown (1 when not zoomed). */
|
|
778
|
+
getZoomLevel() { let z = 1; for (const ax of Object.values(this.scales)) if (Number.isFinite(ax.dataMin) && ax.max > ax.min && ax.dataMax > ax.dataMin) z = Math.max(z, (ax.dataMax - ax.dataMin) / (ax.max - ax.min)); return z; }
|
|
779
|
+
|
|
780
|
+
// ── data that keeps coming ───────────────────────────────────────────────────────
|
|
781
|
+
/**
|
|
782
|
+
* Add a point to a dataset, as Highcharts's addPoint: shift drops the first (the marks slide
|
|
783
|
+
* along), maxPoints keeps no more than that many; label adds a label for a category axis.
|
|
784
|
+
*/
|
|
785
|
+
addPoint(datasetIndex, point, { label, shift = false, maxPoints, mode } = {}) {
|
|
786
|
+
const ds = this.data.datasets?.[datasetIndex];
|
|
787
|
+
if (!ds) return this;
|
|
788
|
+
(ds.data ??= []).push(point);
|
|
789
|
+
const labels = this.data.labels, withLabel = label !== undefined && Array.isArray(labels);
|
|
790
|
+
if (withLabel) labels.push(label);
|
|
791
|
+
const max = maxPoints ?? ds.maxPoints;
|
|
792
|
+
if (shift || (max && ds.data.length > max)) { ds.data.shift(); if (withLabel) labels.shift(); this._slide(withLabel ? null : datasetIndex); }
|
|
793
|
+
this.update(mode);
|
|
794
|
+
return this;
|
|
795
|
+
}
|
|
796
|
+
/** New data at the end of each dataset, as ApexCharts's appendData: [{ data: [...] }, …] by position. */
|
|
797
|
+
appendData(list, { labels, maxPoints, mode } = {}) {
|
|
798
|
+
let slid = 0;
|
|
799
|
+
(list ?? []).forEach((item, d) => {
|
|
800
|
+
const ds = this.data.datasets?.[d]; if (!ds) return;
|
|
801
|
+
(ds.data ??= []).push(...(item?.data ?? item ?? []));
|
|
802
|
+
const max = maxPoints ?? ds.maxPoints;
|
|
803
|
+
if (max && ds.data.length > max) { const k = ds.data.length - max; ds.data.splice(0, k); slid = Math.max(slid, k); if (!labels) for (let j = 0; j < k; j++) this._slide(d); }
|
|
804
|
+
});
|
|
805
|
+
if (labels && Array.isArray(this.data.labels)) { this.data.labels.push(...labels); const max = maxPoints; if (max && this.data.labels.length > max) { const k = this.data.labels.length - max; this.data.labels.splice(0, k); for (let j = 0; j < k; j++) this._slide(null); } }
|
|
806
|
+
this.update(mode);
|
|
807
|
+
return this;
|
|
808
|
+
}
|
|
809
|
+
// the marks shown move down one place, so they slide along rather than jump
|
|
810
|
+
_slide(d) {
|
|
811
|
+
const next = new Map();
|
|
812
|
+
for (const [id, e] of this._shown) { const [di, i] = id.split(':').map(Number); if (d == null || di === d) { if (i > 0) next.set(di + ':' + (i - 1), e); } else next.set(id, e); }
|
|
813
|
+
this._shown = next;
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
// ── a view to come back to, the data as a file, the data as sound ─────────────────
|
|
817
|
+
/** The view as a short token (zoom, hidden datasets and points, drilldown): put it in a URL. */
|
|
818
|
+
saveView() { return need('viewToken')(this); }
|
|
819
|
+
/** Back to a view saveView() gave. */
|
|
820
|
+
restoreView(token, mode = 'none') { need('applyViewToken')(this, token); this.update(mode); return this; }
|
|
821
|
+
/** The data as CSV: a row per label (or x), a column per dataset. */
|
|
822
|
+
toCSV(options) { return need('toCSV')(this, options); }
|
|
823
|
+
/** The picture as an SVG string, from either kind of chart. */
|
|
824
|
+
toSVG() { return this.svg ? serialize(this) : renderToSVG(this.config, { width: this.width, height: this.height }); }
|
|
825
|
+
/** Save the picture or the data as a file: 'png', 'jpeg', 'svg' or 'csv'. */
|
|
826
|
+
async download(format = 'png', filename = 'chart') {
|
|
827
|
+
const f = String(format).toLowerCase();
|
|
828
|
+
const url = f === 'svg' ? 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(this.toSVG()) : f === 'csv' ? 'data:text/csv;charset=utf-8,' + encodeURIComponent(this.toCSV()) : await this.toImage(f === 'jpg' || f === 'jpeg' ? 'image/jpeg' : 'image/png');
|
|
829
|
+
const a = document.createElement('a'); a.href = url; a.download = `${filename}.${f === 'jpeg' ? 'jpg' : f}`; document.body.appendChild(a); a.click(); a.remove();
|
|
830
|
+
return url;
|
|
831
|
+
}
|
|
832
|
+
/**
|
|
833
|
+
* Hear the data: each dataset in turn as rising and falling notes (higher for larger values,
|
|
834
|
+
* left to right across the stereo field), each point shown as it sounds.
|
|
835
|
+
* → { notes, stop(), done }
|
|
836
|
+
*/
|
|
837
|
+
sonify(options) { return need('sonify')(this, options); }
|
|
838
|
+
/** Into a point's drilldown series (as a click on it does), and back out. */
|
|
839
|
+
drillDown(datasetIndex, index) { return need('drillDown')(this, datasetIndex, index); }
|
|
840
|
+
drillUp() { return need('drillUp')(this); }
|
|
841
|
+
|
|
842
|
+
// ── pictures ──────────────────────────────────────────────────────────────────
|
|
843
|
+
/** The picture as a data URL: a PNG (or `type`) from a canvas; an SVG from an SVG chart (use toImage() for a PNG). */
|
|
844
|
+
toBase64Image(type = 'image/png', quality = 1) {
|
|
845
|
+
if (this.canvas) return this.canvas.toDataURL(type, quality);
|
|
846
|
+
const text = serialize(this);
|
|
847
|
+
return 'data:image/svg+xml;base64,' + (typeof btoa === 'function' ? btoa(unescape(encodeURIComponent(text))) : Buffer.from(text).toString('base64'));
|
|
848
|
+
}
|
|
849
|
+
/** The picture as a PNG (or JPEG, WebP) data URL, from either kind of chart. */
|
|
850
|
+
async toImage(type = 'image/png', quality = 1, scale = 2) {
|
|
851
|
+
if (this.canvas) return this.canvas.toDataURL(type, quality);
|
|
852
|
+
const img = new Image(); img.src = this.toBase64Image();
|
|
853
|
+
await img.decode();
|
|
854
|
+
const c = document.createElement('canvas'); c.width = this.width * scale; c.height = this.height * scale;
|
|
855
|
+
const g = c.getContext('2d'); g.scale(scale, scale); g.drawImage(img, 0, 0);
|
|
856
|
+
return c.toDataURL(type, quality);
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
// an SVG standing on its own: CSS variables replaced by what they are on the page
|
|
861
|
+
function serialize(chart) {
|
|
862
|
+
const svg = chart.svg.cloneNode(true), cs = (globalThis.getComputedStyle ?? chart.svg.ownerDocument?.defaultView?.getComputedStyle)?.(chart.container);
|
|
863
|
+
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
|
|
864
|
+
const fix = (v) => v?.replace(/var\(\s*(--[\w-]+)\s*(?:,\s*([^)]+))?\)/g, (_, name, fb) => cs?.getPropertyValue(name).trim() || fb || '#666');
|
|
865
|
+
for (const el of svg.querySelectorAll('*')) for (const a of ['fill', 'stroke', 'stop-color']) if (el.getAttribute(a)?.includes('var(')) el.setAttribute(a, fix(el.getAttribute(a)));
|
|
866
|
+
const XS = globalThis.XMLSerializer ?? chart.svg.ownerDocument?.defaultView?.XMLSerializer;
|
|
867
|
+
return new XS().serializeToString(svg);
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
/** A sentence on what a chart shows: its type, its datasets, and for each where it starts, ends, peaks and dips. */
|
|
871
|
+
export function describe(chart, title = '') {
|
|
872
|
+
const names = { line: 'Line chart', bar: 'Bar chart', pie: 'Pie chart', doughnut: 'Doughnut chart', polarArea: 'Polar area chart', radar: 'Radar chart', scatter: 'Scatter chart', bubble: 'Bubble chart' };
|
|
873
|
+
const labels = chart.data.labels ?? [], fmt = (v) => formatNumber(v, { locale: chart.resolved?.locale });
|
|
874
|
+
const parts = chart.metas.filter((m) => chart.isDatasetVisible(m.index)).map((m) => {
|
|
875
|
+
if (m.controller.describe) return m.controller.describe(chart, m, fmt);
|
|
876
|
+
const vals = m.parsed.map((p, i) => [p.value, i]).filter((q) => Number.isFinite(q[0]));
|
|
877
|
+
if (!vals.length) return `${m.label || 'Dataset ' + (m.index + 1)}: no values`;
|
|
878
|
+
const ix = chart.scales[m.iAxisID], timeAxis = ix?.type?.startsWith('time');
|
|
879
|
+
const hi = vals.reduce((a, b) => (b[0] > a[0] ? b : a)), lo = vals.reduce((a, b) => (b[0] < a[0] ? b : a)), name = (i) => String(m.parsed[i]?.name ?? labels[i] ?? (timeAxis && Number.isFinite(m.parsed[i]?.index) ? formatTime(m.parsed[i].index, 'MMM d, yyyy') : m.parsed[i]?.raw?.x) ?? i + 1);
|
|
880
|
+
if (ROUND.has(m.type) || m.controller.legend === 'points') { const sum = vals.reduce((a, q) => a + q[0], 0) || 1; return `${m.label ? m.label + ': ' : ''}${vals.map((q) => `${name(q[1])} ${Math.round((q[0] / sum) * 100)}%`).join(', ')}`; }
|
|
881
|
+
return `${m.label ? m.label + ': ' : ''}from ${fmt(vals[0][0])} to ${fmt(vals.at(-1)[0])}, highest ${fmt(hi[0])} at ${name(hi[1])}, lowest ${fmt(lo[0])} at ${name(lo[1])}`;
|
|
882
|
+
});
|
|
883
|
+
return `${title ? title + '. ' : ''}${names[chart.type] ?? registry.controllers[chart.type]?.name ?? 'Chart'}. ${parts.join('. ')}.`;
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
// the options of the first responsive rule that fits the size (later rules add to it)
|
|
887
|
+
function responsiveRule(spec, w, h, chart) {
|
|
888
|
+
const rules = Array.isArray(spec) ? spec.slice().sort((a, b) => (b.breakpoint ?? 0) - (a.breakpoint ?? 0)).map((r) => ({ condition: { maxWidth: r.breakpoint }, chartOptions: r.options })) : spec && typeof spec === 'object' ? spec.rules ?? [] : [];
|
|
889
|
+
let out = null;
|
|
890
|
+
for (const r of rules) {
|
|
891
|
+
const c = r.condition ?? {};
|
|
892
|
+
const ok = (c.maxWidth == null || w <= c.maxWidth) && (c.minWidth == null || w >= c.minWidth) && (c.maxHeight == null || h <= c.maxHeight) && (c.minHeight == null || h >= c.minHeight) && (typeof c.callback !== 'function' || c.callback.call(chart, { width: w, height: h }));
|
|
893
|
+
if (ok) out = merge(out ?? {}, r.chartOptions ?? r.options ?? {});
|
|
894
|
+
}
|
|
895
|
+
return out;
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
/**
|
|
899
|
+
* A chart drawn as an SVG string, with no page (a server, an e-mail, a file): the same config.
|
|
900
|
+
* renderToSVG(config, { width: 640, height: 320 }) → '<svg …>…</svg>'
|
|
901
|
+
*/
|
|
902
|
+
export function renderToSVG(config, { width = 640, height } = {}) {
|
|
903
|
+
const painter = stringPainter();
|
|
904
|
+
const chart = Object.create(Chart.prototype);
|
|
905
|
+
Object.assign(chart, {
|
|
906
|
+
id: 'ssr', config: { type: config.type ?? 'bar', data: config.data ?? { datasets: [] }, options: { ...(config.options ?? {}), animation: false }, plugins: config.plugins ?? [] },
|
|
907
|
+
painter, metas: [], scales: {}, boxes: [], _active: [], _hiddenIndices: new Set(), _shown: new Map(), _plugins: [...registry.plugins, ...(config.plugins ?? [])],
|
|
908
|
+
container: { clientWidth: width, clientHeight: height ?? 0, getAttribute: () => null }, surface: { style: {}, setAttribute() {} },
|
|
909
|
+
_fixedWidth: width, _fixedHeight: height,
|
|
910
|
+
});
|
|
911
|
+
chart.update('none');
|
|
912
|
+
const title = [chart.resolved.plugins?.title?.text].flat().filter(Boolean).join(' ');
|
|
913
|
+
return painter.toString(describe(chart, title));
|
|
914
|
+
}
|