@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/depth.js ADDED
@@ -0,0 +1,316 @@
1
+ // @clarity-js/charts — charts with depth, as Highcharts 3D draws them: columns and bars as boxes in a
2
+ // frame with a back wall and a floor, a pie with thickness, and points and a surface in a cube that
3
+ // turns. They are drawn as SVG (or on a canvas) from projected points, so the tooltip, the legend, the
4
+ // sentence for a screen reader and the server's string all still work; a drag turns them.
5
+ //
6
+ // options.chart3d: { alpha: 15, beta: 15, depth: 50, viewDistance: 25 } (Highcharts's chart.options3d)
7
+ // new Chart(el, { type: 'column3d', data }) // also bar3d (across), pie3d, doughnut3d, scatter3d, surface
8
+
9
+ import { bar, bandOf, extentOf, num } from './controllers.js';
10
+ import { shade, mix, contrastOn } from './fills.js';
11
+ import { formatNumber } from './format.js';
12
+ import { niceStep } from './scale.js';
13
+ import { PALETTE } from './plugins.js';
14
+ import { colorScaleOf } from './types.js';
15
+
16
+ const RAD = Math.PI / 180, TAU = Math.PI * 2;
17
+ const r1 = (v) => Math.round(v * 10) / 10;
18
+ const themeOf = (chart) => chart.resolved.theme ?? {};
19
+ const fmtOf = (chart) => (v) => formatNumber(v, { locale: chart.resolved.locale });
20
+ const poly = (pts) => 'M' + pts.map((p) => `${r1(p[0])},${r1(p[1])}`).join('L') + 'Z';
21
+ 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; };
22
+
23
+ /** The view of a chart with depth: its tilt (alpha), turn (beta), depth and distance; a drag changes the first two. */
24
+ export function view3d(chart, d = {}) {
25
+ const o = { alpha: 15, beta: 15, depth: 50, viewDistance: 25, ...d, ...(chart.resolved.chart3d ?? {}) };
26
+ return { ...o, alpha: chart._rot?.alpha ?? o.alpha, beta: chart._rot?.beta ?? o.beta };
27
+ }
28
+
29
+ // ── columns and bars as boxes ─────────────────────────────────────────────────────────────────
30
+ // an oblique view: a point at depth z is moved by z·(sin β, −sin α)
31
+ const oblique = (chart) => { const v = view3d(chart); return { ...v, kx: Math.sin(v.beta * RAD), ky: -Math.sin(v.alpha * RAD) }; };
32
+ const column3d = {
33
+ ...bar, name: '3D column chart', three: 'oblique', stack: true,
34
+ defaults: { interaction: { mode: 'index', intersect: false } },
35
+ scales: () => ({ index: { offset: true, grid: { drawOnChartArea: false } }, value: { beginAtZero: true, grid: { drawOnChartArea: false } } }),
36
+ reserve(chart) { const v = oblique(chart); return { right: Math.max(0, v.depth * v.kx), left: Math.max(0, -v.depth * v.kx), top: Math.max(0, -v.depth * v.ky), bottom: Math.max(0, v.depth * v.ky) }; },
37
+ update(chart, meta, mode) {
38
+ bar.update(chart, meta, mode);
39
+ const v = oblique(chart), metas = chart.metas.filter((m) => m.type === meta.type), k = Math.max(0, metas.indexOf(meta));
40
+ // datasets side by side share the depth; with grouped: false each stands in a row of its own, one behind the other
41
+ const rows = meta.dataset.grouped === false || chart.resolved.datasets?.[meta.type]?.grouped === false || chart.resolved.grouped === false ? metas.length : 1, row = rows > 1 ? k : 0, dz = v.depth / rows;
42
+ meta.z = [dz * row + dz * 0.12, dz * row + dz * 0.88];
43
+ meta.depth3 = v;
44
+ if (rows > 1) {
45
+ // in rows, each column has its category's whole width rather than a share of it
46
+ const ix = chart.scales[meta.iAxisID], { slot } = bandOf(chart, meta), w = slot * chart.option(meta, 'categoryPercentage', 0, null, 0.8) * chart.option(meta, 'barPercentage', 0, null, 0.9);
47
+ for (const e of meta.elements) { const c = ix.getPixelForValue(e.parsed.index, e.parsed.i); if (e.horizontal) e.y = c; else e.x = c; e.width = w; }
48
+ }
49
+ for (const e of meta.elements) {
50
+ const box = e.horizontal ? { l: Math.min(e.base, e.x), r: Math.max(e.base, e.x), t: e.y - e.width / 2, b: e.y + e.width / 2 } : { l: e.x - e.width / 2, r: e.x + e.width / 2, t: Math.min(e.base, e.y), b: Math.max(e.base, e.y) };
51
+ const z1 = meta.z[1];
52
+ e.bounds = { l: Math.min(box.l, box.l + z1 * v.kx), r: Math.max(box.r, box.r + z1 * v.kx), t: Math.min(box.t, box.t + z1 * v.ky), b: Math.max(box.b, box.b + z1 * v.ky) };
53
+ e.tip = { x: (box.l + box.r) / 2 + (z1 * v.kx) / 2, y: box.t + (z1 * v.ky) / 2 };
54
+ }
55
+ },
56
+ draw(painter, meta, chart) {
57
+ const v = meta.depth3, first = chart.metas.find((m) => m.controller.three === 'oblique' && chart.isDatasetVisible(m.index));
58
+ if (first === meta) drawFrame(painter, chart, v);
59
+ painter.layer('datasets');
60
+ const P = (x, y, z) => [x + z * v.kx, y + z * v.ky], [z0, z1] = meta.z;
61
+ const els = meta.elements.filter((e) => !e.skip).slice();
62
+ // the further side first: with the right sides seen, from the left
63
+ els.sort((a, b) => (v.kx >= 0 ? a.x - b.x : b.x - a.x) || (v.ky <= 0 ? b.y - a.y : a.y - b.y));
64
+ for (const e of els) {
65
+ const o = e.options, active = chart.isActive(meta.index, e.index), c = active ? o.hoverBackgroundColor : o.backgroundColor, base = typeof c === 'string' ? c : PALETTE[0];
66
+ const l = e.horizontal ? Math.min(e.base, e.x) : e.x - e.width / 2, r = e.horizontal ? Math.max(e.base, e.x) : e.x + e.width / 2;
67
+ const t = e.horizontal ? e.y - e.width / 2 : Math.min(e.base, e.y), b = e.horizontal ? e.y + e.width / 2 : Math.max(e.base, e.y);
68
+ const edge = o.borderWidth > 0 ? o.borderColor : shade(base, -0.25), st = (fill) => ({ fill, stroke: edge, width: 0.5, join: 'round', clip: null });
69
+ const side = v.kx >= 0 ? r : l;
70
+ painter.path(poly([P(side, t, z0), P(side, t, z1), P(side, b, z1), P(side, b, z0)]), st(shade(base, -0.22)));
71
+ const cap = v.ky <= 0 ? t : b;
72
+ painter.path(poly([P(l, cap, z0), P(r, cap, z0), P(r, cap, z1), P(l, cap, z1)]), st(shade(base, 0.18)));
73
+ painter.path(poly([P(l, t, z0), P(r, t, z0), P(r, b, z0), P(l, b, z0)]), st(c));
74
+ }
75
+ },
76
+ };
77
+ // the back wall and floor of the frame, with the value axis's grid on them
78
+ function drawFrame(painter, chart, v) {
79
+ const a = chart.chartArea, th = themeOf(chart), d = v.depth, P = (x, y, z) => [x + z * v.kx, y + z * v.ky];
80
+ const wall = th.mode === 'dark' ? 'rgba(255,255,255,0.03)' : 'rgba(20,32,43,0.025)', grid = th.grid ?? 'rgba(0,0,0,0.1)';
81
+ painter.layer('grid');
82
+ const back = [P(a.left, a.top, d), P(a.right, a.top, d), P(a.right, a.bottom, d), P(a.left, a.bottom, d)];
83
+ painter.path(poly(back), { fill: wall, stroke: grid, width: 1 });
84
+ painter.path(poly([P(a.left, a.bottom, 0), P(a.right, a.bottom, 0), P(a.right, a.bottom, d), P(a.left, a.bottom, d)]), { fill: wall, stroke: grid, width: 1 });
85
+ const sx = v.kx >= 0 ? a.left : a.right;
86
+ painter.path(poly([P(sx, a.top, 0), P(sx, a.top, d), P(sx, a.bottom, d), P(sx, a.bottom, 0)]), { fill: wall, stroke: grid, width: 1 });
87
+ for (const ax of Object.values(chart.scales)) {
88
+ if (ax.axis === 'r' || ax.options.display === false) continue;
89
+ for (const tk of ax.ticks) {
90
+ const p = ax.getPixelForValue(tk.value);
91
+ if (!ax.isHorizontal() && p >= a.top - 0.5 && p <= a.bottom + 0.5) { painter.line(...P(a.left, p, d), ...P(a.right, p, d), { stroke: grid, width: 1 }); painter.line(...P(sx, p, 0), ...P(sx, p, d), { stroke: grid, width: 1 }); }
92
+ if (ax.isHorizontal() && ax.type !== 'category' && p >= a.left && p <= a.right) { painter.line(...P(p, a.top, d), ...P(p, a.bottom, d), { stroke: grid, width: 1 }); painter.line(...P(p, a.bottom, 0), ...P(p, a.bottom, d), { stroke: grid, width: 1 }); }
93
+ }
94
+ }
95
+ }
96
+
97
+ // ── a pie with thickness ─────────────────────────────────────────────────────────────────────────
98
+ // a point on the rim at angle a (0 at the top, clockwise), tilted: the top of the pie is squashed by cos(alpha)
99
+ const pie3d = (donut) => ({
100
+ element: 'arc', name: donut ? '3D doughnut chart' : '3D pie chart', three: 'pie', axes: 'none', legend: 'points', colors: 'points',
101
+ defaults: { aspectRatio: 1.6, interaction: { mode: 'nearest', intersect: true }, plugins: { legend: { display: true, position: 'right' } } },
102
+ limits: () => [Infinity, -Infinity],
103
+ update(chart, meta) {
104
+ const a = chart.chartArea, v = view3d(chart, { alpha: 50, depth: 40 }), tilt = Math.max(5, Math.min(85, v.alpha)) * RAD, thick = v.depth * Math.sin(tilt);
105
+ const out = Math.max(0, ...meta.parsed.map((p) => num(chart.option(meta, 'offset', p.i, null, 0)) || (p.raw?.sliced ? 14 : 0)));
106
+ const W = a.right - a.left - out * 2, H = a.bottom - a.top - out * 2, R = Math.max(0, Math.min(W / 2, (H - thick) / (2 * Math.cos(tilt)))) * 0.94;
107
+ const cx = (a.left + a.right) / 2, cy = a.top + (H - thick) / 2, ky = Math.cos(tilt), inner = donut ? pct(chart.option(meta, 'cutout', 0, null, '50%'), R) : 0;
108
+ const vis = meta.parsed.map((p) => chart.getDataVisibility(p.i) && p.value > 0), tot = meta.parsed.reduce((s, p, i) => s + (vis[i] ? p.value : 0), 0) || 1;
109
+ let t = (chart.option(meta, 'rotation', 0, null, 0) + (v.beta ?? 0)) * RAD;
110
+ meta.pie = { cx, cy, R, ky, thick, inner };
111
+ meta.elements = meta.parsed.map((p, i) => {
112
+ const span = vis[i] ? (p.value / tot) * TAU : 0, a0 = t; t += span;
113
+ const c = chart.fillOf(meta, p.i);
114
+ const hit = (x, y) => { const dx = x - cx, dy = (y - cy) / ky, d = Math.hypot(dx, dy); if (d > R || d < inner) return false; let ang = Math.atan2(dx, -dy); while (ang < a0) ang += TAU; while (ang >= a0 + TAU) ang -= TAU; return ang <= a0 + span; };
115
+ const mid = a0 + span / 2;
116
+ return { kind: 'arc', datasetIndex: meta.index, index: p.i, cx, cy, startAngle: a0, endAngle: a0 + span, innerRadius: inner, outerRadius: R, share: p.value / tot, color: c, skip: !vis[i], raw: p.raw, parsed: p, hit, center: { x: cx + Math.sin(mid) * (R + inner) / 2, y: cy - Math.cos(mid) * ky * (R + inner) / 2 }, tip: { x: cx + Math.sin(mid) * R * 0.7, y: cy - Math.cos(mid) * ky * R * 0.7 }, options: { backgroundColor: c } };
117
+ });
118
+ },
119
+ initial(el) { return { ...el, endAngle: el.startAngle }; },
120
+ draw(painter, meta, chart) {
121
+ const { cx, cy, ky, thick } = meta.pie, th = themeOf(chart), off = chart.option(meta, 'hoverOffset', 0, null, 10);
122
+ const rim = (e, r, a, dx, dy, down = 0) => [cx + dx + Math.sin(a) * r, cy + dy - Math.cos(a) * r * ky + down];
123
+ const arcPts = (e, r, a0, a1, dx, dy, down = 0) => { const n = Math.max(2, Math.ceil(((a1 - a0) / TAU) * 72)); return Array.from({ length: n + 1 }, (_, k) => rim(e, r, a0 + ((a1 - a0) * k) / n, dx, dy, down)); };
124
+ const els = meta.elements.filter((e) => !e.skip && e.endAngle - e.startAngle > 1e-4).map((e) => {
125
+ // a slice pulled out: Chart.js's offset, Highcharts's sliced (and a little more under the pointer)
126
+ const m = (e.startAngle + e.endAngle) / 2, o = (num(chart.option(meta, 'offset', e.index, null, 0)) || (e.raw?.sliced ? 14 : 0)) + (chart.isActive(meta.index, e.index) ? off : 0);
127
+ return { e, dx: Math.sin(m) * o, dy: -Math.cos(m) * o * ky, m };
128
+ });
129
+ const edge = th.bg ?? '#fff';
130
+ // the walls: the inner one on the far side, then the outer one on the near side, nearest last
131
+ const walls = [];
132
+ for (const s of els) {
133
+ const { e, dx, dy } = s, side = shade(e.color, -0.22);
134
+ for (const [lo, hi] of nearSpans(e.startAngle, e.endAngle, true)) walls.push({ y: Math.max(...arcPts(e, e.outerRadius, lo, hi, dx, dy).map((p) => p[1])), d: poly([...arcPts(e, e.outerRadius, lo, hi, dx, dy), ...arcPts(e, e.outerRadius, lo, hi, dx, dy, thick).reverse()]), fill: side });
135
+ if (e.innerRadius > 0) for (const [lo, hi] of nearSpans(e.startAngle, e.endAngle, false)) walls.push({ y: -1e9, d: poly([...arcPts(e, e.innerRadius, lo, hi, dx, dy), ...arcPts(e, e.innerRadius, lo, hi, dx, dy, thick).reverse()]), fill: shade(e.color, -0.35) });
136
+ if (dx || dy) for (const a of [e.startAngle, e.endAngle]) walls.push({ y: Math.max(rim(e, e.outerRadius, a, dx, dy)[1], cy + dy), d: poly([rim(e, e.innerRadius, a, dx, dy), rim(e, e.outerRadius, a, dx, dy), rim(e, e.outerRadius, a, dx, dy, thick), rim(e, e.innerRadius, a, dx, dy, thick)]), fill: shade(e.color, -0.3) });
137
+ }
138
+ walls.sort((p, q) => p.y - q.y);
139
+ for (const w of walls) painter.path(w.d, { fill: w.fill, stroke: edge, width: 0.6, join: 'round' });
140
+ for (const { e, dx, dy } of els) {
141
+ const top = e.innerRadius > 0 ? [...arcPts(e, e.outerRadius, e.startAngle, e.endAngle, dx, dy), ...arcPts(e, e.innerRadius, e.startAngle, e.endAngle, dx, dy).reverse()] : [[cx + dx, cy + dy], ...arcPts(e, e.outerRadius, e.startAngle, e.endAngle, dx, dy)];
142
+ painter.path(poly(top), { fill: chart.isActive(meta.index, e.index) ? shade(e.color, -0.06) : e.color, stroke: edge, width: 1, join: 'round' });
143
+ }
144
+ },
145
+ label(chart, meta, el) { return String(chart.data.labels?.[el.index] ?? el.index + 1); },
146
+ format(chart, meta, el, fmt) { return `${fmt(el.parsed.value)} (${Math.round(el.share * 100)}%)`; },
147
+ swatch(chart, meta, el) { return el.color; },
148
+ });
149
+ const pct = (v, of) => (typeof v === 'string' && v.trim().endsWith('%') ? (parseFloat(v) / 100) * of : Number(v) || 0);
150
+ // the parts of [a0, a1] on the near half of the rim (π/2 … 3π/2) or the far half
151
+ function nearSpans(a0, a1, near) {
152
+ const out = [], base = Math.floor(a0 / TAU) * TAU;
153
+ for (let k = -1; k <= 2; k++) {
154
+ const lo = base + k * TAU + (near ? Math.PI / 2 : -Math.PI / 2), hi = lo + Math.PI;
155
+ const s = Math.max(a0, lo), e = Math.min(a1, hi);
156
+ if (e - s > 1e-6) out.push([s, e]);
157
+ }
158
+ return out;
159
+ }
160
+
161
+ // ── points and a surface in a cube that turns ────────────────────────────────────────────────────
162
+ function cubeOf(chart, metas) {
163
+ const v = view3d(chart, { alpha: 20, beta: 30 }), a = chart.chartArea, ax3 = chart.resolved.chart3d?.axes ?? {};
164
+ const pts = metas.flatMap((m) => m.parsed.filter((p) => Number.isFinite(p.value)));
165
+ const range = (key, lo, hi, own) => {
166
+ let mn = own?.min ?? lo, mx = own?.max ?? hi; if (!(mx > mn)) { mn -= 1; mx += 1; }
167
+ const step = niceStep(mx - mn, 4); if (own?.min == null) mn = Math.floor(mn / step) * step; if (own?.max == null) mx = Math.ceil(mx / step) * step;
168
+ const ticks = []; for (let t = mn, k = 0; t <= mx + step * 1e-9 && k < 20; t += step, k++) ticks.push(+t.toPrecision(12));
169
+ return { min: mn, max: mx, ticks, title: own?.title };
170
+ };
171
+ const [xl, xh] = extentOf(pts.map((p) => p.x3)), [yl, yh] = extentOf(pts.map((p) => p.value)), [zl, zh] = extentOf(pts.map((p) => p.z3));
172
+ const X = range('x', xl, xh, ax3.x), Y = range('y', yl, yh, ax3.y), Z = range('z', zl, zh, ax3.z);
173
+ const ca = Math.cos(v.alpha * RAD), sa = Math.sin(v.alpha * RAD), cb = Math.cos(v.beta * RAD), sb = Math.sin(v.beta * RAD), D = Math.max(2, v.viewDistance / 6);
174
+ // as large as fits whichever way it is turned around its upright (a corner reaches √2 across), and as tall as it is
175
+ // seen now, with its middle in the middle
176
+ const unit = (px, py, pz) => { const x1 = px * cb + pz * sb, z1 = -px * sb + pz * cb, y2 = py * ca + z1 * sa, z2 = -py * sa + z1 * ca, s = D / (D + z2); return [x1 * s, -y2 * s]; };
177
+ const corners = [-1, 1].flatMap((x) => [-1, 1].flatMap((y) => [-1, 1].map((z) => unit(x, y, z)))), ys = corners.map((p) => p[1]), top = Math.min(...ys), bot = Math.max(...ys);
178
+ const wide = Math.max(Math.SQRT2 * D / (D - Math.SQRT2), ...corners.map((p) => Math.abs(p[0])));
179
+ const R = Math.max(10, Math.min((a.right - a.left - 72) / (2 * wide), (a.bottom - a.top - 44) / (bot - top))), cx = (a.left + a.right) / 2, cy = (a.top + a.bottom) / 2 - ((top + bot) / 2) * R;
180
+ const norm = (val, r) => ((val - r.min) / ((r.max - r.min) || 1)) * 2 - 1;
181
+ // a point of the cube (each of -1 … 1) → the screen, and how far it is (larger: further); seen from above when alpha > 0,
182
+ // so the far side of the floor is higher up the screen and the top of the cube is nearer
183
+ const at = (px, py, pz) => { const x1 = px * cb + pz * sb, z1 = -px * sb + pz * cb, y2 = py * ca + z1 * sa, z2 = -py * sa + z1 * ca, s = D / (D + z2); return [cx + x1 * R * s, cy - y2 * R * s, z2, s]; };
184
+ return { v, X, Y, Z, at, toScreen: (x, y, z) => at(norm(x, X), norm(y, Y), norm(z, Z)), R, cx, cy, norm };
185
+ }
186
+ function drawCube(painter, chart, cube) {
187
+ const th = themeOf(chart), grid = th.grid ?? 'rgba(0,0,0,0.1)', wall = th.mode === 'dark' ? 'rgba(255,255,255,0.03)' : 'rgba(20,32,43,0.03)', f = { ...chart.resolved.font, size: 10 }, at = cube.at, fmt = fmtOf(chart);
188
+ const P = (x, y, z) => at(x, y, z).slice(0, 2);
189
+ // the walls further away: one of x = ±1, one of z = ±1, the floor (or the ceiling seen from below)
190
+ const xw = at(1, 0, 0)[2] > at(-1, 0, 0)[2] ? 1 : -1, zw = at(0, 0, 1)[2] > at(0, 0, -1)[2] ? 1 : -1, yw = cube.v.alpha >= 0 ? -1 : 1;
191
+ painter.layer('grid');
192
+ const face = (pts) => painter.path(poly(pts.map((p) => P(...p))), { fill: wall, stroke: grid, width: 1 });
193
+ face([[xw, -1, -1], [xw, 1, -1], [xw, 1, 1], [xw, -1, 1]]); face([[-1, -1, zw], [1, -1, zw], [1, 1, zw], [-1, 1, zw]]); face([[-1, yw, -1], [1, yw, -1], [1, yw, 1], [-1, yw, 1]]);
194
+ const n = (val, r) => cube.norm(val, r);
195
+ for (const t of cube.Y.ticks) { const y = n(t, cube.Y); painter.line(...P(xw, y, -1), ...P(xw, y, 1), { stroke: grid, width: 1 }); painter.line(...P(-1, y, zw), ...P(1, y, zw), { stroke: grid, width: 1 }); }
196
+ for (const t of cube.X.ticks) { const x = n(t, cube.X); painter.line(...P(x, yw, -1), ...P(x, yw, 1), { stroke: grid, width: 1 }); painter.line(...P(x, -1, zw), ...P(x, 1, zw), { stroke: grid, width: 1 }); }
197
+ for (const t of cube.Z.ticks) { const z = n(t, cube.Z); painter.line(...P(-1, yw, z), ...P(1, yw, z), { stroke: grid, width: 1 }); painter.line(...P(xw, -1, z), ...P(xw, 1, z), { stroke: grid, width: 1 }); }
198
+ painter.layer('axes');
199
+ const ink = chart.resolved.color;
200
+ // the numbers along the near edges of the floor, and up the near corner of the back walls: each pushed out from
201
+ // the middle of its face, and left out where it would cover one already written (at the corners the axes meet)
202
+ const placed = [], put = (text, p, from, gap, opts = {}) => {
203
+ const dx = p[0] - from[0], dy = p[1] - from[1], d = Math.hypot(dx, dy) || 1, w = painter.measure(text, f), x = p[0] + (dx / d) * gap, y = p[1] + (dy / d) * gap;
204
+ const align = Math.abs(dx / d) < 0.35 ? 'center' : dx > 0 ? 'left' : 'right', l = align === 'center' ? x - w / 2 : align === 'left' ? x : x - w, box = { l: l - 2, r: l + w + 2, t: y - f.size / 2 - 1, b: y + f.size / 2 + 1 };
205
+ if (placed.some((q) => box.l < q.r && box.r > q.l && box.t < q.b && box.b > q.t)) return;
206
+ placed.push(box); painter.text(text, x, y, { fill: ink, font: opts.font ?? f, align, baseline: 'middle' });
207
+ };
208
+ for (const t of cube.Y.ticks) put(fmt(t), P(xw, n(t, cube.Y), -zw), P(-xw, n(t, cube.Y), -zw), 6);
209
+ for (const t of cube.X.ticks) put(fmt(t), P(n(t, cube.X), yw, -zw), P(n(t, cube.X), yw, zw), 9);
210
+ for (const t of cube.Z.ticks) put(fmt(t), P(-xw, yw, n(t, cube.Z)), P(xw, yw, n(t, cube.Z)), 9);
211
+ const titles = [[cube.X.title, P(0, yw, -zw), P(0, yw, zw), 26], [cube.Z.title, P(-xw, yw, 0), P(xw, yw, 0), 30], [cube.Y.title, P(xw, 1, -zw), P(xw, -1, -zw), 14]];
212
+ for (const [text, p, from, gap] of titles) if (text) put(String(text), p, from, gap, { font: { ...f, size: 11, weight: '600' } });
213
+ }
214
+ const xyz = (chart, meta) => (meta.dataset.data ?? []).map((raw, i) => {
215
+ const o = Array.isArray(raw) ? { x: raw[0], y: raw[1], z: raw[2] } : raw ?? {};
216
+ return { index: i, x3: num(o.x), value: num(o.y), z3: num(o.z ?? 0), raw, i };
217
+ });
218
+ const scatter3d = {
219
+ element: 'point', name: '3D scatter chart', three: 'cube', axes: 'none', solid: true,
220
+ defaults: { aspectRatio: 1.3, interaction: { mode: 'nearest', intersect: true } },
221
+ parse: xyz,
222
+ limits: () => [Infinity, -Infinity],
223
+ update(chart, meta) {
224
+ const metas = chart.metas.filter((m) => m.controller.three === 'cube' && chart.isDatasetVisible(m.index)), cube = cubeOf(chart, metas);
225
+ chart._cube = cube;
226
+ meta.elements = meta.parsed.map((p) => {
227
+ const q = cube.toScreen(p.x3, p.value, p.z3), r = chart.option(meta, 'pointRadius', p.i, 'radius', 4) * q[3];
228
+ return { kind: 'point', datasetIndex: meta.index, index: p.i, x: q[0], y: q[1], depth: q[2], radius: r, skip: !Number.isFinite(q[0]) || !Number.isFinite(p.value), raw: p.raw, parsed: p, options: chart.pointOptions(meta, p.i) };
229
+ });
230
+ },
231
+ initial(el) { return { ...el, radius: 0 }; },
232
+ draw(painter, meta, chart) {
233
+ const first = chart.metas.find((m) => m.controller.three === 'cube' && chart.isDatasetVisible(m.index));
234
+ if (first === meta) drawCube(painter, chart, chart._cube);
235
+ painter.layer('datasets');
236
+ const c = chart.option(meta, 'backgroundColor', 0) ?? meta.auto?.borderColor ?? PALETTE[0], th = themeOf(chart), far = th.mode === 'dark' ? '#161b22' : '#ffffff';
237
+ for (const e of meta.elements.filter((x) => !x.skip).sort((a, b) => b.depth - a.depth)) {
238
+ const own = chart.option(meta, 'backgroundColor', e.index) ?? c, fill = mix(typeof own === 'string' ? own : PALETTE[0], far, Math.max(0, Math.min(0.45, e.depth * 0.22)));
239
+ painter.circle(e.x, e.y, chart.isActive(meta.index, e.index) ? e.radius + 2 : e.radius, { fill, stroke: chart.isActive(meta.index, e.index) ? th.ink : shade(fill, -0.2), width: 1 });
240
+ }
241
+ },
242
+ label() { return ''; },
243
+ format(chart, meta, el, fmt) { const p = el.parsed; return `x ${fmt(p.x3)}, y ${fmt(p.value)}, z ${fmt(p.z3)}`; },
244
+ swatch(chart, meta) { return chart.option(meta, 'backgroundColor', 0) ?? meta.auto?.borderColor; },
245
+ };
246
+ // a surface: a grid of heights, as rows of numbers (x along a row, z down the rows) or { x, y, z } points on a grid
247
+ const surface = {
248
+ ...scatter3d, element: 'quad', name: 'Surface chart', colorAxis: true, colors: 'none', legend: 'none',
249
+ parse(chart, meta) {
250
+ const d = meta.dataset.data ?? [];
251
+ if (Array.isArray(d[0])) { const xs = meta.dataset.x ?? d[0].map((_, j) => j), zs = meta.dataset.z ?? d.map((_, k) => k); meta.grid = { cols: d[0].length, rows: d.length }; return d.flatMap((row, k) => row.map((v, j) => ({ index: k * row.length + j, x3: num(xs[j]), z3: num(zs[k]), value: num(v), raw: v, i: k * row.length + j }))); }
252
+ const pts = xyz(chart, meta), xs = [...new Set(pts.map((p) => p.x3))].sort((a, b) => a - b), zs = [...new Set(pts.map((p) => p.z3))].sort((a, b) => a - b);
253
+ meta.grid = { cols: xs.length, rows: zs.length };
254
+ const at = new Map(pts.map((p) => [p.x3 + '|' + p.z3, p]));
255
+ return zs.flatMap((z, k) => xs.map((x, j) => ({ ...(at.get(x + '|' + z) ?? { x3: x, z3: z, value: NaN, raw: null }), index: k * xs.length + j, i: k * xs.length + j })));
256
+ },
257
+ update(chart, meta) {
258
+ const metas = chart.metas.filter((m) => m.controller.three === 'cube' && chart.isDatasetVisible(m.index)), cube = cubeOf(chart, metas), scale = colorScaleOf(chart, meta);
259
+ chart._cube = cube;
260
+ const { cols, rows } = meta.grid, P = meta.parsed.map((p) => cube.toScreen(p.x3, p.value, p.z3));
261
+ const els = [];
262
+ for (let k = 0; k + 1 < rows; k++) for (let j = 0; j + 1 < cols; j++) {
263
+ const ids = [k * cols + j, k * cols + j + 1, (k + 1) * cols + j + 1, (k + 1) * cols + j], ps = ids.map((i) => meta.parsed[i]);
264
+ if (ps.some((p) => !Number.isFinite(p?.value))) continue;
265
+ const pts = ids.map((i) => P[i]), mean = ps.reduce((s, p) => s + p.value, 0) / 4;
266
+ els.push({ kind: 'quad', datasetIndex: meta.index, index: ids[0], pts: pts.map((q) => [q[0], q[1]]), depth: pts.reduce((s, q) => s + q[2], 0) / 4, color: scale.colorOf(mean), mean, skip: false, raw: ps[0].raw, parsed: { ...ps[0], value: mean, corners: ps }, hit: (x, y) => inPoly(pts, x, y), center: { x: pts.reduce((s, q) => s + q[0], 0) / 4, y: pts.reduce((s, q) => s + q[1], 0) / 4 } });
267
+ }
268
+ meta.elements = els;
269
+ },
270
+ initial(el) { return el; },
271
+ draw(painter, meta, chart) {
272
+ const first = chart.metas.find((m) => m.controller.three === 'cube' && chart.isDatasetVisible(m.index));
273
+ if (first === meta) drawCube(painter, chart, chart._cube);
274
+ painter.layer('datasets');
275
+ const wire = meta.dataset.wireframe !== false;
276
+ for (const e of meta.elements.slice().sort((a, b) => b.depth - a.depth)) {
277
+ const active = chart.isActive(meta.index, e.index);
278
+ painter.path(poly(e.pts), { fill: active ? shade(e.color, -0.2) : e.color, stroke: wire ? shade(e.color, -0.18) : e.color, width: wire ? 0.6 : 0.3, join: 'round' });
279
+ }
280
+ },
281
+ format(chart, meta, el, fmt) { const c = el.parsed.corners?.[0] ?? el.parsed; return `x ${fmt(c.x3)}, z ${fmt(c.z3)}: ${fmt(el.mean)}`; },
282
+ swatch(chart, meta, el) { return el.color; },
283
+ describe(chart, meta, fmt) { const ps = meta.parsed.filter((p) => Number.isFinite(p.value)); if (!ps.length) return 'no values'; const hi = ps.reduce((a, b) => (b.value > a.value ? b : a)), lo = ps.reduce((a, b) => (b.value < a.value ? b : a)); return `${meta.label ? meta.label + ': ' : ''}a surface of ${meta.grid.cols} by ${meta.grid.rows}, highest ${fmt(hi.value)} at x ${fmt(hi.x3)}, z ${fmt(hi.z3)}, lowest ${fmt(lo.value)} at x ${fmt(lo.x3)}, z ${fmt(lo.z3)}`; },
284
+ };
285
+
286
+ // ── turning them: a drag changes alpha and beta ─────────────────────────────────────────────────────
287
+ export const rotate3d = {
288
+ id: 'rotate3d',
289
+ defaults: { enabled: true, speed: 0.4 },
290
+ afterInit(chart) {
291
+ if (typeof chart.surface?.addEventListener !== 'function') return;
292
+ let drag = null;
293
+ chart.surface.addEventListener('pointerdown', (e) => {
294
+ const o = chart.resolved?.plugins?.rotate3d ?? {}, kind = chart.metas.find((m) => m.controller.three)?.controller.three;
295
+ if (!kind || o.enabled === false || chart.resolved?.plugins?.zoom?.zoom?.drag?.enabled) return;
296
+ const p = chart._pos(e); if (!chart.isPointInArea(p)) return;
297
+ const v = view3d(chart, kind === 'pie' ? { alpha: 50, beta: 0 } : kind === 'cube' ? { alpha: 20, beta: 30 } : {});
298
+ drag = { x: p.x, y: p.y, alpha: v.alpha, beta: v.beta, kind, moved: 0 };
299
+ chart.surface.setPointerCapture?.(e.pointerId);
300
+ });
301
+ chart.surface.addEventListener('pointermove', (e) => {
302
+ if (!drag) return;
303
+ const p = chart._pos(e), s = chart.resolved?.plugins?.rotate3d?.speed ?? 0.4, dx = p.x - drag.x, dy = p.y - drag.y;
304
+ drag.moved = Math.max(drag.moved, Math.abs(dx) + Math.abs(dy));
305
+ if (drag.moved < 3) return;
306
+ const lim = drag.kind === 'oblique' ? 45 : drag.kind === 'pie' ? 85 : 89;
307
+ chart._rot = { alpha: Math.max(drag.kind === 'pie' ? 10 : -lim, Math.min(lim, drag.alpha + dy * s)), beta: drag.kind === 'oblique' ? Math.max(-lim, Math.min(lim, drag.beta + dx * s)) : drag.beta + dx * s };
308
+ chart.update('none');
309
+ });
310
+ const end = () => { if (drag?.moved >= 3) chart._justDragged = true; drag = null; };
311
+ chart.surface.addEventListener('pointerup', end); chart.surface.addEventListener('pointercancel', end);
312
+ },
313
+ };
314
+
315
+ export const DEPTH_TYPES = { column3d, bar3d: { ...column3d, name: '3D bar chart', indexAxis: 'y' }, pie3d: pie3d(false), doughnut3d: pie3d(true), scatter3d, surface };
316
+ void contrastOn;