@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/features.js
ADDED
|
@@ -0,0 +1,783 @@
|
|
|
1
|
+
// @clarity-js/charts — what Highcharts and ApexCharts add around a chart, as plugins with Chart.js's
|
|
2
|
+
// hooks: annotations and plot bands/lines, data labels, zoom, pan and a measuring ruler, a
|
|
3
|
+
// crosshair, charts that follow one another (a group), a navigator and range selector (as
|
|
4
|
+
// Highcharts Stock), a brush (as ApexCharts), a toolbar with export, drilldown, data grouping and
|
|
5
|
+
// a colour-axis legend. And the functions behind chart.sonify(), chart.toCSV(), saveView().
|
|
6
|
+
|
|
7
|
+
import { frame } from '@ozsarman/clarityjs/game-loop';
|
|
8
|
+
import { toTime, formatTime } from './axes.js';
|
|
9
|
+
import { formatNumber } from './format.js';
|
|
10
|
+
import { contrastOn, cssPaint, solidOf, withAlpha } from './fills.js';
|
|
11
|
+
import { centerOf, tipPoint } from './controllers.js';
|
|
12
|
+
import { colorScaleOf } from './types.js';
|
|
13
|
+
import { niceStep } from './scale.js';
|
|
14
|
+
import { groupPoints } from './layouts.js';
|
|
15
|
+
import { zoomMap, panMap } from './maps.js';
|
|
16
|
+
const geoOnly = (chart) => chart.metas.some((m) => m.controller.geo) && !Object.values(chart.scales).some((s) => s.axis !== 'r');
|
|
17
|
+
|
|
18
|
+
const themeOf = (chart) => chart.resolved?.theme ?? {};
|
|
19
|
+
const fontOf = (chart, own) => ({ ...chart.resolved.font, ...(own ?? {}) });
|
|
20
|
+
const lineOf = (f) => (f?.size ?? 12) * (f?.lineHeight ?? 1.2);
|
|
21
|
+
const fmt = (chart, v) => formatNumber(v, { locale: chart.resolved.locale });
|
|
22
|
+
const isDom = (chart) => typeof chart.surface?.addEventListener === 'function' && typeof document !== 'undefined';
|
|
23
|
+
const resolveFn = (v, ctx) => (typeof v === 'function' ? v(ctx) : v);
|
|
24
|
+
const horizontals = (chart) => Object.values(chart.scales).filter((s) => s.axis !== 'r' && s.isHorizontal());
|
|
25
|
+
const verticals = (chart) => Object.values(chart.scales).filter((s) => s.axis !== 'r' && !s.isHorizontal());
|
|
26
|
+
const scalesFor = (chart, mode) => [...(String(mode).includes('x') ? horizontals(chart) : []), ...(String(mode).includes('y') ? verticals(chart) : [])];
|
|
27
|
+
/** A value as an axis reads it (a label on a category axis, a date on a time axis). */
|
|
28
|
+
export function valueOn(ax, v) {
|
|
29
|
+
if (v == null || !ax) return NaN;
|
|
30
|
+
if (ax.type === 'category') return typeof v === 'string' ? ax.labels.indexOf(v) : Number(v);
|
|
31
|
+
if (ax.type?.startsWith('time')) return toTime(v);
|
|
32
|
+
return Number(v);
|
|
33
|
+
}
|
|
34
|
+
const pixel = (ax, v) => ax.getPixelForValue(valueOn(ax, v));
|
|
35
|
+
/** How a value on an axis is written (a tick's way). */
|
|
36
|
+
function valueText(ax, v) {
|
|
37
|
+
if (!ax || !Number.isFinite(v)) return '';
|
|
38
|
+
if (ax.type === 'category') return String(ax.labels[Math.round(v)] ?? '');
|
|
39
|
+
if (ax.type?.startsWith('time')) return formatTime(v, ax.options.time?.tooltipFormat ?? (ax.max - ax.min < 2 * 864e5 ? 'MMM d, HH:mm' : 'MMM d, yyyy'));
|
|
40
|
+
return formatNumber(v, { locale: ax.chart.resolved.locale, decimals: Math.abs(ax.max - ax.min) < 10 ? 2 : Math.abs(ax.max - ax.min) < 1000 ? 1 : 0 });
|
|
41
|
+
}
|
|
42
|
+
// a word or two on a box (labels of annotations, crosshair values, data labels)
|
|
43
|
+
function tag(p, lines, x, y, { fill = '#666', bg = null, font, padding = 4, align = 'center', baseline = 'middle', radius = 3, border = null, opacity = 1 } = {}) {
|
|
44
|
+
const ls = [].concat(lines).map(String), lh = lineOf(font), w = Math.max(...ls.map((l) => p.measure(l, font))) + padding * 2, h = ls.length * lh + padding * 2;
|
|
45
|
+
const x0 = align === 'left' || align === 'start' ? x : align === 'right' || align === 'end' ? x - w : x - w / 2, y0 = baseline === 'top' ? y : baseline === 'bottom' ? y - h : y - h / 2;
|
|
46
|
+
if (bg) p.rect(x0, y0, w, h, { fill: bg, radius, stroke: border, width: border ? 1 : 0, opacity });
|
|
47
|
+
ls.forEach((l, k) => p.text(l, x0 + w / 2, y0 + padding + lh * (k + 0.5), { fill, font, align: 'center', baseline: 'middle', opacity }));
|
|
48
|
+
return { l: x0, r: x0 + w, t: y0, b: y0 + h };
|
|
49
|
+
}
|
|
50
|
+
function controls(chart) {
|
|
51
|
+
if (!isDom(chart)) return null;
|
|
52
|
+
if (chart._controls?.isConnected || (chart._controls && chart._controls.parentNode === chart.container)) return chart._controls;
|
|
53
|
+
const el = document.createElement('div');
|
|
54
|
+
el.className = 'clarity-chart-controls';
|
|
55
|
+
Object.assign(el.style, { position: 'absolute', top: '4px', right: '4px', display: 'flex', gap: '4px', zIndex: '2', alignItems: 'center', flexWrap: 'wrap', justifyContent: 'flex-end' });
|
|
56
|
+
chart.container.appendChild(el);
|
|
57
|
+
chart._controls = el;
|
|
58
|
+
return el;
|
|
59
|
+
}
|
|
60
|
+
function button(chart, text, label, onClick, { pressed } = {}) {
|
|
61
|
+
const c = themeOf(chart).control ?? {}, b = document.createElement('button');
|
|
62
|
+
b.type = 'button'; b.textContent = text; b.setAttribute('aria-label', label); b.title = label;
|
|
63
|
+
if (pressed != null) b.setAttribute('aria-pressed', pressed ? 'true' : 'false');
|
|
64
|
+
Object.assign(b.style, { font: `12px/1 ${chart.resolved.font.family}`, minWidth: '26px', height: '24px', padding: '0 6px', borderRadius: '5px', border: `1px solid ${c.border ?? 'rgba(0,0,0,0.15)'}`, background: pressed ? c.active ?? '#3d7dd8' : c.background ?? '#fff', color: pressed ? '#fff' : c.color ?? '#1b2430', cursor: 'pointer' });
|
|
65
|
+
b.addEventListener('click', (e) => { e.stopPropagation(); onClick(e); });
|
|
66
|
+
return b;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// ── annotations, plot bands and plot lines ─────────────────────────────────────────────────
|
|
70
|
+
function annotationsOf(chart, o) {
|
|
71
|
+
const list = Array.isArray(o.annotations) ? o.annotations.map((a, k) => ({ id: a.id ?? String(k), ...a })) : Object.entries(o.annotations ?? {}).map(([id, a]) => ({ id, ...a }));
|
|
72
|
+
// Highcharts's plotBands and plotLines, written on an axis
|
|
73
|
+
for (const ax of Object.values(chart.scales)) {
|
|
74
|
+
if (ax.axis === 'r') continue;
|
|
75
|
+
const h = ax.isHorizontal(), min = h ? 'xMin' : 'yMin', max = h ? 'xMax' : 'yMax', sid = h ? 'xScaleID' : 'yScaleID';
|
|
76
|
+
for (const b of ax.options.plotBands ?? []) list.push({ type: 'box', drawTime: 'beforeDatasetsDraw', [min]: b.from, [max]: b.to, [sid]: ax.id, backgroundColor: b.color ?? withAlpha('#3d7dd8', 0.08), borderWidth: b.borderWidth ?? 0, borderColor: b.borderColor, label: b.label ? { display: true, content: b.label.text ?? b.label.content, position: b.label.align === 'right' ? 'end' : b.label.align === 'center' ? 'center' : 'start', color: b.label.style?.color ?? b.label.color, backgroundColor: null } : undefined });
|
|
77
|
+
for (const l of ax.options.plotLines ?? []) list.push({ type: 'line', drawTime: 'afterDatasetsDraw', scaleID: ax.id, value: l.value, borderColor: l.color ?? themeOf(chart).axis, borderWidth: l.width ?? 1, borderDash: l.dash ?? dashOf(l.dashStyle), label: l.label ? { display: true, content: l.label.text ?? l.label.content, position: l.label.align === 'right' ? 'end' : l.label.align === 'center' ? 'center' : 'start', color: l.label.style?.color ?? l.label.color } : undefined });
|
|
78
|
+
}
|
|
79
|
+
return list.filter((a) => resolveFn(a.display, { chart }) !== false);
|
|
80
|
+
}
|
|
81
|
+
const dashOf = (s) => ({ Dash: [8, 6], ShortDash: [6, 2], Dot: [1, 3], ShortDot: [2, 2], DashDot: [8, 3, 1, 3], LongDash: [16, 6] })[s] ?? [];
|
|
82
|
+
function drawAnnotation(chart, a) {
|
|
83
|
+
const p = chart.painter, area = chart.chartArea, th = themeOf(chart), xs = chart.scales[a.xScaleID ?? 'x'], ys = chart.scales[a.yScaleID ?? 'y'];
|
|
84
|
+
const st = { stroke: a.borderColor ?? th.axis, width: a.borderWidth ?? (a.type === 'box' ? 0 : 1.5), dash: a.borderDash, clip: a.clip === false ? null : chart.clip };
|
|
85
|
+
const f = fontOf(chart, a.label?.font), lab = a.label;
|
|
86
|
+
const say = (x, y, align, baseline) => { if (lab && lab.display !== false && (lab.content ?? lab.text) != null) return tag(p, lab.content ?? lab.text, x + (lab.xAdjust ?? 0), y + (lab.yAdjust ?? 0), { fill: lab.color ?? (lab.backgroundColor === null ? th.ink : '#fff'), bg: lab.backgroundColor === null ? null : lab.backgroundColor ?? solidOf(a.borderColor) ?? 'rgba(20,32,43,0.8)', font: f, padding: lab.padding ?? 4, align, baseline, radius: lab.borderRadius ?? 3 }); return null; };
|
|
87
|
+
let box = null;
|
|
88
|
+
if (a.type === 'line') {
|
|
89
|
+
let x0, y0, x1, y1;
|
|
90
|
+
const sc = a.scaleID ? chart.scales[a.scaleID] : null;
|
|
91
|
+
if (sc) { const v0 = pixel(sc, a.value), v1 = a.endValue != null ? pixel(sc, a.endValue) : v0; if (sc.isHorizontal()) { x0 = v0; x1 = v1; y0 = area.bottom; y1 = area.top; } else { y0 = v0; y1 = v1; x0 = area.left; x1 = area.right; } }
|
|
92
|
+
else { x0 = a.xMin != null ? pixel(xs, a.xMin) : area.left; x1 = a.xMax != null ? pixel(xs, a.xMax) : area.right; y0 = a.yMin != null ? pixel(ys, a.yMin) : area.bottom; y1 = a.yMax != null ? pixel(ys, a.yMax) : area.top; }
|
|
93
|
+
if (![x0, y0, x1, y1].every(Number.isFinite)) return null;
|
|
94
|
+
p.line(x0, y0, x1, y1, st);
|
|
95
|
+
const pos = lab?.position ?? 'center', t = pos === 'start' ? 0.06 : pos === 'end' ? 0.94 : 0.5;
|
|
96
|
+
const vertical = Math.abs(x1 - x0) < 1;
|
|
97
|
+
say(x0 + (x1 - x0) * (vertical ? 0 : t), y0 + (y1 - y0) * (vertical ? 1 - t : 0) + (vertical ? 0 : -2), vertical ? 'center' : pos === 'start' ? 'left' : pos === 'end' ? 'right' : 'center', vertical ? 'middle' : 'bottom');
|
|
98
|
+
box = { l: Math.min(x0, x1) - 3, r: Math.max(x0, x1) + 3, t: Math.min(y0, y1) - 3, b: Math.max(y0, y1) + 3 };
|
|
99
|
+
} else if (a.type === 'box' || a.type === 'ellipse') {
|
|
100
|
+
const l = a.xMin != null ? pixel(xs, a.xMin) - (xs?.type === 'category' && xs.offset ? xs.bandSize / 2 : 0) : area.left, r = a.xMax != null ? pixel(xs, a.xMax) + (xs?.type === 'category' && xs.offset ? xs.bandSize / 2 : 0) : area.right;
|
|
101
|
+
const t = a.yMax != null ? pixel(ys, a.yMax) : area.top, b = a.yMin != null ? pixel(ys, a.yMin) : area.bottom;
|
|
102
|
+
if (![l, r, t, b].every(Number.isFinite)) return null;
|
|
103
|
+
const x = Math.max(area.left, Math.min(l, r)), w = Math.min(area.right, Math.max(l, r)) - x, y = Math.max(area.top, Math.min(t, b)), h = Math.min(area.bottom, Math.max(t, b)) - y;
|
|
104
|
+
const sty = { fill: a.backgroundColor ?? withAlpha('#3d7dd8', 0.1), stroke: (a.borderWidth ?? 0) > 0 ? a.borderColor ?? th.axis : null, width: a.borderWidth ?? 0, dash: a.borderDash };
|
|
105
|
+
if (a.type === 'ellipse') p.path(`M${x},${y + h / 2}a${w / 2},${h / 2} 0 1,0 ${w},0a${w / 2},${h / 2} 0 1,0 ${-w},0Z`, sty);
|
|
106
|
+
else p.rect(x, y, w, h, { ...sty, radius: a.borderRadius ?? 0 });
|
|
107
|
+
const pos = lab?.position ?? 'start';
|
|
108
|
+
say(pos === 'end' ? x + w - 4 : pos === 'center' ? x + w / 2 : x + 4, y + 4, pos === 'end' ? 'right' : pos === 'center' ? 'center' : 'left', 'top');
|
|
109
|
+
box = { l: x, r: x + w, t: y, b: y + h };
|
|
110
|
+
} else if (a.type === 'point' || a.type === 'label' || a.type === 'polygon') {
|
|
111
|
+
const x = a.xValue != null ? pixel(xs, a.xValue) : (area.left + area.right) / 2, y = a.yValue != null ? pixel(ys, a.yValue) : (area.top + area.bottom) / 2;
|
|
112
|
+
if (!Number.isFinite(x) || !Number.isFinite(y)) return null;
|
|
113
|
+
if (a.type === 'label') {
|
|
114
|
+
return tag(p, a.content ?? a.text ?? '', x + (a.xAdjust ?? 0), y + (a.yAdjust ?? 0), { fill: a.color ?? th.ink, bg: a.backgroundColor ?? null, font: fontOf(chart, a.font), padding: a.padding ?? 4, align: a.textAlign ?? 'center', baseline: a.position === 'top' ? 'bottom' : a.position === 'bottom' ? 'top' : 'middle', border: a.borderColor });
|
|
115
|
+
}
|
|
116
|
+
const r = a.radius ?? 5, sides = a.type === 'polygon' ? a.sides ?? 3 : 0;
|
|
117
|
+
if (sides) { const rot = ((a.rotation ?? 0) * Math.PI) / 180; p.path('M' + Array.from({ length: sides }, (_, k) => { const ang = rot + (k * 2 * Math.PI) / sides; return `${(x + Math.sin(ang) * r).toFixed(2)},${(y - Math.cos(ang) * r).toFixed(2)}`; }).join('L') + 'Z', { fill: a.backgroundColor ?? '#3d7dd8', stroke: a.borderColor ?? th.bg, width: a.borderWidth ?? 1 }); }
|
|
118
|
+
else p.circle(x, y, r, { fill: a.backgroundColor ?? '#3d7dd8', stroke: a.borderColor ?? th.bg, width: a.borderWidth ?? 1.5 });
|
|
119
|
+
say(x, y - r - 4, 'center', 'bottom');
|
|
120
|
+
box = { l: x - r, r: x + r, t: y - r, b: y + r };
|
|
121
|
+
}
|
|
122
|
+
return box;
|
|
123
|
+
}
|
|
124
|
+
const annotation = {
|
|
125
|
+
id: 'annotation',
|
|
126
|
+
defaults: { annotations: {}, drawTime: 'afterDatasetsDraw' },
|
|
127
|
+
_draw(chart, o, when) {
|
|
128
|
+
const list = annotationsOf(chart, o).filter((a) => (a.drawTime ?? o.drawTime) === when);
|
|
129
|
+
if (!list.length) return;
|
|
130
|
+
chart.painter.layer(when === 'beforeDatasetsDraw' ? 'fill' : when === 'beforeDraw' ? 'background' : when === 'afterDraw' ? 'over' : 'datasets');
|
|
131
|
+
if (!chart.clip && when === 'beforeDraw') { const a = chart.chartArea; chart.clip = chart.painter.clipRect(a.left, a.top, a.right - a.left, a.bottom - a.top); }
|
|
132
|
+
for (const a of list) { const b = drawAnnotation(chart, a); if (b) (chart._annotationHits ??= []).push({ a, b }); }
|
|
133
|
+
},
|
|
134
|
+
beforeDraw(chart, _a, o) { chart._annotationHits = []; this._draw(chart, o, 'beforeDraw'); },
|
|
135
|
+
beforeDatasetsDraw(chart, _a, o) { this._draw(chart, o, 'beforeDatasetsDraw'); },
|
|
136
|
+
afterDatasetsDraw(chart, _a, o) { this._draw(chart, o, 'afterDatasetsDraw'); },
|
|
137
|
+
afterDraw(chart, _a, o) { this._draw(chart, o, 'afterDraw'); },
|
|
138
|
+
afterEvent(chart, { event }) {
|
|
139
|
+
if (event.type !== 'click' && event.type !== 'mousemove') return;
|
|
140
|
+
for (const { a, b } of chart._annotationHits ?? []) if (event.x >= b.l && event.x <= b.r && event.y >= b.t && event.y <= b.b) { if (event.type === 'click') a.click?.({ chart, element: a }, event); else a.enter?.({ chart, element: a }, event); }
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
// ── data labels (as chartjs-plugin-datalabels, Highcharts's and ApexCharts's dataLabels) ────────
|
|
145
|
+
const OWN_LABELS = new Set(['treemap', 'sunburst', 'funnel', 'pyramid', 'sankey', 'wordcloud', 'gauge', 'solidgauge', 'radialBar', 'item', 'parliament']);
|
|
146
|
+
function anchorOf(e, anchor) {
|
|
147
|
+
if (e.kind === 'bar' && e.base != null) {
|
|
148
|
+
const end = { x: e.x, y: e.y }, start = e.horizontal ? { x: e.base, y: e.y } : { x: e.x, y: e.base };
|
|
149
|
+
return anchor === 'end' ? end : anchor === 'start' ? start : { x: (end.x + start.x) / 2, y: (end.y + start.y) / 2 };
|
|
150
|
+
}
|
|
151
|
+
if (e.kind === 'arc') { const mid = (e.startAngle + e.endAngle) / 2, rr = anchor === 'end' ? e.outerRadius : anchor === 'start' ? e.innerRadius : (e.innerRadius + e.outerRadius) / 2; return { x: e.cx + Math.sin(mid) * rr, y: e.cy - Math.cos(mid) * rr, angle: mid }; }
|
|
152
|
+
if (e.bounds && e.kind !== 'point') { const b = e.bounds; return anchor === 'end' ? { x: (b.l + b.r) / 2, y: b.t } : anchor === 'start' ? { x: (b.l + b.r) / 2, y: b.b } : centerOf(e); }
|
|
153
|
+
return { x: e.x, y: e.y };
|
|
154
|
+
}
|
|
155
|
+
function alignVector(e, align, a) {
|
|
156
|
+
if (typeof align === 'number') { const r = (align * Math.PI) / 180; return [Math.cos(r), Math.sin(r)]; }
|
|
157
|
+
if (align === 'top') return [0, -1]; if (align === 'bottom') return [0, 1]; if (align === 'left') return [-1, 0]; if (align === 'right') return [1, 0];
|
|
158
|
+
if (align === 'center') return [0, 0];
|
|
159
|
+
if (e.kind === 'arc' && a.angle != null) { const s = align === 'start' ? -1 : 1; return [Math.sin(a.angle) * s, -Math.cos(a.angle) * s]; }
|
|
160
|
+
if (e.kind === 'bar' && e.base != null) { const dir = e.horizontal ? Math.sign(e.x - e.base) || 1 : Math.sign(e.y - e.base) || -1, s = align === 'start' ? -1 : 1; return e.horizontal ? [dir * s, 0] : [0, dir * s]; }
|
|
161
|
+
return align === 'start' ? [0, 1] : [0, -1];
|
|
162
|
+
}
|
|
163
|
+
const datalabels = {
|
|
164
|
+
id: 'datalabels',
|
|
165
|
+
defaults: { display: false, anchor: 'center', align: 'center', offset: 4, color: 'auto', font: {}, formatter: null, backgroundColor: null, borderRadius: 3, padding: 2, rotation: 0, opacity: 1, clamp: false },
|
|
166
|
+
afterDatasetsDraw(chart, _a, base) {
|
|
167
|
+
const p = chart.painter, kept = [];
|
|
168
|
+
p.layer('datasets');
|
|
169
|
+
for (const m of chart.getSortedVisibleDatasetMetas()) {
|
|
170
|
+
if (OWN_LABELS.has(m.type)) continue;
|
|
171
|
+
const o = { ...base, ...(m.dataset.datalabels ?? {}) };
|
|
172
|
+
if (!o.display && !m.dataset.datalabels?.display) continue;
|
|
173
|
+
const f = fontOf(chart, { size: 11, weight: '600', ...o.font });
|
|
174
|
+
for (const e of m.drawn ?? m.elements) {
|
|
175
|
+
if (e.skip) continue;
|
|
176
|
+
const ctx = { chart, dataset: m.dataset, datasetIndex: m.index, dataIndex: e.index, active: chart.isActive(m.index, e.index), percent: m.shares?.[e.index] ?? (e.share != null ? e.share * 100 : undefined), raw: e.raw, parsed: e.parsed };
|
|
177
|
+
const show = resolveFn(o.display, ctx);
|
|
178
|
+
if (show === false) continue;
|
|
179
|
+
const value = e.parsed?.value;
|
|
180
|
+
let text = typeof o.formatter === 'function' ? o.formatter(value, ctx) : m.controller.text ? m.controller.text(chart, m, e, (v) => fmt(chart, v)) : m.shares ? `${Math.round(m.shares[e.index])}%` : e.kind === 'arc' && e.share != null && o.percent ? `${Math.round(e.share * 100)}%` : Number.isFinite(value) ? fmt(chart, value) : '';
|
|
181
|
+
if (text == null || text === '' || (Array.isArray(text) && !text.length)) continue;
|
|
182
|
+
const anchor = resolveFn(o.anchor, ctx), align = resolveFn(o.align, ctx), a = anchorOf(e, anchor), [vx, vy] = alignVector(e, align, a), off = align === 'center' ? 0 : resolveFn(o.offset, ctx) ?? 4;
|
|
183
|
+
const lines = [].concat(text).map(String), w = Math.max(...lines.map((l) => p.measure(l, f))) + o.padding * 2, h = lines.length * lineOf(f) + o.padding * 2;
|
|
184
|
+
let x = a.x + vx * (off + w / 2), y = a.y + vy * (off + h / 2);
|
|
185
|
+
if (o.clamp) { const ar = chart.chartArea; x = Math.max(ar.left + w / 2, Math.min(ar.right - w / 2, x)); y = Math.max(ar.top + h / 2, Math.min(ar.bottom - h / 2, y)); }
|
|
186
|
+
const box = { l: x - w / 2, r: x + w / 2, t: y - h / 2, b: y + h / 2 };
|
|
187
|
+
if (show === 'auto' && kept.some((k) => box.l < k.r && box.r > k.l && box.t < k.b && box.b > k.t)) continue;
|
|
188
|
+
kept.push(box);
|
|
189
|
+
const inside = align === 'center' && e.kind !== 'point', fillUnder = e.kind === 'arc' ? e.options?.backgroundColor : e.kind === 'bar' ? e.options?.backgroundColor : e.color;
|
|
190
|
+
const colour = resolveFn(o.color, ctx);
|
|
191
|
+
const fill = colour && colour !== 'auto' ? colour : o.backgroundColor ? contrastOn(resolveFn(o.backgroundColor, ctx)) : inside && fillUnder ? contrastOn(fillUnder) : themeOf(chart).ink;
|
|
192
|
+
tag(p, lines, x, y, { fill, bg: resolveFn(o.backgroundColor, ctx), font: f, padding: o.padding, radius: o.borderRadius, opacity: o.opacity });
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
// ── zoom, pan and the measuring ruler ─────────────────────────────────────────────────────────
|
|
199
|
+
function limitOf(chart, ax) { const l = chart.resolved.plugins?.zoom?.limits ?? {}; return l[ax.id] ?? l[ax.axis] ?? {}; }
|
|
200
|
+
function clampView(chart, ax, min, max) {
|
|
201
|
+
const lim = limitOf(chart, ax), lo = lim.min === 'original' ? ax.dataMin : lim.min, hi = lim.max === 'original' ? ax.dataMax : lim.max;
|
|
202
|
+
let span = max - min;
|
|
203
|
+
if (lim.minRange && span < lim.minRange) { const c = (min + max) / 2; min = c - lim.minRange / 2; max = c + lim.minRange / 2; span = lim.minRange; }
|
|
204
|
+
if (lo != null && min < lo) { min = lo; max = Math.max(max, lo + span); }
|
|
205
|
+
if (hi != null && max > hi) { max = hi; min = Math.min(min, hi - span); if (lo != null) min = Math.max(lo, min); }
|
|
206
|
+
if (ax.type === 'category') { min = Math.max(0, Math.round(min)); max = Math.min(ax.labels.length - 1, Math.round(max)); if (max <= min) max = Math.min(ax.labels.length - 1, min + 1); }
|
|
207
|
+
return [min, max];
|
|
208
|
+
}
|
|
209
|
+
function applyView(chart, views, how = 'zoom') {
|
|
210
|
+
chart._view ??= {};
|
|
211
|
+
for (const [id, [min, max]] of views) chart._view[id] = { min, max };
|
|
212
|
+
chart.update('none');
|
|
213
|
+
chart.notify('viewChanged', { how });
|
|
214
|
+
const o = chart.resolved.plugins?.zoom ?? {};
|
|
215
|
+
(how === 'pan' ? o.pan?.onPan : o.zoom?.onZoom)?.({ chart });
|
|
216
|
+
// charts in the same group follow along the x axis
|
|
217
|
+
const g = groupOf(chart);
|
|
218
|
+
if (g && o.sync !== false && !chart._following) for (const c of others(chart, g)) {
|
|
219
|
+
const x = views.find(([id]) => chart.scales[id]?.isHorizontal());
|
|
220
|
+
if (!x || !c.scales.x) continue;
|
|
221
|
+
c._following = true; try { c._view = { ...(c._view ?? {}), x: { min: x[1][0], max: x[1][1] } }; c.update('none'); c.notify('viewChanged', { how }); } finally { c._following = false; }
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
/** chart.zoom(): a number (> 1 nearer) for the axes of `mode`, { x: 1.5, y: 1 }, or { x: [min, max] }; about `focal` (pixels) or the middle. */
|
|
225
|
+
export function zoomBy(chart, amount, mode, focal) {
|
|
226
|
+
if (geoOnly(chart)) { const k = typeof amount === 'number' ? amount : Number(amount?.k ?? amount?.x ?? 1); if (k > 0) { zoomMap(chart, k, focal); chart.notify('viewChanged', { how: 'zoom' }); } return; }
|
|
227
|
+
const o = chart.resolved?.plugins?.zoom ?? {};
|
|
228
|
+
mode = mode ?? o.zoom?.mode ?? 'xy';
|
|
229
|
+
const views = [];
|
|
230
|
+
for (const ax of scalesFor(chart, mode)) {
|
|
231
|
+
let want = typeof amount === 'number' ? amount : amount?.[ax.id] ?? amount?.[ax.axis];
|
|
232
|
+
if (want == null) continue;
|
|
233
|
+
if (Array.isArray(want)) { views.push([ax.id, clampView(chart, ax, valueOn(ax, want[0]), valueOn(ax, want[1]))]); continue; }
|
|
234
|
+
want = Number(want); if (!(want > 0)) continue;
|
|
235
|
+
const h = ax.isHorizontal(), fp = focal ? (h ? focal.x : focal.y) : (h ? (ax.left + ax.right) / 2 : (ax.top + ax.bottom) / 2);
|
|
236
|
+
const c = ax.getValueForPixel(fp), min = ax.min, max = ax.max;
|
|
237
|
+
views.push([ax.id, clampView(chart, ax, c - (c - min) / want, c + (max - c) / want)]);
|
|
238
|
+
}
|
|
239
|
+
if (views.length) applyView(chart, views, 'zoom');
|
|
240
|
+
}
|
|
241
|
+
/** chart.pan(): move the view by pixels, { x: -40, y: 0 }. */
|
|
242
|
+
export function panBy(chart, delta, mode) {
|
|
243
|
+
if (geoOnly(chart)) { const d = typeof delta === 'number' ? { x: delta, y: delta } : delta ?? {}; panMap(chart, d.x ?? 0, d.y ?? 0); chart.notify('viewChanged', { how: 'pan' }); return; }
|
|
244
|
+
const o = chart.resolved?.plugins?.zoom ?? {};
|
|
245
|
+
mode = mode ?? o.pan?.mode ?? 'xy';
|
|
246
|
+
const d = typeof delta === 'number' ? { x: delta, y: delta } : delta ?? {}, views = [];
|
|
247
|
+
for (const ax of scalesFor(chart, mode)) {
|
|
248
|
+
const px = ax.isHorizontal() ? d.x ?? 0 : d.y ?? 0;
|
|
249
|
+
if (!px) continue;
|
|
250
|
+
const p0 = ax.isHorizontal() ? ax.left : ax.bottom;
|
|
251
|
+
let dv = ax.getValueForPixel(p0) - ax.getValueForPixel(p0 + px);
|
|
252
|
+
if (ax.type === 'category') { chart._panRest = (chart._panRest ?? 0) + (dv = (px / -(ax.bandSize || 1)) * (ax.isHorizontal() ? 1 : -1)); dv = Math.trunc(chart._panRest); chart._panRest -= dv; if (!dv) continue; }
|
|
253
|
+
const span = ax.max - ax.min, [a] = clampView(chart, ax, ax.min + dv, ax.max + dv);
|
|
254
|
+
views.push([ax.id, ax.type === 'category' ? clampView(chart, ax, a, a + span) : [a, a + span]]);
|
|
255
|
+
}
|
|
256
|
+
if (views.length) applyView(chart, views, 'pan');
|
|
257
|
+
}
|
|
258
|
+
const modOk = (e, key) => !key || !!e[key + 'Key'];
|
|
259
|
+
const zoom = {
|
|
260
|
+
id: 'zoom',
|
|
261
|
+
defaults: { zoom: { wheel: { enabled: false, speed: 0.1, modifierKey: null }, drag: { enabled: false, borderWidth: 1, threshold: 4, modifierKey: null }, pinch: { enabled: false }, mode: 'x' }, pan: { enabled: false, mode: 'x', modifierKey: null, threshold: 4 }, limits: {}, sync: true },
|
|
262
|
+
afterInit(chart) {
|
|
263
|
+
if (!isDom(chart)) return;
|
|
264
|
+
const s = chart.surface, o = () => chart.resolved?.plugins?.zoom ?? {}, me = () => chart.resolved?.plugins?.measure ?? {};
|
|
265
|
+
const touches = new Map();
|
|
266
|
+
let drag = null;
|
|
267
|
+
const pos = (e) => chart._pos(e);
|
|
268
|
+
s.addEventListener('wheel', (e) => {
|
|
269
|
+
const w = o().zoom?.wheel; if (!w?.enabled || !modOk(e, w.modifierKey)) return;
|
|
270
|
+
const p = pos(e); if (!chart.isPointInArea(p)) return;
|
|
271
|
+
e.preventDefault();
|
|
272
|
+
zoomBy(chart, e.deltaY < 0 ? 1 + (w.speed ?? 0.1) : 1 / (1 + (w.speed ?? 0.1)), o().zoom?.mode, p);
|
|
273
|
+
o().zoom?.onZoomComplete?.({ chart });
|
|
274
|
+
}, { passive: false });
|
|
275
|
+
s.addEventListener('pointerdown', (e) => {
|
|
276
|
+
if (e.button != null && e.button !== 0) return;
|
|
277
|
+
const p = pos(e); if (!chart.isPointInArea(p)) return;
|
|
278
|
+
touches.set(e.pointerId, p);
|
|
279
|
+
if (touches.size === 2 && o().zoom?.pinch?.enabled) { const [a, b] = [...touches.values()]; drag = { kind: 'pinch', dist: Math.hypot(a.x - b.x, a.y - b.y) }; return; }
|
|
280
|
+
const pan = o().pan ?? {}, dz = o().zoom?.drag ?? {}, m = me();
|
|
281
|
+
if (m.enabled && modOk(e, m.modifierKey ?? 'shift')) drag = { kind: 'measure', x0: p.x, y0: p.y, x1: p.x, y1: p.y };
|
|
282
|
+
else if (pan.enabled && modOk(e, pan.modifierKey) && (chart._toolMode === 'pan' || !dz.enabled || pan.modifierKey)) drag = { kind: 'pan', last: p, moved: 0 };
|
|
283
|
+
else if (dz.enabled && modOk(e, dz.modifierKey) && chart._toolMode !== 'pan') drag = { kind: 'zoom', x0: p.x, y0: p.y, x1: p.x, y1: p.y };
|
|
284
|
+
if (drag) s.setPointerCapture?.(e.pointerId);
|
|
285
|
+
});
|
|
286
|
+
s.addEventListener('pointermove', (e) => {
|
|
287
|
+
if (!drag) return;
|
|
288
|
+
const p = pos(e);
|
|
289
|
+
if (touches.has(e.pointerId)) touches.set(e.pointerId, p);
|
|
290
|
+
if (drag.kind === 'pinch' && touches.size === 2) { const [a, b] = [...touches.values()], d = Math.hypot(a.x - b.x, a.y - b.y); if (drag.dist && Math.abs(d / drag.dist - 1) > 0.04) { zoomBy(chart, d / drag.dist, o().zoom?.mode, { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }); drag.dist = d; } return; }
|
|
291
|
+
if (drag.kind === 'pan') { const dx = p.x - drag.last.x, dy = p.y - drag.last.y; drag.moved += Math.abs(dx) + Math.abs(dy); if (drag.moved < (o().pan?.threshold ?? 4)) return; panBy(chart, { x: dx, y: dy }, o().pan?.mode); drag.last = p; return; }
|
|
292
|
+
drag.x1 = p.x; drag.y1 = p.y; chart._drag = drag; chart.render();
|
|
293
|
+
});
|
|
294
|
+
const end = (e) => {
|
|
295
|
+
touches.delete(e.pointerId);
|
|
296
|
+
if (!drag) return;
|
|
297
|
+
const d = drag; drag = null; chart._drag = null;
|
|
298
|
+
if (d.kind === 'zoom') {
|
|
299
|
+
const mode = o().zoom?.mode ?? 'x', th = o().zoom?.drag?.threshold ?? 4, views = [];
|
|
300
|
+
if (Math.abs(d.x1 - d.x0) >= th && mode.includes('x')) for (const ax of horizontals(chart)) views.push([ax.id, clampView(chart, ax, ...[ax.getValueForPixel(Math.min(d.x0, d.x1)), ax.getValueForPixel(Math.max(d.x0, d.x1))].sort((a, b) => a - b))]);
|
|
301
|
+
if (Math.abs(d.y1 - d.y0) >= th && mode.includes('y')) for (const ax of verticals(chart)) views.push([ax.id, clampView(chart, ax, ...[ax.getValueForPixel(Math.min(d.y0, d.y1)), ax.getValueForPixel(Math.max(d.y0, d.y1))].sort((a, b) => a - b))]);
|
|
302
|
+
if (views.length) { applyView(chart, views, 'zoom'); o().zoom?.onZoomComplete?.({ chart }); } else chart.render();
|
|
303
|
+
chart._justDragged = views.length > 0;
|
|
304
|
+
} else if (d.kind === 'pan') { if (d.moved >= (o().pan?.threshold ?? 4)) { o().pan?.onPanComplete?.({ chart }); chart._justDragged = true; } }
|
|
305
|
+
else if (d.kind === 'measure') { chart._ruler = null; chart.render(); }
|
|
306
|
+
};
|
|
307
|
+
s.addEventListener('pointerup', end); s.addEventListener('pointercancel', end);
|
|
308
|
+
},
|
|
309
|
+
afterDraw(chart) {
|
|
310
|
+
const d = chart._drag; if (!d) return;
|
|
311
|
+
const p = chart.painter, th = themeOf(chart), a = chart.chartArea, mode = chart.resolved.plugins?.zoom?.zoom?.mode ?? 'x';
|
|
312
|
+
p.layer('over');
|
|
313
|
+
if (d.kind === 'zoom') {
|
|
314
|
+
const x0 = mode.includes('x') ? Math.min(d.x0, d.x1) : a.left, x1 = mode.includes('x') ? Math.max(d.x0, d.x1) : a.right, y0 = mode.includes('y') ? Math.min(d.y0, d.y1) : a.top, y1 = mode.includes('y') ? Math.max(d.y0, d.y1) : a.bottom;
|
|
315
|
+
const dz = chart.resolved.plugins.zoom.zoom.drag;
|
|
316
|
+
p.rect(x0, y0, x1 - x0, y1 - y0, { fill: dz.backgroundColor ?? th.mask, stroke: dz.borderColor ?? th.control?.active, width: dz.borderWidth ?? 1 });
|
|
317
|
+
}
|
|
318
|
+
if (d.kind === 'measure') drawRuler(chart, d);
|
|
319
|
+
},
|
|
320
|
+
};
|
|
321
|
+
function drawRuler(chart, d) {
|
|
322
|
+
const p = chart.painter, th = themeOf(chart), xs = horizontals(chart)[0], ys = verticals(chart)[0], f = fontOf(chart, { size: 11 });
|
|
323
|
+
const c = chart.resolved.plugins?.measure?.color ?? th.control?.active ?? '#3d7dd8';
|
|
324
|
+
p.line(d.x0, d.y0, d.x1, d.y1, { stroke: c, width: 1.5, dash: [5, 3] });
|
|
325
|
+
p.circle(d.x0, d.y0, 3, { fill: c }); p.circle(d.x1, d.y1, 3, { fill: c });
|
|
326
|
+
const v0 = ys ? ys.getValueForPixel(d.y0) : NaN, v1 = ys ? ys.getValueForPixel(d.y1) : NaN, u0 = xs ? xs.getValueForPixel(d.x0) : NaN, u1 = xs ? xs.getValueForPixel(d.x1) : NaN;
|
|
327
|
+
const dy = v1 - v0, pct = v0 ? (dy / Math.abs(v0)) * 100 : NaN, lines = [];
|
|
328
|
+
if (xs) lines.push(xs.type?.startsWith('time') ? duration(Math.abs(u1 - u0)) : xs.type === 'category' ? `${Math.abs(Math.round(u1) - Math.round(u0))} steps` : `Δx ${fmt(chart, u1 - u0)}`);
|
|
329
|
+
if (ys) lines.push(`${dy >= 0 ? '+' : ''}${fmt(chart, +dy.toPrecision(4))}${Number.isFinite(pct) ? ` (${pct >= 0 ? '+' : ''}${pct.toFixed(1)}%)` : ''}`);
|
|
330
|
+
chart._ruler = { dx: u1 - u0, dy, percent: pct, text: lines };
|
|
331
|
+
tag(p, lines, d.x1 + 8, d.y1 - 8, { fill: '#fff', bg: c, font: f, padding: 4, align: 'left', baseline: 'bottom' });
|
|
332
|
+
}
|
|
333
|
+
const duration = (ms) => { const d = ms / 864e5; return d >= 365 ? `${(d / 365.25).toFixed(1)} years` : d >= 60 ? `${(d / 30.44).toFixed(1)} months` : d >= 2 ? `${Math.round(d)} days` : ms >= 36e5 ? `${(ms / 36e5).toFixed(1)} hours` : `${Math.round(ms / 6e4)} minutes`; };
|
|
334
|
+
const measure = { id: 'measure', defaults: { enabled: false, modifierKey: 'shift', color: null } };
|
|
335
|
+
/** The ruler between two points (pixels), as the measure plugin would draw it: { dx, dy, percent, text }. */
|
|
336
|
+
export function measureBetween(chart, x0, y0, x1, y1) { const keep = chart.painter; chart.painter = { line() {}, circle() {}, rect() {}, text() {}, measure: keep.measure }; try { drawRuler(chart, { x0, y0, x1, y1 }); } finally { chart.painter = keep; } return chart._ruler; }
|
|
337
|
+
|
|
338
|
+
// ── a crosshair, and charts that follow one another ────────────────────────────────────────────
|
|
339
|
+
const groupOf = (chart) => chart.resolved?.group ?? chart.resolved?.plugins?.crosshair?.group ?? null;
|
|
340
|
+
const others = (chart, g) => Object.values(chart.constructor.instances ?? {}).filter((c) => c !== chart && !c._destroyed && groupOf(c) === g);
|
|
341
|
+
const crosshair = {
|
|
342
|
+
id: 'crosshair',
|
|
343
|
+
defaults: { enabled: false, mode: 'x', snap: true, color: null, width: 1, dash: [4, 3], labels: true, group: null },
|
|
344
|
+
afterEvent(chart, { event }, o) {
|
|
345
|
+
const g = groupOf(chart);
|
|
346
|
+
if (!o.enabled && !g) return;
|
|
347
|
+
if (event.type !== 'mousemove' && event.type !== 'mouseout' && event.type !== 'touchmove') return;
|
|
348
|
+
const inside = event.type !== 'mouseout' && chart.isPointInArea(event);
|
|
349
|
+
const xs = horizontals(chart)[0];
|
|
350
|
+
chart._cross = inside ? { x: event.x, y: event.y } : null;
|
|
351
|
+
if (o.enabled) chart.render();
|
|
352
|
+
if (!g || chart._following) return;
|
|
353
|
+
const value = inside && xs ? xs.getValueForPixel(event.x) : null;
|
|
354
|
+
for (const c of others(chart, g)) {
|
|
355
|
+
c._following = true;
|
|
356
|
+
try {
|
|
357
|
+
const cx = c.scales.x;
|
|
358
|
+
if (value == null || !cx) { c._cross = null; c.setActiveElements([]); c.tooltip?.setActiveElements([]); continue; }
|
|
359
|
+
const px = cx.getPixelForValue(value);
|
|
360
|
+
c._cross = { x: px, y: null };
|
|
361
|
+
const els = c.getElementsAtEventForMode({ x: px, y: (c.chartArea.top + c.chartArea.bottom) / 2 }, 'index', { intersect: false, axis: 'x' });
|
|
362
|
+
c.setActiveElements(els);
|
|
363
|
+
c.tooltip?.setActiveElements(els);
|
|
364
|
+
if (!els.length) c.render();
|
|
365
|
+
} finally { c._following = false; }
|
|
366
|
+
}
|
|
367
|
+
},
|
|
368
|
+
afterDraw(chart, _a, o) {
|
|
369
|
+
const at = chart._cross;
|
|
370
|
+
if (!o.enabled || !at) return;
|
|
371
|
+
const p = chart.painter, a = chart.chartArea, th = themeOf(chart), st = { stroke: o.color ?? th.axis, width: o.width, dash: o.dash };
|
|
372
|
+
let x = at.x, y = at.y;
|
|
373
|
+
if (o.snap) { const act = chart.getActiveElements()[0]?.element; if (act) { const t = tipPoint(act); x = t.x; if (y != null) y = act.kind === 'point' ? t.y : y; } }
|
|
374
|
+
p.layer('over');
|
|
375
|
+
if (o.mode.includes('x') && Number.isFinite(x) && x >= a.left && x <= a.right) p.line(x, a.top, x, a.bottom, st);
|
|
376
|
+
if (o.mode.includes('y') && Number.isFinite(y) && y != null && y >= a.top && y <= a.bottom) p.line(a.left, y, a.right, y, st);
|
|
377
|
+
if (!o.labels) return;
|
|
378
|
+
const f = fontOf(chart, { size: 11 }), bg = th.tooltip?.backgroundColor ?? 'rgba(20,32,43,0.9)', fg = th.tooltip?.color ?? '#fff';
|
|
379
|
+
const xs = horizontals(chart)[0], ys = verticals(chart)[0];
|
|
380
|
+
if (o.mode.includes('x') && xs && Number.isFinite(x)) tag(p, valueText(xs, xs.getValueForPixel(x)), x, a.bottom + 2, { fill: fg, bg, font: f, baseline: 'top' });
|
|
381
|
+
if (o.mode.includes('y') && ys && Number.isFinite(y) && y != null) tag(p, valueText(ys, ys.getValueForPixel(y)), a.left - 2, y, { fill: fg, bg, font: f, align: 'right' });
|
|
382
|
+
},
|
|
383
|
+
};
|
|
384
|
+
|
|
385
|
+
// ── a window on the whole range: the navigator (in the chart) and the brush (another chart) ──────
|
|
386
|
+
function windowControl(chart, area, axisOf, target) {
|
|
387
|
+
const H = 6;
|
|
388
|
+
return {
|
|
389
|
+
hitAt(x, y) {
|
|
390
|
+
const ar = area(); if (!ar || x < ar.left - H || x > ar.right + H || y < ar.top || y > ar.bottom) return null;
|
|
391
|
+
const ax = axisOf(), t = target(), v = t.getView('x'); if (!ax || !v) return null;
|
|
392
|
+
const w0 = ax.getPixelForValue(v.min), w1 = ax.getPixelForValue(v.max);
|
|
393
|
+
if (Math.abs(x - w0) <= H) return { part: 'min', w0, w1 };
|
|
394
|
+
if (Math.abs(x - w1) <= H) return { part: 'max', w0, w1 };
|
|
395
|
+
if (x > w0 && x < w1) return { part: 'move', w0, w1, grab: x };
|
|
396
|
+
return { part: 'jump', w0, w1 };
|
|
397
|
+
},
|
|
398
|
+
drag(hit, x) {
|
|
399
|
+
const ax = axisOf(), t = target(), tx = t.scales.x; if (!ax || !tx) return;
|
|
400
|
+
const ar = area(), val = (px) => ax.getValueForPixel(Math.max(ar.left, Math.min(ar.right, px)));
|
|
401
|
+
let a = hit.w0, b = hit.w1;
|
|
402
|
+
if (hit.part === 'min') a = Math.min(x, b - 4); else if (hit.part === 'max') b = Math.max(x, a + 4);
|
|
403
|
+
else { const w = b - a, c = hit.part === 'jump' ? x : x - (hit.grab - (a + b) / 2); a = Math.max(ar.left, Math.min(ar.right - w, c - w / 2)); b = a + w; }
|
|
404
|
+
let lo = val(a), hi = val(b);
|
|
405
|
+
if (tx.type === 'category') { lo = Math.round(lo); hi = Math.round(hi); if (hi <= lo) hi = lo + 1; }
|
|
406
|
+
const full = Math.abs(a - ar.left) < 1 && Math.abs(b - ar.right) < 1;
|
|
407
|
+
t._view = { ...(t._view ?? {}) }; if (full) delete t._view.x; else t._view.x = { min: lo, max: hi };
|
|
408
|
+
t.update('none'); t.notify('viewChanged', { how: 'navigator' });
|
|
409
|
+
if (t !== chart) chart.render();
|
|
410
|
+
},
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
function bindWindow(chart, key, control) {
|
|
414
|
+
if (!isDom(chart) || chart['_' + key + 'Bound']) return;
|
|
415
|
+
chart['_' + key + 'Bound'] = true;
|
|
416
|
+
let hit = null;
|
|
417
|
+
chart.surface.addEventListener('pointerdown', (e) => {
|
|
418
|
+
const p = chart._pos(e), h = control().hitAt(p.x, p.y);
|
|
419
|
+
if (!h) return;
|
|
420
|
+
hit = h; e.stopPropagation(); chart.surface.setPointerCapture?.(e.pointerId);
|
|
421
|
+
if (h.part === 'jump') { control().drag(h, p.x); hit = { ...control().hitAt(p.x, p.y) ?? h, part: 'move', grab: p.x }; }
|
|
422
|
+
});
|
|
423
|
+
chart.surface.addEventListener('pointermove', (e) => { if (!hit) return; control().drag(hit, chart._pos(e).x); });
|
|
424
|
+
const end = () => { if (hit) chart._justDragged = true; hit = null; };
|
|
425
|
+
chart.surface.addEventListener('pointerup', end); chart.surface.addEventListener('pointercancel', end);
|
|
426
|
+
}
|
|
427
|
+
function drawWindow(p, chart, ar, w0, w1, th) {
|
|
428
|
+
const mask = th.mask ?? 'rgba(61,125,216,0.12)', line = th.axis ?? 'rgba(0,0,0,0.25)';
|
|
429
|
+
p.rect(ar.left, ar.top, Math.max(0, w0 - ar.left), ar.bottom - ar.top, { fill: withAlpha(solidOf(th.bg) ?? '#ffffff', 0.55) });
|
|
430
|
+
p.rect(w1, ar.top, Math.max(0, ar.right - w1), ar.bottom - ar.top, { fill: withAlpha(solidOf(th.bg) ?? '#ffffff', 0.55) });
|
|
431
|
+
p.rect(w0, ar.top, Math.max(0, w1 - w0), ar.bottom - ar.top, { fill: mask, stroke: line, width: 1 });
|
|
432
|
+
const hh = Math.min(16, (ar.bottom - ar.top) * 0.6), hy = (ar.top + ar.bottom) / 2 - hh / 2;
|
|
433
|
+
for (const x of [w0, w1]) { p.rect(x - 3.5, hy, 7, hh, { fill: th.control?.background ?? '#fff', stroke: line, width: 1, radius: 2 }); p.line(x - 1, hy + 4, x - 1, hy + hh - 4, { stroke: line, width: 1 }); p.line(x + 1, hy + 4, x + 1, hy + hh - 4, { stroke: line, width: 1 }); }
|
|
434
|
+
}
|
|
435
|
+
const navigator = {
|
|
436
|
+
id: 'navigator',
|
|
437
|
+
defaults: { enabled: false, height: 44, margin: 10, datasetIndex: null },
|
|
438
|
+
beforeLayout(chart, _a, o) {
|
|
439
|
+
if (!o.enabled || !chart.scales.x) return;
|
|
440
|
+
chart.addBox({ id: 'navigator', weight: 10, position: 'bottom', size: () => o.height + o.margin, draw(p, r) { chart._navRect = { left: chart.chartArea.left, right: chart.chartArea.right, top: r.top + o.margin, bottom: r.bottom }; drawNavigator(chart, p, o); } });
|
|
441
|
+
bindWindow(chart, 'nav', () => windowControl(chart, () => chart._navRect, () => navAxis(chart), () => chart));
|
|
442
|
+
},
|
|
443
|
+
};
|
|
444
|
+
// the navigator's own axis: the whole range of the data, along the chart's width
|
|
445
|
+
function navAxis(chart) {
|
|
446
|
+
const ax = chart.scales.x, r = chart._navRect; if (!ax || !r) return null;
|
|
447
|
+
const lo = ax.type === 'category' ? 0 : ax.dataMin, hi = ax.type === 'category' ? Math.max(1, ax.labels.length - 1) : ax.dataMax, span = (hi - lo) || 1;
|
|
448
|
+
return { getPixelForValue: (v) => r.left + ((valueOn(ax, v) - lo) / span) * (r.right - r.left), getValueForPixel: (px) => lo + ((px - r.left) / ((r.right - r.left) || 1)) * span };
|
|
449
|
+
}
|
|
450
|
+
function drawNavigator(chart, p, o) {
|
|
451
|
+
const r = chart._navRect, th = themeOf(chart), ax = navAxis(chart);
|
|
452
|
+
if (!ax) return;
|
|
453
|
+
p.rect(r.left, r.top, r.right - r.left, r.bottom - r.top, { fill: 'none', stroke: th.grid, width: 1 });
|
|
454
|
+
const m = o.datasetIndex != null ? chart.metas[o.datasetIndex] : chart.metas.find((q) => q.iAxisID === 'x' && !q.controller.derived);
|
|
455
|
+
const pts = (m?.ungrouped ?? m?.parsed ?? []).map((q) => ({ i: q.index, v: Number.isFinite(q.close) ? q.close : q.value })).filter((q) => Number.isFinite(q.i) && Number.isFinite(q.v));
|
|
456
|
+
if (pts.length) {
|
|
457
|
+
const lo = Math.min(...pts.map((q) => q.v)), hi = Math.max(...pts.map((q) => q.v)), Y = (v) => r.bottom - 3 - ((v - lo) / ((hi - lo) || 1)) * (r.bottom - r.top - 6);
|
|
458
|
+
const step = Math.max(1, Math.floor(pts.length / Math.max(50, r.right - r.left)));
|
|
459
|
+
const line = pts.filter((_, k) => k % step === 0).map((q, k) => `${k ? 'L' : 'M'}${ax.getPixelForValue(q.i).toFixed(1)},${Y(q.v).toFixed(1)}`).join('');
|
|
460
|
+
const colour = m.controller.element === 'candle' ? chart.resolved.plugins?.colors?.palette?.[0] ?? '#3d7dd8' : m.type === 'bar' ? solidOf(chart.fillOf(m, 0)) : chart.lineOptions(m).borderColor;
|
|
461
|
+
p.path(line + `L${ax.getPixelForValue(pts.at(-1).i).toFixed(1)},${r.bottom}L${ax.getPixelForValue(pts[0].i).toFixed(1)},${r.bottom}Z`, { fill: withAlpha(solidOf(colour), 0.15) });
|
|
462
|
+
p.path(line, { stroke: colour, width: 1 });
|
|
463
|
+
}
|
|
464
|
+
const v = chart.getView('x');
|
|
465
|
+
drawWindow(p, chart, r, ax.getPixelForValue(v.min), ax.getPixelForValue(v.max), th);
|
|
466
|
+
}
|
|
467
|
+
const brush = {
|
|
468
|
+
id: 'brush',
|
|
469
|
+
defaults: { enabled: false, target: null },
|
|
470
|
+
_target(chart, o) { const t = o.target; if (!t) return null; if (typeof t === 'object' && typeof t.setView === 'function') return t; const C = chart.constructor; return Object.values(C.instances ?? {}).find((c) => c !== chart && (c.resolved?.id === t || c.config?.options?.id === t)) ?? C.getChart?.(t) ?? null; },
|
|
471
|
+
afterInit(chart) { bindWindow(chart, 'brush', () => { const o = chart.resolved?.plugins?.brush ?? {}; const t = brush._target(chart, o); return windowControl(chart, () => (o.enabled && t ? chart.chartArea : null), () => chart.scales.x, () => t); }); },
|
|
472
|
+
afterDraw(chart, _a, o) {
|
|
473
|
+
if (!o.enabled) return;
|
|
474
|
+
const t = this._target(chart, o), ax = chart.scales.x; if (!t || !ax || !t.scales.x) return;
|
|
475
|
+
if (o.selection && !chart._brushStarted) { chart._brushStarted = true; t._view = { ...(t._view ?? {}), x: { min: valueOn(t.scales.x, o.selection.min), max: valueOn(t.scales.x, o.selection.max) } }; t.update('none'); }
|
|
476
|
+
const v = t.getView('x'), p = chart.painter; p.layer('over');
|
|
477
|
+
drawWindow(p, chart, chart.chartArea, Math.max(chart.chartArea.left, ax.getPixelForValue(v.min)), Math.min(chart.chartArea.right, ax.getPixelForValue(v.max)), themeOf(chart));
|
|
478
|
+
},
|
|
479
|
+
viewChanged(chart) { for (const c of Object.values(chart.constructor.instances ?? {})) if (c !== chart && c.resolved?.plugins?.brush?.enabled && brush._target(c, c.resolved.plugins.brush) === chart) c.render(); },
|
|
480
|
+
};
|
|
481
|
+
|
|
482
|
+
// ── range selector buttons (1m, 3m, 6m, YTD, 1y, All) ─────────────────────────────────────────
|
|
483
|
+
const UNIT_MS = { millisecond: 1, second: 1e3, minute: 6e4, hour: 36e5, day: 864e5, week: 6048e5 };
|
|
484
|
+
/** The x range a range-selector button stands for, ending at the end of the data. */
|
|
485
|
+
export function rangeOf(chart, btn) {
|
|
486
|
+
const ax = chart.scales.x; if (!ax) return null;
|
|
487
|
+
const end = ax.dataMax, count = btn.count ?? 1;
|
|
488
|
+
if (btn.type === 'all') return null;
|
|
489
|
+
if (!ax.type?.startsWith('time')) return [Math.max(ax.dataMin, end - count * (btn.size ?? 1)), end];
|
|
490
|
+
const d = new Date(end);
|
|
491
|
+
let start;
|
|
492
|
+
if (btn.type === 'ytd') start = Date.UTC(d.getUTCFullYear(), 0, 1);
|
|
493
|
+
else if (btn.type === 'month') start = Date.UTC(d.getUTCFullYear(), d.getUTCMonth() - count, d.getUTCDate(), d.getUTCHours());
|
|
494
|
+
else if (btn.type === 'year') start = Date.UTC(d.getUTCFullYear() - count, d.getUTCMonth(), d.getUTCDate(), d.getUTCHours());
|
|
495
|
+
else start = end - count * (UNIT_MS[btn.type] ?? 864e5);
|
|
496
|
+
return [Math.max(ax.dataMin, start), end];
|
|
497
|
+
}
|
|
498
|
+
const rangeSelector = {
|
|
499
|
+
id: 'rangeSelector',
|
|
500
|
+
defaults: { enabled: false, buttons: [{ type: 'month', count: 1, text: '1m' }, { type: 'month', count: 3, text: '3m' }, { type: 'month', count: 6, text: '6m' }, { type: 'ytd', text: 'YTD' }, { type: 'year', count: 1, text: '1y' }, { type: 'all', text: 'All' }], selected: null, position: 'top', align: 'left' },
|
|
501
|
+
select(chart, k) {
|
|
502
|
+
const o = chart.resolved.plugins.rangeSelector, btn = o.buttons[k]; if (!btn) return;
|
|
503
|
+
chart._rangeSelected = k;
|
|
504
|
+
const r = rangeOf(chart, btn);
|
|
505
|
+
chart._view = { ...(chart._view ?? {}) };
|
|
506
|
+
if (r) chart._view.x = { min: r[0], max: r[1] }; else delete chart._view.x;
|
|
507
|
+
chart.update('none'); chart.notify('viewChanged', { how: 'range' });
|
|
508
|
+
},
|
|
509
|
+
afterInit(chart) { chart.selectRange = (k) => rangeSelector.select(chart, typeof k === 'number' ? k : (chart.resolved.plugins.rangeSelector.buttons ?? []).findIndex((b) => b.text === k)); },
|
|
510
|
+
afterUpdate(chart, _a, o) { if (o.enabled && o.selected != null && chart._rangeSelected == null) { chart._rangeSelected = o.selected; queueMicrotask?.(() => rangeSelector.select(chart, o.selected)); } },
|
|
511
|
+
beforeLayout(chart, _a, o) {
|
|
512
|
+
if (!o.enabled || !chart.scales.x) return;
|
|
513
|
+
const f = fontOf(chart, { size: 11 }), pad = 7, h = lineOf(f) + 10;
|
|
514
|
+
let hits = [];
|
|
515
|
+
chart.addBox({
|
|
516
|
+
id: 'rangeSelector', weight: 1200, position: o.position ?? 'top', size: () => h + 8,
|
|
517
|
+
draw(p, r) {
|
|
518
|
+
hits = [];
|
|
519
|
+
const th = themeOf(chart), c = th.control ?? {};
|
|
520
|
+
let x = o.align === 'right' ? r.right - o.buttons.reduce((s, b) => s + p.measure(b.text, f) + pad * 2 + 4, 0) : chart.chartArea.left;
|
|
521
|
+
p.text('Zoom', x, r.top + h / 2 + 2, { fill: chart.resolved.color, font: f, baseline: 'middle' });
|
|
522
|
+
x += p.measure('Zoom', f) + 8;
|
|
523
|
+
o.buttons.forEach((b, k) => {
|
|
524
|
+
const w = p.measure(b.text, f) + pad * 2, on = chart._rangeSelected === k;
|
|
525
|
+
p.rect(x, r.top + 2, w, h, { fill: on ? c.active ?? '#3d7dd8' : th.grid, radius: 4 });
|
|
526
|
+
p.text(b.text, x + w / 2, r.top + 2 + h / 2, { fill: on ? '#fff' : th.ink, font: f, align: 'center', baseline: 'middle' });
|
|
527
|
+
hits.push({ l: x, r: x + w, t: r.top + 2, b: r.top + 2 + h, k });
|
|
528
|
+
x += w + 4;
|
|
529
|
+
});
|
|
530
|
+
},
|
|
531
|
+
handle(event) { const hit = hits.find((q) => event.x >= q.l && event.x <= q.r && event.y >= q.t && event.y <= q.b); if (!hit) return false; if (event.type === 'click') rangeSelector.select(chart, hit.k); return true; },
|
|
532
|
+
});
|
|
533
|
+
},
|
|
534
|
+
afterDraw(chart, _a, o) {
|
|
535
|
+
if (!o.enabled || !chart._a11yEl) return;
|
|
536
|
+
let wrap = chart._a11yEl.querySelector?.('.clarity-chart-ranges');
|
|
537
|
+
if (!wrap) { wrap = document.createElement('div'); wrap.className = 'clarity-chart-ranges'; wrap.setAttribute('role', 'group'); wrap.setAttribute('aria-label', 'Range'); chart._a11yEl.prepend(wrap); }
|
|
538
|
+
const key = o.buttons.map((b) => b.text).join('|') + chart._rangeSelected;
|
|
539
|
+
if (wrap.dataset.key === key) return;
|
|
540
|
+
wrap.dataset.key = key; wrap.replaceChildren();
|
|
541
|
+
o.buttons.forEach((b, k) => { const el = document.createElement('button'); el.type = 'button'; el.textContent = b.text; el.setAttribute('aria-pressed', chart._rangeSelected === k ? 'true' : 'false'); el.addEventListener('click', () => rangeSelector.select(chart, k)); wrap.appendChild(el); });
|
|
542
|
+
},
|
|
543
|
+
};
|
|
544
|
+
|
|
545
|
+
// ── the toolbar: zoom in and out, pan, reset, download ─────────────────────────────────────────
|
|
546
|
+
const toolbar = {
|
|
547
|
+
id: 'toolbar',
|
|
548
|
+
defaults: { display: false, buttons: ['zoomIn', 'zoomOut', 'pan', 'reset', 'download'], download: ['png', 'svg', 'csv'], filename: 'chart' },
|
|
549
|
+
afterUpdate(chart, _a, o) {
|
|
550
|
+
const box = controls(chart); if (!box) return;
|
|
551
|
+
let bar = box.querySelector('.clarity-chart-toolbar');
|
|
552
|
+
if (!o.display) { bar?.remove(); return; }
|
|
553
|
+
const key = o.buttons.join() + (chart._toolMode ?? '') + (chart.isZoomedOrPanned() ? 'z' : '') + o.download.join() + (themeOf(chart).mode ?? '');
|
|
554
|
+
if (bar && bar.dataset.key === key) return;
|
|
555
|
+
if (!bar) { bar = document.createElement('div'); bar.className = 'clarity-chart-toolbar'; bar.setAttribute('role', 'toolbar'); bar.setAttribute('aria-label', 'Chart tools'); Object.assign(bar.style, { display: 'flex', gap: '3px', position: 'relative' }); box.appendChild(bar); }
|
|
556
|
+
bar.dataset.key = key; bar.replaceChildren();
|
|
557
|
+
const mode = () => chart.resolved.plugins?.zoom?.zoom?.mode ?? 'x';
|
|
558
|
+
const make = {
|
|
559
|
+
zoomIn: () => button(chart, '+', 'Zoom in', () => chart.zoom(1.5, mode())),
|
|
560
|
+
zoomOut: () => button(chart, '−', 'Zoom out', () => chart.zoom(1 / 1.5, mode())),
|
|
561
|
+
pan: () => button(chart, '✥', 'Pan', () => { chart._toolMode = chart._toolMode === 'pan' ? null : 'pan'; toolbar.afterUpdate(chart, {}, o); }, { pressed: chart._toolMode === 'pan' }),
|
|
562
|
+
reset: () => button(chart, '⟲', 'Reset zoom', () => chart.resetZoom()),
|
|
563
|
+
download: () => {
|
|
564
|
+
const b = button(chart, '⤓', 'Download', () => { menu.style.display = menu.style.display === 'none' ? 'flex' : 'none'; });
|
|
565
|
+
const menu = document.createElement('div');
|
|
566
|
+
Object.assign(menu.style, { display: 'none', position: 'absolute', right: '0', top: '28px', flexDirection: 'column', gap: '2px', background: themeOf(chart).control?.background ?? '#fff', border: `1px solid ${themeOf(chart).control?.border ?? 'rgba(0,0,0,0.15)'}`, borderRadius: '6px', padding: '3px', zIndex: '4' });
|
|
567
|
+
for (const fmtName of o.download) menu.appendChild(button(chart, fmtName.toUpperCase(), `Download ${fmtName.toUpperCase()}`, () => { menu.style.display = 'none'; chart.download(fmtName, o.filename); }));
|
|
568
|
+
const wrap = document.createElement('span'); Object.assign(wrap.style, { position: 'relative', display: 'inline-flex' }); wrap.append(b, menu);
|
|
569
|
+
return wrap;
|
|
570
|
+
},
|
|
571
|
+
};
|
|
572
|
+
for (const name of o.buttons) if (make[name]) bar.appendChild(make[name]());
|
|
573
|
+
},
|
|
574
|
+
};
|
|
575
|
+
|
|
576
|
+
// ── drilldown: a point opens its own series, and Back returns ────────────────────────────────────
|
|
577
|
+
function seriesData(series) {
|
|
578
|
+
const raw = series.data ?? [], labels = series.labels ? [...series.labels] : [];
|
|
579
|
+
const values = raw.map((d, i) => { if (Array.isArray(d)) { labels[i] = labels[i] ?? String(d[0]); return d[1]; } if (d && typeof d === 'object') { labels[i] = labels[i] ?? String(d.name ?? d.label ?? d.x ?? i + 1); return d.y ?? d.value ?? d.v; } return d; });
|
|
580
|
+
const drill = raw.map((d) => (d && typeof d === 'object' && !Array.isArray(d) ? d.drilldown ?? null : null));
|
|
581
|
+
return { labels, values, drill };
|
|
582
|
+
}
|
|
583
|
+
export function drillDown(chart, d, i) {
|
|
584
|
+
const o = chart.resolved?.drilldown ?? chart.config.options?.drilldown;
|
|
585
|
+
const meta = chart.metas[d], id = meta?.dataset.drilldown?.[i] ?? meta?.dataset.data?.[i]?.drilldown;
|
|
586
|
+
const series = (o?.series ?? []).find((s) => s.id === id);
|
|
587
|
+
if (!series) return false;
|
|
588
|
+
(chart._drill ??= []).push({ data: chart.config.data, type: chart.config.type, name: String(chart.data.labels?.[i] ?? meta.label ?? ''), at: [d, i], view: chart._view });
|
|
589
|
+
const s = seriesData(series), parent = meta.dataset;
|
|
590
|
+
chart.config.data = series.datasets ? { labels: series.labels ?? s.labels, datasets: series.datasets } : { labels: s.labels, datasets: [{ ...(series.dataset ?? {}), label: series.name ?? series.label ?? String(chart.data.labels?.[i] ?? id), data: s.values, drilldown: s.drill.some(Boolean) ? s.drill : undefined, ...(parent.backgroundColor && !series.backgroundColor ? {} : {}), ...(series.backgroundColor ? { backgroundColor: series.backgroundColor } : {}) }] };
|
|
591
|
+
if (series.type) chart.config.type = series.type;
|
|
592
|
+
chart._view = null; chart._hiddenIndices.clear();
|
|
593
|
+
chart.update();
|
|
594
|
+
return true;
|
|
595
|
+
}
|
|
596
|
+
export function drillUp(chart) {
|
|
597
|
+
const top = chart._drill?.pop();
|
|
598
|
+
if (!top) return false;
|
|
599
|
+
chart.config.data = top.data; chart.config.type = top.type; chart._view = top.view ?? null; chart._hiddenIndices.clear();
|
|
600
|
+
chart.update();
|
|
601
|
+
return true;
|
|
602
|
+
}
|
|
603
|
+
const drilldown = {
|
|
604
|
+
id: 'drilldown',
|
|
605
|
+
afterEvent(chart, { event }) {
|
|
606
|
+
if (event.type !== 'click' || chart._justDragged) { chart._justDragged = false; return; }
|
|
607
|
+
const o = chart.resolved.drilldown; if (!o?.series?.length) return;
|
|
608
|
+
const hit = chart.getElementsAtEventForMode(event, 'nearest', { intersect: true, axis: 'xy' })[0];
|
|
609
|
+
if (hit) drillDown(chart, hit.datasetIndex, hit.index);
|
|
610
|
+
},
|
|
611
|
+
afterUpdate(chart) {
|
|
612
|
+
const box = controls(chart); if (!box) return;
|
|
613
|
+
let back = box.querySelector('.clarity-chart-back');
|
|
614
|
+
const top = chart._drill?.at(-1);
|
|
615
|
+
if (!top) { back?.remove(); return; }
|
|
616
|
+
const text = `◂ Back to ${top.name || 'previous'}`;
|
|
617
|
+
if (back && back.textContent === text) return;
|
|
618
|
+
back?.remove();
|
|
619
|
+
back = button(chart, text, text.slice(2), () => chart.drillUp());
|
|
620
|
+
back.className = 'clarity-chart-back';
|
|
621
|
+
box.prepend(back);
|
|
622
|
+
},
|
|
623
|
+
afterDatasetsUpdate(chart) {
|
|
624
|
+
// a point with a drilldown says so to a pointer
|
|
625
|
+
if (chart.resolved.drilldown?.series?.length && chart.surface?.style) chart._drillable = true;
|
|
626
|
+
},
|
|
627
|
+
};
|
|
628
|
+
|
|
629
|
+
// ── data grouping: many points become fewer, one group to a few pixels ──────────────────────────
|
|
630
|
+
const TIME_GROUPS = [1e3, 6e4, 3e5, 9e5, 18e5, 36e5, 72e5, 216e5, 432e5, 864e5, 6048e5, 2629746e3, 31556952e3];
|
|
631
|
+
const dataGrouping = {
|
|
632
|
+
id: 'dataGrouping',
|
|
633
|
+
defaults: { enabled: false, groupPixelWidth: 4, approximation: null, forced: false },
|
|
634
|
+
afterParse(chart, _a, base) {
|
|
635
|
+
const width = Math.max(50, chart.chartArea?.width || chart.width * 0.85);
|
|
636
|
+
for (const m of chart.metas) {
|
|
637
|
+
const o = { ...base, ...(m.dataset.dataGrouping ?? {}) };
|
|
638
|
+
m.ungrouped = null; m.grouping = null;
|
|
639
|
+
if (!o.enabled || m.controller.derived) continue;
|
|
640
|
+
const ix = chart.scales[m.iAxisID];
|
|
641
|
+
if (!ix || ix.type === 'category' || !['line', 'bar', 'candlestick', 'ohlc', 'hlc', 'heikinashi', 'hollowcandlestick', 'areaRange', 'arearange', 'rangeArea'].includes(m.type)) continue;
|
|
642
|
+
const pts = m.parsed.filter((p) => Number.isFinite(p.index)); if (pts.length < 3) continue;
|
|
643
|
+
const v = chart._view?.[ix.id] ?? {}, lo = v.min != null ? valueOn(ix, v.min) : pts[0].index, hi = v.max != null ? valueOn(ix, v.max) : pts.at(-1).index;
|
|
644
|
+
const inView = pts.filter((p) => p.index >= lo && p.index <= hi).length, slots = width / o.groupPixelWidth;
|
|
645
|
+
if (!o.forced && inView <= slots) continue;
|
|
646
|
+
let size = (hi - lo) / slots;
|
|
647
|
+
size = ix.type.startsWith('time') ? TIME_GROUPS.find((g) => g >= size) ?? size : niceStep(size * 2, 2);
|
|
648
|
+
const approx = o.approximation ?? (Number.isFinite(pts[0].close) ? 'ohlc' : m.type === 'bar' ? 'sum' : 'average');
|
|
649
|
+
m.ungrouped = m.parsed; m.grouping = { size, approximation: approx };
|
|
650
|
+
m.parsed = groupPoints(pts, size, approx);
|
|
651
|
+
}
|
|
652
|
+
},
|
|
653
|
+
};
|
|
654
|
+
|
|
655
|
+
// ── the colour axis's legend: a gradient (or classes) with its values ──────────────────────────
|
|
656
|
+
const colorAxisLegend = {
|
|
657
|
+
id: 'colorAxis',
|
|
658
|
+
beforeLayout(chart) {
|
|
659
|
+
const ca = chart.resolved.colorAxis ?? {}, metas = chart.getSortedVisibleDatasetMetas().filter((m) => m.controller.colorAxis || (m.dataset.colorBy === 'value' && chart.resolved.colorAxis));
|
|
660
|
+
const lg = { display: true, position: 'bottom', ...(ca.legend ?? {}) };
|
|
661
|
+
if (!metas.length || lg.display === false || ca.showInLegend === false || !colorScaleOf(chart, metas[0]).hasValues) return;
|
|
662
|
+
const f = fontOf(chart, { size: 11 }), thick = lg.thickness ?? 10, horiz = lg.position === 'top' || lg.position === 'bottom';
|
|
663
|
+
chart.addBox({
|
|
664
|
+
id: 'colorAxis', weight: 900, position: lg.position,
|
|
665
|
+
size: (len, h) => (h ? thick + lineOf(f) + 16 : thick + 50),
|
|
666
|
+
draw(p, r) {
|
|
667
|
+
const scale = colorScaleOf(chart, metas[0]), ink = chart.resolved.color;
|
|
668
|
+
if (!scale.hasValues) return;
|
|
669
|
+
if (scale.classes) {
|
|
670
|
+
let x = horiz ? (r.left + r.right) / 2 - scale.classes.reduce((s, c) => s + p.measure(c.name ?? `${c.from ?? ''}–${c.to ?? ''}`, f) + 22, 0) / 2 : r.left + 8, y = horiz ? r.top + 8 : r.top + 8;
|
|
671
|
+
for (const c of scale.classes) { const name = c.name ?? `${c.from != null ? fmt(chart, c.from) : '…'} – ${c.to != null ? fmt(chart, c.to) : '…'}`; p.rect(x, y, 12, 12, { fill: c.color, radius: 2 }); p.text(name, x + 16, y + 6, { fill: ink, font: f, baseline: 'middle' }); if (horiz) x += p.measure(name, f) + 26; else y += 18; }
|
|
672
|
+
return;
|
|
673
|
+
}
|
|
674
|
+
const len = horiz ? Math.min(360, (r.right - r.left) * 0.6) : Math.min(260, (r.bottom - r.top) * 0.8);
|
|
675
|
+
const x0 = horiz ? (r.left + r.right) / 2 - len / 2 : r.left + 10, y0 = horiz ? r.top + 6 : (r.top + r.bottom) / 2 - len / 2;
|
|
676
|
+
const stops = scale.stops.map(([o, c]) => [horiz ? o : 1 - o, c]).sort((a, b) => a[0] - b[0]);
|
|
677
|
+
p.rect(x0, y0, horiz ? len : thick, horiz ? thick : len, { fill: { linearGradient: horiz ? { x1: 0, y1: 0, x2: 1, y2: 0 } : { x1: 0, y1: 0, x2: 0, y2: 1 }, stops }, radius: 2 });
|
|
678
|
+
const log = scale.log, L = (v) => (log ? Math.log10(Math.max(1e-12, v)) : v), step = niceStep(scale.max - scale.min, 4);
|
|
679
|
+
const ticks = log ? [1, 2, 5].flatMap((m) => Array.from({ length: 12 }, (_, e) => m * 10 ** (e - 4))).filter((v) => v >= scale.min * 0.999 && v <= scale.max * 1.001).sort((a, b) => a - b) : [];
|
|
680
|
+
if (!log) for (let v = Math.ceil(scale.min / step) * step, k = 0; v <= scale.max + step * 1e-9 && k < 12; v += step, k++) ticks.push(v);
|
|
681
|
+
for (const v of ticks) {
|
|
682
|
+
const t = (L(v) - L(scale.min)) / ((L(scale.max) - L(scale.min)) || 1);
|
|
683
|
+
if (horiz) p.text(fmt(chart, +v.toPrecision(10)), x0 + t * len, y0 + thick + lineOf(f) * 0.9 + 2, { fill: ink, font: f, align: 'center' });
|
|
684
|
+
else p.text(fmt(chart, +v.toPrecision(10)), x0 + thick + 6, y0 + (1 - t) * len, { fill: ink, font: f, baseline: 'middle' });
|
|
685
|
+
}
|
|
686
|
+
},
|
|
687
|
+
});
|
|
688
|
+
},
|
|
689
|
+
};
|
|
690
|
+
|
|
691
|
+
export const MORE_PLUGINS = [dataGrouping, annotation, datalabels, zoom, measure, crosshair, navigator, rangeSelector, brush, toolbar, drilldown, colorAxisLegend];
|
|
692
|
+
export { annotation as Annotation, datalabels as DataLabels, zoom as Zoom, measure as Measure, crosshair as Crosshair, navigator as Navigator, rangeSelector as RangeSelector, brush as Brush, toolbar as Toolbar, drilldown as Drilldown, dataGrouping as DataGrouping, colorAxisLegend as ColorAxisLegend };
|
|
693
|
+
|
|
694
|
+
// ── the data as sound ───────────────────────────────────────────────────────────────────────
|
|
695
|
+
/**
|
|
696
|
+
* Each shown dataset in turn as notes from `low` to `high` Hz (larger values higher), panned
|
|
697
|
+
* from left to right with their place on the x axis; each point is shown as it sounds.
|
|
698
|
+
* Without Web Audio (a server, a test) the notes are worked out and shown, silently.
|
|
699
|
+
*/
|
|
700
|
+
export function sonify(chart, { duration = 3000, low = 220, high = 880, datasetIndex, type = 'sine', volume = 0.2, gap = 300, highlight = true } = {}) {
|
|
701
|
+
const metas = (datasetIndex != null ? [chart.metas[datasetIndex]] : chart.getSortedVisibleDatasetMetas()).filter(Boolean);
|
|
702
|
+
const vals = metas.flatMap((m) => m.parsed.map((p) => (Number.isFinite(p.close) ? p.close : p.value))).filter(Number.isFinite);
|
|
703
|
+
const lo = Math.min(...vals), hi = Math.max(...vals), a = chart.chartArea, notes = [];
|
|
704
|
+
const count = metas.reduce((s, m) => s + m.parsed.length, 0) || 1, per = (duration - gap * Math.max(0, metas.length - 1)) / count;
|
|
705
|
+
let t = 0;
|
|
706
|
+
for (const m of metas) {
|
|
707
|
+
for (const p of m.parsed) {
|
|
708
|
+
const v = Number.isFinite(p.close) ? p.close : p.value, el = m.elements.find((e) => e.index === p.i);
|
|
709
|
+
if (Number.isFinite(v)) {
|
|
710
|
+
const k = hi > lo ? (v - lo) / (hi - lo) : 0.5, x = el ? centerOf(el).x : a.left;
|
|
711
|
+
notes.push({ time: t, duration: per * 0.9, frequency: low * (high / low) ** k, pan: Math.max(-1, Math.min(1, ((x - a.left) / ((a.right - a.left) || 1)) * 2 - 1)), value: v, datasetIndex: m.index, index: p.i });
|
|
712
|
+
}
|
|
713
|
+
t += per;
|
|
714
|
+
}
|
|
715
|
+
t += gap;
|
|
716
|
+
}
|
|
717
|
+
let ctx = null, stopFrame = null, stopped = false, resolveDone;
|
|
718
|
+
const done = new Promise((r) => { resolveDone = r; });
|
|
719
|
+
const AC = globalThis.AudioContext ?? globalThis.webkitAudioContext;
|
|
720
|
+
if (AC) {
|
|
721
|
+
try {
|
|
722
|
+
ctx = new AC();
|
|
723
|
+
const t0 = ctx.currentTime + 0.05;
|
|
724
|
+
for (const n of notes) {
|
|
725
|
+
const osc = ctx.createOscillator(), g = ctx.createGain(), pan = ctx.createStereoPanner?.();
|
|
726
|
+
osc.type = type; osc.frequency.value = n.frequency;
|
|
727
|
+
g.gain.setValueAtTime(0, t0 + n.time / 1000); g.gain.linearRampToValueAtTime(volume, t0 + n.time / 1000 + 0.01); g.gain.linearRampToValueAtTime(0, t0 + (n.time + n.duration) / 1000);
|
|
728
|
+
if (pan) { pan.pan.value = n.pan; osc.connect(g).connect(pan).connect(ctx.destination); } else osc.connect(g).connect(ctx.destination);
|
|
729
|
+
osc.start(t0 + n.time / 1000); osc.stop(t0 + (n.time + n.duration) / 1000 + 0.02);
|
|
730
|
+
}
|
|
731
|
+
} catch { ctx = null; }
|
|
732
|
+
}
|
|
733
|
+
let elapsed = 0, shown = -1;
|
|
734
|
+
const finish = () => { if (stopped) return; stopped = true; stopFrame?.(); try { ctx?.close?.(); } catch { /* closed */ } if (highlight) { chart.setActiveElements([]); chart.tooltip?.setActiveElements([]); } resolveDone(notes); };
|
|
735
|
+
stopFrame = frame((dt) => {
|
|
736
|
+
elapsed += dt * 1000;
|
|
737
|
+
if (highlight) {
|
|
738
|
+
let k = shown; while (k + 1 < notes.length && notes[k + 1].time <= elapsed) k++;
|
|
739
|
+
if (k !== shown && k >= 0) { shown = k; const n = notes[k]; chart.setActiveElements([{ datasetIndex: n.datasetIndex, index: n.index }]); chart.tooltip?.setActiveElements([{ datasetIndex: n.datasetIndex, index: n.index }]); }
|
|
740
|
+
}
|
|
741
|
+
if (elapsed >= t) finish();
|
|
742
|
+
}, { own: false });
|
|
743
|
+
return { notes, stop: finish, done, get playing() { return !stopped; } };
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
// ── the data as CSV ───────────────────────────────────────────────────────────────────────────
|
|
747
|
+
const csvCell = (v, d) => { const s = v == null || (typeof v === 'number' && !Number.isFinite(v)) ? '' : String(v); return /["\n\r]/.test(s) || s.includes(d) ? `"${s.replace(/"/g, '""')}"` : s; };
|
|
748
|
+
export function toCSV(chart, { delimiter = ',', lineEnd = '\n' } = {}) {
|
|
749
|
+
const labels = chart.data.labels ?? [], metas = chart.metas, xs = chart.scales.x;
|
|
750
|
+
const cols = metas.map((m) => {
|
|
751
|
+
const p = m.parsed.find((q) => q && Number.isFinite(q.value)) ?? m.parsed[0] ?? {}, name = m.label || `Dataset ${m.index + 1}`;
|
|
752
|
+
if ('close' in p) return { names: ['Open', 'High', 'Low', 'Close'].map((n) => `${name} ${n}`), get: (q) => [q?.open, q?.high, q?.low, q?.close] };
|
|
753
|
+
if ('q1' in p) return { names: ['Min', 'Q1', 'Median', 'Q3', 'Max'].map((n) => `${name} ${n}`), get: (q) => [q?.min, q?.q1, q?.median, q?.q3, q?.max] };
|
|
754
|
+
if (Number.isFinite(p.low) && 'high' in p) return { names: [`${name} Low`, `${name} High`], get: (q) => [q?.low, q?.high] };
|
|
755
|
+
if (Number.isFinite(p.low)) return { names: [`${name} Start`, `${name} End`], get: (q) => [q?.low, q?.value] };
|
|
756
|
+
return { names: [name], get: (q) => [q?.value] };
|
|
757
|
+
});
|
|
758
|
+
const head = [xs?.options?.title?.text || 'Label', ...cols.flatMap((c) => c.names)];
|
|
759
|
+
const n = Math.max(labels.length, ...metas.map((m) => m.ungrouped?.length ?? m.parsed.length));
|
|
760
|
+
const rows = [head];
|
|
761
|
+
for (let i = 0; i < n; i++) {
|
|
762
|
+
const first = metas[0] ? (metas[0].ungrouped ?? metas[0].parsed)[i] : null;
|
|
763
|
+
const label = labels[i] ?? first?.name ?? (xs?.type?.startsWith('time') && Number.isFinite(first?.index) ? new Date(first.index).toISOString() : first?.raw?.x ?? i + 1);
|
|
764
|
+
rows.push([label, ...metas.flatMap((m, k) => cols[k].get((m.ungrouped ?? m.parsed)[i]))]);
|
|
765
|
+
}
|
|
766
|
+
return rows.map((r) => r.map((v) => csvCell(v, delimiter)).join(delimiter)).join(lineEnd);
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
// ── a view as a token ───────────────────────────────────────────────────────────────────────────
|
|
770
|
+
const b64 = { enc: (s) => (typeof btoa === 'function' ? btoa(unescape(encodeURIComponent(s))) : Buffer.from(s).toString('base64')).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''), dec: (s) => { const t = s.replace(/-/g, '+').replace(/_/g, '/'); return typeof atob === 'function' ? decodeURIComponent(escape(atob(t))) : Buffer.from(t, 'base64').toString(); } };
|
|
771
|
+
export function viewToken(chart) {
|
|
772
|
+
return b64.enc(JSON.stringify({ v: 1, view: chart._view ?? null, hidden: chart.metas.map((m) => m.hiddenOverride), points: [...chart._hiddenIndices], drill: (chart._drill ?? []).map((d) => d.at), range: chart._rangeSelected ?? null }));
|
|
773
|
+
}
|
|
774
|
+
export function applyViewToken(chart, token) {
|
|
775
|
+
let s; try { s = JSON.parse(b64.dec(String(token))); } catch { throw new Error('[clarity-charts] restoreView(token): not a token from saveView()'); }
|
|
776
|
+
while (chart._drill?.length) drillUp(chart);
|
|
777
|
+
for (const [d, i] of s.drill ?? []) drillDown(chart, d, i);
|
|
778
|
+
chart._view = s.view ?? null;
|
|
779
|
+
chart._hiddenIndices = new Set(s.points ?? []);
|
|
780
|
+
chart._rangeSelected = s.range ?? undefined;
|
|
781
|
+
(s.hidden ?? []).forEach((h, k) => { if (chart.metas[k]) chart.metas[k].hiddenOverride = h; });
|
|
782
|
+
}
|
|
783
|
+
void cssPaint;
|