@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/types.js
ADDED
|
@@ -0,0 +1,1193 @@
|
|
|
1
|
+
// @clarity-js/charts — the types Highcharts and ApexCharts have beyond Chart.js's eight: ranges
|
|
2
|
+
// (areaRange, timeline/xrange/rangeBar, dumbbell, errorBar), statistics (boxplot, violin),
|
|
3
|
+
// finance (candlestick, hollow candles, Heikin-Ashi, ohlc, hlc, and the indicators SMA, EMA, WMA,
|
|
4
|
+
// Bollinger bands, MACD, RSI, momentum), matrices and trees (heatmap, treemap, sunburst), flows
|
|
5
|
+
// (sankey, funnel, pyramid, waterfall), dials (gauge, solidgauge, radialBar), and lollipop,
|
|
6
|
+
// bullet, wordcloud, item (a parliament) and streamgraph. Each is a controller as Chart.js's are
|
|
7
|
+
// (element, limits, update, initial, draw) with a few more hooks the core reads: parse, scales,
|
|
8
|
+
// axes, format, label, lines, legend, describe.
|
|
9
|
+
|
|
10
|
+
import { lineLike, bar, arcs, drawPoints, pathThrough, runsOf, pointShape, barPath, bandOf, extentOf, num, pct } from './controllers.js';
|
|
11
|
+
import { arcPath } from './shape.js';
|
|
12
|
+
import { toTime, formatTime } from './axes.js';
|
|
13
|
+
import { PALETTE } from './plugins.js';
|
|
14
|
+
import { niceStep } from './scale.js';
|
|
15
|
+
import { formatNumber } from './format.js';
|
|
16
|
+
import { mix, shade, withAlpha, contrastOn, parseColor } from './fills.js';
|
|
17
|
+
import * as L from './layouts.js';
|
|
18
|
+
|
|
19
|
+
const TAU = Math.PI * 2, deg = (d) => (d * Math.PI) / 180;
|
|
20
|
+
const r2 = (v) => Math.round(v * 100) / 100;
|
|
21
|
+
const at = (v, i) => (Array.isArray(v) ? v[((i % v.length) + v.length) % v.length] : v);
|
|
22
|
+
const fmtOf = (chart) => (v) => formatNumber(v, { locale: chart.resolved.locale });
|
|
23
|
+
const paletteOf = (chart, meta) => meta?.auto?.palette ?? chart.resolved.plugins?.colors?.palette ?? PALETTE;
|
|
24
|
+
const themeOf = (chart) => chart.resolved.theme ?? {};
|
|
25
|
+
const looksTime = (v) => v instanceof Date || (typeof v === 'string' && !Number.isFinite(Number(v)) && Number.isFinite(Date.parse(v))) || (typeof v === 'number' && Math.abs(v) > 1e11);
|
|
26
|
+
const fontOf = (chart, own) => ({ ...chart.resolved.font, ...(own ?? {}) });
|
|
27
|
+
const opt = (chart, meta, name, d, i = 0) => chart.option(meta, name, i, null, d);
|
|
28
|
+
|
|
29
|
+
/** How the index of a raw value is read on the dataset's index axis. */
|
|
30
|
+
function indexReader(chart, meta) {
|
|
31
|
+
const ix = chart.scales[meta.iAxisID], labels = chart.data.labels ?? [];
|
|
32
|
+
return (v, i) => {
|
|
33
|
+
if (!ix) return i;
|
|
34
|
+
if (ix.type === 'category') { if (v == null) return i; const k = typeof v === 'string' ? ix.labels.indexOf(v) : Number(v); return k < 0 || !Number.isFinite(k) ? i : k; }
|
|
35
|
+
if (ix.type.startsWith('time')) return toTime(v ?? labels[i]);
|
|
36
|
+
return num(v ?? labels[i] ?? i);
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
/** A low and a high: [low, high], [x, low, high], { x, low, high }, { x, y: [low, high] }, { yMin, yMax }. */
|
|
40
|
+
function rangeOf(raw) {
|
|
41
|
+
if (raw == null) return null;
|
|
42
|
+
if (Array.isArray(raw)) return raw.length >= 3 ? { x: raw[0], low: num(raw[1]), high: num(raw[2]) } : { low: num(raw[0]), high: num(raw[1]) };
|
|
43
|
+
if (typeof raw !== 'object') return { low: num(raw), high: num(raw) };
|
|
44
|
+
if (Array.isArray(raw.y)) return { x: raw.x, low: num(raw.y[0]), high: num(raw.y[1]) };
|
|
45
|
+
if (Array.isArray(raw.x) && raw.y != null) return { x: raw.y, low: num(raw.x[0]), high: num(raw.x[1]) };
|
|
46
|
+
return { x: raw.x ?? raw.name ?? raw.label, low: num(raw.low ?? raw.min ?? raw.yMin ?? raw.xMin ?? raw.start), high: num(raw.high ?? raw.max ?? raw.yMax ?? raw.xMax ?? raw.end), y: raw.y };
|
|
47
|
+
}
|
|
48
|
+
const parseRanges = (chart, meta) => {
|
|
49
|
+
const read = indexReader(chart, meta), labels = chart.data.labels ?? [];
|
|
50
|
+
return (meta.dataset.data ?? []).map((raw, i) => {
|
|
51
|
+
const r = rangeOf(raw);
|
|
52
|
+
if (!r || !Number.isFinite(r.low) || !Number.isFinite(r.high)) return { index: read(r?.x ?? labels[i], i), value: NaN, low: NaN, high: NaN, raw, i };
|
|
53
|
+
const lo = Math.min(r.low, r.high), hi = Math.max(r.low, r.high);
|
|
54
|
+
return { index: read(r.x ?? labels[i], i), low: lo, high: hi, value: Number.isFinite(num(r.y)) ? num(r.y) : (lo + hi) / 2, raw, i };
|
|
55
|
+
});
|
|
56
|
+
};
|
|
57
|
+
const rangeLimits = (meta, axis) => (axis.id === meta.iAxisID ? extentOf(meta.parsed.map((p) => p.index)) : extentOf(meta.parsed.flatMap((p) => [p.low, p.high, p.value])));
|
|
58
|
+
const nameOf = (chart, meta) => (p) => { const ix = chart.scales[meta.iAxisID]; return ix?.type?.startsWith('time') ? formatTime(p.index, 'MMM d, yyyy') : String(chart.data.labels?.[p.i] ?? ix?.labels?.[p.index] ?? p.i + 1); };
|
|
59
|
+
const named = (meta) => (meta.label ? meta.label + ': ' : '');
|
|
60
|
+
function rangeDescribe(chart, meta, fmt) {
|
|
61
|
+
const ps = meta.parsed.filter((p) => Number.isFinite(p.low)); if (!ps.length) return `${meta.label || 'Ranges'}: no values`;
|
|
62
|
+
const name = nameOf(chart, meta), lo = ps.reduce((a, b) => (b.low < a.low ? b : a)), hi = ps.reduce((a, b) => (b.high > a.high ? b : a)), r = (p) => `${fmt(p.low)} to ${fmt(p.high)}`;
|
|
63
|
+
return `${named(meta)}from ${r(ps[0])} at ${name(ps[0])} to ${r(ps.at(-1))} at ${name(ps.at(-1))}, lowest ${fmt(lo.low)} at ${name(lo)}, highest ${fmt(hi.high)} at ${name(hi)}`;
|
|
64
|
+
}
|
|
65
|
+
const rangeFormat = (chart, meta, el, fmt) => (Number.isFinite(el.parsed.low) ? `${fmt(el.parsed.low)} – ${fmt(el.parsed.high)}` : '');
|
|
66
|
+
// where (u along the index axis, v along the value axis) is on the page
|
|
67
|
+
const place = (horiz) => (horiz ? (u, v) => ({ x: v, y: u }) : (u, v) => ({ x: u, y: v }));
|
|
68
|
+
const boxAround = (horiz, u0, u1, v0, v1) => (horiz ? { l: Math.min(v0, v1), r: Math.max(v0, v1), t: Math.min(u0, u1), b: Math.max(u0, u1) } : { l: Math.min(u0, u1), r: Math.max(u0, u1), t: Math.min(v0, v1), b: Math.max(v0, v1) });
|
|
69
|
+
|
|
70
|
+
// ── areaRange: a band between a low and a high line (Highcharts arearange, ApexCharts rangeArea) ──
|
|
71
|
+
const INDEX = { interaction: { mode: 'index', intersect: false } };
|
|
72
|
+
const areaRange = {
|
|
73
|
+
element: 'point', name: 'Range area chart', alpha: 0.3, defaults: INDEX,
|
|
74
|
+
datasetDefaults: { pointRadius: 0, pointHoverRadius: 4 },
|
|
75
|
+
parse: parseRanges, limits: rangeLimits, format: rangeFormat, describe: rangeDescribe,
|
|
76
|
+
update(chart, meta) {
|
|
77
|
+
const ix = chart.scales[meta.iAxisID], vx = chart.scales[meta.vAxisID];
|
|
78
|
+
meta.elements = meta.parsed.map((p) => {
|
|
79
|
+
const skip = !Number.isFinite(p.low) || !Number.isFinite(p.index), x = ix.getPixelForValue(p.index, p.i);
|
|
80
|
+
const y = skip ? NaN : vx.getPixelForValue(p.high), y2 = skip ? NaN : vx.getPixelForValue(p.low), mid = Number.isFinite(p.mid) ? vx.getPixelForValue(p.mid) : NaN;
|
|
81
|
+
return { kind: 'point', datasetIndex: meta.index, index: p.i, x, y, y2, mid, radius: chart.option(meta, 'pointRadius', p.i, 'radius'), skip, raw: p.raw, parsed: p, options: chart.pointOptions(meta, p.i), bounds: { l: x - 8, r: x + 8, t: Math.min(y, y2) - 4, b: Math.max(y, y2) + 4 }, tip: { x, y: Math.min(y, y2) }, center: { x, y: (y + y2) / 2 } };
|
|
82
|
+
});
|
|
83
|
+
},
|
|
84
|
+
initial(el) { const m = (el.y + el.y2) / 2; return { ...el, y: m, y2: m, mid: m }; },
|
|
85
|
+
draw(painter, meta, chart) {
|
|
86
|
+
const o = chart.lineOptions(meta), els = meta.elements;
|
|
87
|
+
for (const run of runsOf(els, o.spanGaps, (e) => e.parsed.index)) {
|
|
88
|
+
const top = pathThrough(run, o), low = run.map((e) => ({ x: e.x, y: e.y2 })), back = pathThrough(low.slice().reverse(), o).replace(/^M/, 'L');
|
|
89
|
+
painter.layer('fill');
|
|
90
|
+
painter.path(top + back + 'Z', { fill: o.backgroundColor, clip: chart.clip });
|
|
91
|
+
painter.layer('datasets');
|
|
92
|
+
if (o.borderWidth > 0) { painter.path(top, { stroke: o.borderColor, width: o.borderWidth, dash: o.borderDash, clip: chart.clip }); painter.path(pathThrough(low, o), { stroke: o.borderColor, width: o.borderWidth, dash: o.borderDash, clip: chart.clip }); }
|
|
93
|
+
if (run.some((e) => Number.isFinite(e.mid))) painter.path(pathThrough(run.filter((e) => Number.isFinite(e.mid)).map((e) => ({ x: e.x, y: e.mid })), o), { stroke: meta.dataset.midColor ?? o.borderColor, width: 1, dash: meta.dataset.midDash ?? [4, 3], clip: chart.clip });
|
|
94
|
+
}
|
|
95
|
+
drawPoints(painter, meta, chart);
|
|
96
|
+
for (const e of els) { if (e.skip || !(e.radius > 0)) continue; painter.path(pointShape(e.options.pointStyle, e.x, e.y2, e.radius), { fill: e.options.backgroundColor, stroke: e.options.borderColor, width: e.options.borderWidth }); }
|
|
97
|
+
},
|
|
98
|
+
legendItem(chart, meta) { const o = chart.lineOptions(meta); return { fillStyle: o.backgroundColor, strokeStyle: o.borderColor, lineWidth: 2 }; },
|
|
99
|
+
swatch(chart, meta) { return chart.lineOptions(meta).borderColor; },
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
// ── boxplot ──────────────────────────────────────────────────────────────────────────
|
|
103
|
+
// raw numbers (the quartiles are worked out), or a summary: { min, q1, median, q3, max, mean?, outliers? }
|
|
104
|
+
// or ApexCharts's { x, y: [min, q1, median, q3, max] }; with summary: true, an array of five is a summary too.
|
|
105
|
+
function statsOf(raw, meta) {
|
|
106
|
+
if (raw == null) return null;
|
|
107
|
+
const coef = meta.dataset.coef ?? 1.5;
|
|
108
|
+
if (Array.isArray(raw)) {
|
|
109
|
+
if (meta.dataset.summary && raw.length >= 5) { const k = raw.length - 5; return { x: k ? raw[0] : undefined, min: num(raw[k]), q1: num(raw[k + 1]), median: num(raw[k + 2]), q3: num(raw[k + 3]), max: num(raw[k + 4]), outliers: [] }; }
|
|
110
|
+
return L.boxStats(raw, { coef });
|
|
111
|
+
}
|
|
112
|
+
if (Array.isArray(raw.y)) { const y = raw.y; if (y.length === 5 && !meta.dataset.samples) return { x: raw.x, min: num(y[0]), q1: num(y[1]), median: num(y[2]), q3: num(y[3]), max: num(y[4]), outliers: raw.outliers ?? [] }; return { x: raw.x, ...L.boxStats(y, { coef }) }; }
|
|
113
|
+
if (Array.isArray(raw.values ?? raw.data)) return { x: raw.x ?? raw.label, ...L.boxStats(raw.values ?? raw.data, { coef }) };
|
|
114
|
+
return { x: raw.x ?? raw.label ?? raw.name, min: num(raw.min ?? raw.low), q1: num(raw.q1), median: num(raw.median), q3: num(raw.q3), max: num(raw.max ?? raw.high), mean: num(raw.mean), outliers: raw.outliers ?? [] };
|
|
115
|
+
}
|
|
116
|
+
const boxplot = {
|
|
117
|
+
element: 'box', name: 'Box plot', alpha: 0.35, defaults: INDEX,
|
|
118
|
+
parse(chart, meta) {
|
|
119
|
+
const read = indexReader(chart, meta), labels = chart.data.labels ?? [];
|
|
120
|
+
return (meta.dataset.data ?? []).map((raw, i) => {
|
|
121
|
+
const s = statsOf(raw, meta);
|
|
122
|
+
if (!s || !Number.isFinite(s.median)) return { index: read(labels[i], i), value: NaN, raw, i };
|
|
123
|
+
return { index: read(s.x ?? labels[i], i), value: s.median, ...s, raw, i };
|
|
124
|
+
});
|
|
125
|
+
},
|
|
126
|
+
scales: () => ({ index: { offset: true } }),
|
|
127
|
+
limits(meta, axis) { return axis.id === meta.iAxisID ? extentOf(meta.parsed.map((p) => p.index)) : extentOf(meta.parsed.flatMap((p) => [p.min, p.max, ...(p.outliers ?? [])])); },
|
|
128
|
+
update(chart, meta) {
|
|
129
|
+
const vx = chart.scales[meta.vAxisID], horiz = meta.indexAxis === 'y', { width, centerOf } = bandOf(chart, meta, { bar: 0.7 });
|
|
130
|
+
meta.horiz = horiz;
|
|
131
|
+
meta.elements = meta.parsed.map((p) => {
|
|
132
|
+
const skip = !Number.isFinite(p.median), u = centerOf(p), V = (v) => (Number.isFinite(v) ? vx.getPixelForValue(v) : NaN);
|
|
133
|
+
const e = { kind: 'box', datasetIndex: meta.index, index: p.i, x: u, width, q1: V(p.q1), q3: V(p.q3), median: V(p.median), wlo: V(p.min), whi: V(p.max), mean: V(p.mean), outliers: (p.outliers ?? []).map(V), horizontal: horiz, skip, raw: p.raw, parsed: p };
|
|
134
|
+
const vs = [e.wlo, e.whi, ...e.outliers].filter(Number.isFinite);
|
|
135
|
+
e.bounds = boxAround(horiz, u - width / 2, u + width / 2, Math.min(...vs), Math.max(...vs));
|
|
136
|
+
const top = place(horiz)(u, horiz ? Math.max(...vs) : Math.min(...vs));
|
|
137
|
+
e.tip = top; e.center = place(horiz)(u, e.median);
|
|
138
|
+
return e;
|
|
139
|
+
});
|
|
140
|
+
},
|
|
141
|
+
initial(el) { return { ...el, q1: el.median, q3: el.median, wlo: el.median, whi: el.median }; },
|
|
142
|
+
draw(painter, meta, chart) {
|
|
143
|
+
const P = place(meta.horiz), line = (u0, v0, u1, v1, st) => { const a = P(u0, v0), b = P(u1, v1); painter.line(a.x, a.y, b.x, b.y, st); };
|
|
144
|
+
for (const e of meta.elements) {
|
|
145
|
+
if (e.skip) continue;
|
|
146
|
+
const i = e.index, active = chart.isActive(meta.index, i), fill = chart.fillOf(meta, i), stroke = chart.strokeOf(meta, i);
|
|
147
|
+
const bw = opt(chart, meta, 'borderWidth', 1.5, i), st = { stroke, width: bw }, u = e.x, hw = e.width / 2, cap = hw * (meta.dataset.whiskerWidth ?? 0.5);
|
|
148
|
+
line(u, e.q3, u, e.whi, st); line(u, e.q1, u, e.wlo, st);
|
|
149
|
+
line(u - cap, e.whi, u + cap, e.whi, st); line(u - cap, e.wlo, u + cap, e.wlo, st);
|
|
150
|
+
const a = P(u - hw, Math.min(e.q1, e.q3)), b = P(u + hw, Math.max(e.q1, e.q3));
|
|
151
|
+
const d = barPath(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.abs(b.x - a.x), Math.abs(b.y - a.y), opt(chart, meta, 'borderRadius', 0, i));
|
|
152
|
+
painter.path(d, { fill: active ? shade(fill, -0.08) : fill, stroke, width: bw });
|
|
153
|
+
line(u - hw, e.median, u + hw, e.median, { stroke: meta.dataset.medianColor ?? stroke, width: bw + 0.5 });
|
|
154
|
+
const mr = opt(chart, meta, 'meanRadius', 0, i);
|
|
155
|
+
if (mr > 0 && Number.isFinite(e.mean)) { const m = P(u, e.mean); painter.path(pointShape('crossRot', m.x, m.y, mr), { stroke, width: 1.5 }); }
|
|
156
|
+
const or = opt(chart, meta, 'outlierRadius', 2.5, i);
|
|
157
|
+
for (const v of e.outliers) if (Number.isFinite(v)) { const q = P(u, v); painter.path(pointShape(meta.dataset.outlierStyle ?? 'circle', q.x, q.y, or), { fill: meta.dataset.outlierColor ?? withAlpha(stroke, 0.5), stroke, width: 1 }); }
|
|
158
|
+
}
|
|
159
|
+
},
|
|
160
|
+
lines(chart, meta, el, fmt) { const p = el.parsed; return [`max ${fmt(p.max)}`, `Q3 ${fmt(p.q3)}`, `median ${fmt(p.median)}`, `Q1 ${fmt(p.q1)}`, `min ${fmt(p.min)}`, ...(Number.isFinite(p.mean) ? [`mean ${fmt(p.mean)}`] : []), ...(p.outliers?.length ? [`${p.outliers.length} outlier${p.outliers.length > 1 ? 's' : ''}`] : [])]; },
|
|
161
|
+
format(chart, meta, el, fmt) { const p = el.parsed; return `median ${fmt(p.median)} (Q1 ${fmt(p.q1)}, Q3 ${fmt(p.q3)})`; },
|
|
162
|
+
swatch(chart, meta, el) { return chart.strokeOf(meta, el.index); },
|
|
163
|
+
describe(chart, meta, fmt) { const name = nameOf(chart, meta); return named(meta) + meta.parsed.filter((p) => Number.isFinite(p.median)).slice(0, 8).map((p) => `${name(p)} median ${fmt(p.median)}, from ${fmt(p.q1)} to ${fmt(p.q3)} in the middle half`).join('; '); },
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
// ── violin: how the values spread, mirrored ───────────────────────────────────────────
|
|
167
|
+
const violin = {
|
|
168
|
+
element: 'box', name: 'Violin plot', alpha: 0.35, defaults: INDEX,
|
|
169
|
+
parse(chart, meta) {
|
|
170
|
+
const read = indexReader(chart, meta), labels = chart.data.labels ?? [];
|
|
171
|
+
return (meta.dataset.data ?? []).map((raw, i) => {
|
|
172
|
+
const values = Array.isArray(raw) ? raw : raw?.values ?? raw?.data ?? (Array.isArray(raw?.y) ? raw.y : null);
|
|
173
|
+
if (!values?.length) return { index: read(labels[i], i), value: NaN, raw, i };
|
|
174
|
+
const s = L.boxStats(values, { coef: 0 }), k = L.density(values, { points: meta.dataset.points ?? 48, bandwidth: meta.dataset.bandwidth });
|
|
175
|
+
return { index: read(raw?.x ?? labels[i], i), value: s.median, ...s, kde: k, raw, i };
|
|
176
|
+
});
|
|
177
|
+
},
|
|
178
|
+
scales: () => ({ index: { offset: true } }),
|
|
179
|
+
limits(meta, axis) { return axis.id === meta.iAxisID ? extentOf(meta.parsed.map((p) => p.index)) : extentOf(meta.parsed.flatMap((p) => [p.min, p.max])); },
|
|
180
|
+
update(chart, meta) {
|
|
181
|
+
const vx = chart.scales[meta.vAxisID], horiz = meta.indexAxis === 'y', { width, centerOf } = bandOf(chart, meta, { bar: 0.9 });
|
|
182
|
+
const peak = Math.max(1e-12, ...meta.parsed.map((p) => p.kde?.max ?? 0));
|
|
183
|
+
meta.horiz = horiz;
|
|
184
|
+
meta.elements = meta.parsed.map((p) => {
|
|
185
|
+
const skip = !Number.isFinite(p.median), u = centerOf(p), V = (v) => vx.getPixelForValue(v);
|
|
186
|
+
const scale = meta.dataset.scaleEach ? p.kde?.max || 1 : peak;
|
|
187
|
+
const coords = skip ? [] : p.kde.coords.map((c) => ({ v: V(c.v), d: (c.d / scale) * (width / 2) }));
|
|
188
|
+
const e = { kind: 'box', datasetIndex: meta.index, index: p.i, x: u, width, coords, median: skip ? NaN : V(p.median), q1: skip ? NaN : V(p.q1), q3: skip ? NaN : V(p.q3), grow: 1, skip, raw: p.raw, parsed: p };
|
|
189
|
+
e.bounds = skip ? null : boxAround(horiz, u - width / 2, u + width / 2, V(p.min), V(p.max));
|
|
190
|
+
e.tip = skip ? { x: u, y: 0 } : place(horiz)(u, horiz ? V(p.max) : Math.min(V(p.max), V(p.min)));
|
|
191
|
+
e.center = place(horiz)(u, e.median);
|
|
192
|
+
return e;
|
|
193
|
+
});
|
|
194
|
+
},
|
|
195
|
+
initial(el) { return { ...el, grow: 0 }; },
|
|
196
|
+
draw(painter, meta, chart) {
|
|
197
|
+
const P = place(meta.horiz);
|
|
198
|
+
for (const e of meta.elements) {
|
|
199
|
+
if (e.skip || !e.coords.length) continue;
|
|
200
|
+
const g = e.grow ?? 1, i = e.index, fill = chart.fillOf(meta, i), stroke = chart.strokeOf(meta, i), active = chart.isActive(meta.index, i);
|
|
201
|
+
const side = (sgn) => e.coords.map((c) => P(e.x + sgn * c.d * g, c.v));
|
|
202
|
+
const right = side(1), left = side(-1).reverse();
|
|
203
|
+
const d = 'M' + [...right, ...left].map((q) => `${r2(q.x)},${r2(q.y)}`).join('L') + 'Z';
|
|
204
|
+
painter.path(d, { fill: active ? shade(fill, -0.08) : fill, stroke, width: opt(chart, meta, 'borderWidth', 1.5, i) });
|
|
205
|
+
const a = P(e.x, e.q1), b = P(e.x, e.q3);
|
|
206
|
+
painter.line(a.x, a.y, b.x, b.y, { stroke, width: 4, cap: 'round' });
|
|
207
|
+
const m = P(e.x, e.median);
|
|
208
|
+
painter.circle(m.x, m.y, 3, { fill: themeOf(chart).bg ?? '#fff', stroke, width: 1.5 });
|
|
209
|
+
}
|
|
210
|
+
},
|
|
211
|
+
lines(chart, meta, el, fmt) { const p = el.parsed; return [`median ${fmt(p.median)}`, `Q1 ${fmt(p.q1)} · Q3 ${fmt(p.q3)}`, `${fmt(p.min)} – ${fmt(p.max)}`, `${p.n} values`]; },
|
|
212
|
+
describe(chart, meta, fmt) { return boxplot.describe(chart, meta, fmt); },
|
|
213
|
+
format(chart, meta, el, fmt) { return `median ${fmt(el.parsed.median)}`; },
|
|
214
|
+
swatch(chart, meta, el) { return chart.strokeOf(meta, el.index); },
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
// ── finance: candlestick (hollow, Heikin-Ashi), ohlc, hlc ─────────────────────────────────
|
|
218
|
+
function ohlcOf(raw, hlc) {
|
|
219
|
+
if (raw == null) return null;
|
|
220
|
+
if (Array.isArray(raw)) {
|
|
221
|
+
if (hlc) return raw.length >= 4 ? { x: raw[0], high: num(raw[1]), low: num(raw[2]), close: num(raw[3]) } : { high: num(raw[0]), low: num(raw[1]), close: num(raw[2]) };
|
|
222
|
+
return raw.length >= 5 ? { x: raw[0], open: num(raw[1]), high: num(raw[2]), low: num(raw[3]), close: num(raw[4]) } : { open: num(raw[0]), high: num(raw[1]), low: num(raw[2]), close: num(raw[3]) };
|
|
223
|
+
}
|
|
224
|
+
if (typeof raw !== 'object') return { close: num(raw), open: num(raw), high: num(raw), low: num(raw) };
|
|
225
|
+
if (Array.isArray(raw.y)) { const y = raw.y; return hlc && y.length === 3 ? { x: raw.x, high: num(y[0]), low: num(y[1]), close: num(y[2]) } : { x: raw.x, open: num(y[0]), high: num(y[1]), low: num(y[2]), close: num(y[3]) }; }
|
|
226
|
+
return { x: raw.x ?? raw.t ?? raw.date ?? raw.time, open: num(raw.open ?? raw.o), high: num(raw.high ?? raw.h), low: num(raw.low ?? raw.l), close: num(raw.close ?? raw.c), volume: num(raw.volume ?? raw.v) };
|
|
227
|
+
}
|
|
228
|
+
const FIN = { up: '#26a69a', down: '#ef5350', unchanged: '#8a94a0' };
|
|
229
|
+
function finColors(chart, meta, i, dir) {
|
|
230
|
+
const ds = meta.dataset, pick = (k) => chart.option(meta, k, i);
|
|
231
|
+
const bg = ds.backgroundColors ?? ds.color ?? {}, bc = ds.borderColors ?? {};
|
|
232
|
+
const fill = dir > 0 ? pick('upColor') ?? bg.up ?? FIN.up : dir < 0 ? pick('downColor') ?? bg.down ?? FIN.down : pick('unchangedColor') ?? bg.unchanged ?? FIN.unchanged;
|
|
233
|
+
const line = dir > 0 ? pick('upLineColor') ?? bc.up : dir < 0 ? pick('downLineColor') ?? pick('lineColor') ?? bc.down : bc.unchanged;
|
|
234
|
+
return { fill, line: line ?? fill };
|
|
235
|
+
}
|
|
236
|
+
function financial(kind) {
|
|
237
|
+
const hlc = kind === 'hlc';
|
|
238
|
+
return {
|
|
239
|
+
element: 'candle', name: { candlestick: 'Candlestick chart', hollow: 'Hollow candlestick chart', heikinashi: 'Heikin-Ashi chart', hlc: 'HLC chart', ohlc: 'OHLC chart' }[kind], colors: 'none',
|
|
240
|
+
defaults: { interaction: { mode: 'index', intersect: false } },
|
|
241
|
+
parse(chart, meta) {
|
|
242
|
+
const read = indexReader(chart, meta), labels = chart.data.labels ?? [];
|
|
243
|
+
let rows = (meta.dataset.data ?? []).map((raw, i) => { const o = ohlcOf(raw, hlc); return o ? { ...o, raw, i } : { raw, i, close: NaN }; });
|
|
244
|
+
if (kind === 'heikinashi' || meta.dataset.heikinAshi) rows = L.heikinAshi(rows);
|
|
245
|
+
return rows.map((o, i) => ({ index: read(o.x ?? labels[i], i), value: o.close, open: o.open, high: o.high, low: o.low, close: o.close, volume: o.volume, prevClose: rows[i - 1]?.close, raw: o.raw, i }));
|
|
246
|
+
},
|
|
247
|
+
scales(meta, chart) {
|
|
248
|
+
const rows = (meta.dataset.data ?? []).map((r) => ohlcOf(r, hlc)).filter(Boolean), withX = rows.filter((r) => r.x != null);
|
|
249
|
+
if (withX.length && looksTime(withX[0].x)) return { index: { type: 'timeseries', offset: true } };
|
|
250
|
+
if (withX.length && !(chart.data.labels ?? []).length && typeof withX[0].x === 'string') return { index: { type: 'category', offset: true, labels: rows.map((r) => r.x) } };
|
|
251
|
+
return { index: { offset: true } };
|
|
252
|
+
},
|
|
253
|
+
limits(meta, axis) { return axis.id === meta.iAxisID ? extentOf(meta.parsed.map((p) => p.index)) : extentOf(meta.parsed.flatMap((p) => [p.low, p.high])); },
|
|
254
|
+
update(chart, meta) {
|
|
255
|
+
const vx = chart.scales[meta.vAxisID], { width, centerOf } = bandOf(chart, meta, { cat: 0.85, bar: 0.8 });
|
|
256
|
+
meta.elements = meta.parsed.map((p) => {
|
|
257
|
+
const skip = !Number.isFinite(p.close) || !Number.isFinite(p.index), x = centerOf(p), V = (v) => (Number.isFinite(v) ? vx.getPixelForValue(v) : NaN);
|
|
258
|
+
const e = { kind: 'candle', datasetIndex: meta.index, index: p.i, x, width, open: V(p.open), high: V(p.high), low: V(p.low), close: V(p.close), skip, raw: p.raw, parsed: p };
|
|
259
|
+
const top = Math.min(e.high, e.low, e.open, e.close), bot = Math.max(e.high, e.low, e.open, e.close);
|
|
260
|
+
e.bounds = { l: x - Math.max(3, width / 2), r: x + Math.max(3, width / 2), t: Number.isFinite(top) ? top : e.close, b: Number.isFinite(bot) ? bot : e.close };
|
|
261
|
+
e.tip = { x, y: e.bounds.t };
|
|
262
|
+
return e;
|
|
263
|
+
});
|
|
264
|
+
},
|
|
265
|
+
initial(el) { const m = Number.isFinite(el.open) ? (el.open + el.close) / 2 : el.close; return { ...el, open: m, close: m, high: m, low: m }; },
|
|
266
|
+
draw(painter, meta, chart) {
|
|
267
|
+
const hollow = !!opt(chart, meta, 'hollow', false) || kind === 'hollow';
|
|
268
|
+
for (const e of meta.elements) {
|
|
269
|
+
if (e.skip) continue;
|
|
270
|
+
const p = e.parsed, i = e.index, active = chart.isActive(meta.index, i);
|
|
271
|
+
const ref = hollow || hlc || !Number.isFinite(p.open) ? p.prevClose ?? p.open : p.open;
|
|
272
|
+
const dir = Number.isFinite(ref) ? Math.sign(p.close - ref) : 1, c = finColors(chart, meta, i, dir);
|
|
273
|
+
const bw = opt(chart, meta, 'borderWidth', kind === 'candlestick' || kind === 'heikinashi' || kind === 'hollow' ? 1 : Math.max(1, Math.min(3, e.width / 6)), i);
|
|
274
|
+
const line = active ? shade(c.line, -0.15) : c.line;
|
|
275
|
+
if (kind === 'ohlc' || hlc) {
|
|
276
|
+
painter.line(e.x, e.high, e.x, e.low, { stroke: line, width: bw });
|
|
277
|
+
if (!hlc && Number.isFinite(e.open)) painter.line(e.x - e.width / 2, e.open, e.x, e.open, { stroke: line, width: bw });
|
|
278
|
+
painter.line(e.x, e.close, e.x + e.width / 2, e.close, { stroke: line, width: bw });
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
const t = Math.min(e.open, e.close), h = Math.max(1, Math.abs(e.close - e.open));
|
|
282
|
+
painter.line(e.x, e.high, e.x, t, { stroke: line, width: bw });
|
|
283
|
+
painter.line(e.x, t + h, e.x, e.low, { stroke: line, width: bw });
|
|
284
|
+
const filled = !hollow || p.close < p.open;
|
|
285
|
+
painter.rect(e.x - e.width / 2, t, e.width, h, { fill: filled ? (active ? shade(c.fill, -0.12) : c.fill) : themeOf(chart).bg ?? '#fff', stroke: line, width: bw });
|
|
286
|
+
}
|
|
287
|
+
},
|
|
288
|
+
lines(chart, meta, el, fmt) { const p = el.parsed; return [...(Number.isFinite(p.open) ? [`Open ${fmt(p.open)}`] : []), `High ${fmt(p.high)}`, `Low ${fmt(p.low)}`, `Close ${fmt(p.close)}`, ...(Number.isFinite(p.volume) ? [`Volume ${fmt(p.volume)}`] : [])]; },
|
|
289
|
+
format(chart, meta, el, fmt) { const p = el.parsed; return `${Number.isFinite(p.open) ? `O ${fmt(p.open)} ` : ''}H ${fmt(p.high)} L ${fmt(p.low)} C ${fmt(p.close)}`; },
|
|
290
|
+
swatch(chart, meta, el) { const p = el.parsed; return finColors(chart, meta, el.index, Math.sign(p.close - (p.open ?? p.prevClose ?? p.close)) || 1).fill; },
|
|
291
|
+
legendItem(chart, meta) { const c = finColors(chart, meta, 0, 1); return { fillStyle: c.fill, strokeStyle: finColors(chart, meta, 0, -1).fill, lineWidth: 2 }; },
|
|
292
|
+
describe(chart, meta, fmt) {
|
|
293
|
+
const ps = meta.parsed.filter((p) => Number.isFinite(p.close)); if (!ps.length) return `${meta.label || 'Prices'}: no values`;
|
|
294
|
+
const hi = ps.reduce((a, b) => (b.high > a.high ? b : a)), lo = ps.reduce((a, b) => (b.low < a.low ? b : a)), ix = chart.scales[meta.iAxisID];
|
|
295
|
+
const name = (p) => (ix?.type?.startsWith('time') ? formatTime(p.index, 'MMM d, yyyy') : String(chart.data.labels?.[p.i] ?? p.i + 1));
|
|
296
|
+
return `${meta.label ? meta.label + ': ' : ''}opened at ${fmt(ps[0].open ?? ps[0].close)}, closed at ${fmt(ps.at(-1).close)}, highest ${fmt(hi.high)} on ${name(hi)}, lowest ${fmt(lo.low)} on ${name(lo)}`;
|
|
297
|
+
},
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// ── heatmap: a grid of cells coloured by their values ────────────────────────────────────
|
|
302
|
+
// { x, y, v } (as chartjs-chart-matrix), [x, y, v] (Highcharts), or a dataset a row (ApexCharts: { x, y } with the row's name the label)
|
|
303
|
+
function cellsOf(chart, meta) {
|
|
304
|
+
const labels = chart.data.labels ?? [];
|
|
305
|
+
return (meta.dataset.data ?? []).map((raw, i) => {
|
|
306
|
+
if (raw == null) return { x: labels[i] ?? i, y: meta.label, v: NaN, raw, i };
|
|
307
|
+
if (typeof raw === 'number' || typeof raw === 'string') return { x: labels[i] ?? i, y: meta.dataset.label ?? meta.index, v: num(raw), raw, i };
|
|
308
|
+
if (Array.isArray(raw)) return { x: raw[0], y: raw[1], v: num(raw[2]), raw, i };
|
|
309
|
+
if (raw.v != null || raw.value != null) return { x: raw.x, y: raw.y, v: num(raw.v ?? raw.value), raw, i };
|
|
310
|
+
return { x: raw.x, y: meta.dataset.label ?? meta.index, v: num(raw.y), raw, i };
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
const keysOf = (cells, key, given) => { if (given?.length) return given; const out = []; for (const c of cells) { const k = c[key]; if (!out.includes(k)) out.push(k); } return out; };
|
|
314
|
+
/** The colour of a value on a chart's colour axis (colorAxis, or a dataset's own): stops, min/max colours, or classes. */
|
|
315
|
+
export function colorScaleOf(chart, meta) {
|
|
316
|
+
const metas = chart.metas.filter((m) => m.controller.colorAxis && chart.isDatasetVisible(m.index));
|
|
317
|
+
const ca = { ...(chart.resolved.colorAxis ?? {}), ...(meta?.dataset.colorAxis ?? {}) };
|
|
318
|
+
const vals = (meta?.dataset.colorAxis ? [meta] : metas).flatMap((m) => (m.parsed ?? []).map((p) => p.color ?? p.value)).filter(Number.isFinite);
|
|
319
|
+
const min = ca.min ?? (vals.length ? Math.min(...vals) : 0), max = ca.max ?? (vals.length ? Math.max(...vals) : 1);
|
|
320
|
+
const base = paletteOf(chart, meta ?? metas[0])[0], bg = themeOf(chart).mode === 'dark' ? '#1d2530' : '#ffffff';
|
|
321
|
+
if (ca.dataClasses?.length) {
|
|
322
|
+
const pal = paletteOf(chart, meta);
|
|
323
|
+
const classes = ca.dataClasses.map((c, k) => ({ ...c, color: c.color ?? mix(bg, base, (k + 1) / ca.dataClasses.length) ?? pal[k % pal.length] }));
|
|
324
|
+
return { min, max, classes, hasValues: vals.length > 0, colorOf: (v) => (!Number.isFinite(v) ? ca.nullColor ?? 'rgba(128,128,128,0.25)' : classes.find((c) => (c.from == null || v >= c.from) && (c.to == null || v <= c.to))?.color ?? ca.nullColor ?? 'rgba(128,128,128,0.25)') };
|
|
325
|
+
}
|
|
326
|
+
const stops = (ca.stops ?? [[0, ca.minColor ?? mix(bg, base, 0.1)], [1, ca.maxColor ?? base]]).map((s) => (Array.isArray(s) ? s : [s.offset, s.color]));
|
|
327
|
+
const log = ca.type === 'logarithmic', f = (v) => (log ? Math.log10(Math.max(1e-12, v)) : v);
|
|
328
|
+
const tOf = (v) => { let t = (f(v) - f(min)) / ((f(max) - f(min)) || 1); t = Math.max(0, Math.min(1, t)); return ca.reversed ? 1 - t : t; };
|
|
329
|
+
const colorAt = (t) => { if (t <= stops[0][0]) return stops[0][1]; for (let k = 1; k < stops.length; k++) if (t <= stops[k][0]) { const [a, ca1] = stops[k - 1], [b, cb] = stops[k]; return mix(ca1, cb, (t - a) / ((b - a) || 1)); } return stops.at(-1)[1]; };
|
|
330
|
+
return { min, max, stops, log, hasValues: vals.length > 0, colorOf: (v) => (Number.isFinite(v) ? colorAt(tOf(v)) : ca.nullColor ?? 'rgba(128,128,128,0.25)') };
|
|
331
|
+
}
|
|
332
|
+
const heatmap = {
|
|
333
|
+
element: 'cell', name: 'Heatmap', colorAxis: true, legend: 'none', colors: 'none',
|
|
334
|
+
defaults: { interaction: { mode: 'nearest', intersect: true } },
|
|
335
|
+
scales(meta, chart) {
|
|
336
|
+
const all = chart.metas.filter((m) => m.type === meta.type).flatMap((m) => cellsOf(chart, m));
|
|
337
|
+
const given = chart.data.labels ?? [], o = chart.resolved.scales ?? {};
|
|
338
|
+
const xs = keysOf(all, 'x', given.length ? given : o[meta.iAxisID]?.labels), xNumeric = !given.length && xs.every((k) => typeof k === 'number');
|
|
339
|
+
const ys = keysOf(all, 'y', o[meta.vAxisID]?.labels);
|
|
340
|
+
return { index: { type: 'category', offset: true, labels: xNumeric ? xs.slice().sort((a, b) => a - b).map(String) : xs.map(String), grid: { display: false } }, value: { type: 'category', offset: true, labels: ys.map(String), grid: { display: false }, reverse: true } };
|
|
341
|
+
},
|
|
342
|
+
parse(chart, meta) {
|
|
343
|
+
const ix = chart.scales[meta.iAxisID], vy = chart.scales[meta.vAxisID];
|
|
344
|
+
const find = (labels, k) => { const j = labels.indexOf(String(k)); return j >= 0 ? j : typeof k === 'number' && k < labels.length && Number.isInteger(k) && !labels.includes(String(k)) ? k : -1; };
|
|
345
|
+
return cellsOf(chart, meta).map((c) => ({ index: find(ix.labels.map(String), c.x), y: find(vy.labels.map(String), c.y), value: c.v, name: `${c.x}, ${c.y}`, xKey: c.x, yKey: c.y, raw: c.raw, i: c.i }));
|
|
346
|
+
},
|
|
347
|
+
limits(meta, axis) { return axis.id === meta.iAxisID ? extentOf(meta.parsed.map((p) => p.index)) : extentOf(meta.parsed.map((p) => p.y)); },
|
|
348
|
+
update(chart, meta) {
|
|
349
|
+
const ix = chart.scales[meta.iAxisID], vy = chart.scales[meta.vAxisID], scale = colorScaleOf(chart, meta);
|
|
350
|
+
const w = ix.bandSize, h = vy.bandSize, gap = opt(chart, meta, 'spacing', w > 8 && h > 8 ? 1 : 0);
|
|
351
|
+
meta.elements = meta.parsed.map((p) => {
|
|
352
|
+
const skip = p.index < 0 || p.y < 0, cx = ix.getPixelForValue(p.index), cy = vy.getPixelForValue(p.y);
|
|
353
|
+
const own = chart.option(meta, 'backgroundColor', p.i);
|
|
354
|
+
const color = own ?? scale.colorOf(p.value);
|
|
355
|
+
const x = cx - w / 2 + gap / 2, y = cy - h / 2 + gap / 2, cw = Math.max(0, w - gap), ch = Math.max(0, h - gap);
|
|
356
|
+
return { kind: 'cell', datasetIndex: meta.index, index: p.i, x, y, width: cw, height: ch, color, skip, raw: p.raw, parsed: p, bounds: { l: x, r: x + cw, t: y, b: y + ch }, center: { x: cx, y: cy }, tip: { x: cx, y } };
|
|
357
|
+
});
|
|
358
|
+
},
|
|
359
|
+
initial(el) { return { ...el, x: el.x + el.width / 2, y: el.y + el.height / 2, width: 0, height: 0 }; },
|
|
360
|
+
draw(painter, meta, chart) {
|
|
361
|
+
const rad = opt(chart, meta, 'borderRadius', 0), bw = opt(chart, meta, 'borderWidth', 0), bc = chart.option(meta, 'borderColor', 0) ?? themeOf(chart).bg;
|
|
362
|
+
for (const e of meta.elements) {
|
|
363
|
+
if (e.skip) continue;
|
|
364
|
+
const active = chart.isActive(meta.index, e.index);
|
|
365
|
+
painter.rect(e.x, e.y, e.width, e.height, { fill: active ? shade(e.color, -0.15) : e.color, radius: rad, stroke: bw > 0 || active ? (active ? themeOf(chart).ink : bc) : null, width: active ? 1.5 : bw });
|
|
366
|
+
}
|
|
367
|
+
},
|
|
368
|
+
label(chart, meta, el) { return `${el.parsed.xKey} · ${el.parsed.yKey}`; },
|
|
369
|
+
format(chart, meta, el, fmt) { return Number.isFinite(el.parsed.value) ? fmt(el.parsed.value) : '–'; },
|
|
370
|
+
swatch(chart, meta, el) { return el.color; },
|
|
371
|
+
text(chart, meta, el, fmt) { return Number.isFinite(el.parsed.value) ? fmt(el.parsed.value) : ''; },
|
|
372
|
+
describe(chart, meta, fmt) {
|
|
373
|
+
const ps = meta.parsed.filter((p) => Number.isFinite(p.value)); if (!ps.length) return 'no values';
|
|
374
|
+
const hi = ps.reduce((a, b) => (b.value > a.value ? b : a)), lo = ps.reduce((a, b) => (b.value < a.value ? b : a));
|
|
375
|
+
return `${meta.label ? meta.label + ': ' : ''}${ps.length} cells, highest ${fmt(hi.value)} at ${hi.name}, lowest ${fmt(lo.value)} at ${lo.name}`;
|
|
376
|
+
},
|
|
377
|
+
};
|
|
378
|
+
|
|
379
|
+
// ── treemap and sunburst: a tree drawn as nested rectangles or rings ────────────────────────
|
|
380
|
+
function treeRows(chart, meta) {
|
|
381
|
+
const labels = chart.data.labels ?? [];
|
|
382
|
+
const rows = (meta.dataset.data ?? []).map((raw, i) => (raw != null && typeof raw === 'object' && !Array.isArray(raw) ? raw : Array.isArray(raw) ? { name: raw[0], value: raw[1] } : { name: labels[i] ?? String(i + 1), value: raw }));
|
|
383
|
+
return L.treeOf(rows, { id: meta.dataset.idKey ?? 'id', parent: meta.dataset.parentKey ?? 'parent', value: meta.dataset.key ?? 'value', name: meta.dataset.nameKey ?? 'name' });
|
|
384
|
+
}
|
|
385
|
+
const pathName = (n) => { const out = []; for (let q = n; q; q = q.parent) out.unshift(q.name); return out.join(' › '); };
|
|
386
|
+
const treeParse = (chart, meta) => { const t = treeRows(chart, meta); meta.tree = t; return t.nodes.map((n) => ({ index: n.i, value: n.value, name: n.name, path: pathName(n), depth: n.depth, leaf: !n.children.length, node: n, raw: n.row, i: n.i })); };
|
|
387
|
+
// the first level with more than one node takes the palette; below it, lighter shades of its colour
|
|
388
|
+
export function topsOf(tree) { let t = tree.roots; while (t.length === 1 && t[0].children.length) t = t[0].children; return t; }
|
|
389
|
+
function nodeColors(chart, meta, tree) {
|
|
390
|
+
const pal = paletteOf(chart, meta), scale = meta.dataset.colorBy === 'value' || chart.resolved.colorAxis ? colorScaleOf(chart, meta) : null, out = new Map(), tops = topsOf(tree);
|
|
391
|
+
const above = themeOf(chart).mode === 'dark' ? '#3a4552' : '#d5dbe2';
|
|
392
|
+
const visit = (n, base, k, below) => {
|
|
393
|
+
const own = n.row?.color ?? chart.option(meta, 'backgroundColor', n.i), top = tops.indexOf(n);
|
|
394
|
+
const c = own ?? (scale ? scale.colorOf(n.value) : top >= 0 ? pal[top % pal.length] : below ? shade(base, Math.min(0.45, 0.14 * below) * (k % 2 ? 1 : 0.7)) : above);
|
|
395
|
+
out.set(n.i, c);
|
|
396
|
+
n.children.forEach((ch, j) => visit(ch, top >= 0 || own ? c : base, j, top >= 0 || below ? (below ?? 0) + 1 : 0));
|
|
397
|
+
};
|
|
398
|
+
tree.roots.forEach((r, k) => visit(r, pal[k % pal.length], k, 0));
|
|
399
|
+
return out;
|
|
400
|
+
}
|
|
401
|
+
const treemap = {
|
|
402
|
+
element: 'rect', name: 'Treemap', axes: 'none', legend: 'points', colorAxis: false, colors: 'none',
|
|
403
|
+
defaults: { aspectRatio: 1.6, interaction: { mode: 'nearest', intersect: true }, plugins: { legend: { display: false } } },
|
|
404
|
+
parse: treeParse,
|
|
405
|
+
limits: () => [Infinity, -Infinity],
|
|
406
|
+
update(chart, meta) {
|
|
407
|
+
const a = chart.chartArea, tree = meta.tree, colors = nodeColors(chart, meta, tree), f = fontOf(chart, meta.dataset.labels?.font);
|
|
408
|
+
const pad = opt(chart, meta, 'spacing', 1), head = f.size * 1.6, maxDepth = meta.dataset.maxDepth ?? Infinity, els = [], groups = [];
|
|
409
|
+
const lay = (nodes, box, depth) => {
|
|
410
|
+
const vis = nodes.filter((n) => depth > 0 || chart.getDataVisibility(n.i)).sort((p, q) => q.value - p.value);
|
|
411
|
+
const rects = L.squarify(vis.map((n) => n.value), box);
|
|
412
|
+
vis.forEach((n, k) => {
|
|
413
|
+
const r = rects[k], c = colors.get(n.i);
|
|
414
|
+
if (!(r.w > 0 && r.h > 0)) return;
|
|
415
|
+
if (n.children.length && depth < maxDepth && r.w > pad * 4 && r.h > head + pad * 4) {
|
|
416
|
+
const showHead = meta.dataset.groupLabels !== false && r.h > head * 2.2;
|
|
417
|
+
groups.push({ node: n, x: r.x, y: r.y, w: r.w, h: r.h, color: c, head: showHead ? head : 0 });
|
|
418
|
+
lay(n.children, { x: r.x + pad, y: r.y + (showHead ? head : pad), w: r.w - pad * 2, h: r.h - (showHead ? head : pad) - pad }, depth + 1);
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
const x = r.x + pad / 2, y = r.y + pad / 2, w = Math.max(0, r.w - pad), h = Math.max(0, r.h - pad);
|
|
422
|
+
els.push({ kind: 'rect', datasetIndex: meta.index, index: n.i, x, y, width: w, height: h, color: c, node: n, skip: false, raw: n.row, parsed: meta.parsed[n.i], bounds: { l: x, r: x + w, t: y, b: y + h }, center: { x: x + w / 2, y: y + h / 2 }, tip: { x: x + w / 2, y } });
|
|
423
|
+
});
|
|
424
|
+
};
|
|
425
|
+
lay(tree.roots, { x: a.left, y: a.top, w: a.right - a.left, h: a.bottom - a.top }, 0);
|
|
426
|
+
meta.groups = groups; meta.elements = els;
|
|
427
|
+
},
|
|
428
|
+
initial(el) { return { ...el, x: el.x + el.width / 2, y: el.y + el.height / 2, width: 0, height: 0 }; },
|
|
429
|
+
draw(painter, meta, chart) {
|
|
430
|
+
const lab = meta.dataset.labels ?? {}, f = fontOf(chart, lab.font), fmt = fmtOf(chart), rad = opt(chart, meta, 'borderRadius', 2);
|
|
431
|
+
for (const g of meta.groups ?? []) {
|
|
432
|
+
painter.rect(g.x, g.y, g.w, g.h, { fill: shade(g.color, -0.18), radius: rad });
|
|
433
|
+
if (g.head) painter.text(clip(painter, g.node.name, g.w - 8, { ...f, weight: 'bold' }), g.x + 5, g.y + g.head * 0.68, { fill: contrastOn(shade(g.color, -0.18)), font: { ...f, weight: 'bold' } });
|
|
434
|
+
}
|
|
435
|
+
for (const e of meta.elements) {
|
|
436
|
+
const active = chart.isActive(meta.index, e.index);
|
|
437
|
+
painter.rect(e.x, e.y, e.width, e.height, { fill: active ? shade(e.color, -0.12) : e.color, radius: rad });
|
|
438
|
+
if (lab.display === false || e.width < 24 || e.height < f.size * 1.3) continue;
|
|
439
|
+
const name = typeof lab.formatter === 'function' ? lab.formatter(e.node.value, { chart, node: e.node, name: e.node.name }) : e.node.name;
|
|
440
|
+
const lines = [].concat(name).map(String);
|
|
441
|
+
if (lab.value !== false && typeof lab.formatter !== 'function' && e.height > f.size * 2.9) lines.push(fmt(e.node.value));
|
|
442
|
+
const color = lab.color && lab.color !== 'auto' ? lab.color : contrastOn(e.color);
|
|
443
|
+
lines.forEach((t, k) => painter.text(clip(painter, t, e.width - 8, k ? f : { ...f, weight: '600' }), e.x + 5, e.y + 5 + f.size * (k * 1.3 + 0.95), { fill: color, font: k ? f : { ...f, weight: '600' }, opacity: k ? 0.85 : 1 }));
|
|
444
|
+
}
|
|
445
|
+
},
|
|
446
|
+
label(chart, meta, el) { return el.parsed?.path ?? ''; },
|
|
447
|
+
format(chart, meta, el, fmt) { return fmt(el.node?.value ?? el.parsed?.value); },
|
|
448
|
+
swatch(chart, meta, el) { return el.color; },
|
|
449
|
+
legendItems(chart, meta) { const pal = paletteOf(chart, meta); return (meta.tree?.roots ?? []).map((r, k) => ({ text: r.name, fillStyle: r.row?.color ?? pal[k % pal.length], strokeStyle: 'transparent', lineWidth: 0, hidden: !chart.getDataVisibility(r.i), index: r.i, pointStyle: 'rect' })); },
|
|
450
|
+
describe(chart, meta, fmt) { const r = (meta.tree ? topsOf(meta.tree) : []).slice().sort((a, b) => b.value - a.value), tot = r.reduce((s, n) => s + n.value, 0) || 1; return `${meta.label ? meta.label + ': ' : ''}${r.map((n) => `${n.name} ${Math.round((n.value / tot) * 100)}%`).join(', ')}`; },
|
|
451
|
+
};
|
|
452
|
+
const clip = (painter, text, w, f) => { const s = String(text); if (painter.measure(s, f) <= w) return s; let k = s.length; while (k > 1 && painter.measure(s.slice(0, k) + '…', f) > w) k--; return k > 1 ? s.slice(0, k) + '…' : ''; };
|
|
453
|
+
|
|
454
|
+
const sunburst = {
|
|
455
|
+
element: 'arc', name: 'Sunburst chart', axes: 'none', legend: 'points', colors: 'none',
|
|
456
|
+
defaults: { aspectRatio: 1, interaction: { mode: 'nearest', intersect: true }, plugins: { legend: { display: false } } },
|
|
457
|
+
parse: treeParse,
|
|
458
|
+
limits: () => [Infinity, -Infinity],
|
|
459
|
+
update(chart, meta) {
|
|
460
|
+
const a = chart.chartArea, tree = meta.tree, colors = nodeColors(chart, meta, tree), cx = (a.left + a.right) / 2, cy = (a.top + a.bottom) / 2;
|
|
461
|
+
const R = Math.max(0, Math.min(a.right - a.left, a.bottom - a.top) / 2), inner = pct(chart.option(meta, 'cutout', 0, null, 0), R);
|
|
462
|
+
const depth = Math.max(0, ...tree.nodes.map((n) => n.depth)) + 1, band = (R - inner) / Math.max(1, depth), bg = themeOf(chart).bg;
|
|
463
|
+
const els = [], start = deg(opt(chart, meta, 'rotation', 0)), sweep = deg(opt(chart, meta, 'circumference', 360));
|
|
464
|
+
const lay = (nodes, a0, a1) => {
|
|
465
|
+
const vis = nodes.filter((n) => n.depth > 0 || chart.getDataVisibility(n.i)), tot = vis.reduce((s, n) => s + n.value, 0) || 1;
|
|
466
|
+
let t = a0;
|
|
467
|
+
for (const n of vis) {
|
|
468
|
+
const span = ((a1 - a0) * n.value) / tot, c = colors.get(n.i);
|
|
469
|
+
els.push({ kind: 'arc', datasetIndex: meta.index, index: n.i, cx, cy, startAngle: t, endAngle: t + span, innerRadius: inner + band * n.depth, outerRadius: inner + band * (n.depth + 1), node: n, skip: false, raw: n.row, parsed: meta.parsed[n.i], options: { backgroundColor: c, hoverBackgroundColor: shade(c, -0.12), borderColor: bg, hoverBorderColor: bg, borderWidth: 1, hoverBorderWidth: 1, offset: 0, hoverOffset: 0, spacing: 0 } });
|
|
470
|
+
if (n.children.length) lay(n.children, t, t + span);
|
|
471
|
+
t += span;
|
|
472
|
+
}
|
|
473
|
+
};
|
|
474
|
+
lay(tree.roots, start, start + sweep);
|
|
475
|
+
meta.elements = els;
|
|
476
|
+
},
|
|
477
|
+
initial(el) { return { ...el, outerRadius: el.innerRadius }; },
|
|
478
|
+
draw(painter, meta, chart) {
|
|
479
|
+
arcs.draw(painter, meta, chart);
|
|
480
|
+
const lab = meta.dataset.labels ?? {}, f = fontOf(chart, { size: 11, ...(lab.font ?? {}) });
|
|
481
|
+
if (lab.display === false) return;
|
|
482
|
+
for (const e of meta.elements) {
|
|
483
|
+
const span = e.endAngle - e.startAngle, mid = (e.startAngle + e.endAngle) / 2, rr = (e.innerRadius + e.outerRadius) / 2, thick = e.outerRadius - e.innerRadius;
|
|
484
|
+
// a level label at the arc's middle: across it lies the ring's thickness where the arc runs up and down, its length where it runs across
|
|
485
|
+
const c = Math.abs(Math.cos(mid)), s = Math.abs(Math.sin(mid)), along = Math.min(span * rr, thick * 3);
|
|
486
|
+
const room = e.innerRadius === 0 && span > 6 ? thick * 1.6 : c * along + s * thick, high = e.innerRadius === 0 && span > 6 ? thick : s * Math.min(span * rr, thick * 3) + c * thick;
|
|
487
|
+
const text = clip(painter, e.node.name, room - 6, f);
|
|
488
|
+
if (!text || high < f.size * 1.2) continue;
|
|
489
|
+
const x = e.innerRadius === 0 && span > 6 ? e.cx : e.cx + Math.sin(mid) * rr, y = e.innerRadius === 0 && span > 6 ? e.cy : e.cy - Math.cos(mid) * rr;
|
|
490
|
+
painter.text(text, x, y, { fill: contrastOn(e.options.backgroundColor), font: f, align: 'center', baseline: 'middle' });
|
|
491
|
+
}
|
|
492
|
+
},
|
|
493
|
+
label(chart, meta, el) { return el.parsed?.path ?? ''; },
|
|
494
|
+
format(chart, meta, el, fmt) { return fmt(el.node?.value ?? el.parsed?.value); },
|
|
495
|
+
swatch(chart, meta, el) { return el.options?.backgroundColor; },
|
|
496
|
+
legendItems: treemap.legendItems,
|
|
497
|
+
describe: treemap.describe,
|
|
498
|
+
};
|
|
499
|
+
|
|
500
|
+
// ── funnel and pyramid ─────────────────────────────────────────────────────────────────
|
|
501
|
+
const pointsOf = (chart, meta) => {
|
|
502
|
+
const labels = chart.data.labels ?? [];
|
|
503
|
+
return (meta.dataset.data ?? []).map((raw, i) => {
|
|
504
|
+
const o = raw != null && typeof raw === 'object' && !Array.isArray(raw) ? raw : Array.isArray(raw) ? { name: raw[0], y: raw[1] } : { y: raw };
|
|
505
|
+
return { index: i, value: num(o.y ?? o.value ?? o.v), name: String(o.name ?? o.label ?? o.x ?? labels[i] ?? i + 1), raw, i };
|
|
506
|
+
});
|
|
507
|
+
};
|
|
508
|
+
const inPoly = (pts, x, y) => { let inside = false; for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) { const [xi, yi] = pts[i], [xj, yj] = pts[j]; if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / ((yj - yi) || 1e-9) + xi) inside = !inside; } return inside; };
|
|
509
|
+
function polyElement(meta, p, pts, color) {
|
|
510
|
+
const xs = pts.map((q) => q[0]), ys = pts.map((q) => q[1]), cx = (Math.min(...xs) + Math.max(...xs)) / 2, cy = (Math.min(...ys) + Math.max(...ys)) / 2;
|
|
511
|
+
return { kind: 'poly', datasetIndex: meta.index, index: p.i, pts, cx: cx, grow: 1, color, skip: false, raw: p.raw, parsed: p, hit: (x, y) => inPoly(pts, x, y), bounds: { l: Math.min(...xs), r: Math.max(...xs), t: Math.min(...ys), b: Math.max(...ys) }, center: { x: cx, y: cy }, tip: { x: cx, y: Math.min(...ys) } };
|
|
512
|
+
}
|
|
513
|
+
function funnelLike(kind) {
|
|
514
|
+
return {
|
|
515
|
+
element: 'poly', name: kind === 'pyramid' ? 'Pyramid chart' : 'Funnel chart', axes: 'none', legend: 'points', colors: 'points',
|
|
516
|
+
defaults: { aspectRatio: 1.4, interaction: { mode: 'nearest', intersect: true }, plugins: { legend: { display: false } } },
|
|
517
|
+
parse: pointsOf,
|
|
518
|
+
limits: () => [Infinity, -Infinity],
|
|
519
|
+
update(chart, meta) {
|
|
520
|
+
const a = chart.chartArea, W = pct(opt(chart, meta, 'width', '90%'), a.right - a.left), H = a.bottom - a.top, cx = (a.left + a.right) / 2;
|
|
521
|
+
const vis = meta.parsed.filter((p) => chart.getDataVisibility(p.i) && p.value > 0), tot = vis.reduce((s, p) => s + p.value, 0) || 1, max = Math.max(1e-12, ...vis.map((p) => p.value));
|
|
522
|
+
const gap = opt(chart, meta, 'spacing', 2), shape = meta.dataset.shape ?? (kind === 'pyramid' ? 'pyramid' : 'funnel');
|
|
523
|
+
const neckW = pct(opt(chart, meta, 'neckWidth', '30%'), W), neckH = pct(opt(chart, meta, 'neckHeight', '25%'), H);
|
|
524
|
+
// the outline's half width at a height from the top
|
|
525
|
+
const half = (y) => (shape === 'pyramid' ? (W / 2) * (y / H) : y >= H - neckH ? neckW / 2 : W / 2 - ((W - neckW) / 2) * (y / Math.max(1e-9, H - neckH)));
|
|
526
|
+
let y = 0;
|
|
527
|
+
meta.elements = meta.parsed.map((p) => {
|
|
528
|
+
if (!vis.includes(p)) return { kind: 'poly', datasetIndex: meta.index, index: p.i, pts: [], skip: true, raw: p.raw, parsed: p };
|
|
529
|
+
const k = vis.indexOf(p), color = chart.fillOf(meta, p.i);
|
|
530
|
+
let pts;
|
|
531
|
+
if (shape === 'bars') { const h = (H - gap * (vis.length - 1)) / vis.length, w = (W * p.value) / max, top = a.top + k * (h + gap); pts = [[cx - w / 2, top], [cx + w / 2, top], [cx + w / 2, top + h], [cx - w / 2, top + h]]; }
|
|
532
|
+
else {
|
|
533
|
+
const h = (H * p.value) / tot, y0 = y, y1 = y + h; y = y1;
|
|
534
|
+
const t = a.top + y0 + (k ? gap / 2 : 0), b = a.top + y1 - (k < vis.length - 1 ? gap / 2 : 0), mid = H - neckH;
|
|
535
|
+
pts = [[cx - half(y0), t], [cx + half(y0), t]];
|
|
536
|
+
if (shape === 'funnel' && y0 < mid && y1 > mid) pts.push([cx + half(mid), a.top + mid], [cx + half(y1), b], [cx - half(y1), b], [cx - half(mid), a.top + mid]);
|
|
537
|
+
else pts.push([cx + half(y1), b], [cx - half(y1), b]);
|
|
538
|
+
}
|
|
539
|
+
return polyElement(meta, p, pts, color);
|
|
540
|
+
});
|
|
541
|
+
},
|
|
542
|
+
initial(el) { return { ...el, grow: 0 }; },
|
|
543
|
+
draw(painter, meta, chart) {
|
|
544
|
+
const fmt = fmtOf(chart), lab = meta.dataset.labels ?? {}, f = fontOf(chart, lab.font);
|
|
545
|
+
let lastOut = -Infinity;
|
|
546
|
+
for (const e of meta.elements) {
|
|
547
|
+
if (e.skip || !e.pts.length) continue;
|
|
548
|
+
const g = e.grow ?? 1, pts = e.pts.map(([x, y]) => [e.cx + (x - e.cx) * g, y]), active = chart.isActive(meta.index, e.index);
|
|
549
|
+
painter.path('M' + pts.map((q) => `${r2(q[0])},${r2(q[1])}`).join('L') + 'Z', { fill: active ? shade(e.color, -0.12) : e.color, stroke: opt(chart, meta, 'borderWidth', 0) > 0 ? chart.strokeOf(meta, e.index) : null, width: opt(chart, meta, 'borderWidth', 0) });
|
|
550
|
+
if (lab.display === false) continue;
|
|
551
|
+
const text = typeof lab.formatter === 'function' ? String(lab.formatter(e.parsed.value, { chart, name: e.parsed.name, index: e.index })) : `${e.parsed.name}: ${fmt(e.parsed.value)}`;
|
|
552
|
+
const w = e.bounds.r - e.bounds.l, h = e.bounds.b - e.bounds.t;
|
|
553
|
+
const inside = h >= f.size * 1.1 && painter.measure(text, f) < w * 0.8;
|
|
554
|
+
if (!inside) { if (e.center.y - lastOut < f.size * 1.15) continue; lastOut = e.center.y; }
|
|
555
|
+
painter.text(inside ? text : clip(painter, text, (chart.chartArea.right - e.bounds.r) - 8, f), inside ? e.center.x : e.bounds.r + 6, e.center.y, { fill: inside ? (lab.color && lab.color !== 'auto' ? lab.color : contrastOn(e.color)) : chart.resolved.color, font: f, align: inside ? 'center' : 'left', baseline: 'middle', opacity: g });
|
|
556
|
+
}
|
|
557
|
+
},
|
|
558
|
+
label(chart, meta, el) { return el.parsed?.name ?? ''; },
|
|
559
|
+
format(chart, meta, el, fmt) { const tot = meta.parsed.reduce((s, p) => s + (chart.getDataVisibility(p.i) && p.value > 0 ? p.value : 0), 0) || 1, first = meta.parsed.find((p) => chart.getDataVisibility(p.i))?.value || tot; return `${fmt(el.parsed.value)} (${Math.round((el.parsed.value / (kind === 'funnel' ? first : tot)) * 100)}%)`; },
|
|
560
|
+
swatch(chart, meta, el) { return el.color; },
|
|
561
|
+
};
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
// ── waterfall: each value moves a running total; sums show where it stands ─────────────────
|
|
565
|
+
const WATER = { up: '#2a9d8f', down: '#d1495b', sum: '#3d7dd8' };
|
|
566
|
+
const waterfall = {
|
|
567
|
+
...bar, name: 'Waterfall chart', colors: 'none', stack: false, defaults: INDEX,
|
|
568
|
+
parse(chart, meta) {
|
|
569
|
+
const read = indexReader(chart, meta), labels = chart.data.labels ?? [];
|
|
570
|
+
let run = 0, lastSum = 0;
|
|
571
|
+
return (meta.dataset.data ?? []).map((raw, i) => {
|
|
572
|
+
const o = raw != null && typeof raw === 'object' && !Array.isArray(raw) ? raw : { y: raw };
|
|
573
|
+
const isSum = o.isSum || o.sum === true || raw === 'sum' || raw === 'total' || o.total === true, isMid = o.isIntermediateSum || o.intermediate === true || raw === 'subtotal';
|
|
574
|
+
if (isSum) return { index: read(o.x ?? labels[i], i), low: 0, value: run, delta: run, kind: 'sum', raw, i };
|
|
575
|
+
if (isMid) { const p = { index: read(o.x ?? labels[i], i), low: lastSum, value: run, delta: run - lastSum, kind: 'sum', raw, i }; lastSum = run; return p; }
|
|
576
|
+
const d = num(o.y ?? o.value);
|
|
577
|
+
if (!Number.isFinite(d)) return { index: read(o.x ?? labels[i], i), value: NaN, raw, i };
|
|
578
|
+
const p = { index: read(o.x ?? labels[i], i), low: run, value: run + d, delta: d, kind: d >= 0 ? 'up' : 'down', raw, i };
|
|
579
|
+
run += d;
|
|
580
|
+
return p;
|
|
581
|
+
});
|
|
582
|
+
},
|
|
583
|
+
scales: () => ({ index: { offset: true }, value: { beginAtZero: true } }),
|
|
584
|
+
update(chart, meta, mode) {
|
|
585
|
+
bar.update(chart, meta, mode);
|
|
586
|
+
const own = meta.dataset.backgroundColor;
|
|
587
|
+
for (const e of meta.elements) {
|
|
588
|
+
const k = e.parsed.kind, c = own != null ? chart.fillOf(meta, e.index) : chart.option(meta, k + 'Color', e.index) ?? (k === 'sum' ? paletteOf(chart, meta)[0] ?? WATER.sum : WATER[k] ?? WATER.up);
|
|
589
|
+
e.options = { ...e.options, backgroundColor: c, hoverBackgroundColor: shade(c, -0.12), borderColor: e.options.borderColor };
|
|
590
|
+
}
|
|
591
|
+
},
|
|
592
|
+
draw(painter, meta, chart) {
|
|
593
|
+
const els = meta.elements, con = meta.dataset.connector ?? {};
|
|
594
|
+
if (meta.dataset.showConnector !== false) for (let k = 1; k < els.length; k++) {
|
|
595
|
+
const a = els[k - 1], b = els[k];
|
|
596
|
+
if (a.skip || b.skip) continue;
|
|
597
|
+
const level = chart.scales[meta.vAxisID].getPixelForValue(a.parsed.value);
|
|
598
|
+
if (a.horizontal) painter.line(level, a.y + a.width / 2, level, b.y - b.width / 2, { stroke: con.color ?? themeOf(chart).axis, width: con.width ?? 1, dash: con.dash ?? [3, 3] });
|
|
599
|
+
else painter.line(a.x + a.width / 2, level, b.x - b.width / 2, level, { stroke: con.color ?? themeOf(chart).axis, width: con.width ?? 1, dash: con.dash ?? [3, 3] });
|
|
600
|
+
}
|
|
601
|
+
bar.draw(painter, meta, chart);
|
|
602
|
+
},
|
|
603
|
+
format(chart, meta, el, fmt) { const p = el.parsed; return p.kind === 'sum' ? fmt(p.value) : `${p.delta >= 0 ? '+' : ''}${fmt(p.delta)} (${fmt(p.value)})`; },
|
|
604
|
+
describe(chart, meta, fmt) {
|
|
605
|
+
const ps = meta.parsed.filter((p) => Number.isFinite(p.value)), moves = ps.filter((p, k) => p.kind !== 'sum' && k > 0), name = nameOf(chart, meta);
|
|
606
|
+
if (!ps.length) return `${meta.label || 'Waterfall'}: no values`;
|
|
607
|
+
const up = moves.reduce((a, b) => (b.delta > (a?.delta ?? -Infinity) ? b : a), null), down = moves.reduce((a, b) => (b.delta < (a?.delta ?? Infinity) ? b : a), null);
|
|
608
|
+
return `${named(meta)}starts at ${fmt(ps[0].kind === 'sum' ? ps[0].value : ps[0].delta)} and ends at ${fmt(ps.at(-1).value)}${up && up.delta > 0 ? `, the largest rise ${fmt(up.delta)} at ${name(up)}` : ''}${down && down.delta < 0 ? `, the largest fall ${fmt(-down.delta)} at ${name(down)}` : ''}`;
|
|
609
|
+
},
|
|
610
|
+
swatch(chart, meta, el) { return el.options?.backgroundColor; },
|
|
611
|
+
legendItem() { return { fillStyle: WATER.up, strokeStyle: WATER.down, lineWidth: 2 }; },
|
|
612
|
+
};
|
|
613
|
+
|
|
614
|
+
// ── timeline: bars from a start to an end on rows (Highcharts xrange, ApexCharts rangeBar) ─────
|
|
615
|
+
function spansOf(chart, meta) {
|
|
616
|
+
return (meta.dataset.data ?? []).map((raw, i) => {
|
|
617
|
+
const s = spanOf(chart, raw, i);
|
|
618
|
+
// Gantt: an id, the tasks this one waits for, and a milestone (a moment, drawn as a diamond)
|
|
619
|
+
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
|
|
620
|
+
s.id = raw.id; s.deps = depsOf(raw.dependency ?? raw.dependencies ?? raw.dependsOn); s.milestone = !!raw.milestone;
|
|
621
|
+
if (s.milestone && (s.end == null || s.end === '')) s.end = s.start;
|
|
622
|
+
}
|
|
623
|
+
return s;
|
|
624
|
+
});
|
|
625
|
+
}
|
|
626
|
+
function spanOf(chart, raw, i) {
|
|
627
|
+
if (raw == null) return { cat: null, start: NaN, end: NaN, raw, i };
|
|
628
|
+
if (raw.x2 != null || (raw.milestone && raw.x != null && !Array.isArray(raw.x))) return { cat: raw.y ?? raw.name, start: raw.x, end: raw.x2, raw, i, done: raw.partialFill?.amount ?? raw.partialFill ?? raw.completed };
|
|
629
|
+
if (Array.isArray(raw.y)) return { cat: raw.x, start: raw.y[0], end: raw.y[1], raw, i, done: raw.completed };
|
|
630
|
+
if (Array.isArray(raw.x)) return { cat: raw.y, start: raw.x[0], end: raw.x[1], raw, i, done: raw.completed };
|
|
631
|
+
if (Array.isArray(raw)) return raw.length >= 3 ? { cat: raw[0], start: raw[1], end: raw[2], raw, i } : { cat: (chart.data.labels ?? [])[i], start: raw[0], end: raw[1], raw, i };
|
|
632
|
+
return { cat: raw.task ?? raw.name ?? raw.label ?? raw.category, start: raw.start ?? raw.from, end: raw.end ?? raw.to, raw, i, done: raw.completed?.amount ?? raw.completed };
|
|
633
|
+
}
|
|
634
|
+
const depsOf = (d) => (d == null || d === '' ? [] : (Array.isArray(d) ? d : [d]).map((x) => (x && typeof x === 'object' ? String(x.to ?? x.id) : String(x))));
|
|
635
|
+
// Gantt dependencies: an elbowed arrow from the end of each task a task waits for to its start
|
|
636
|
+
function drawLinks(painter, meta, chart) {
|
|
637
|
+
const mine = meta.elements.filter((e) => !e.skip && e.parsed.deps?.length);
|
|
638
|
+
if (!mine.length || meta.dataset.dependencies === false) return;
|
|
639
|
+
const all = new Map();
|
|
640
|
+
for (const m of chart.metas) if (m.controller === meta.controller && chart.isDatasetVisible(m.index)) for (const e of m.elements) if (!e.skip && e.parsed.id != null) all.set(e.parsed.id, e);
|
|
641
|
+
const th = themeOf(chart), c = meta.dataset.dependencyColor ?? chart.resolved.plugins?.gantt?.dependencyColor ?? th.axis, act = (e) => chart.isActive(meta.index, e.index);
|
|
642
|
+
const ends = (e) => (e.parsed.milestone ? { l: e.x - e.width * 0.42, r: e.x + e.width * 0.42 } : { l: Math.min(e.base, e.x), r: Math.max(e.base, e.x) });
|
|
643
|
+
for (const to of mine) for (const id of to.parsed.deps) {
|
|
644
|
+
const from = all.get(id); if (!from) continue;
|
|
645
|
+
const x1 = ends(from).r, y1 = from.y, x2 = ends(to).l, y2 = to.y, hot = act(to) || chart.metas.some((m) => m.elements.includes(from) && chart.isActive(m.index, from.index));
|
|
646
|
+
const st = { stroke: hot ? th.ink : c, width: hot ? 2 : 1.25, clip: chart.clip, join: 'round' };
|
|
647
|
+
const d = x2 - x1 >= 14 ? `M${x1},${y1}H${(x1 + x2) / 2}V${y2}H${x2 - 5}` : `M${x1},${y1}H${x1 + 7}V${(y1 + y2) / 2}H${x2 - 12}V${y2}H${x2 - 5}`;
|
|
648
|
+
painter.path(d, st);
|
|
649
|
+
painter.path(`M${x2 - 6},${y2 - 4}L${x2},${y2}L${x2 - 6},${y2 + 4}Z`, { fill: st.stroke, clip: chart.clip });
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
const timeline = {
|
|
653
|
+
...bar, name: 'Timeline chart', indexAxis: 'y', stack: false, solid: true, defaults: { interaction: { mode: 'nearest', intersect: true, axis: 'xy' } },
|
|
654
|
+
// room for a milestone's diamond at either end
|
|
655
|
+
limits(meta, axis) {
|
|
656
|
+
const r = bar.limits(meta, axis);
|
|
657
|
+
if (axis.id !== meta.vAxisID || !meta.parsed.some((p) => p.milestone) || !(r[1] > r[0])) return r;
|
|
658
|
+
const pad = (r[1] - r[0]) * 0.03; return [r[0] - pad, r[1] + pad];
|
|
659
|
+
},
|
|
660
|
+
scales(meta, chart) {
|
|
661
|
+
const spans = chart.metas.filter((m) => m.type === meta.type).flatMap((m) => spansOf(chart, m));
|
|
662
|
+
const timey = spans.some((s) => looksTime(s.start) || looksTime(s.end)), given = chart.data.labels ?? [];
|
|
663
|
+
const cats = given.length ? null : keysOf(spans.filter((s) => s.cat != null), 'cat');
|
|
664
|
+
return { index: { type: 'category', offset: true, ...(cats ? { labels: cats.map(String) } : {}), grid: { offset: true } }, value: { type: timey ? 'time' : 'linear', beginAtZero: false } };
|
|
665
|
+
},
|
|
666
|
+
parse(chart, meta) {
|
|
667
|
+
const ix = chart.scales[meta.iAxisID], vx = chart.scales[meta.vAxisID], time = vx?.type?.startsWith('time');
|
|
668
|
+
const v = (x) => (time ? toTime(x) : num(x));
|
|
669
|
+
return spansOf(chart, meta).map((s) => {
|
|
670
|
+
const k = s.cat == null ? s.i : typeof s.cat === 'number' && !ix.labels.includes(String(s.cat)) ? s.cat : ix.labels.map(String).indexOf(String(s.cat));
|
|
671
|
+
const a = v(s.start), b = v(s.end);
|
|
672
|
+
return { index: k < 0 ? s.i : k, low: Math.min(a, b), value: Math.max(a, b), done: num(s.done), cat: s.cat, raw: s.raw, i: s.i, id: s.id == null ? null : String(s.id), deps: s.deps ?? [], milestone: !!s.milestone };
|
|
673
|
+
});
|
|
674
|
+
},
|
|
675
|
+
update(chart, meta, mode) {
|
|
676
|
+
bar.update(chart, meta, mode);
|
|
677
|
+
const pal = paletteOf(chart, meta), byCat = meta.dataset.colorByPoint ?? meta.dataset.distributed;
|
|
678
|
+
if (byCat && meta.dataset.backgroundColor == null) for (const e of meta.elements) { const c = pal[e.parsed.index % pal.length]; e.options = { ...e.options, backgroundColor: c, hoverBackgroundColor: shade(c, -0.12) }; }
|
|
679
|
+
for (const e of meta.elements) if (opt(chart, meta, 'borderRadius', null, e.index) == null) e.options = { ...e.options, borderRadius: Math.min(4, e.width / 4) };
|
|
680
|
+
// a milestone is a diamond as tall as the bar would be, at its moment
|
|
681
|
+
for (const e of meta.elements) if (e.parsed?.milestone && !e.skip) { const r = e.width * 0.42; e.bounds = { l: e.x - r - 2, r: e.x + r + 2, t: e.y - r - 2, b: e.y + r + 2 }; e.tip = { x: e.x, y: e.y - r }; }
|
|
682
|
+
},
|
|
683
|
+
draw(painter, meta, chart) {
|
|
684
|
+
drawLinks(painter, meta, chart);
|
|
685
|
+
for (const e of meta.elements) {
|
|
686
|
+
if (e.skip) continue;
|
|
687
|
+
if (e.parsed.milestone) { const r = e.width * 0.42 * (e.grow ?? 1), c = e.options.backgroundColor, act = chart.isActive(meta.index, e.index); painter.path(`M${e.x},${e.y - r}L${e.x + r},${e.y}L${e.x},${e.y + r}L${e.x - r},${e.y}Z`, { fill: act ? e.options.hoverBackgroundColor : c, stroke: themeOf(chart).bg, width: 1, clip: chart.clip }); continue; }
|
|
688
|
+
const o = e.options, active = chart.isActive(meta.index, e.index), l = Math.min(e.base, e.x), w = Math.abs(e.x - e.base), t = e.y - e.width / 2;
|
|
689
|
+
painter.path(barPath(l, t, w, e.width, o.borderRadius), { fill: active ? o.hoverBackgroundColor : o.backgroundColor, clip: chart.clip });
|
|
690
|
+
const done = e.parsed.done;
|
|
691
|
+
if (Number.isFinite(done) && done > 0) painter.path(barPath(l, t, w * Math.min(1, done), e.width, o.borderRadius), { fill: shade(typeof o.backgroundColor === 'string' ? o.backgroundColor : '#3d7dd8', -0.25), clip: chart.clip, opacity: 0.85 });
|
|
692
|
+
}
|
|
693
|
+
},
|
|
694
|
+
label(chart, meta, el) { return String(chart.scales[meta.iAxisID].labels[el.parsed.index] ?? el.parsed.cat ?? ''); },
|
|
695
|
+
describe(chart, meta, fmt) {
|
|
696
|
+
const vx = chart.scales[meta.vAxisID], f = (v) => (vx.type.startsWith('time') ? formatTime(v, 'MMM d, yyyy') : fmt(v)), ix = chart.scales[meta.iAxisID];
|
|
697
|
+
return named(meta) + meta.parsed.filter((p) => Number.isFinite(p.value)).slice(0, 10).map((p) => `${ix.labels[p.index] ?? p.cat} from ${f(p.low)} to ${f(p.value)}`).join('; ');
|
|
698
|
+
},
|
|
699
|
+
format(chart, meta, el, fmt) {
|
|
700
|
+
const vx = chart.scales[meta.vAxisID], p = el.parsed, f = (v) => (vx.type.startsWith('time') ? formatTime(v, vx.options.time?.tooltipFormat ?? 'MMM d, yyyy') : fmt(v));
|
|
701
|
+
if (p.milestone) return `milestone ${f(p.value)}`;
|
|
702
|
+
return `${f(p.low)} – ${f(p.value)}${Number.isFinite(p.done) ? ` (${Math.round(p.done * 100)}% done)` : ''}${p.deps?.length ? `, after ${p.deps.join(', ')}` : ''}`;
|
|
703
|
+
},
|
|
704
|
+
swatch(chart, meta, el) { return el.options?.backgroundColor; },
|
|
705
|
+
};
|
|
706
|
+
|
|
707
|
+
// ── errorBar, dumbbell, lollipop, bullet ─────────────────────────────────────────────────
|
|
708
|
+
const errorBar = {
|
|
709
|
+
element: 'whisker', name: 'Error bars', colors: 'none', legend: 'none', parse: parseRanges, limits: rangeLimits, format: rangeFormat, describe: (c, m, f) => `error bars ${rangeDescribe(c, m, f)}`,
|
|
710
|
+
update(chart, meta) {
|
|
711
|
+
const vx = chart.scales[meta.vAxisID], ix = chart.scales[meta.iAxisID], horiz = meta.indexAxis === 'y', ds = meta.dataset;
|
|
712
|
+
const link = ds.linkedTo != null ? chart.metas.find((m) => m !== meta && (m.index === ds.linkedTo || (m.dataset.id != null && m.dataset.id === ds.linkedTo))) : null;
|
|
713
|
+
const slot = ix.type === 'category' || ix.type === 'timeseries' ? ix.bandSize : 24;
|
|
714
|
+
meta.horiz = horiz;
|
|
715
|
+
meta.elements = meta.parsed.map((p) => {
|
|
716
|
+
const linked = link?.elements?.find((e) => e.index === p.i);
|
|
717
|
+
const u = linked ? (horiz ? linked.y : linked.x) : ix.getPixelForValue(p.index, p.i), w = (linked?.width ?? slot * 0.5) * (ds.whiskerWidth ?? 0.4);
|
|
718
|
+
const skip = !Number.isFinite(p.low), lo = skip ? NaN : vx.getPixelForValue(p.low), hi = skip ? NaN : vx.getPixelForValue(p.high);
|
|
719
|
+
return { kind: 'whisker', datasetIndex: meta.index, index: p.i, x: u, width: w, low: lo, high: hi, skip, raw: p.raw, parsed: p, bounds: boxAround(horiz, u - w / 2 - 2, u + w / 2 + 2, lo, hi), tip: place(horiz)(u, horiz ? Math.max(lo, hi) : Math.min(lo, hi)) };
|
|
720
|
+
});
|
|
721
|
+
},
|
|
722
|
+
initial(el) { const m = (el.low + el.high) / 2; return { ...el, low: m, high: m }; },
|
|
723
|
+
draw(painter, meta, chart) {
|
|
724
|
+
const P = place(meta.horiz);
|
|
725
|
+
for (const e of meta.elements) {
|
|
726
|
+
if (e.skip) continue;
|
|
727
|
+
const c = chart.option(meta, 'borderColor', e.index) ?? chart.option(meta, 'color', e.index) ?? themeOf(chart).ink, w = opt(chart, meta, 'borderWidth', 1.5, e.index), st = { stroke: chart.isActive(meta.index, e.index) ? shade(c, 0.2) : c, width: w };
|
|
728
|
+
const seg = (u0, v0, u1, v1) => { const a = P(u0, v0), b = P(u1, v1); painter.line(a.x, a.y, b.x, b.y, st); };
|
|
729
|
+
seg(e.x, e.low, e.x, e.high); seg(e.x - e.width / 2, e.low, e.x + e.width / 2, e.low); seg(e.x - e.width / 2, e.high, e.x + e.width / 2, e.high);
|
|
730
|
+
}
|
|
731
|
+
},
|
|
732
|
+
swatch(chart, meta) { return chart.option(meta, 'borderColor', 0) ?? themeOf(chart).ink; },
|
|
733
|
+
};
|
|
734
|
+
const dumbbell = {
|
|
735
|
+
element: 'point', name: 'Dumbbell chart', solid: true, defaults: INDEX, parse: parseRanges, limits: rangeLimits, format: rangeFormat, describe: rangeDescribe,
|
|
736
|
+
scales: () => ({ index: { offset: true } }),
|
|
737
|
+
update(chart, meta) {
|
|
738
|
+
const vx = chart.scales[meta.vAxisID], ix = chart.scales[meta.iAxisID], horiz = meta.indexAxis === 'y', r = opt(chart, meta, 'radius', 5);
|
|
739
|
+
meta.horiz = horiz;
|
|
740
|
+
meta.elements = meta.parsed.map((p) => {
|
|
741
|
+
const skip = !Number.isFinite(p.low), u = ix.getPixelForValue(p.index, p.i), lo = skip ? NaN : vx.getPixelForValue(p.low), hi = skip ? NaN : vx.getPixelForValue(p.high);
|
|
742
|
+
return { kind: 'point', datasetIndex: meta.index, index: p.i, u, low: lo, high: hi, x: place(horiz)(u, hi).x, y: place(horiz)(u, hi).y, radius: r, skip, raw: p.raw, parsed: p, bounds: boxAround(horiz, u - r - 2, u + r + 2, Math.min(lo, hi) - r, Math.max(lo, hi) + r), tip: place(horiz)(u, horiz ? Math.max(lo, hi) : Math.min(lo, hi)), center: place(horiz)(u, (lo + hi) / 2) };
|
|
743
|
+
});
|
|
744
|
+
},
|
|
745
|
+
initial(el) { const m = (el.low + el.high) / 2; return { ...el, low: m, high: m }; },
|
|
746
|
+
draw(painter, meta, chart) {
|
|
747
|
+
const P = place(meta.horiz);
|
|
748
|
+
for (const e of meta.elements) {
|
|
749
|
+
if (e.skip) continue;
|
|
750
|
+
const i = e.index, active = chart.isActive(meta.index, i), hiC = chart.fillOf(meta, i), loC = chart.option(meta, 'lowColor', i) ?? shade(hiC, 0.45);
|
|
751
|
+
const a = P(e.u, e.low), b = P(e.u, e.high), r = active ? e.radius + 1.5 : e.radius;
|
|
752
|
+
painter.line(a.x, a.y, b.x, b.y, { stroke: chart.option(meta, 'connectorColor', i) ?? themeOf(chart).axis, width: opt(chart, meta, 'connectorWidth', 2, i) });
|
|
753
|
+
painter.circle(a.x, a.y, r, { fill: loC, stroke: themeOf(chart).bg, width: 1 });
|
|
754
|
+
painter.circle(b.x, b.y, r, { fill: hiC, stroke: themeOf(chart).bg, width: 1 });
|
|
755
|
+
}
|
|
756
|
+
},
|
|
757
|
+
swatch(chart, meta, el) { return chart.fillOf(meta, el.index); },
|
|
758
|
+
};
|
|
759
|
+
const lollipop = {
|
|
760
|
+
element: 'point', name: 'Lollipop chart', solid: true, defaults: INDEX,
|
|
761
|
+
scales: () => ({ index: { offset: true }, value: { beginAtZero: true } }),
|
|
762
|
+
limits(meta, axis) { return axis.id === meta.iAxisID ? extentOf(meta.parsed.map((p) => p.index)) : extentOf(meta.parsed.map((p) => p.value).concat(0)); },
|
|
763
|
+
update(chart, meta) {
|
|
764
|
+
const vx = chart.scales[meta.vAxisID], ix = chart.scales[meta.iAxisID], horiz = meta.indexAxis === 'y', r = opt(chart, meta, 'radius', 6), base = vx.getBasePixel();
|
|
765
|
+
meta.horiz = horiz;
|
|
766
|
+
meta.elements = meta.parsed.map((p) => {
|
|
767
|
+
const skip = !Number.isFinite(p.value), u = ix.getPixelForValue(p.index, p.i), v = skip ? base : vx.getPixelForValue(p.value), pos = place(horiz)(u, v);
|
|
768
|
+
return { kind: 'point', datasetIndex: meta.index, index: p.i, x: pos.x, y: pos.y, u, base, radius: r, skip, raw: p.raw, parsed: p, options: chart.pointOptions(meta, p.i), bounds: boxAround(horiz, u - r - 2, u + r + 2, base, v + (v < base ? -r : r)), tip: pos, center: pos };
|
|
769
|
+
});
|
|
770
|
+
},
|
|
771
|
+
initial(el, meta) { return meta.horiz ? { ...el, x: el.base } : { ...el, y: el.base }; },
|
|
772
|
+
draw(painter, meta, chart) {
|
|
773
|
+
for (const e of meta.elements) {
|
|
774
|
+
if (e.skip) continue;
|
|
775
|
+
const c = chart.fillOf(meta, e.index), b = place(meta.horiz)(e.u, e.base), active = chart.isActive(meta.index, e.index);
|
|
776
|
+
painter.line(b.x, b.y, e.x, e.y, { stroke: chart.option(meta, 'connectorColor', e.index) ?? c, width: opt(chart, meta, 'connectorWidth', 2, e.index) });
|
|
777
|
+
painter.circle(e.x, e.y, active ? e.radius + 1.5 : e.radius, { fill: c, stroke: themeOf(chart).bg, width: 1.5 });
|
|
778
|
+
}
|
|
779
|
+
},
|
|
780
|
+
swatch(chart, meta, el) { return chart.fillOf(meta, el.index); },
|
|
781
|
+
};
|
|
782
|
+
|
|
783
|
+
const bullet = {
|
|
784
|
+
element: 'bar', name: 'Bullet chart', solid: true, defaults: INDEX,
|
|
785
|
+
parse(chart, meta) {
|
|
786
|
+
const read = indexReader(chart, meta), labels = chart.data.labels ?? [], targets = meta.dataset.targets ?? [];
|
|
787
|
+
return (meta.dataset.data ?? []).map((raw, i) => {
|
|
788
|
+
const o = raw != null && typeof raw === 'object' && !Array.isArray(raw) ? raw : { y: raw };
|
|
789
|
+
return { index: read(o.x ?? labels[i], i), value: num(o.y ?? o.value), target: num(o.target ?? at(targets, i)), ranges: o.ranges ?? o.bands ?? null, raw, i };
|
|
790
|
+
});
|
|
791
|
+
},
|
|
792
|
+
scales: () => ({ index: { offset: true }, value: { beginAtZero: true } }),
|
|
793
|
+
limits(meta, axis) {
|
|
794
|
+
if (axis.id === meta.iAxisID) return extentOf(meta.parsed.map((p) => p.index));
|
|
795
|
+
const bands = (p) => (p.ranges ?? meta.dataset.ranges ?? meta.dataset.bands ?? []).flatMap((b) => (typeof b === 'number' ? [b] : [b.from, b.to]));
|
|
796
|
+
return extentOf(meta.parsed.flatMap((p) => [p.value, p.target, 0, ...bands(p)]));
|
|
797
|
+
},
|
|
798
|
+
update(chart, meta) {
|
|
799
|
+
const vx = chart.scales[meta.vAxisID], horiz = meta.indexAxis === 'y', { width, centerOf } = bandOf(chart, meta, { bar: 0.9 }), base = vx.getBasePixel();
|
|
800
|
+
meta.horiz = horiz;
|
|
801
|
+
meta.elements = meta.parsed.map((p) => {
|
|
802
|
+
const skip = !Number.isFinite(p.value), u = centerOf(p), v = skip ? base : vx.getPixelForValue(p.value), t = Number.isFinite(p.target) ? vx.getPixelForValue(p.target) : NaN;
|
|
803
|
+
const bands = (p.ranges ?? meta.dataset.ranges ?? meta.dataset.bands ?? []).map((b, k, all) => (typeof b === 'number' ? { from: k ? all[k - 1] : vx.getBaseValue(), to: b } : b)).map((b) => ({ ...b, a: vx.getPixelForValue(b.from ?? vx.getBaseValue()), b: vx.getPixelForValue(b.to) }));
|
|
804
|
+
const pos = place(horiz)(u, v), vs = [base, v, t, ...bands.flatMap((b) => [b.a, b.b])].filter(Number.isFinite);
|
|
805
|
+
return { kind: 'bar', datasetIndex: meta.index, index: p.i, x: pos.x, y: pos.y, u, base, width, target: t, bands, horizontal: horiz, skip, raw: p.raw, parsed: p, bounds: boxAround(horiz, u - width / 2, u + width / 2, Math.min(...vs), Math.max(...vs)), tip: place(horiz)(u, horiz ? Math.max(v, Number.isFinite(t) ? t : v) : Math.min(v, Number.isFinite(t) ? t : v)), center: place(horiz)(u, v) };
|
|
806
|
+
});
|
|
807
|
+
},
|
|
808
|
+
initial(el) { return el.horizontal ? { ...el, x: el.base } : { ...el, y: el.base }; },
|
|
809
|
+
draw(painter, meta, chart) {
|
|
810
|
+
const P = place(meta.horiz), grey = themeOf(chart).mode === 'dark' ? ['#3a4552', '#2e3742', '#252c35'] : ['#cfd5dc', '#e0e4e9', '#eef1f4'];
|
|
811
|
+
const rect = (u0, u1, v0, v1, st) => { const a = P(u0, v0), b = P(u1, v1); painter.rect(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.abs(b.x - a.x), Math.abs(b.y - a.y), st); };
|
|
812
|
+
for (const e of meta.elements) {
|
|
813
|
+
if (e.skip) continue;
|
|
814
|
+
const hw = e.width / 2, c = chart.fillOf(meta, e.index), active = chart.isActive(meta.index, e.index);
|
|
815
|
+
e.bands.forEach((b, k) => rect(e.u - hw, e.u + hw, b.a, b.b, { fill: b.color ?? grey[k % grey.length] }));
|
|
816
|
+
const v = meta.horiz ? e.x : e.y;
|
|
817
|
+
rect(e.u - hw * 0.4, e.u + hw * 0.4, e.base, v, { fill: active ? shade(c, -0.12) : c });
|
|
818
|
+
if (Number.isFinite(e.target)) { const a = P(e.u - hw * 0.75, e.target), b = P(e.u + hw * 0.75, e.target); painter.line(a.x, a.y, b.x, b.y, { stroke: chart.option(meta, 'targetColor', e.index) ?? themeOf(chart).ink, width: opt(chart, meta, 'targetWidth', 3, e.index) }); }
|
|
819
|
+
}
|
|
820
|
+
},
|
|
821
|
+
format(chart, meta, el, fmt) { const p = el.parsed; return `${fmt(p.value)}${Number.isFinite(p.target) ? ` (target ${fmt(p.target)})` : ''}`; },
|
|
822
|
+
describe(chart, meta, fmt) { const name = nameOf(chart, meta); return named(meta) + meta.parsed.filter((p) => Number.isFinite(p.value)).map((p) => `${name(p)} ${fmt(p.value)}${Number.isFinite(p.target) ? ` against a target of ${fmt(p.target)}` : ''}`).join('; '); },
|
|
823
|
+
swatch(chart, meta, el) { return chart.fillOf(meta, el.index); },
|
|
824
|
+
};
|
|
825
|
+
|
|
826
|
+
// ── gauge, solidgauge, radialBar ─────────────────────────────────────────────────────────
|
|
827
|
+
// the largest circle whose arc from a0 to a1 (0 at the top, clockwise) fits a box, and its centre
|
|
828
|
+
function fitArc(area, a0, a1, innerShare = 0) {
|
|
829
|
+
const pts = [[0, 0]]; for (let a = a0; a <= a1 + 1e-9; a += (a1 - a0) / 48) pts.push([Math.sin(a), -Math.cos(a)]);
|
|
830
|
+
for (const q of [0, Math.PI / 2, Math.PI, (3 * Math.PI) / 2, -Math.PI / 2, -Math.PI]) if (q >= a0 && q <= a1) pts.push([Math.sin(q), -Math.cos(q)]);
|
|
831
|
+
void innerShare;
|
|
832
|
+
const xs = pts.map((q) => q[0]), ys = pts.map((q) => q[1]), w = Math.max(...xs) - Math.min(...xs), h = Math.max(...ys) - Math.min(...ys);
|
|
833
|
+
const R = Math.max(0, Math.min((area.right - area.left) / (w || 1), (area.bottom - area.top) / (h || 1)));
|
|
834
|
+
return { R, cx: (area.left + area.right) / 2 - ((Math.max(...xs) + Math.min(...xs)) / 2) * R, cy: (area.top + area.bottom) / 2 - ((Math.max(...ys) + Math.min(...ys)) / 2) * R };
|
|
835
|
+
}
|
|
836
|
+
const gaugeOpts = (chart, meta) => ({ min: opt(chart, meta, 'min', 0), max: opt(chart, meta, 'max', 100), a0: deg(opt(chart, meta, 'startAngle', -120)), a1: deg(opt(chart, meta, 'endAngle', 120)) });
|
|
837
|
+
function gaugeLike(solid) {
|
|
838
|
+
return {
|
|
839
|
+
element: 'arc', name: solid ? 'Solid gauge' : 'Gauge', axes: 'none', legend: 'none', colors: 'none',
|
|
840
|
+
defaults: { aspectRatio: 1.6, interaction: { mode: 'nearest', intersect: true }, plugins: { legend: { display: false } } },
|
|
841
|
+
limits: () => [Infinity, -Infinity],
|
|
842
|
+
update(chart, meta) {
|
|
843
|
+
const g = gaugeOpts(chart, meta), first = chart.metas.find((m) => m.type === meta.type), fit = fitArc(chart.chartArea, g.a0, g.a1);
|
|
844
|
+
const R = fit.R * 0.92, inner = pct(opt(chart, meta, 'innerRadius', solid ? '62%' : '0%'), R), t = (v) => Math.max(0, Math.min(1, (v - g.min) / ((g.max - g.min) || 1)));
|
|
845
|
+
meta.gauge = { ...g, ...fit, R, inner, primary: first === meta };
|
|
846
|
+
meta.elements = meta.parsed.slice(0, 1).map((p) => {
|
|
847
|
+
const angle = g.a0 + (g.a1 - g.a0) * t(p.value), skip = !Number.isFinite(p.value);
|
|
848
|
+
const color = chart.option(meta, 'backgroundColor', p.i) ?? (solid ? stopColor(meta.dataset.stops ?? chart.resolved.colorAxis?.stops, t(p.value), paletteOf(chart, meta)[0]) : themeOf(chart).ink);
|
|
849
|
+
return { kind: 'arc', datasetIndex: meta.index, index: p.i, cx: fit.cx, cy: fit.cy, startAngle: g.a0, endAngle: solid ? angle : angle + 0.0001, innerRadius: solid ? inner : 0, outerRadius: R, angle, color, skip, raw: p.raw, parsed: p, options: { backgroundColor: color }, ...(solid ? {} : { hit: (x, y) => Math.hypot(x - fit.cx, y - fit.cy) < R * 0.95 }), center: { x: fit.cx, y: fit.cy }, tip: { x: fit.cx, y: fit.cy - R * 0.4 } };
|
|
850
|
+
});
|
|
851
|
+
},
|
|
852
|
+
initial(el) { return { ...el, angle: el.startAngle, endAngle: el.startAngle + 0.0001 }; },
|
|
853
|
+
draw(painter, meta, chart) {
|
|
854
|
+
const G = meta.gauge, th = themeOf(chart), f = fontOf(chart), fmt = fmtOf(chart), ds = meta.dataset;
|
|
855
|
+
if (G.primary) {
|
|
856
|
+
const track = ds.track ?? {}, bands = ds.bands ?? ds.plotBands ?? [];
|
|
857
|
+
if (solid || track.display !== false) painter.path(arcPath(G.cx, G.cy, solid ? G.inner : G.R * 0.96, G.R, G.a0, G.a1), { fill: track.backgroundColor ?? (solid ? th.grid : 'transparent'), stroke: solid ? null : th.axis, width: 1 });
|
|
858
|
+
for (const b of bands) { const t = (v) => G.a0 + (G.a1 - G.a0) * Math.max(0, Math.min(1, (v - G.min) / ((G.max - G.min) || 1))); const th2 = pct(b.thickness ?? '12%', G.R); painter.path(arcPath(G.cx, G.cy, G.R - th2, G.R, t(b.from ?? G.min), t(b.to ?? G.max)), { fill: b.color ?? th.grid }); }
|
|
859
|
+
if (!solid && ds.ticks !== false) {
|
|
860
|
+
const step = ds.tickInterval ?? niceStep(G.max - G.min, 5), small = { ...f, size: Math.max(9, f.size - 1) };
|
|
861
|
+
for (let v = G.min, k = 0; v <= G.max + 1e-9 && k < 100; v += step, k++) {
|
|
862
|
+
const a = G.a0 + ((G.a1 - G.a0) * (v - G.min)) / ((G.max - G.min) || 1), s = Math.sin(a), c = -Math.cos(a);
|
|
863
|
+
painter.line(G.cx + s * G.R * 0.86, G.cy + c * G.R * 0.86, G.cx + s * G.R * 0.96, G.cy + c * G.R * 0.96, { stroke: th.axis, width: 1.5 });
|
|
864
|
+
painter.text(fmt(v), G.cx + s * G.R * 0.74, G.cy + c * G.R * 0.74, { fill: chart.resolved.color, font: small, align: 'center', baseline: 'middle' });
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
if (solid) { const small = { ...f, size: Math.max(9, f.size - 1) }; const lo = { x: G.cx + Math.sin(G.a0) * (G.inner + G.R) / 2, y: G.cy - Math.cos(G.a0) * (G.inner + G.R) / 2 }, hi = { x: G.cx + Math.sin(G.a1) * (G.inner + G.R) / 2, y: G.cy - Math.cos(G.a1) * (G.inner + G.R) / 2 }; painter.text(fmt(G.min), lo.x, lo.y + f.size * 1.2, { fill: chart.resolved.color, font: small, align: 'center' }); painter.text(fmt(G.max), hi.x, hi.y + f.size * 1.2, { fill: chart.resolved.color, font: small, align: 'center' }); }
|
|
868
|
+
}
|
|
869
|
+
for (const e of meta.elements) {
|
|
870
|
+
if (e.skip) continue;
|
|
871
|
+
const active = chart.isActive(meta.index, e.index);
|
|
872
|
+
if (solid) painter.path(arcPath(e.cx, e.cy, e.innerRadius, e.outerRadius, e.startAngle, Math.max(e.startAngle + 1e-4, e.endAngle)), { fill: active ? shade(e.color, -0.1) : e.color });
|
|
873
|
+
else {
|
|
874
|
+
const n = ds.needle ?? {}, len = pct(n.length ?? '88%', G.R), base = n.width ?? Math.max(3, G.R * 0.04), a = e.angle, s = Math.sin(a), c = -Math.cos(a);
|
|
875
|
+
const tip = [e.cx + s * len, e.cy + c * len], l = [e.cx + c * base, e.cy - s * base], r = [e.cx - c * base, e.cy + s * base], tail = [e.cx - s * base * 2, e.cy - c * base * 2];
|
|
876
|
+
painter.path(`M${r2(l[0])},${r2(l[1])}L${r2(tip[0])},${r2(tip[1])}L${r2(r[0])},${r2(r[1])}L${r2(tail[0])},${r2(tail[1])}Z`, { fill: n.color ?? e.color, stroke: n.color ?? e.color, width: 1, join: 'round' });
|
|
877
|
+
painter.circle(e.cx, e.cy, base * 1.4, { fill: n.color ?? e.color });
|
|
878
|
+
}
|
|
879
|
+
if (G.primary && ds.valueLabel !== false) {
|
|
880
|
+
const big = { ...f, size: Math.max(14, Math.round(G.R * (solid ? 0.28 : 0.18))), weight: '600' }, text = typeof ds.formatter === 'function' ? String(ds.formatter(e.parsed.value)) : fmt(e.parsed.value) + (ds.unit ?? '');
|
|
881
|
+
painter.text(text, e.cx, solid ? e.cy - big.size * 0.1 : e.cy + G.R * 0.42, { fill: th.ink, font: big, align: 'center', baseline: 'middle' });
|
|
882
|
+
if (ds.label) painter.text(String(ds.label), e.cx, (solid ? e.cy : e.cy + G.R * 0.42) + big.size * 0.85, { fill: chart.resolved.color, font: f, align: 'center', baseline: 'middle' });
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
},
|
|
886
|
+
format(chart, meta, el, fmt) { return fmt(el.parsed.value) + (meta.dataset.unit ?? ''); },
|
|
887
|
+
swatch(chart, meta, el) { return el.color; },
|
|
888
|
+
describe(chart, meta, fmt) { const g = gaugeOpts(chart, meta), v = meta.parsed[0]?.value; return `${meta.label ? meta.label + ': ' : ''}${Number.isFinite(v) ? fmt(v) : 'no value'}${meta.dataset.unit ?? ''} on a scale from ${fmt(g.min)} to ${fmt(g.max)}`; },
|
|
889
|
+
};
|
|
890
|
+
}
|
|
891
|
+
function stopColor(stops, t, fallback) {
|
|
892
|
+
if (!stops?.length) return fallback;
|
|
893
|
+
const s = stops.map((q) => (Array.isArray(q) ? q : [q.offset, q.color]));
|
|
894
|
+
if (t <= s[0][0]) return s[0][1];
|
|
895
|
+
for (let k = 1; k < s.length; k++) if (t <= s[k][0]) return mix(s[k - 1][1], s[k][1], (t - s[k - 1][0]) / ((s[k][0] - s[k - 1][0]) || 1));
|
|
896
|
+
return s.at(-1)[1];
|
|
897
|
+
}
|
|
898
|
+
const radialBar = {
|
|
899
|
+
element: 'arc', name: 'Radial bar chart', axes: 'none', legend: 'points', colors: 'points',
|
|
900
|
+
defaults: { aspectRatio: 1, interaction: { mode: 'nearest', intersect: true }, plugins: { legend: { display: false } } },
|
|
901
|
+
parse: pointsOf,
|
|
902
|
+
limits: () => [Infinity, -Infinity],
|
|
903
|
+
update(chart, meta) {
|
|
904
|
+
const a0 = deg(opt(chart, meta, 'startAngle', 0)), a1 = deg(opt(chart, meta, 'endAngle', 360)), max = opt(chart, meta, 'max', 100);
|
|
905
|
+
const fit = fitArc(chart.chartArea, a0, Math.min(a1, a0 + TAU)), R = fit.R * 0.96, hollow = pct(opt(chart, meta, 'hollow', '35%'), R);
|
|
906
|
+
const vis = meta.parsed.filter((p) => chart.getDataVisibility(p.i)), n = Math.max(1, vis.length), band = (R - hollow) / n, thick = band * opt(chart, meta, 'barWidth', 0.72);
|
|
907
|
+
meta.radial = { a0, a1, R, hollow, cx: fit.cx, cy: fit.cy, max };
|
|
908
|
+
meta.elements = meta.parsed.map((p) => {
|
|
909
|
+
const k = vis.indexOf(p), skip = k < 0 || !Number.isFinite(p.value), rMid = R - band * (k + 0.5), t = Math.max(0, Math.min(1, p.value / (max || 1)));
|
|
910
|
+
const c = chart.fillOf(meta, p.i);
|
|
911
|
+
return { kind: 'arc', datasetIndex: meta.index, index: p.i, cx: fit.cx, cy: fit.cy, startAngle: a0, endAngle: a0 + (a1 - a0) * t, innerRadius: rMid - thick / 2, outerRadius: rMid + thick / 2, thick, color: c, skip, raw: p.raw, parsed: p, options: { backgroundColor: c } };
|
|
912
|
+
});
|
|
913
|
+
},
|
|
914
|
+
initial(el) { return { ...el, endAngle: el.startAngle }; },
|
|
915
|
+
draw(painter, meta, chart) {
|
|
916
|
+
const G = meta.radial, th = themeOf(chart), cap = meta.dataset.lineCap ?? 'round', track = meta.dataset.track ?? {};
|
|
917
|
+
for (const e of meta.elements) {
|
|
918
|
+
if (e.skip) continue;
|
|
919
|
+
const rMid = (e.innerRadius + e.outerRadius) / 2, active = chart.isActive(meta.index, e.index);
|
|
920
|
+
if (track.display !== false) painter.path(arcLine(e.cx, e.cy, rMid, G.a0, G.a1), { stroke: track.background ?? th.grid, width: e.thick, cap: 'butt' });
|
|
921
|
+
if (e.endAngle - e.startAngle > 1e-4) painter.path(arcLine(e.cx, e.cy, rMid, e.startAngle, e.endAngle), { stroke: active ? shade(e.color, -0.12) : e.color, width: e.thick, cap });
|
|
922
|
+
}
|
|
923
|
+
const vis = meta.elements.filter((e) => !e.skip), f = fontOf(chart), fmt = fmtOf(chart), act = vis.find((e) => chart.isActive(meta.index, e.index));
|
|
924
|
+
const show = act ?? (vis.length === 1 ? vis[0] : null), total = meta.dataset.total;
|
|
925
|
+
if (show || total) {
|
|
926
|
+
const big = { ...f, size: Math.max(14, Math.round(G.hollow * 0.42)), weight: '600' };
|
|
927
|
+
const value = show ? show.parsed.value : vis.reduce((s, e) => s + e.parsed.value, 0) / (vis.length || 1);
|
|
928
|
+
const text = typeof meta.dataset.formatter === 'function' ? String(meta.dataset.formatter(value, { chart, index: show?.index })) : `${fmt(Math.round(value * 10) / 10)}${G.max === 100 ? '%' : ''}`;
|
|
929
|
+
painter.text(text, G.cx, G.cy, { fill: th.ink, font: big, align: 'center', baseline: 'middle' });
|
|
930
|
+
painter.text(show ? show.parsed.name : total?.label ?? 'Average', G.cx, G.cy + big.size * 0.9, { fill: chart.resolved.color, font: f, align: 'center', baseline: 'middle' });
|
|
931
|
+
}
|
|
932
|
+
},
|
|
933
|
+
label(chart, meta, el) { return el.parsed?.name ?? ''; },
|
|
934
|
+
format(chart, meta, el, fmt) { return `${fmt(el.parsed.value)}${opt(chart, meta, 'max', 100) === 100 ? '%' : ''}`; },
|
|
935
|
+
swatch(chart, meta, el) { return el.color; },
|
|
936
|
+
};
|
|
937
|
+
// a circular arc as a line (stroked, so its ends can be round)
|
|
938
|
+
function arcLine(cx, cy, r, a0, a1) {
|
|
939
|
+
const full = a1 - a0 >= TAU - 1e-6; if (full) a1 = a0 + TAU - 1e-3;
|
|
940
|
+
const P = (a) => `${r2(cx + r * Math.sin(a))},${r2(cy - r * Math.cos(a))}`;
|
|
941
|
+
return `M${P(a0)}A${r2(r)},${r2(r)} 0 ${a1 - a0 > Math.PI ? 1 : 0} 1 ${P(a1)}`;
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
// ── sankey ───────────────────────────────────────────────────────────────────────────────
|
|
945
|
+
const sankey = {
|
|
946
|
+
element: 'flow', name: 'Sankey diagram', axes: 'none', legend: 'none', colors: 'none',
|
|
947
|
+
defaults: { aspectRatio: 1.8, interaction: { mode: 'nearest', intersect: true }, plugins: { legend: { display: false } } },
|
|
948
|
+
parse(chart, meta) { return (meta.dataset.data ?? []).map((raw, i) => { const o = Array.isArray(raw) ? { from: raw[0], to: raw[1], flow: raw[2] } : raw ?? {}; return { index: i, value: num(o.flow ?? o.weight ?? o.value), from: o.from, to: o.to, name: `${o.from} → ${o.to}`, raw, i }; }); },
|
|
949
|
+
limits: () => [Infinity, -Infinity],
|
|
950
|
+
update(chart, meta) {
|
|
951
|
+
const a = chart.chartArea, f = fontOf(chart), ds = meta.dataset, labelsOf = ds.labels ?? {};
|
|
952
|
+
const widest = Math.max(0, ...meta.parsed.flatMap((p) => [p.from, p.to]).map((n) => chart.painter.measure(String(labelsOf[n] ?? n), f)));
|
|
953
|
+
const L0 = a.left, W = Math.max(10, a.right - a.left - widest - 8);
|
|
954
|
+
const lay = L.sankeyLayout(meta.parsed.map((p) => ({ from: p.from, to: p.to, flow: p.value })), { x: L0, y: a.top, w: W, h: a.bottom - a.top, nodeWidth: ds.nodeWidth ?? 12, nodePadding: ds.nodePadding ?? 10, order: ds.nodes });
|
|
955
|
+
const pal = paletteOf(chart, meta), colors = ds.colors ?? {};
|
|
956
|
+
const colorOf = (n) => colors[n.name] ?? (typeof ds.colorFrom === 'function' ? ds.colorFrom(n) : pal[n.k % pal.length]);
|
|
957
|
+
meta.nodes = lay.nodes.map((n) => ({ ...n, color: colorOf(n), label: String(labelsOf[n.name] ?? n.name) }));
|
|
958
|
+
const n0 = meta.parsed.length;
|
|
959
|
+
const links = lay.links.map((l) => {
|
|
960
|
+
const p = meta.parsed[l.i], c = meta.nodes[l.s].color, mx = (l.x0 + l.x1) / 2;
|
|
961
|
+
const d = `M${r2(l.x0)},${r2(l.y0 - l.width / 2)}C${r2(mx)},${r2(l.y0 - l.width / 2)} ${r2(mx)},${r2(l.y1 - l.width / 2)} ${r2(l.x1)},${r2(l.y1 - l.width / 2)}L${r2(l.x1)},${r2(l.y1 + l.width / 2)}C${r2(mx)},${r2(l.y1 + l.width / 2)} ${r2(mx)},${r2(l.y0 + l.width / 2)} ${r2(l.x0)},${r2(l.y0 + l.width / 2)}Z`;
|
|
962
|
+
// inside the band: at x the band's middle is on the curve (a cubic in t, with x(t) close to linear)
|
|
963
|
+
const hit = (x, y) => { if (x < l.x0 || x > l.x1) return false; const t = (x - l.x0) / ((l.x1 - l.x0) || 1), s = t * t * (3 - 2 * t), yc = l.y0 + (l.y1 - l.y0) * s; return Math.abs(y - yc) <= Math.max(2, l.width / 2); };
|
|
964
|
+
return { kind: 'flow', datasetIndex: meta.index, index: l.i, d, color: c, link: l, grow: 1, skip: false, raw: p.raw, parsed: p, hit, center: { x: mx, y: (l.y0 + l.y1) / 2 }, tip: { x: mx, y: (l.y0 + l.y1) / 2 - l.width / 2 } };
|
|
965
|
+
});
|
|
966
|
+
const nodes = meta.nodes.map((n, k) => ({ kind: 'node', datasetIndex: meta.index, index: n0 + k, node: n, color: n.color, grow: 1, skip: false, parsed: { index: n0 + k, value: n.value, name: n.label }, bounds: { l: n.x0, r: n.x1, t: n.y0, b: n.y1 }, center: { x: (n.x0 + n.x1) / 2, y: (n.y0 + n.y1) / 2 }, tip: { x: (n.x0 + n.x1) / 2, y: n.y0 } }));
|
|
967
|
+
meta.elements = [...links, ...nodes];
|
|
968
|
+
},
|
|
969
|
+
initial(el) { return { ...el, grow: 0 }; },
|
|
970
|
+
draw(painter, meta, chart) {
|
|
971
|
+
const f = fontOf(chart), ds = meta.dataset, a = chart.chartArea;
|
|
972
|
+
for (const e of meta.elements) {
|
|
973
|
+
if (e.kind !== 'flow') continue;
|
|
974
|
+
const active = chart.isActive(meta.index, e.index);
|
|
975
|
+
painter.path(e.d, { fill: ds.colorMode === 'to' ? meta.nodes[e.link.t].color : e.color, opacity: (active ? 0.75 : ds.flowOpacity ?? 0.4) * (e.grow ?? 1) });
|
|
976
|
+
}
|
|
977
|
+
for (const e of meta.elements) {
|
|
978
|
+
if (e.kind !== 'node') continue;
|
|
979
|
+
const n = e.node, active = chart.isActive(meta.index, e.index), h = (n.y1 - n.y0) * (e.grow ?? 1);
|
|
980
|
+
painter.rect(n.x0, n.y0 + (n.y1 - n.y0 - h) / 2, n.x1 - n.x0, Math.max(1, h), { fill: active ? shade(n.color, -0.15) : n.color, radius: 1 });
|
|
981
|
+
const right = n.x1 + 6 + painter.measure(n.label, f) < a.right + 1;
|
|
982
|
+
painter.text(n.label, right ? n.x1 + 6 : n.x0 - 6, (n.y0 + n.y1) / 2, { fill: chart.resolved.theme?.ink ?? chart.resolved.color, font: f, align: right ? 'left' : 'right', baseline: 'middle' });
|
|
983
|
+
}
|
|
984
|
+
},
|
|
985
|
+
label(chart, meta, el) { return el.kind === 'node' ? el.node.label : `${meta.dataset.labels?.[el.parsed.from] ?? el.parsed.from} → ${meta.dataset.labels?.[el.parsed.to] ?? el.parsed.to}`; },
|
|
986
|
+
format(chart, meta, el, fmt) { return fmt(el.kind === 'node' ? el.node.value : el.parsed.value); },
|
|
987
|
+
swatch(chart, meta, el) { return el.color; },
|
|
988
|
+
describe(chart, meta, fmt) {
|
|
989
|
+
const ps = meta.parsed.filter((p) => Number.isFinite(p.value)).sort((a, b) => b.value - a.value);
|
|
990
|
+
return `${meta.label ? meta.label + ': ' : ''}${ps.length} flows between ${meta.nodes?.length ?? 0} nodes; the largest ${ps.slice(0, 3).map((p) => `${p.from} to ${p.to} ${fmt(p.value)}`).join(', ')}`;
|
|
991
|
+
},
|
|
992
|
+
};
|
|
993
|
+
|
|
994
|
+
// ── wordcloud ─────────────────────────────────────────────────────────────────────────────
|
|
995
|
+
const wordcloud = {
|
|
996
|
+
element: 'word', name: 'Word cloud', axes: 'none', legend: 'none', colors: 'points',
|
|
997
|
+
defaults: { aspectRatio: 1.8, interaction: { mode: 'nearest', intersect: true }, plugins: { legend: { display: false } } },
|
|
998
|
+
parse(chart, meta) {
|
|
999
|
+
const labels = chart.data.labels ?? [];
|
|
1000
|
+
return (meta.dataset.data ?? []).map((raw, i) => { const o = raw != null && typeof raw === 'object' && !Array.isArray(raw) ? raw : Array.isArray(raw) ? { name: raw[0], weight: raw[1] } : { weight: raw }; return { index: i, value: num(o.weight ?? o.value ?? o.y ?? 1), name: String(o.text ?? o.name ?? o.word ?? o.label ?? o.x ?? labels[i] ?? ''), raw, i }; });
|
|
1001
|
+
},
|
|
1002
|
+
limits: () => [Infinity, -Infinity],
|
|
1003
|
+
update(chart, meta) {
|
|
1004
|
+
const a = chart.chartArea, ds = meta.dataset, W = a.right - a.left, H = a.bottom - a.top, f = fontOf(chart, ds.font);
|
|
1005
|
+
const ps = meta.parsed.filter((p) => p.name && Number.isFinite(p.value) && chart.getDataVisibility(p.i)).sort((p, q) => q.value - p.value);
|
|
1006
|
+
const lo = Math.min(...ps.map((p) => p.value)), hi = Math.max(...ps.map((p) => p.value));
|
|
1007
|
+
const minS = ds.minFontSize ?? 10, rot = ds.rotations ?? (ds.rotation ? spread(ds.rotation) : [0]);
|
|
1008
|
+
let maxS = ds.maxFontSize ?? Math.max(minS + 4, Math.min(72, H / 4.5)), sized, placed;
|
|
1009
|
+
// smaller words until (nearly) all of them find room, unless the largest size was given
|
|
1010
|
+
for (let tries = 0; tries < 8; tries++) {
|
|
1011
|
+
sized = ps.map((p, k) => {
|
|
1012
|
+
const t = hi > lo ? (p.value - lo) / (hi - lo) : 1, size = minS + (maxS - minS) * (ds.scale === 'linear' ? t : Math.sqrt(t));
|
|
1013
|
+
const angle = rot[(p.i * 7 + k) % rot.length] ?? 0, tw = chart.painter.measure(p.name, { ...f, size, weight: ds.fontWeight ?? '600' }), th = size * 1.05;
|
|
1014
|
+
const vertical = Math.abs(angle) === 90;
|
|
1015
|
+
return { p, size, angle, w: vertical ? th : tw, h: vertical ? tw : th };
|
|
1016
|
+
});
|
|
1017
|
+
placed = L.cloudLayout(sized, { w: W, h: H, padding: ds.padding ?? 2, spiral: ds.spiral });
|
|
1018
|
+
if (ds.maxFontSize != null || placed.filter((b) => b.placed).length >= Math.ceil(ps.length * 0.95) || maxS <= minS + 2) break;
|
|
1019
|
+
maxS = Math.max(minS + 2, maxS * 0.82);
|
|
1020
|
+
}
|
|
1021
|
+
const pal = paletteOf(chart, meta);
|
|
1022
|
+
meta.elements = meta.parsed.map((p) => {
|
|
1023
|
+
const k = sized.findIndex((s) => s.p === p), s = sized[k], b = placed[k];
|
|
1024
|
+
if (!s || !b?.placed) return { kind: 'word', datasetIndex: meta.index, index: p.i, skip: true, raw: p.raw, parsed: p };
|
|
1025
|
+
const x = a.left + b.x, y = a.top + b.y, color = chart.option(meta, 'backgroundColor', p.i) ?? chart.option(meta, 'color', p.i) ?? pal[k % pal.length];
|
|
1026
|
+
return { kind: 'word', datasetIndex: meta.index, index: p.i, text: p.name, size: s.size, angle: s.angle, color, grow: 1, skip: false, raw: p.raw, parsed: p, bounds: { l: x, r: x + b.w, t: y, b: y + b.h }, center: { x: x + b.w / 2, y: y + b.h / 2 }, tip: { x: x + b.w / 2, y } };
|
|
1027
|
+
});
|
|
1028
|
+
},
|
|
1029
|
+
initial(el) { return { ...el, grow: 0 }; },
|
|
1030
|
+
draw(painter, meta, chart) {
|
|
1031
|
+
const f = fontOf(chart, meta.dataset.font);
|
|
1032
|
+
for (const e of meta.elements) {
|
|
1033
|
+
if (e.skip) continue;
|
|
1034
|
+
const active = chart.isActive(meta.index, e.index);
|
|
1035
|
+
painter.text(e.text, e.center.x, e.center.y, { fill: active ? shade(e.color, -0.25) : e.color, font: { ...f, size: e.size, weight: meta.dataset.fontWeight ?? '600' }, align: 'center', baseline: 'middle', rotate: e.angle || 0, opacity: e.grow ?? 1 });
|
|
1036
|
+
}
|
|
1037
|
+
},
|
|
1038
|
+
label(chart, meta, el) { return el.parsed?.name ?? ''; },
|
|
1039
|
+
format(chart, meta, el, fmt) { return fmt(el.parsed.value); },
|
|
1040
|
+
swatch(chart, meta, el) { return el.color; },
|
|
1041
|
+
describe(chart, meta) { return `${meta.label ? meta.label + ': ' : ''}the largest words ${meta.parsed.slice().sort((a, b) => b.value - a.value).slice(0, 5).map((p) => p.name).join(', ')}`; },
|
|
1042
|
+
};
|
|
1043
|
+
const spread = (r) => { const n = Math.max(1, r.orientations ?? 2), a = r.from ?? 0, b = r.to ?? 90; return Array.from({ length: n }, (_, k) => (n === 1 ? a : a + ((b - a) * k) / (n - 1))); };
|
|
1044
|
+
|
|
1045
|
+
// ── item: a count as that many dots, in rows of a half ring (a parliament) or a grid ─────────────
|
|
1046
|
+
const item = {
|
|
1047
|
+
element: 'item', name: 'Item chart', axes: 'none', legend: 'points', colors: 'points',
|
|
1048
|
+
defaults: { aspectRatio: 1.8, interaction: { mode: 'nearest', intersect: true }, plugins: { legend: { display: true, position: 'bottom' } } },
|
|
1049
|
+
parse: pointsOf,
|
|
1050
|
+
limits: () => [Infinity, -Infinity],
|
|
1051
|
+
update(chart, meta) {
|
|
1052
|
+
const a = chart.chartArea, ds = meta.dataset, vis = meta.parsed.filter((p) => chart.getDataVisibility(p.i)), counts = vis.map((p) => Math.max(0, Math.round(p.value) || 0)), n = counts.reduce((s, c) => s + c, 0);
|
|
1053
|
+
const W = a.right - a.left, H = a.bottom - a.top, seats = [];
|
|
1054
|
+
let r;
|
|
1055
|
+
if ((ds.layout ?? 'parliament') === 'grid') {
|
|
1056
|
+
const cols = Math.max(1, Math.ceil(Math.sqrt((n * W) / Math.max(1, H)))), rows = Math.ceil(n / cols), cell = Math.min(W / cols, H / Math.max(1, rows));
|
|
1057
|
+
r = cell * 0.4;
|
|
1058
|
+
for (let k = 0; k < n; k++) seats.push({ x: a.left + (W - cell * cols) / 2 + cell * ((k % cols) + 0.5), y: a.top + (H - cell * rows) / 2 + cell * (Math.floor(k / cols) + 0.5) });
|
|
1059
|
+
} else {
|
|
1060
|
+
const s0 = opt(chart, meta, 'startAngle', -90), s1 = opt(chart, meta, 'endAngle', 90), lay = L.parliamentSeats(n, { rows: ds.rows, startAngle: s0, endAngle: s1, inner: ds.innerSize != null ? pct(ds.innerSize, 1) : 0.4 });
|
|
1061
|
+
// the seats on the straight edge stand out by their radius: keep them inside the box
|
|
1062
|
+
const fit = fitArc(a, deg(s0), deg(s1)), R = (fit.R * 0.98) / (1 + lay.r), cy = fit.cy - lay.r * R;
|
|
1063
|
+
r = lay.r * R;
|
|
1064
|
+
meta.seatCenter = { x: fit.cx, y: cy, R };
|
|
1065
|
+
for (const s of lay.seats) seats.push({ x: fit.cx + s.x * R, y: cy + s.y * R });
|
|
1066
|
+
}
|
|
1067
|
+
let k = 0;
|
|
1068
|
+
meta.elements = meta.parsed.map((p) => {
|
|
1069
|
+
const j = vis.indexOf(p), c = j < 0 ? 0 : counts[j], mine = seats.slice(k, k + c);
|
|
1070
|
+
k += c;
|
|
1071
|
+
if (!mine.length) return { kind: 'item', datasetIndex: meta.index, index: p.i, seats: [], skip: true, raw: p.raw, parsed: p };
|
|
1072
|
+
const xs = mine.map((s) => s.x), ys = mine.map((s) => s.y);
|
|
1073
|
+
return { kind: 'item', datasetIndex: meta.index, index: p.i, seats: mine, r, color: chart.fillOf(meta, p.i), grow: 1, skip: false, raw: p.raw, parsed: p, hit: (x, y) => mine.some((s) => Math.hypot(s.x - x, s.y - y) <= r + 1), bounds: { l: Math.min(...xs) - r, r: Math.max(...xs) + r, t: Math.min(...ys) - r, b: Math.max(...ys) + r }, center: { x: xs.reduce((s, v) => s + v, 0) / xs.length, y: ys.reduce((s, v) => s + v, 0) / ys.length }, tip: { x: xs.reduce((s, v) => s + v, 0) / xs.length, y: Math.min(...ys) - r } };
|
|
1074
|
+
});
|
|
1075
|
+
},
|
|
1076
|
+
initial(el) { return { ...el, grow: 0 }; },
|
|
1077
|
+
draw(painter, meta, chart) {
|
|
1078
|
+
for (const e of meta.elements) {
|
|
1079
|
+
if (e.skip) continue;
|
|
1080
|
+
const active = chart.isActive(meta.index, e.index), rr = e.r * (e.grow ?? 1) * (active ? 1.12 : 1), style = meta.dataset.marker ?? 'circle';
|
|
1081
|
+
for (const s of e.seats) painter.path(pointShape(style, s.x, s.y, rr), { fill: active ? shade(e.color, -0.12) : e.color });
|
|
1082
|
+
}
|
|
1083
|
+
const total = meta.parsed.reduce((s, p) => s + (chart.getDataVisibility(p.i) ? Math.round(p.value) || 0 : 0), 0);
|
|
1084
|
+
if ((meta.dataset.layout ?? 'parliament') !== 'grid' && meta.dataset.total !== false && total) {
|
|
1085
|
+
const first = meta.elements.find((e) => !e.skip), f = fontOf(chart), big = { ...f, size: Math.max(14, Math.round((first?.r ?? 6) * 3)), weight: '600' };
|
|
1086
|
+
const c = meta.seatCenter ?? { x: 0, y: 0, R: 0 }, inner = meta.dataset.innerSize != null ? pct(meta.dataset.innerSize, 1) : 0.4;
|
|
1087
|
+
painter.text(fmtOf(chart)(total), c.x, c.y - Math.min(big.size * 0.6, c.R * inner * 0.45), { fill: themeOf(chart).ink, font: big, align: 'center', baseline: 'middle' });
|
|
1088
|
+
}
|
|
1089
|
+
},
|
|
1090
|
+
label(chart, meta, el) { return el.parsed?.name ?? ''; },
|
|
1091
|
+
format(chart, meta, el, fmt) { return fmt(el.parsed.value); },
|
|
1092
|
+
swatch(chart, meta, el) { return el.color; },
|
|
1093
|
+
};
|
|
1094
|
+
|
|
1095
|
+
// ── streamgraph: layers around a middle line ──────────────────────────────────────────────
|
|
1096
|
+
const streamgraph = { ...lineLike, name: 'Streamgraph', alpha: 0.85, filled: true, scales: () => ({ value: { stacked: 'stream', display: false } }), datasetDefaults: { fill: 'stack', tension: 0.35, pointRadius: 0, pointHoverRadius: 3, borderWidth: 0.5 } };
|
|
1097
|
+
|
|
1098
|
+
// ── technical indicators: read the dataset they are linked to ───────────────────────────────────
|
|
1099
|
+
// { type: 'sma', linkedTo: 0 | 'prices', period: 14 } (Highcharts: linkedTo and params: { period })
|
|
1100
|
+
function sourceOf(chart, meta) {
|
|
1101
|
+
const ds = meta.dataset, to = ds.linkedTo;
|
|
1102
|
+
if (to != null) return chart.metas.find((m) => m !== meta && (m.index === to || (m.dataset.id != null && m.dataset.id === to) || (typeof to === 'string' && m.dataset.label === to)));
|
|
1103
|
+
for (let k = meta.index - 1; k >= 0; k--) if (!chart.metas[k].controller.derived) return chart.metas[k];
|
|
1104
|
+
return null;
|
|
1105
|
+
}
|
|
1106
|
+
const param = (meta, k, d) => meta.dataset.params?.[k] ?? meta.dataset[k] ?? d;
|
|
1107
|
+
function indicator(id, compute, label) {
|
|
1108
|
+
return {
|
|
1109
|
+
...lineLike, name: `${id.toUpperCase()} line`, derived: true, stack: false,
|
|
1110
|
+
datasetDefaults: { pointRadius: 0, pointHoverRadius: 3, borderWidth: 1.5, fill: false },
|
|
1111
|
+
parse(chart, meta) {
|
|
1112
|
+
const src = sourceOf(chart, meta);
|
|
1113
|
+
if (!meta.label) meta.label = label(meta);
|
|
1114
|
+
if (!src?.parsed) return [];
|
|
1115
|
+
const xs = src.parsed.map((p) => (Number.isFinite(p.close) ? p.close : p.value));
|
|
1116
|
+
const out = compute(xs, meta);
|
|
1117
|
+
return src.parsed.map((p, i) => ({ index: p.index, value: out[i], raw: { x: p.raw?.x, y: out[i] }, i }));
|
|
1118
|
+
},
|
|
1119
|
+
};
|
|
1120
|
+
}
|
|
1121
|
+
const smaT = indicator('sma', (x, m) => L.sma(x, param(m, 'period', 14)), (m) => `SMA (${param(m, 'period', 14)})`);
|
|
1122
|
+
const emaT = indicator('ema', (x, m) => L.ema(x, param(m, 'period', 14)), (m) => `EMA (${param(m, 'period', 14)})`);
|
|
1123
|
+
const wmaT = indicator('wma', (x, m) => L.wma(x, param(m, 'period', 14)), (m) => `WMA (${param(m, 'period', 14)})`);
|
|
1124
|
+
const momentumT = indicator('momentum', (x, m) => L.momentum(x, param(m, 'period', 10)), (m) => `Momentum (${param(m, 'period', 10)})`);
|
|
1125
|
+
const rsiT = {
|
|
1126
|
+
...indicator('rsi', (x, m) => L.rsi(x, param(m, 'period', 14)), (m) => `RSI (${param(m, 'period', 14)})`),
|
|
1127
|
+
scales: () => ({ value: { min: 0, max: 100 } }),
|
|
1128
|
+
draw(painter, meta, chart) {
|
|
1129
|
+
const vx = chart.scales[meta.vAxisID], a = chart.chartArea, levels = meta.dataset.levels ?? [30, 70];
|
|
1130
|
+
if (levels) for (const v of levels) { const y = vx.getPixelForValue(v); painter.line(a.left, y, a.right, y, { stroke: themeOf(chart).axis, width: 1, dash: [4, 4] }); }
|
|
1131
|
+
lineLike.draw(painter, meta, chart);
|
|
1132
|
+
},
|
|
1133
|
+
};
|
|
1134
|
+
const bollingerT = {
|
|
1135
|
+
...areaRange, name: 'Bollinger bands', derived: true, alpha: 0.15,
|
|
1136
|
+
parse(chart, meta) {
|
|
1137
|
+
const src = sourceOf(chart, meta), n = param(meta, 'period', 20), k = param(meta, 'standardDeviation', param(meta, 'k', 2));
|
|
1138
|
+
if (!meta.label) meta.label = `Bollinger (${n}, ${k})`;
|
|
1139
|
+
if (!src?.parsed) return [];
|
|
1140
|
+
const b = L.bollinger(src.parsed.map((p) => (Number.isFinite(p.close) ? p.close : p.value)), n, k);
|
|
1141
|
+
return src.parsed.map((p, i) => ({ index: p.index, low: b[i].low, high: b[i].high, mid: b[i].mid, value: b[i].mid, raw: { x: p.raw?.x }, i }));
|
|
1142
|
+
},
|
|
1143
|
+
lines(chart, meta, el, fmt) { const p = el.parsed; return [`upper ${fmt(p.high)}`, `middle ${fmt(p.mid)}`, `lower ${fmt(p.low)}`]; },
|
|
1144
|
+
};
|
|
1145
|
+
const macdT = {
|
|
1146
|
+
element: 'point', name: 'MACD', derived: true, stack: false, defaults: INDEX,
|
|
1147
|
+
datasetDefaults: { pointRadius: 0, pointHoverRadius: 3, borderWidth: 1.5 },
|
|
1148
|
+
parse(chart, meta) {
|
|
1149
|
+
const src = sourceOf(chart, meta), s = param(meta, 'shortPeriod', 12), l = param(meta, 'longPeriod', 26), g = param(meta, 'signalPeriod', 9);
|
|
1150
|
+
if (!meta.label) meta.label = `MACD (${s}, ${l}, ${g})`;
|
|
1151
|
+
if (!src?.parsed) return [];
|
|
1152
|
+
const m = L.macd(src.parsed.map((p) => (Number.isFinite(p.close) ? p.close : p.value)), s, l, g);
|
|
1153
|
+
return src.parsed.map((p, i) => ({ index: p.index, value: m[i].macd, signal: m[i].signal, histogram: m[i].histogram, raw: { x: p.raw?.x }, i }));
|
|
1154
|
+
},
|
|
1155
|
+
limits(meta, axis) { return axis.id === meta.iAxisID ? extentOf(meta.parsed.map((p) => p.index)) : extentOf(meta.parsed.flatMap((p) => [p.value, p.signal, p.histogram, 0])); },
|
|
1156
|
+
update(chart, meta) {
|
|
1157
|
+
const ix = chart.scales[meta.iAxisID], vx = chart.scales[meta.vAxisID], { width } = ix.type === 'category' || ix.type === 'timeseries' ? { width: ix.bandSize * 0.6 } : { width: 3 };
|
|
1158
|
+
meta.zero = vx.getPixelForValue(0);
|
|
1159
|
+
meta.elements = meta.parsed.map((p) => {
|
|
1160
|
+
const skip = !Number.isFinite(p.value), x = ix.getPixelForValue(p.index, p.i), V = (v) => (Number.isFinite(v) ? vx.getPixelForValue(v) : NaN);
|
|
1161
|
+
return { kind: 'point', datasetIndex: meta.index, index: p.i, x, y: V(p.value), sig: V(p.signal), hist: V(p.histogram), width, radius: chart.option(meta, 'pointRadius', p.i, 'radius'), skip, raw: p.raw, parsed: p, options: chart.pointOptions(meta, p.i) };
|
|
1162
|
+
});
|
|
1163
|
+
},
|
|
1164
|
+
initial(el, meta) { return { ...el, y: meta.zero, sig: meta.zero, hist: meta.zero }; },
|
|
1165
|
+
draw(painter, meta, chart) {
|
|
1166
|
+
const o = chart.lineOptions(meta), z = meta.zero, up = meta.dataset.upColor ?? FIN.up, down = meta.dataset.downColor ?? FIN.down;
|
|
1167
|
+
for (const e of meta.elements) if (Number.isFinite(e.hist)) painter.rect(e.x - e.width / 2, Math.min(z, e.hist), e.width, Math.abs(e.hist - z), { fill: withAlpha(e.hist <= z ? up : down, 0.55), clip: chart.clip });
|
|
1168
|
+
const pts = meta.elements.filter((e) => !e.skip);
|
|
1169
|
+
if (pts.length) painter.path(pathThrough(pts, o), { stroke: o.borderColor, width: o.borderWidth, clip: chart.clip });
|
|
1170
|
+
const sg = meta.elements.filter((e) => Number.isFinite(e.sig)).map((e) => ({ x: e.x, y: e.sig }));
|
|
1171
|
+
if (sg.length) painter.path(pathThrough(sg, o), { stroke: meta.dataset.signalColor ?? '#e0793a', width: o.borderWidth, clip: chart.clip });
|
|
1172
|
+
drawPoints(painter, meta, chart);
|
|
1173
|
+
},
|
|
1174
|
+
lines(chart, meta, el, fmt) { const p = el.parsed; return [`MACD ${fmt(p.value)}`, `signal ${fmt(p.signal)}`, `histogram ${fmt(p.histogram)}`]; },
|
|
1175
|
+
swatch(chart, meta) { return chart.lineOptions(meta).borderColor; },
|
|
1176
|
+
};
|
|
1177
|
+
|
|
1178
|
+
/** The types added to Chart.js's eight (each also under the names Highcharts and ApexCharts give it). */
|
|
1179
|
+
export const MORE_TYPES = {
|
|
1180
|
+
areaRange, arearange: areaRange, rangeArea: areaRange, areasplinerange: { ...areaRange, datasetDefaults: { ...areaRange.datasetDefaults, tension: 0.4 } },
|
|
1181
|
+
boxplot, boxPlot: boxplot, violin,
|
|
1182
|
+
candlestick: financial('candlestick'), hollowcandlestick: financial('hollow'), hollowCandlestick: financial('hollow'), heikinashi: financial('heikinashi'), ohlc: financial('ohlc'), hlc: financial('hlc'),
|
|
1183
|
+
heatmap, matrix: heatmap,
|
|
1184
|
+
treemap, sunburst,
|
|
1185
|
+
funnel: funnelLike('funnel'), pyramid: funnelLike('pyramid'),
|
|
1186
|
+
waterfall,
|
|
1187
|
+
timeline, xrange: timeline, rangeBar: timeline, gantt: timeline,
|
|
1188
|
+
errorBar, errorbar: errorBar, dumbbell, lollipop, bullet,
|
|
1189
|
+
gauge: gaugeLike(false), solidgauge: gaugeLike(true), radialBar,
|
|
1190
|
+
sankey, wordcloud, item, parliament: item, streamgraph,
|
|
1191
|
+
sma: smaT, ema: emaT, wma: wmaT, momentum: momentumT, rsi: rsiT, bollinger: bollingerT, bb: bollingerT, macd: macdT,
|
|
1192
|
+
};
|
|
1193
|
+
void parseColor;
|