@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/src/index.js ADDED
@@ -0,0 +1,53 @@
1
+ // @clarity-js/charts — charts for Clarity, with Chart.js's configuration and API.
2
+ //
3
+ // import { Chart } from '@clarity-js/charts'
4
+ // new Chart(el, { type: 'line', data, options }) // as in Chart.js
5
+ // <Chart type="line" data={ data } options={ options } /> // in markup, bound to state
6
+ //
7
+ // Every type of Chart.js (line, bar, radar, pie, doughnut, polarArea, bubble, scatter, mixed), its
8
+ // axes (category, linear, logarithmic, time, timeseries, radialLinear), its plugins (title,
9
+ // subtitle, legend, tooltip, filler, decimation, colors) and its API (update, destroy, resize,
10
+ // toBase64Image, getElementsAtEventForMode, setActiveElements, hide/show …), drawn as SVG by
11
+ // default (accessible, server-drawn, CSP-safe) or on a canvas. And what Highcharts and ApexCharts
12
+ // have beyond it: forty more types (candlesticks, box plots, heatmaps, treemaps, sankeys, gauges, maps,
13
+ // 3D columns, pies, scatters and surfaces, networks, organization charts, Venn diagrams, parallel
14
+ // coordinates, Gantt charts …), annotations, data labels, zoom and pan, a navigator, drilldown, themes,
15
+ // gradients, sound, and their own configuration read as they write it (Highcharts.chart(), new ApexCharts()).
16
+
17
+ import { Chart as Core, defaults, merge, renderToSVG, describe, EASING, VERSION } from './core.js';
18
+ import { installMore } from './full.js';
19
+ installMore();
20
+ import { ChartView } from './components.js';
21
+
22
+ /**
23
+ * `new Chart(el, config)` makes a chart (Chart.js's way); `<Chart … />` in markup is the component.
24
+ * One name for both, as a Chart.js user expects to write it.
25
+ */
26
+ function Chart(item, config) {
27
+ if (!new.target) return ChartView(item);
28
+ return new Core(item, config);
29
+ }
30
+ Chart.prototype = Core.prototype;
31
+ for (const k of ['defaults', 'overrides', 'instances', 'version', 'registry', 'register', 'unregister', 'getChart', 'registerTheme', 'themes', 'palettes']) Object.defineProperty(Chart, k, { get: () => (typeof Core[k] === 'function' ? Core[k].bind(Core) : Core[k]), enumerable: true });
32
+
33
+ export { Chart, ChartView, defaults, merge, renderToSVG, describe, EASING as easing, VERSION };
34
+ export { LineChart, AreaChart, BarChart, ScatterChart, PieChart, Histogram, Sparkline } from './components.js';
35
+ export { Axis, RadialAxis, formatTime } from './axes.js';
36
+ export { CONTROLLERS, pathThrough, pointShape, barPath } from './controllers.js';
37
+ export { BUILT_IN_PLUGINS, Title, SubTitle, Legend, Tooltip, Filler, Decimation, Colors, PALETTE, lttb, minMax, generateLabels } from './plugins.js';
38
+ export { MORE_TYPES, colorScaleOf } from './types.js';
39
+ export { MAP_TYPES, PROJECTIONS, orthographic, featuresOf } from './maps.js';
40
+ export { DEPTH_TYPES } from './depth.js';
41
+ export { GRAPH_TYPES, forceLayout, treeLayout, vennLayout, overlap as circleOverlap } from './graphs.js';
42
+ export { MORE_PLUGINS, Annotation, DataLabels, Zoom, Measure, Crosshair, Navigator, RangeSelector, Brush, Toolbar, Drilldown, DataGrouping, ColorAxisLegend, measureBetween, rangeOf } from './features.js';
43
+ export { THEMES, PALETTES, registerTheme, resolveTheme, monochrome } from './themes.js';
44
+ export { isPaint, normalizePaint, cssPaint, mix, shade, withAlpha, luminance, contrastOn, parseColor } from './fills.js';
45
+ export { quantile, boxStats, density, heikinAshi, sma, ema, wma, bollinger, macd, rsi, momentum, squarify, treeOf, sankeyLayout, cloudLayout, parliamentSeats, groupPoints } from './layouts.js';
46
+ export { Highcharts, ApexCharts, fromHighcharts, fromApex } from './compat.js';
47
+ export { installMore };
48
+ export { svgPainter, canvasPainter, stringPainter, measureText } from './painter.js';
49
+ export { linear, log, band, time, niceStep } from './scale.js';
50
+ export { linePath, areaPath, arcPath, stack, extent, bins, decimate } from './shape.js';
51
+ export { formatNumber, formatDate, formatFull } from './format.js';
52
+ /** Chart.js's tree-shaking registrables, for code that registers them: they are always registered here. */
53
+ export const registerables = [];
package/src/layouts.js ADDED
@@ -0,0 +1,272 @@
1
+ // @clarity-js/charts — the arithmetic behind the newer types, with no drawing: quartiles and
2
+ // densities (box plots, violins), Heikin-Ashi candles, technical indicators (SMA, EMA, WMA,
3
+ // Bollinger bands, MACD, RSI, momentum), a squarified treemap, a Sankey diagram, a word cloud,
4
+ // the seats of a parliament, and points gathered into groups. Each is a plain function.
5
+
6
+ // ── statistics ────────────────────────────────────────────────────────────────────
7
+ /** The p-quantile (0 … 1) of sorted numbers, between neighbours (the usual "type 7"). */
8
+ export function quantile(sorted, p) {
9
+ if (!sorted.length) return NaN;
10
+ const h = (sorted.length - 1) * p, lo = Math.floor(h), hi = Math.ceil(h);
11
+ return sorted[lo] + (sorted[hi] - sorted[lo]) * (h - lo);
12
+ }
13
+ /**
14
+ * What a box plot draws for numbers: the quartiles, whiskers to the furthest values within
15
+ * coef × IQR of the box (Tukey's 1.5), the values beyond as outliers, and the mean.
16
+ */
17
+ export function boxStats(values, { coef = 1.5 } = {}) {
18
+ const v = values.map(Number).filter(Number.isFinite).sort((a, b) => a - b);
19
+ if (!v.length) return null;
20
+ const q1 = quantile(v, 0.25), median = quantile(v, 0.5), q3 = quantile(v, 0.75), iqr = q3 - q1;
21
+ const lo = coef > 0 ? q1 - coef * iqr : -Infinity, hi = coef > 0 ? q3 + coef * iqr : Infinity;
22
+ const inside = v.filter((x) => x >= lo && x <= hi);
23
+ return { min: inside[0] ?? v[0], q1, median, q3, max: inside.at(-1) ?? v.at(-1), mean: v.reduce((a, b) => a + b, 0) / v.length, outliers: v.filter((x) => x < lo || x > hi), n: v.length, sorted: v };
24
+ }
25
+ /** A smooth estimate of how numbers are spread (Gaussian kernels, Silverman's bandwidth): [{ v, d }]. */
26
+ export function density(values, { points = 48, bandwidth } = {}) {
27
+ const v = values.map(Number).filter(Number.isFinite).sort((a, b) => a - b);
28
+ if (!v.length) return { coords: [], max: 0, min: NaN, maxV: NaN };
29
+ const n = v.length, mean = v.reduce((a, b) => a + b, 0) / n, sd = Math.sqrt(v.reduce((a, b) => a + (b - mean) ** 2, 0) / Math.max(1, n - 1));
30
+ const iqr = quantile(v, 0.75) - quantile(v, 0.25);
31
+ const h = bandwidth ?? (1.06 * Math.min(sd || 1, iqr / 1.34 || sd || 1) * n ** -0.2 || 1);
32
+ const lo = v[0], hi = v.at(-1), coords = [];
33
+ for (let i = 0; i < points; i++) {
34
+ const x = lo + ((hi - lo) * i) / Math.max(1, points - 1);
35
+ let d = 0; for (const s of v) d += Math.exp(-0.5 * ((x - s) / h) ** 2);
36
+ coords.push({ v: x, d: d / (n * h * Math.sqrt(2 * Math.PI)) });
37
+ }
38
+ return { coords, max: Math.max(...coords.map((c) => c.d)), min: lo, maxV: hi };
39
+ }
40
+
41
+ // ── finance ───────────────────────────────────────────────────────────────────────
42
+ /** Heikin-Ashi candles from plain ones: [{ open, high, low, close }] → the same, smoothed. */
43
+ export function heikinAshi(candles) {
44
+ const out = [];
45
+ let po = NaN, pc = NaN;
46
+ for (const c of candles) {
47
+ if (!c || !Number.isFinite(c.close)) { out.push(c); continue; }
48
+ const close = (c.open + c.high + c.low + c.close) / 4, open = Number.isFinite(po) ? (po + pc) / 2 : (c.open + c.close) / 2;
49
+ out.push({ ...c, open, close, high: Math.max(c.high, open, close), low: Math.min(c.low, open, close) });
50
+ po = open; pc = close;
51
+ }
52
+ return out;
53
+ }
54
+ /** Simple moving average over `period` values (NaN until there are enough). */
55
+ export function sma(values, period = 14) {
56
+ const out = []; let sum = 0, k = 0;
57
+ const q = [];
58
+ for (const v of values) {
59
+ if (!Number.isFinite(v)) { out.push(NaN); continue; }
60
+ q.push(v); sum += v; k++;
61
+ if (q.length > period) sum -= q.shift();
62
+ out.push(q.length === period ? sum / period : NaN);
63
+ }
64
+ void k;
65
+ return out;
66
+ }
67
+ /** Exponential moving average (starting from the simple average of the first `period`). */
68
+ export function ema(values, period = 14) {
69
+ const out = [], a = 2 / (period + 1);
70
+ let prev = NaN, seed = [];
71
+ for (const v of values) {
72
+ if (!Number.isFinite(v)) { out.push(NaN); continue; }
73
+ if (!Number.isFinite(prev)) { seed.push(v); if (seed.length === period) { prev = seed.reduce((s, x) => s + x, 0) / period; out.push(prev); } else out.push(NaN); continue; }
74
+ prev = v * a + prev * (1 - a); out.push(prev);
75
+ }
76
+ return out;
77
+ }
78
+ /** Weighted moving average: the latest value counts `period` times, the oldest once. */
79
+ export function wma(values, period = 14) {
80
+ const out = [], q = [], w = (period * (period + 1)) / 2;
81
+ for (const v of values) {
82
+ if (!Number.isFinite(v)) { out.push(NaN); continue; }
83
+ q.push(v); if (q.length > period) q.shift();
84
+ out.push(q.length === period ? q.reduce((s, x, i) => s + x * (i + 1), 0) / w : NaN);
85
+ }
86
+ return out;
87
+ }
88
+ /** Bollinger bands: the simple average and `k` standard deviations either side. */
89
+ export function bollinger(values, period = 20, k = 2) {
90
+ const mid = sma(values, period), q = [];
91
+ return values.map((v, i) => {
92
+ if (Number.isFinite(v)) { q.push(v); if (q.length > period) q.shift(); }
93
+ if (!Number.isFinite(mid[i])) return { mid: NaN, low: NaN, high: NaN };
94
+ const sd = Math.sqrt(q.reduce((s, x) => s + (x - mid[i]) ** 2, 0) / q.length);
95
+ return { mid: mid[i], low: mid[i] - k * sd, high: mid[i] + k * sd };
96
+ });
97
+ }
98
+ /** MACD: the short EMA less the long, its signal line (an EMA of it) and the difference. */
99
+ export function macd(values, short = 12, long = 26, signal = 9) {
100
+ const a = ema(values, short), b = ema(values, long), line = a.map((x, i) => x - b[i]);
101
+ const sig = new Array(line.length).fill(NaN), firstValid = line.findIndex(Number.isFinite);
102
+ if (firstValid >= 0) { const s = ema(line.slice(firstValid), signal); s.forEach((x, i) => { sig[firstValid + i] = x; }); }
103
+ return line.map((m, i) => ({ macd: m, signal: sig[i], histogram: m - sig[i] }));
104
+ }
105
+ /** Relative strength index (Wilder's smoothing), 0 … 100. */
106
+ export function rsi(values, period = 14) {
107
+ const out = [NaN]; let gain = 0, loss = 0;
108
+ for (let i = 1; i < values.length; i++) {
109
+ const d = values[i] - values[i - 1], g = Math.max(0, d), l = Math.max(0, -d);
110
+ if (i <= period) { gain += g; loss += l; if (i < period) { out.push(NaN); continue; } gain /= period; loss /= period; }
111
+ else { gain = (gain * (period - 1) + g) / period; loss = (loss * (period - 1) + l) / period; }
112
+ out.push(loss === 0 ? 100 : 100 - 100 / (1 + gain / loss));
113
+ }
114
+ return out;
115
+ }
116
+ /** Momentum: each value less the one `period` before it. */
117
+ export const momentum = (values, period = 10) => values.map((v, i) => (i >= period ? v - values[i - period] : NaN));
118
+
119
+ // ── a treemap: Bruls, Huizing and van Wijk's squarified layout ─────────────────────────
120
+ /**
121
+ * Rectangles for values inside a rectangle, each as near square as the rest allow, in the order
122
+ * given (sorted largest first gives the squarest). → [{ x, y, w, h, i }]
123
+ */
124
+ export function squarify(values, { x = 0, y = 0, w = 1, h = 1 } = {}) {
125
+ const items = values.map((v, i) => ({ v: Math.max(0, Number(v) || 0), i })).filter((d) => d.v > 0);
126
+ const total = items.reduce((s, d) => s + d.v, 0), out = [];
127
+ if (!total || w <= 0 || h <= 0) return values.map((_, i) => ({ x, y, w: 0, h: 0, i }));
128
+ const scale = (w * h) / total;
129
+ let rect = { x, y, w, h }, row = [], rest = items.map((d) => ({ ...d, a: d.v * scale }));
130
+ const worst = (r, side) => { const s = r.reduce((t, d) => t + d.a, 0), mx = Math.max(...r.map((d) => d.a)), mn = Math.min(...r.map((d) => d.a)); return Math.max((side * side * mx) / (s * s), (s * s) / (side * side * mn)); };
131
+ const layRow = (r) => {
132
+ const s = r.reduce((t, d) => t + d.a, 0), wide = rect.w >= rect.h;
133
+ if (wide) { const cw = s / rect.h; let cy = rect.y; for (const d of r) { const ch = d.a / cw; out.push({ x: rect.x, y: cy, w: cw, h: ch, i: d.i }); cy += ch; } rect = { x: rect.x + cw, y: rect.y, w: rect.w - cw, h: rect.h }; }
134
+ else { const ch = s / rect.w; let cx = rect.x; for (const d of r) { const cw = d.a / ch; out.push({ x: cx, y: rect.y, w: cw, h: ch, i: d.i }); cx += cw; } rect = { x: rect.x, y: rect.y + ch, w: rect.w, h: rect.h - ch }; }
135
+ };
136
+ while (rest.length) {
137
+ const side = Math.min(rect.w, rect.h), d = rest[0];
138
+ if (!row.length || worst([...row, d], side) <= worst(row, side)) { row.push(d); rest.shift(); }
139
+ else { layRow(row); row = []; }
140
+ }
141
+ if (row.length) layRow(row);
142
+ const byI = new Map(out.map((r) => [r.i, r]));
143
+ return values.map((_, i) => byI.get(i) ?? { x, y, w: 0, h: 0, i });
144
+ }
145
+
146
+ /** A tree from flat rows with ids and parents (Highcharts's way), or rows with children. → { roots, nodes } */
147
+ export function treeOf(rows, { id = 'id', parent = 'parent', value = 'value', name = 'name' } = {}) {
148
+ const nodes = rows.map((r, i) => ({ row: r, i, id: r?.[id] ?? r?.name ?? r?.label ?? r?.x ?? String(i), name: String(r?.[name] ?? r?.label ?? r?.x ?? r?.[id] ?? i), own: Number(r?.[value] ?? r?.y ?? r?.v), children: [], depth: 0, parent: null }));
149
+ const byId = new Map(nodes.map((n) => [n.id, n]));
150
+ const roots = [];
151
+ for (const n of nodes) { const p = n.row?.[parent]; const pn = p != null && p !== '' ? byId.get(p) : null; if (pn && pn !== n) { n.parent = pn; pn.children.push(n); } else roots.push(n); }
152
+ const sum = (n, d) => { n.depth = d; const kids = n.children.reduce((s, c) => s + sum(c, d + 1), 0); n.value = n.children.length ? (Number.isFinite(n.own) && n.own > kids ? n.own : kids) : Math.max(0, Number.isFinite(n.own) ? n.own : 0); return n.value; };
153
+ for (const r of roots) sum(r, 0);
154
+ return { roots, nodes };
155
+ }
156
+
157
+ // ── a Sankey diagram ─────────────────────────────────────────────────────────────────
158
+ /**
159
+ * Columns of nodes and the bands between them, for flows [{ from, to, flow }]. Nodes go in the
160
+ * column after their furthest source; each is as tall as the larger of what flows in and out.
161
+ * → { nodes: [{ name, x0, x1, y0, y1, value, column }], links: [{ from, to, flow, y0, y1, width, i }] }
162
+ */
163
+ export function sankeyLayout(flows, { x = 0, y = 0, w = 1, h = 1, nodeWidth = 12, nodePadding = 10, order } = {}) {
164
+ const names = [], idx = new Map();
165
+ const node = (n) => { const k = String(n); if (!idx.has(k)) { idx.set(k, names.length); names.push(k); } return idx.get(k); };
166
+ if (order) for (const n of order) node(n);
167
+ const links = flows.map((f, i) => ({ s: node(f.from), t: node(f.to), flow: Math.max(0, Number(f.flow ?? f.weight ?? f.value) || 0), i })).filter((l) => l.s !== l.t);
168
+ const N = names.length, ins = Array.from({ length: N }, () => 0), outs = Array.from({ length: N }, () => 0);
169
+ for (const l of links) { outs[l.s] += l.flow; ins[l.t] += l.flow; }
170
+ // the column: the longest way in (a cycle stops where it started)
171
+ const col = new Array(N).fill(0);
172
+ for (let pass = 0; pass < N; pass++) { let moved = false; for (const l of links) if (col[l.t] < col[l.s] + 1 && col[l.s] + 1 < N) { col[l.t] = col[l.s] + 1; moved = true; } if (!moved) break; }
173
+ // nodes with nothing going out stand in the last column
174
+ const last = Math.max(0, ...col);
175
+ for (let k = 0; k < N; k++) if (!outs[k] && ins[k]) col[k] = last;
176
+ const value = names.map((_, k) => Math.max(ins[k], outs[k]));
177
+ const columns = Array.from({ length: last + 1 }, () => []);
178
+ for (let k = 0; k < N; k++) columns[col[k]].push(k);
179
+ const ky = Math.min(...columns.map((c) => (h - nodePadding * Math.max(0, c.length - 1)) / Math.max(1e-9, c.reduce((s, k) => s + value[k], 0))).filter(Number.isFinite));
180
+ const step = last ? (w - nodeWidth) / last : 0;
181
+ const nodes = names.map((name, k) => ({ name, value: value[k], column: col[k], x0: x + col[k] * step, x1: x + col[k] * step + nodeWidth, y0: 0, y1: 0, k }));
182
+ for (const c of columns) {
183
+ const used = c.reduce((s, k) => s + value[k] * ky, 0) + nodePadding * Math.max(0, c.length - 1);
184
+ let cy = y + (h - used) / 2;
185
+ for (const k of c) { nodes[k].y0 = cy; nodes[k].y1 = cy + value[k] * ky; cy = nodes[k].y1 + nodePadding; }
186
+ }
187
+ // the bands leave and arrive in the order of the nodes at their other end, so they do not cross at a node
188
+ const outBy = Array.from({ length: N }, () => []), inBy = Array.from({ length: N }, () => []);
189
+ for (const l of links) { outBy[l.s].push(l); inBy[l.t].push(l); }
190
+ const placed = links.map((l) => ({ from: names[l.s], to: names[l.t], s: l.s, t: l.t, flow: l.flow, i: l.i, width: l.flow * ky, y0: 0, y1: 0 }));
191
+ const byI = new Map(placed.map((p) => [p.i, p]));
192
+ for (let k = 0; k < N; k++) {
193
+ let a = nodes[k].y0;
194
+ for (const l of outBy[k].sort((p, q) => nodes[p.t].y0 - nodes[q.t].y0)) { const p = byI.get(l.i); p.y0 = a + p.width / 2; a += p.width; }
195
+ let b = nodes[k].y0;
196
+ for (const l of inBy[k].sort((p, q) => nodes[p.s].y0 - nodes[q.s].y0)) { const p = byI.get(l.i); p.y1 = b + p.width / 2; b += p.width; }
197
+ }
198
+ for (const p of placed) { p.x0 = nodes[p.s].x1; p.x1 = nodes[p.t].x0; }
199
+ return { nodes, links: placed, ky };
200
+ }
201
+
202
+ // ── a word cloud ──────────────────────────────────────────────────────────────────────
203
+ /**
204
+ * Places for words of given sizes ([{ w, h }], largest first) on an Archimedean spiral from the
205
+ * middle, none overlapping; a word that finds no room is left out (placed: false).
206
+ */
207
+ export function cloudLayout(words, { w = 600, h = 300, padding = 2, spiral = 'archimedean' } = {}) {
208
+ const boxes = [], cx = w / 2, cy = h / 2, ratio = w / Math.max(1, h);
209
+ const hits = (b) => b.x < 0 || b.y < 0 || b.x + b.w > w || b.y + b.h > h || boxes.some((o) => b.x < o.x + o.w + padding && b.x + b.w + padding > o.x && b.y < o.y + o.h + padding && b.y + b.h + padding > o.y);
210
+ return words.map((wd) => {
211
+ for (let t = 0; t < 2400; t++) {
212
+ const a = t * 0.11, r = spiral === 'rectangular' ? Math.floor(Math.sqrt(t)) * 3 : 1.6 * a;
213
+ const px = cx + r * Math.cos(a) * ratio - wd.w / 2, py = cy + r * Math.sin(a) - wd.h / 2;
214
+ const b = { x: px, y: py, w: wd.w, h: wd.h };
215
+ if (!hits(b)) { boxes.push(b); return { ...b, placed: true }; }
216
+ }
217
+ return { x: 0, y: 0, w: wd.w, h: wd.h, placed: false };
218
+ });
219
+ }
220
+
221
+ // ── the seats of a parliament ───────────────────────────────────────────────────────────
222
+ /**
223
+ * Places for n seats in rows of a half ring (or from startAngle to endAngle, in degrees, 0 at the
224
+ * top), filled from the left across every row, as Highcharts's item chart does.
225
+ * → { seats: [{ x, y }], r } in a box of 1 × 1 centred at (0.5, 1) … scaled by the caller.
226
+ */
227
+ export function parliamentSeats(n, { rows: rowsOpt, startAngle = -90, endAngle = 90, inner = 0.4 } = {}) {
228
+ if (n <= 0) return { seats: [], r: 0 };
229
+ const a0 = (startAngle * Math.PI) / 180, a1 = (endAngle * Math.PI) / 180, sweep = a1 - a0;
230
+ let rows = rowsOpt ?? 1;
231
+ if (!rowsOpt) for (rows = 1; rows < 60; rows++) { const cap = capacity(rows); if (cap >= n) break; }
232
+ function capacity(k) { let c = 0; const band = (1 - inner) / k; for (let j = 0; j < k; j++) { const rr = inner + band * (j + 0.5); c += Math.max(1, Math.floor((Math.abs(sweep) * rr) / band)); } return c; }
233
+ const band = (1 - inner) / rows, ring = [];
234
+ for (let j = 0; j < rows; j++) { const rr = inner + band * (j + 0.5); ring.push({ rr, cap: Math.max(1, Math.floor((Math.abs(sweep) * rr) / band)) }); }
235
+ const total = ring.reduce((s, q) => s + q.cap, 0);
236
+ // share the seats among the rows by their room
237
+ let left = n;
238
+ ring.forEach((q, j) => { q.n = j === ring.length - 1 ? left : Math.min(left, Math.round((n * q.cap) / total)); left -= q.n; });
239
+ const seats = [];
240
+ for (const q of ring) for (let k = 0; k < q.n; k++) { const a = a0 + (q.n === 1 ? sweep / 2 : (sweep * k) / (q.n - 1)); seats.push({ x: Math.sin(a) * q.rr, y: -Math.cos(a) * q.rr, a }); }
241
+ seats.sort((p, q) => p.a - q.a || q.y - p.y);
242
+ return { seats, r: band * 0.42 };
243
+ }
244
+
245
+ // ── points gathered into groups (data grouping) ─────────────────────────────────────────
246
+ /**
247
+ * Points [{ index, value, open?, high?, low?, close? }] gathered into groups `size` wide along
248
+ * the index; approximation: 'average' | 'sum' | 'open' | 'high' | 'low' | 'close' | 'ohlc'.
249
+ */
250
+ export function groupPoints(points, size, approximation = 'average') {
251
+ if (!(size > 0)) return points;
252
+ const groups = new Map();
253
+ for (const p of points) {
254
+ if (!Number.isFinite(p.index)) continue;
255
+ const k = Math.floor(p.index / size) * size;
256
+ if (!groups.has(k)) groups.set(k, []);
257
+ groups.get(k).push(p);
258
+ }
259
+ return [...groups.entries()].sort((a, b) => a[0] - b[0]).map(([k, list], gi) => {
260
+ const vals = list.map((p) => p.value).filter(Number.isFinite);
261
+ const first = list[0], lastP = list.at(-1);
262
+ const base = { index: first.index, i: gi, raw: first.raw, group: list.length, groupStart: k, groupEnd: k + size };
263
+ if (approximation === 'ohlc' || Number.isFinite(first.open)) {
264
+ const open = first.open ?? first.value, close = lastP.close ?? lastP.value;
265
+ const high = Math.max(...list.map((p) => p.high ?? p.value)), low = Math.min(...list.map((p) => p.low ?? p.value));
266
+ return { ...base, open, high, low, close, value: close };
267
+ }
268
+ const sum = vals.reduce((a, b) => a + b, 0);
269
+ const value = !vals.length ? NaN : approximation === 'sum' ? sum : approximation === 'open' ? vals[0] : approximation === 'close' ? vals.at(-1) : approximation === 'high' ? Math.max(...vals) : approximation === 'low' ? Math.min(...vals) : sum / vals.length;
270
+ return { ...base, value };
271
+ });
272
+ }
package/src/lite.js ADDED
@@ -0,0 +1,40 @@
1
+ // @clarity-js/charts/lite — Chart.js's configuration and API alone: its eight types, its axes and plugins, without
2
+ // what the full package adds (the types and plugins of Highcharts and ApexCharts). A third of the size.
3
+ //
4
+ // import { Chart } from '@clarity-js/charts/lite'
5
+ // new Chart(el, { type: 'line', data, options }) // as in Chart.js
6
+ // <Chart type="line" data={ data } options={ options } /> // in markup, bound to state
7
+ //
8
+ // Every type of Chart.js (line, bar, radar, pie, doughnut, polarArea, bubble, scatter, mixed), its
9
+ // axes (category, linear, logarithmic, time, timeseries, radialLinear), its plugins (title,
10
+ // subtitle, legend, tooltip, filler, decimation, colors) and its API (update, destroy, resize,
11
+ // toBase64Image, getElementsAtEventForMode, setActiveElements, hide/show …), drawn as SVG by
12
+ // default (accessible, server-drawn, CSP-safe) or on a canvas.
13
+
14
+ import { Chart as Core, defaults, merge, renderToSVG, describe, EASING, VERSION } from './core.js';
15
+ import { ChartView } from './components.js';
16
+
17
+ /**
18
+ * `new Chart(el, config)` makes a chart (Chart.js's way); `<Chart … />` in markup is the component.
19
+ * One name for both, as a Chart.js user expects to write it.
20
+ */
21
+ function Chart(item, config) {
22
+ if (!new.target) return ChartView(item);
23
+ return new Core(item, config);
24
+ }
25
+ Chart.prototype = Core.prototype;
26
+ for (const k of ['defaults', 'overrides', 'instances', 'version', 'registry', 'register', 'unregister', 'getChart', 'registerTheme', 'themes', 'palettes']) Object.defineProperty(Chart, k, { get: () => (typeof Core[k] === 'function' ? Core[k].bind(Core) : Core[k]), enumerable: true });
27
+
28
+ export { Chart, ChartView, defaults, merge, renderToSVG, describe, EASING as easing, VERSION };
29
+ export { LineChart, AreaChart, BarChart, ScatterChart, PieChart, Histogram, Sparkline } from './components.js';
30
+ export { Axis, RadialAxis, formatTime } from './axes.js';
31
+ export { CONTROLLERS, pathThrough, pointShape, barPath } from './controllers.js';
32
+ export { BUILT_IN_PLUGINS, Title, SubTitle, Legend, Tooltip, Filler, Decimation, Colors, PALETTE, lttb, minMax, generateLabels } from './plugins.js';
33
+ export { THEMES, PALETTES, registerTheme, resolveTheme, monochrome } from './themes.js';
34
+ export { isPaint, normalizePaint, cssPaint, mix, shade, withAlpha, luminance, contrastOn, parseColor } from './fills.js';
35
+ export { svgPainter, canvasPainter, stringPainter, measureText } from './painter.js';
36
+ export { linear, log, band, time, niceStep } from './scale.js';
37
+ export { linePath, areaPath, arcPath, stack, extent, bins, decimate } from './shape.js';
38
+ export { formatNumber, formatDate, formatFull } from './format.js';
39
+ /** Chart.js's tree-shaking registrables, for code that registers them: they are always registered here. */
40
+ export const registerables = [];
package/src/maps.js ADDED
@@ -0,0 +1,227 @@
1
+ // @clarity-js/charts — maps, as Highcharts Maps has them: a region coloured by its value on a colour
2
+ // axis (map, choropleth), bubbles sized by a value (mapbubble) and points by longitude and latitude
3
+ // (mappoint), in a projection (equalEarth, naturalEarth, mercator, equirectangular, orthographic: a
4
+ // globe), fitted to the chart, zoomed and panned with the zoom plugin. The map data is a module of
5
+ // its own, so a page loads only the map it draws:
6
+ //
7
+ // import world from '@clarity-js/charts/maps/world' // the countries (ISO codes), Natural Earth 1:50m
8
+ // import turkey from '@clarity-js/charts/maps/turkey' // the 81 provinces (TR-34, plate 34)
9
+ // new Chart(el, { type: 'map', data: { datasets: [{ map: turkey, data: [{ id: 'TR-34', value: 15.6 }, [6, 5.8]] }] } })
10
+ //
11
+ // A map of one's own is any GeoJSON FeatureCollection, or { features: [{ id, name, rings }] } as these are.
12
+
13
+ import { colorScaleOf } from './types.js';
14
+ import { formatNumber } from './format.js';
15
+ import { shade, contrastOn, withAlpha } from './fills.js';
16
+ import { PALETTE } from './plugins.js';
17
+
18
+ const RAD = Math.PI / 180;
19
+ const themeOf = (chart) => chart.resolved.theme ?? {};
20
+ const fmtOf = (chart) => (v) => formatNumber(v, { locale: chart.resolved.locale });
21
+
22
+ // ── projections: [longitude, latitude] in degrees → [x, y] with y up, in radians' units ────────────
23
+ const A1 = 1.340264, A2 = -0.081106, A3 = 0.000893, A4 = 0.003796, M = Math.sqrt(3) / 2;
24
+ export const PROJECTIONS = {
25
+ equirectangular: (l, p) => [l * RAD, p * RAD],
26
+ mercator: (l, p) => [l * RAD, Math.log(Math.tan(Math.PI / 4 + (Math.max(-85, Math.min(85, p)) * RAD) / 2))],
27
+ equalEarth: (l, p) => { const t = Math.asin(M * Math.sin(p * RAD)), t2 = t * t, t6 = t2 * t2 * t2; return [(l * RAD * Math.cos(t)) / (M * (A1 + 3 * A2 * t2 + t6 * (7 * A3 + 9 * A4 * t2))), t * (A1 + A2 * t2 + t6 * (A3 + A4 * t2))]; },
28
+ naturalEarth: (l, p) => { const f = p * RAD, f2 = f * f, f4 = f2 * f2; return [l * RAD * (0.8707 - 0.131979 * f2 + f4 * (-0.013791 + f4 * (0.003971 * f2 - 0.001529 * f4))), f * (1.007226 + f2 * (0.015085 + f4 * (-0.044475 + 0.028874 * f2 - 0.005916 * f4)))]; },
29
+ };
30
+ /** A globe seen from above (longitude, latitude) = rotate: points on the far side are folded onto its edge, flagged. */
31
+ export function orthographic([l0, p0] = [0, 20]) {
32
+ const sp0 = Math.sin(p0 * RAD), cp0 = Math.cos(p0 * RAD);
33
+ return (l, p) => {
34
+ const dl = (l - l0) * RAD, sp = Math.sin(p * RAD), cp = Math.cos(p * RAD), cosc = sp0 * sp + cp0 * cp * Math.cos(dl);
35
+ let x = cp * Math.sin(dl), y = cp0 * sp - sp0 * cp * Math.cos(dl);
36
+ if (cosc < 0) { const r = Math.hypot(x, y) || 1; x /= r; y /= r; return [x, y, true]; }
37
+ return [x, y, false];
38
+ };
39
+ }
40
+ const projectionOf = (name, rotate) => (name === 'orthographic' ? orthographic(rotate) : PROJECTIONS[name] ?? PROJECTIONS.equalEarth);
41
+
42
+ // ── map data: these modules' rings, or GeoJSON ───────────────────────────────────────────────────
43
+ const decoded = new WeakMap();
44
+ /** A map's features with their rings as [[lon, lat], …], read once. */
45
+ export function featuresOf(map) {
46
+ if (!map) return [];
47
+ if (decoded.has(map)) return decoded.get(map);
48
+ let out;
49
+ if (map.type === 'FeatureCollection' || Array.isArray(map.features) && map.features[0]?.geometry) {
50
+ out = map.features.map((f, k) => {
51
+ const g = f.geometry ?? {}, polys = g.type === 'Polygon' ? [g.coordinates] : g.type === 'MultiPolygon' ? g.coordinates : [];
52
+ const p = f.properties ?? {};
53
+ return { ...p, id: f.id ?? p.id ?? p.iso_a2 ?? p.ISO_A2 ?? p.code ?? p.name ?? String(k), name: p.name ?? p.NAME ?? String(f.id ?? k), rings: polys.flat(), label: p.label ?? null };
54
+ });
55
+ } else {
56
+ const s = map.scale ?? 1;
57
+ out = (map.features ?? []).map((f) => ({ ...f, rings: f.rings.map((r) => { const pts = []; let x = 0, y = 0; for (let i = 0; i < r.length; i += 2) { x += r[i]; y += r[i + 1]; pts.push([x / s, y / s]); } return pts; }) }));
58
+ }
59
+ for (const f of out) if (!f.label) { const big = f.rings.reduce((a, r) => (r.length > (a?.length ?? 0) ? r : a), null); f.label = big ? [big.reduce((s, p) => s + p[0], 0) / big.length, big.reduce((s, p) => s + p[1], 0) / big.length] : [0, 0]; }
60
+ decoded.set(map, out);
61
+ return out;
62
+ }
63
+ /** The feature a data point joins: by id, ISO alpha-3, plate number, name (in any language given), case-insensitively. */
64
+ function finder(features, joinBy) {
65
+ const idx = new Map(), key = (v) => String(v).toLowerCase();
66
+ const add = (k, f) => { if (k != null && k !== '' && !idx.has(key(k))) idx.set(key(k), f); };
67
+ for (const f of features) { if (joinBy) add(f[joinBy], f); add(f.id, f); add(f.iso3, f); add(f.plate, f); add(f.name, f); add(f.nameTr, f); add(f.nameEn, f); }
68
+ return (k) => (k == null ? null : idx.get(key(k)) ?? null);
69
+ }
70
+ const JOIN = { 'iso-a2': 'id', 'iso-a3': 'iso3', 'hc-key': 'id', name: 'name' };
71
+ const joinKey = (raw, joinBy) => (Array.isArray(raw) ? raw[0] : raw && typeof raw === 'object' ? raw[joinBy] ?? raw.id ?? raw.code ?? raw.key ?? raw['hc-key'] ?? raw['iso-a2'] ?? raw.iso3 ?? raw.plate ?? raw.name : null);
72
+ const valueOf = (raw) => Number(Array.isArray(raw) ? raw[1] : raw && typeof raw === 'object' ? raw.value ?? raw.v ?? raw.y ?? raw.z : raw);
73
+
74
+ // ── the geography of a chart: one projection and one fit for every map dataset in it ─────────────────
75
+ function geoOf(chart) {
76
+ if (chart._geo?.stamp === chart._updates) return chart._geo;
77
+ const metas = chart.metas.filter((m) => m.controller.geo), base = metas.find((m) => m.dataset.map) ?? null;
78
+ const map = base?.dataset.map ?? null, opt = (k, d) => base?.dataset[k] ?? chart.resolved.mapView?.[k] ?? d;
79
+ const name = opt('projection', map?.projection ?? 'equalEarth'), rotate = chart._mapRotate ?? opt('rotate', [map ? (map.name === 'turkey' ? 35 : 10) : 0, map?.name === 'turkey' ? 39 : 20]);
80
+ const proj = projectionOf(name, rotate), feats = featuresOf(map);
81
+ // what is fitted: the whole map, the features named in fitTo, or the points of the other datasets
82
+ const fitTo = opt('fitTo', null), pts = [];
83
+ if (name === 'orthographic') pts.push([-1, -1], [1, 1]);
84
+ else if (feats.length) for (const f of fitTo ? feats.filter((g) => fitTo.includes(g.id) || fitTo.includes(g.name)) : feats) for (const r of f.rings) for (const p of r) { const q = proj(p[0], p[1]); pts.push([q[0], q[1]]); }
85
+ else for (const m of metas) for (const raw of m.dataset.data ?? []) { const ll = lonLat(raw); if (ll) { const q = proj(ll[0], ll[1]); pts.push([q[0], q[1]]); } }
86
+ const a = chart.chartArea, xs = pts.map((p) => p[0]), ys = pts.map((p) => p[1]);
87
+ const x0 = Math.min(...xs, Infinity), x1 = Math.max(...xs, -Infinity), y0 = Math.min(...ys, Infinity), y1 = Math.max(...ys, -Infinity);
88
+ const ok = Number.isFinite(x0) && x1 > x0, w = a.right - a.left, h = a.bottom - a.top;
89
+ const s = ok ? Math.min(w / (x1 - x0 || 1), h / (y1 - y0 || 1)) * 0.98 : 1, cx = (a.left + a.right) / 2, cy = (a.top + a.bottom) / 2, mx = ok ? (x0 + x1) / 2 : 0, my = ok ? (y0 + y1) / 2 : 0;
90
+ const v = chart._mapView ?? { k: 1, x: 0, y: 0 };
91
+ const toScreen = (l, p) => { const q = proj(l, p); return [cx + (q[0] - mx) * s * v.k + v.x, cy - (q[1] - my) * s * v.k + v.y, q[2]]; };
92
+ chart._geo = { stamp: chart._updates, proj, name, rotate, toScreen, feats, map, base, scale: s * v.k, center: [cx, cy], radius: name === 'orthographic' ? s * v.k : null, view: v };
93
+ return chart._geo;
94
+ }
95
+ function lonLat(raw) {
96
+ if (raw == null) return null;
97
+ if (Array.isArray(raw) && raw.length >= 2 && typeof raw[0] === 'number' && typeof raw[1] === 'number') return [raw[0], raw[1]];
98
+ if (typeof raw === 'object') { const lon = raw.lon ?? raw.lng ?? raw.longitude, lat = raw.lat ?? raw.latitude; if (lon != null && lat != null) return [Number(lon), Number(lat)]; }
99
+ return null;
100
+ }
101
+ const r2 = (v) => Math.round(v * 10) / 10;
102
+ const inRing = (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; };
103
+
104
+ // ── the region map (choropleth) ─────────────────────────────────────────────────────────────────
105
+ const map = {
106
+ element: 'region', name: 'Map', geo: true, axes: 'none', legend: 'none', colors: 'none', colorAxis: true, order: 100,
107
+ defaults: { aspectRatio: 1.6, interaction: { mode: 'nearest', intersect: true }, plugins: { legend: { display: false } } },
108
+ parse(chart, meta) {
109
+ // joinBy names a property of the map's features (Highcharts's 'iso-a2', 'hc-key' …: for these modules' maps, their id)
110
+ const feats = featuresOf(meta.dataset.map), jb = meta.dataset.joinBy, joinBy = jb != null && feats.some((f) => f[jb] != null) ? jb : JOIN[jb] ?? jb, find = finder(feats, joinBy), byFeature = new Map();
111
+ (meta.dataset.data ?? []).forEach((raw, i) => { const f = find(joinKey(raw, joinBy)); if (f) byFeature.set(f, { raw, i }); });
112
+ meta.unmatched = (meta.dataset.data ?? []).filter((raw) => !find(joinKey(raw, joinBy)));
113
+ return feats.map((f, k) => { const hit = byFeature.get(f); return { index: k, value: hit ? valueOf(hit.raw) : NaN, name: f.name, id: f.id, feature: f, raw: hit?.raw, i: k, dataIndex: hit?.i }; });
114
+ },
115
+ limits: () => [Infinity, -Infinity],
116
+ update(chart, meta) {
117
+ const g = geoOf(chart), scale = colorScaleOf(chart, meta), th = themeOf(chart), none = meta.dataset.nullColor ?? chart.resolved.colorAxis?.nullColor ?? (th.mode === 'dark' ? '#2b333d' : '#e4e8ed');
118
+ meta.elements = meta.parsed.map((p) => {
119
+ const rings = [];
120
+ for (const r of p.feature.rings) {
121
+ const pts = r.map((q) => g.toScreen(q[0], q[1]));
122
+ if (g.name === 'orthographic' && pts.every((q) => q[2])) continue;
123
+ rings.push(pts);
124
+ }
125
+ const d = rings.map((pts) => 'M' + pts.map((q) => `${r2(q[0])},${r2(q[1])}`).join('L') + 'Z').join('');
126
+ const xs = rings.flat().map((q) => q[0]), ys = rings.flat().map((q) => q[1]);
127
+ const own = chart.option(meta, 'backgroundColor', p.dataIndex ?? 0);
128
+ const color = Number.isFinite(p.value) ? (p.raw?.color ?? (meta.dataset.backgroundColor != null ? own : scale.colorOf(p.value))) : none;
129
+ const lab = g.toScreen(p.feature.label[0], p.feature.label[1]);
130
+ return { kind: 'region', datasetIndex: meta.index, index: p.i, d, color, rings, nodata: !Number.isFinite(p.value), skip: !rings.length, raw: p.raw, parsed: p, grow: 1,
131
+ bounds: xs.length ? { l: Math.min(...xs), r: Math.max(...xs), t: Math.min(...ys), b: Math.max(...ys) } : null,
132
+ hit: (x, y) => rings.some((pts) => inRing(pts, x, y)), center: { x: lab[0], y: lab[1] }, tip: { x: lab[0], y: lab[1] - 4 } };
133
+ });
134
+ },
135
+ initial(el) { return { ...el, grow: 0 }; },
136
+ draw(painter, meta, chart) {
137
+ const g = geoOf(chart), th = themeOf(chart), border = chart.option(meta, 'borderColor', 0) ?? th.bg, bw = chart.option(meta, 'borderWidth', 0, null, 0.6);
138
+ if (g.name === 'orthographic') painter.circle(g.center[0] + g.view.x, g.center[1] + g.view.y, g.radius, { fill: meta.dataset.oceanColor ?? (th.mode === 'dark' ? '#16212c' : '#eaf2fb'), stroke: th.axis, width: 1 });
139
+ const active = [];
140
+ for (const e of meta.elements) {
141
+ if (e.skip) continue;
142
+ if (chart.isActive(meta.index, e.index)) { active.push(e); continue; }
143
+ painter.path(e.d, { fill: e.color, stroke: border, width: bw, join: 'round', opacity: e.grow < 1 ? 0.3 + 0.7 * e.grow : null, clip: chart.clip });
144
+ }
145
+ for (const e of active) painter.path(e.d, { fill: e.nodata ? e.color : shade(e.color, -0.15), stroke: th.ink, width: 1.5, join: 'round', clip: chart.clip });
146
+ const lab = meta.dataset.labels;
147
+ if (lab?.display) {
148
+ const f = { ...chart.resolved.font, size: 10, ...(lab.font ?? {}) };
149
+ for (const e of meta.elements) {
150
+ if (e.skip || !e.bounds) continue;
151
+ const text = typeof lab.formatter === 'function' ? lab.formatter(e.parsed.value, { feature: e.parsed.feature, chart }) : String(e.parsed.feature[lab.key ?? 'name'] ?? '');
152
+ const w = painter.measure(text, f);
153
+ if (!text || w > (e.bounds.r - e.bounds.l) * (lab.fit ?? 1.1) || e.bounds.b - e.bounds.t < f.size) continue;
154
+ painter.text(text, e.center.x, e.center.y, { fill: lab.color && lab.color !== 'auto' ? lab.color : contrastOn(e.color), font: f, align: 'center', baseline: 'middle' });
155
+ }
156
+ }
157
+ },
158
+ label(chart, meta, el) { return el.parsed?.name ?? ''; },
159
+ format(chart, meta, el, fmt) { return Number.isFinite(el.parsed.value) ? fmt(el.parsed.value) : 'no data'; },
160
+ lines(chart, meta, el, fmt) { return [`${meta.label ? meta.label + ': ' : ''}${Number.isFinite(el.parsed.value) ? fmt(el.parsed.value) : 'no data'}`]; },
161
+ swatch(chart, meta, el) { return el.color; },
162
+ describe(chart, meta, fmt) {
163
+ const ps = meta.parsed.filter((p) => Number.isFinite(p.value)).sort((a, b) => b.value - a.value);
164
+ if (!ps.length) return `${meta.label || 'Map'}: no values`;
165
+ return `${meta.label ? meta.label + ': ' : ''}${ps.length} of ${meta.parsed.length} regions have values; highest ${ps.slice(0, 3).map((p) => `${p.name} ${fmt(p.value)}`).join(', ')}; lowest ${ps.at(-1).name} ${fmt(ps.at(-1).value)}`;
166
+ },
167
+ };
168
+
169
+ // ── bubbles and points on a map ────────────────────────────────────────────────────────────────
170
+ function placesOf(chart, meta) {
171
+ const base = meta.dataset.map ?? chart.metas.find((m) => m.controller.geo && m.dataset.map)?.dataset.map, find = finder(featuresOf(base)), labels = chart.data.labels ?? [];
172
+ return (meta.dataset.data ?? []).map((raw, i) => {
173
+ let ll = lonLat(raw), f = null;
174
+ if (!ll) { f = find(joinKey(raw)); ll = f ? f.label : null; }
175
+ return { index: i, value: valueOf(raw), name: String((raw && typeof raw === 'object' ? raw.name ?? raw.label : null) ?? f?.name ?? labels[i] ?? i + 1), lonLat: ll, raw, i };
176
+ });
177
+ }
178
+ function dotType(kind) {
179
+ return {
180
+ element: 'point', name: kind === 'bubble' ? 'Bubble map' : 'Point map', geo: true, axes: 'none', legend: 'dataset', solid: true,
181
+ defaults: { aspectRatio: 1.6, interaction: { mode: 'nearest', intersect: true } },
182
+ parse: placesOf,
183
+ limits: () => [Infinity, -Infinity],
184
+ update(chart, meta) {
185
+ const g = geoOf(chart), vals = meta.parsed.map((p) => Math.abs(p.value)).filter(Number.isFinite), hi = Math.max(1e-12, ...vals), a = chart.chartArea;
186
+ const maxR = chart.option(meta, 'maxSize', 0, null, Math.min(a.right - a.left, a.bottom - a.top) * 0.08), minR = chart.option(meta, 'minSize', 0, null, 3);
187
+ meta.elements = meta.parsed.map((p) => {
188
+ const q = p.lonLat ? g.toScreen(p.lonLat[0], p.lonLat[1]) : [NaN, NaN, true];
189
+ const r = kind === 'bubble' ? (Number.isFinite(p.value) ? minR + (maxR - minR) * Math.sqrt(Math.abs(p.value) / hi) : 0) : chart.option(meta, 'pointRadius', p.i, 'radius', 4);
190
+ return { kind: 'point', datasetIndex: meta.index, index: p.i, x: q[0], y: q[1], radius: r, skip: !p.lonLat || q[2] || !Number.isFinite(q[0]), raw: p.raw, parsed: p, options: chart.pointOptions(meta, p.i), grow: 1 };
191
+ });
192
+ },
193
+ initial(el) { return { ...el, radius: 0 }; },
194
+ draw(painter, meta, chart) {
195
+ const th = themeOf(chart), f = { ...chart.resolved.font, size: 11 };
196
+ const els = meta.elements.filter((e) => !e.skip).sort((p, q) => q.radius - p.radius);
197
+ for (const e of els) {
198
+ const active = chart.isActive(meta.index, e.index), c = chart.option(meta, 'backgroundColor', e.index) ?? meta.auto?.borderColor ?? PALETTE[0];
199
+ if (kind === 'bubble') painter.circle(e.x, e.y, e.radius, { fill: withAlpha(typeof c === 'string' ? c : PALETTE[0], active ? 0.85 : 0.6), stroke: active ? th.ink : th.bg, width: active ? 1.5 : 1 });
200
+ else { painter.circle(e.x, e.y, active ? e.radius + 1.5 : e.radius, { fill: c, stroke: th.bg, width: 1.5 }); if (meta.dataset.labels !== false) painter.text(e.parsed.name, e.x + e.radius + 4, e.y, { fill: th.ink, font: f, baseline: 'middle' }); }
201
+ }
202
+ },
203
+ label(chart, meta, el) { return el.parsed?.name ?? ''; },
204
+ format(chart, meta, el, fmt) { return Number.isFinite(el.parsed.value) ? fmt(el.parsed.value) : ''; },
205
+ swatch(chart, meta, el) { return chart.option(meta, 'backgroundColor', el.index) ?? meta.auto?.borderColor; },
206
+ };
207
+ }
208
+
209
+ /** Zoom and pan on a map (the zoom plugin and the toolbar call these when a chart has no axes but a map). */
210
+ export function zoomMap(chart, factor, focal) {
211
+ const a = chart.chartArea, c = [(a.left + a.right) / 2, (a.top + a.bottom) / 2], v = chart._mapView ?? { k: 1, x: 0, y: 0 }, f = focal ? [focal.x, focal.y] : c;
212
+ const k = Math.max(1, Math.min(chart.resolved.mapView?.maxZoom ?? 24, v.k * factor)), s = k / v.k;
213
+ chart._mapView = clampMap(chart, { k, x: (f[0] - c[0]) * (1 - s) + v.x * s, y: (f[1] - c[1]) * (1 - s) + v.y * s });
214
+ if (k === 1) chart._mapView = null;
215
+ chart.update('none');
216
+ }
217
+ export function panMap(chart, dx, dy) {
218
+ const g = chart._geo;
219
+ if (g?.name === 'orthographic') { const [l, p] = g.rotate; chart._mapRotate = [l - dx * (90 / (g.radius || 200)), Math.max(-89, Math.min(89, p + dy * (90 / (g.radius || 200))))]; chart.update('none'); return; }
220
+ const v = chart._mapView ?? { k: 1, x: 0, y: 0 };
221
+ chart._mapView = clampMap(chart, { ...v, x: v.x + dx, y: v.y + dy });
222
+ chart.update('none');
223
+ }
224
+ function clampMap(chart, v) { const a = chart.chartArea, w = (a.right - a.left) * v.k / 2, h = (a.bottom - a.top) * v.k / 2; return { k: v.k, x: Math.max(-w, Math.min(w, v.x)), y: Math.max(-h, Math.min(h, v.y)) }; }
225
+
226
+ export const MAP_TYPES = { map: map, choropleth: map, mapbubble: dotType('bubble'), mappoint: dotType('point') };
227
+ void fmtOf;