@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/compat.js ADDED
@@ -0,0 +1,414 @@
1
+ // @clarity-js/charts — Highcharts's and ApexCharts's configuration, read as they write it and drawn
2
+ // by these charts. The common options of each are translated; what has no match here is left out.
3
+ //
4
+ // import { Highcharts, ApexCharts } from '@clarity-js/charts'
5
+ // Highcharts.chart('el', { chart: { type: 'column' }, xAxis: { categories }, series: [{ name: 'Sales', data }] })
6
+ // new ApexCharts(el, { chart: { type: 'area' }, series: [{ name: 'Visits', data }], xaxis: { type: 'datetime' } }).render()
7
+ //
8
+ // fromHighcharts(options) and fromApex(options) give the configuration itself, to read or change.
9
+
10
+ import { Chart, merge } from './core.js';
11
+ import { withAlpha, parseColor } from './fills.js';
12
+ import { PALETTE } from './plugins.js';
13
+
14
+ const arr = (v) => (v == null ? [] : Array.isArray(v) ? v : [v]);
15
+ const isObj = (v) => v && typeof v === 'object' && !Array.isArray(v);
16
+ const pctOf = (v) => (typeof v === 'string' && v.trim().endsWith('%') ? parseFloat(v) / 100 : typeof v === 'number' ? v : null);
17
+ const dash = (s) => ({ Solid: [], Dash: [8, 6], ShortDash: [6, 2], Dot: [1, 3], ShortDot: [2, 2], DashDot: [8, 3, 1, 3], ShortDashDot: [6, 2, 1, 2], LongDash: [16, 6], LongDashDot: [16, 6, 1, 6] })[s];
18
+ const fill = (c, a) => (typeof c === 'string' && parseColor(c) ? withAlpha(c, a) : c);
19
+ const sizeOf = (el, h) => { if (h == null || h === 'auto' || !el?.style) return false; el.style.height = typeof h === 'number' || /^\d+$/.test(String(h)) ? `${h}px` : String(h); return true; };
20
+ const target = (el) => (typeof el === 'string' ? globalThis.document?.getElementById(el) ?? globalThis.document?.querySelector(el) : el);
21
+
22
+ // "{point.y:.2f} {series.name}" — the parts of Highcharts's format strings that are used most
23
+ function hcFormat(tpl, ctx, locale) {
24
+ return String(tpl).replace(/\{([\w.]+)(?::([^}]*))?\}/g, (_, path, spec) => {
25
+ let v = path.split('.').reduce((o, k) => o?.[k], ctx);
26
+ if (spec && typeof v === 'number') { const m = /^,?\.(\d+)f$/.exec(spec); if (m) v = v.toLocaleString(locale, { minimumFractionDigits: +m[1], maximumFractionDigits: +m[1], useGrouping: spec.startsWith(',') }); }
27
+ return v == null ? '' : String(v);
28
+ }).replace(/<br\s*\/?>/gi, '\n').replace(/<[^>]+>/g, '');
29
+ }
30
+
31
+ // ── Highcharts ────────────────────────────────────────────────────────────────────────────────
32
+ const HC_TYPES = {
33
+ line: 'line', spline: 'line', area: 'line', areaspline: 'line', column: 'bar', bar: 'bar', pie: 'pie', variablepie: 'pie', scatter: 'scatter', bubble: 'bubble',
34
+ arearange: 'areaRange', areasplinerange: 'areasplinerange', columnrange: 'bar', boxplot: 'boxplot', errorbar: 'errorBar', candlestick: 'candlestick', ohlc: 'ohlc', hlc: 'hlc',
35
+ heikinashi: 'heikinashi', hollowcandlestick: 'hollowcandlestick', heatmap: 'heatmap', treemap: 'treemap', sunburst: 'sunburst', funnel: 'funnel', pyramid: 'pyramid',
36
+ gauge: 'gauge', solidgauge: 'solidgauge', waterfall: 'waterfall', sankey: 'sankey', xrange: 'xrange', dumbbell: 'dumbbell', lollipop: 'lollipop', bullet: 'bullet',
37
+ wordcloud: 'wordcloud', item: 'item', streamgraph: 'streamgraph', networkgraph: 'network', organization: 'organization', treegraph: 'treegraph', venn: 'venn',
38
+ gantt: 'gantt', map: 'map', mapbubble: 'mapbubble', mappoint: 'mappoint', scatter3d: 'scatter3d', sma: 'sma', ema: 'ema', wma: 'wma', bb: 'bollinger', macd: 'macd', rsi: 'rsi', momentum: 'momentum',
39
+ };
40
+ let hcDefaults = {};
41
+ const hcCallback = (fn) => (typeof fn === 'function' ? function (v) { return fn.call({ value: this.type === 'category' ? this.labels[v] ?? v : v, axis: this, isFirst: false, isLast: false }); } : undefined);
42
+ function hcAxis(a, id, horizontal, out, extra = {}) {
43
+ if (!a) return;
44
+ const o = {};
45
+ if (a.type === 'datetime') o.type = 'time'; else if (a.type === 'logarithmic') o.type = 'logarithmic'; else if (a.type === 'category' || a.categories) o.type = 'category';
46
+ if (a.title?.text) o.title = { display: true, text: a.title.text };
47
+ if (a.min != null) o.min = a.min; if (a.max != null) o.max = a.max;
48
+ if (a.softMin != null) o.suggestedMin = a.softMin; if (a.softMax != null) o.suggestedMax = a.softMax;
49
+ if (a.reversed) o.reverse = true;
50
+ if (a.opposite) o.position = horizontal ? 'top' : 'right';
51
+ if (a.visible === false) o.display = false;
52
+ if (a.gridLineWidth === 0) o.grid = { display: false }; else if (a.gridLineWidth) o.grid = { lineWidth: a.gridLineWidth, color: a.gridLineColor };
53
+ if (a.labels?.enabled === false) o.ticks = { display: false };
54
+ else if (a.labels?.formatter) o.ticks = { callback: hcCallback(a.labels.formatter) };
55
+ else if (a.labels?.format) o.ticks = { callback(v) { return hcFormat(a.labels.format, { value: this.type === 'category' ? this.labels[v] : v }); } };
56
+ if (a.tickInterval) o.ticks = { ...(o.ticks ?? {}), stepSize: a.tickInterval };
57
+ if (a.plotBands) o.plotBands = a.plotBands;
58
+ if (a.plotLines) o.plotLines = a.plotLines;
59
+ if (a.categories) o.labels = a.categories;
60
+ // stock panes: yAxis [{ height: '60%' }, { top: '65%', height: '35%' }] → axes in a stack
61
+ if (!horizontal && a.height != null && pctOf(a.height) != null) { o.stack = 'panes'; o.stackWeight = pctOf(a.height) * 100; }
62
+ out[id] = merge(out[id] ?? {}, o, extra);
63
+ }
64
+ function hcSeriesType(s, chartType, polar, hc) {
65
+ const t = (s.type ?? chartType ?? 'line').toLowerCase();
66
+ if (polar && (t === 'line' || t === 'area' || t === 'column')) return 'radar';
67
+ // chart.options3d turns columns, bars, pies and scatters solid; chart.parallelCoordinates lines into parallel axes
68
+ if (hc?.chart?.options3d?.enabled) { const d3 = { column: 'column3d', bar: 'bar3d', scatter: 'scatter3d' }[t]; if (d3) return d3; if (t === 'pie') return (s.innerSize ?? hc.plotOptions?.pie?.innerSize) ? 'doughnut3d' : 'pie3d'; }
69
+ if (hc?.chart?.parallelCoordinates && (t === 'line' || t === 'spline')) return 'parallel';
70
+ return HC_TYPES[t] ?? t;
71
+ }
72
+ /** Highcharts options → this package's configuration. */
73
+ export function fromHighcharts(input = {}) {
74
+ const hc = merge(hcDefaults, input), ch = hc.chart ?? {}, chartType = (ch.type ?? 'line').toLowerCase(), polar = !!ch.polar;
75
+ const po = hc.plotOptions ?? {}, sAll = po.series ?? {}, scales = {}, options = { plugins: {} }, labelsFromNames = [];
76
+ const xAxes = arr(hc.xAxis), yAxes = arr(hc.yAxis), inverted = !!ch.inverted || chartType === 'bar';
77
+ // Highcharts's xAxis is the axis of the categories: across a bar chart, it stands up
78
+ const catId = (k) => (inverted ? (k ? `y${k}` : 'y') : k ? `x${k}` : 'x'), valId = (k) => (inverted ? (k ? `x${k}` : 'x') : k ? `y${k}` : 'y');
79
+ xAxes.forEach((a, k) => hcAxis(a, catId(k), !inverted, scales));
80
+ yAxes.forEach((a, k) => hcAxis(a, valId(k), inverted, scales));
81
+ const labels = xAxes[0]?.categories ? [...xAxes[0].categories] : undefined;
82
+ const stacking = sAll.stacking ?? po[chartType]?.stacking ?? po.column?.stacking ?? po.area?.stacking;
83
+ const series = arr(hc.series);
84
+ const datasets = series.map((s, k) => {
85
+ const raw = (s.type ?? chartType).toLowerCase(), type = hcSeriesType(s, chartType, polar, hc), opt = { ...sAll, ...(po[raw] ?? {}), ...s };
86
+ const ds = { label: s.name ?? (['sma', 'ema', 'wma', 'bollinger', 'macd', 'rsi', 'momentum'].includes(type) ? undefined : `Series ${k + 1}`) };
87
+ if (s.id != null) ds.id = s.id;
88
+ if (type !== hcSeriesType({}, chartType, polar, hc)) ds.type = type;
89
+ let data = arr(s.data);
90
+ // { name, y, drilldown } points with no categories: the names are the labels
91
+ if (!labels && ['bar', 'line', 'pie', 'funnel', 'pyramid', 'item', 'radialBar'].includes(type) && data.length && data.every((d) => isObj(d) && d.name != null || (Array.isArray(d) && typeof d[0] === 'string'))) {
92
+ data.forEach((d, i) => { labelsFromNames[i] = labelsFromNames[i] ?? String(Array.isArray(d) ? d[0] : d.name); });
93
+ if (data.some((d) => isObj(d) && d.drilldown)) ds.drilldown = data.map((d) => (isObj(d) ? d.drilldown ?? null : null));
94
+ if (data.some((d) => isObj(d) && d.color)) ds.backgroundColor = data.map((d) => (isObj(d) ? d.color : undefined) ?? null).map((c, i, a) => c ?? undefined);
95
+ data = data.map((d) => (Array.isArray(d) ? d[1] : d.y));
96
+ }
97
+ if (raw === 'boxplot') ds.summary = true;
98
+ if (raw === 'columnrange') data = data.map((d) => (Array.isArray(d) ? d.slice(-2) : isObj(d) ? [d.low, d.high] : d));
99
+ if (raw === 'sankey') data = data.map((d) => (Array.isArray(d) ? { from: d[0], to: d[1], flow: d[2] } : d));
100
+ if (raw === 'treemap' || raw === 'sunburst') data = data.map((d) => (isObj(d) ? { ...d, parent: d.parent, id: d.id, name: d.name, value: d.value } : d));
101
+ if (raw === 'bubble') data = data.map((d) => (Array.isArray(d) ? { x: d[0], y: d[1], r: Math.sqrt(d[2] ?? 1) * 3 } : isObj(d) ? { x: d.x, y: d.y, r: Math.sqrt(d.z ?? 1) * 3 } : d));
102
+ if (type === 'parallel') { const ys = yAxes; data = [data.map((v, d) => (ys[d]?.categories && typeof v === 'number' ? ys[d].categories[v] : v))]; }
103
+ if (raw === 'networkgraph' || raw === 'organization') { const keys = opt.keys ?? ['from', 'to']; data = data.map((d) => (Array.isArray(d) ? Object.fromEntries(keys.map((k2, j) => [k2, d[j]])) : d)); if (s.nodes) ds.nodes = s.nodes; }
104
+ if (raw === 'organization' && (opt.hangingIndent != null || ch.inverted)) ds.inverted = !!ch.inverted;
105
+ if (raw === 'map' || raw === 'mapbubble' || raw === 'mappoint') {
106
+ const jb = opt.joinBy, mapKey = Array.isArray(jb) ? jb[0] : jb, dataKey = Array.isArray(jb) ? jb[1] ?? jb[0] : jb;
107
+ ds.map = s.mapData ?? ch.map; if (mapKey) ds.joinBy = mapKey;
108
+ if (dataKey) data = data.map((d) => (isObj(d) && d[dataKey] != null ? { ...d, [mapKey]: d[dataKey], id: d.id ?? d[dataKey], value: d.value ?? d.z ?? d.y } : d));
109
+ if (raw === 'mapbubble') { if (opt.minSize != null) ds.minSize = opt.minSize; if (opt.maxSize != null) ds.maxSize = opt.maxSize; }
110
+ if (opt.nullColor) ds.nullColor = opt.nullColor;
111
+ if (opt.dataLabels?.enabled) ds.labels = { display: true, ...(opt.dataLabels.format ? { formatter: (f) => hcFormat(opt.dataLabels.format, { point: { name: f.name, value: f.value } }) } : {}) };
112
+ }
113
+ ds.data = data;
114
+ if (s.color) { ds.borderColor = s.color; ds.backgroundColor = ['line', 'radar'].includes(type) ? fill(s.color, raw.startsWith('area') ? 0.35 : 1) : s.color; }
115
+ if (raw === 'area' || raw === 'areaspline') ds.fill = stacking ? (k ? '-1' : 'origin') : 'origin';
116
+ if (raw === 'spline' || raw === 'areaspline') ds.tension = 0.4;
117
+ if (s.step) ds.stepped = s.step === 'center' ? 'middle' : s.step === 'right' ? 'after' : 'before';
118
+ if (opt.dashStyle && dash(opt.dashStyle)) ds.borderDash = dash(opt.dashStyle);
119
+ if (opt.lineWidth != null) ds.borderWidth = opt.lineWidth;
120
+ if (opt.marker?.enabled === false) ds.pointRadius = 0; else if (opt.marker?.radius != null) ds.pointRadius = opt.marker.radius;
121
+ if (opt.marker?.symbol) ds.pointStyle = { circle: 'circle', square: 'rect', diamond: 'rectRot', triangle: 'triangle', 'triangle-down': 'triangle' }[opt.marker.symbol] ?? 'circle';
122
+ if (s.visible === false) ds.hidden = true;
123
+ if (s.yAxis != null) ds[inverted ? 'xAxisID' : 'yAxisID'] = typeof s.yAxis === 'number' ? valId(s.yAxis) : s.yAxis;
124
+ if (s.xAxis != null) ds[inverted ? 'yAxisID' : 'xAxisID'] = typeof s.xAxis === 'number' ? catId(s.xAxis) : s.xAxis;
125
+ if (s.stack != null) ds.stack = String(s.stack);
126
+ if (opt.dataLabels?.enabled) ds.datalabels = { display: true, ...(opt.dataLabels.format ? { formatter: (v, c) => hcFormat(opt.dataLabels.format, { y: v, point: { y: v, name: c.chart.data.labels?.[c.dataIndex] }, percentage: c.percent }) } : {}), ...(opt.dataLabels.color ? { color: opt.dataLabels.color } : {}) };
127
+ if (opt.colorByPoint && ['bar'].includes(type) && !s.color) { ds.backgroundColor = hc.colors ?? PALETTE; ds.colorByPoint = true; }
128
+ if (type === 'pie') {
129
+ const inner = pctOf(opt.innerSize); if (inner) ds.cutout = `${inner * 100}%`;
130
+ if (opt.startAngle != null) ds.rotation = opt.startAngle;
131
+ if (opt.startAngle != null && opt.endAngle != null) ds.circumference = opt.endAngle - opt.startAngle;
132
+ }
133
+ if (raw === 'gauge' || raw === 'solidgauge') {
134
+ const pane = isObj(hc.pane) ? hc.pane : arr(hc.pane)[0] ?? {}, ya = yAxes[s.yAxis ?? 0] ?? {};
135
+ Object.assign(ds, { min: ya.min ?? 0, max: ya.max ?? 100, startAngle: pane.startAngle ?? (raw === 'solidgauge' ? -90 : -150), endAngle: pane.endAngle ?? (raw === 'solidgauge' ? 90 : 150), bands: ya.plotBands, stops: ya.stops, ...(s.tooltip?.valueSuffix ? { unit: s.tooltip.valueSuffix } : {}) });
136
+ }
137
+ if (raw === 'waterfall') { ds.upColor = s.upColor ?? opt.upColor; ds.downColor = s.color ?? opt.color; }
138
+ if (raw === 'candlestick' || raw === 'ohlc' || raw === 'hlc' || raw === 'heikinashi' || raw === 'hollowcandlestick') { if (opt.upColor) ds.upColor = opt.upColor; if (s.color) { ds.downColor = s.color; delete ds.backgroundColor; delete ds.borderColor; } if (opt.upLineColor) ds.upLineColor = opt.upLineColor; if (opt.lineColor) ds.lineColor = opt.lineColor; }
139
+ if (raw === 'xrange') { ds.colorByPoint = opt.colorByPoint !== false && !s.color; }
140
+ if (s.linkedTo != null) ds.linkedTo = s.linkedTo;
141
+ if (s.params) ds.params = s.params;
142
+ if (raw === 'item') { if (opt.startAngle != null) ds.startAngle = opt.startAngle; if (opt.endAngle != null) ds.endAngle = opt.endAngle; if (opt.rows) ds.rows = opt.rows; if (opt.startAngle == null && opt.endAngle == null) ds.layout = 'grid'; }
143
+ if (raw === 'wordcloud' && opt.rotation) ds.rotation = opt.rotation;
144
+ return ds;
145
+ });
146
+ const type = hcSeriesType({}, chartType, polar, hc);
147
+ const o3 = ch.options3d;
148
+ if (o3?.enabled) {
149
+ const za = hc.zAxis ? arr(hc.zAxis)[0] : null, ax = (a) => (a ? { min: a.min ?? undefined, max: a.max ?? undefined, title: a.title?.text } : undefined);
150
+ options.chart3d = { alpha: o3.alpha, beta: o3.beta, depth: po.pie?.depth ?? o3.depth, viewDistance: o3.viewDistance, ...(type === 'scatter3d' ? { axes: { x: ax(xAxes[0]), y: ax(yAxes[0]), z: ax(za) } } : {}) };
151
+ if (po.column?.grouping === false || sAll.grouping === false) options.grouped = false;
152
+ }
153
+ if (type === 'gantt') options.scales = { ...(options.scales ?? {}), x: { ...(options.scales?.x ?? {}), type: options.scales?.x?.type ?? 'time' } };
154
+ if (type === 'parallel') options.parallelAxes = yAxes.map((a) => ({ min: a.min ?? undefined, max: a.max ?? undefined, reversed: !!a.reversed }));
155
+ const ownAxes = ['pie', 'heatmap', 'treemap', 'sunburst', 'funnel', 'pyramid', 'sankey', 'gauge', 'solidgauge', 'wordcloud', 'item', 'xrange', 'gantt', 'organization', 'treegraph', 'network', 'venn', 'map', 'pie3d', 'doughnut3d', 'column3d', 'bar3d', 'scatter3d', 'parallel'];
156
+ if (inverted && !ownAxes.includes(type) && !(datasets.length && datasets.every((d) => ownAxes.includes(d.type ?? type)))) options.indexAxis = 'y';
157
+ if (stacking) {
158
+ const how = stacking === 'percent' ? 'percent' : true;
159
+ const idx = inverted ? 'y' : 'x', val = idx === 'x' ? 'y' : 'x';
160
+ scales[idx] = merge(scales[idx] ?? {}, { stacked: true });
161
+ scales[val] = merge(scales[val] ?? {}, { stacked: how });
162
+ for (const id of Object.keys(scales)) if (id !== idx && id.startsWith(val)) scales[id].stacked = how;
163
+ }
164
+ if (Object.keys(scales).length) options.scales = scales;
165
+ // title, subtitle, legend, tooltip
166
+ if (hc.title?.text) options.plugins.title = { display: true, text: hc.title.text, align: hc.title.align === 'left' ? 'start' : hc.title.align === 'right' ? 'end' : 'center' };
167
+ if (hc.subtitle?.text) options.plugins.subtitle = { display: true, text: hc.subtitle.text };
168
+ if (hc.legend) options.plugins.legend = { display: hc.legend.enabled !== false, ...(hc.legend.layout === 'vertical' ? { position: hc.legend.align === 'left' ? 'left' : 'right' } : hc.legend.verticalAlign === 'top' ? { position: 'top' } : { position: 'bottom' }) };
169
+ else options.plugins.legend = { position: 'bottom', display: !['pie', 'treemap', 'sunburst', 'gauge', 'solidgauge', 'heatmap', 'funnel', 'pyramid', 'sankey', 'wordcloud', 'network', 'organization', 'treegraph', 'venn', 'map', 'gantt', 'surface'].includes(type) || type === 'item' };
170
+ const tt = hc.tooltip ?? {};
171
+ if (tt.enabled === false) options.plugins.tooltip = { enabled: false };
172
+ else {
173
+ const t = {};
174
+ if (tt.shared) options.interaction = { mode: 'index', intersect: false }; else if (tt.shared === false) options.interaction = { mode: 'nearest', intersect: true };
175
+ const pre = tt.valuePrefix ?? '', suf = tt.valueSuffix ?? '', dec = tt.valueDecimals;
176
+ if (tt.pointFormat || pre || suf || dec != null) t.callbacks = { label: (c) => (tt.pointFormat ? hcFormat(tt.pointFormat, { point: { y: c.parsed.y, x: c.parsed.x, name: c.label, key: c.label, percentage: c.chart.getDatasetMeta(c.datasetIndex).shares?.[c.dataIndex] }, series: { name: c.dataset.label } }).trim() : `${c.dataset.label ? c.dataset.label + ': ' : ''}${pre}${dec != null && Number.isFinite(c.parsed.y) ? c.parsed.y.toFixed(dec) : c.formattedValue}${suf}`) };
177
+ if (tt.formatter) t.callbacks = { ...(t.callbacks ?? {}), label: (c) => String(tt.formatter.call({ x: c.label, y: c.parsed.y, point: { name: c.label, y: c.parsed.y }, series: { name: c.dataset.label } }) ?? '').replace(/<br\s*\/?>/gi, '\n').replace(/<[^>]+>/g, '') };
178
+ if (Object.keys(t).length) options.plugins.tooltip = t;
179
+ }
180
+ if (hc.colors) options.plugins.colors = { palette: hc.colors };
181
+ if (ch.backgroundColor) options.background = ch.backgroundColor;
182
+ if (ch.plotBackgroundColor) options.chartArea = { backgroundColor: ch.plotBackgroundColor };
183
+ if (ch.style?.fontFamily) options.font = { family: ch.style.fontFamily };
184
+ const zt = ch.zooming?.type ?? ch.zoomType;
185
+ if (zt) options.plugins.zoom = { zoom: { drag: { enabled: true }, mode: zt }, pan: { enabled: !!(ch.panning?.enabled ?? ch.panning), mode: ch.panning?.type ?? zt, modifierKey: ch.panKey ?? 'shift' } };
186
+ if (hc.exporting?.enabled !== false && (hc.exporting || input.exporting)) options.plugins.toolbar = { display: hc.exporting?.enabled !== false, buttons: zt ? ['zoomIn', 'zoomOut', 'reset', 'download'] : ['download'] };
187
+ if (hc.navigator?.enabled) options.plugins.navigator = { enabled: true, height: hc.navigator.height ?? 40 };
188
+ if (hc.rangeSelector?.enabled !== false && hc.rangeSelector) options.plugins.rangeSelector = { enabled: true, ...(hc.rangeSelector.buttons ? { buttons: hc.rangeSelector.buttons.map((b) => ({ type: b.type, count: b.count, text: b.text })) } : {}), ...(hc.rangeSelector.selected != null ? { selected: hc.rangeSelector.selected } : {}) };
189
+ if (hc.drilldown?.series) options.drilldown = { series: hc.drilldown.series.map((s) => ({ ...s, type: s.type ? hcSeriesType(s, chartType, polar, hc) : undefined })) };
190
+ if (hc.colorAxis) { const ca = arr(hc.colorAxis)[0]; options.colorAxis = { min: ca.min, max: ca.max, stops: ca.stops, minColor: ca.minColor, maxColor: ca.maxColor, dataClasses: ca.dataClasses, type: ca.type, reversed: ca.reversed }; }
191
+ if (hc.annotations) {
192
+ const list = [];
193
+ for (const a of arr(hc.annotations)) {
194
+ for (const l of a.labels ?? []) list.push({ type: 'label', xValue: l.point?.x, yValue: l.point?.y, content: l.text, backgroundColor: a.labelOptions?.backgroundColor ?? 'rgba(255,255,255,0.85)', borderColor: a.labelOptions?.borderColor ?? '#999', position: 'top', yAdjust: -6 });
195
+ for (const sh of a.shapes ?? []) if (sh.type === 'circle' && sh.point) list.push({ type: 'point', xValue: sh.point.x, yValue: sh.point.y, radius: sh.r ?? 6, backgroundColor: sh.fill ?? 'transparent', borderColor: sh.stroke ?? '#e0793a', borderWidth: sh.strokeWidth ?? 2 });
196
+ }
197
+ options.plugins.annotation = { annotations: list };
198
+ }
199
+ if (hc.responsive?.rules) options.responsive = { rules: hc.responsive.rules.map((r) => ({ condition: r.condition, chartOptions: fromHighcharts({ ...r.chartOptions, chart: { type: chartType, ...(r.chartOptions?.chart ?? {}) } }).options })) };
200
+ if (ch.animation === false || sAll.animation === false) options.animation = false;
201
+ if (sAll.point?.events?.click || sAll.events?.click) { const f = sAll.point?.events?.click ?? sAll.events?.click; options.onClick = (e, els, chart) => { if (els[0]) f.call({ x: els[0].index, y: chart.getDatasetMeta(els[0].datasetIndex).parsed[els[0].index]?.value, category: chart.data.labels?.[els[0].index], series: { name: chart.data.datasets[els[0].datasetIndex].label } }, e); }; }
202
+ if (labelsFromNames.length && !labels) { if (options.scales?.x) options.scales.x.type = options.scales.x.type ?? 'category'; }
203
+ const data = { datasets };
204
+ if (labels) data.labels = labels; else if (labelsFromNames.length) data.labels = labelsFromNames;
205
+ // a heatmap's rows go up from the bottom unless reversed (the opposite of how this package writes it)
206
+ if (type === 'heatmap') { if (labels) data.labels = labels; options.scales = { ...(options.scales ?? {}), y: { ...(options.scales?.y ?? {}), ...(yAxes[0]?.categories ? { labels: yAxes[0].categories } : {}), reverse: !yAxes[0]?.reversed } }; }
207
+ return { type, data, options };
208
+ }
209
+
210
+ /** A Highcharts chart's handle: its series and axes, update(), redraw(), destroy() and the rest, on a Chart. */
211
+ class HighchartsChart {
212
+ constructor(el, options, cb) {
213
+ const host = target(el);
214
+ if (!host) throw new Error('[clarity-charts] Highcharts.chart(el, options): no such element');
215
+ const cfg = fromHighcharts(options);
216
+ if (sizeOf(host, options.chart?.height)) cfg.options.maintainAspectRatio = false;
217
+ this.container = host; this.options = options;
218
+ this.chart = new Chart(host, cfg);
219
+ cb?.call(this, this);
220
+ }
221
+ get series() {
222
+ const c = this.chart;
223
+ return c.data.datasets.map((ds, i) => ({
224
+ name: ds.label, index: i, get visible() { return c.isDatasetVisible(i); }, get data() { return ds.data; },
225
+ setData: (data, redraw = true) => { ds.data = data; if (redraw) c.update(); },
226
+ addPoint: (point, redraw = true, shift = false) => { if (redraw) c.addPoint(i, point, { shift }); else { ds.data.push(point); if (shift) ds.data.shift(); } },
227
+ setVisible: (v = !c.isDatasetVisible(i)) => { c.setDatasetVisibility(i, v); c.update(); }, hide: () => c.hide(i), show: () => c.show(i),
228
+ update: (o) => { Object.assign(ds, fromHighcharts({ ...this.options, series: [{ ...this.options.series?.[i], ...o }] }).data.datasets[0]); c.update(); },
229
+ remove: () => { c.data.datasets.splice(i, 1); c.update(); },
230
+ }));
231
+ }
232
+ axis(id) { const c = this.chart; return { setExtremes: (min, max) => (min == null && max == null ? c.resetView() : c.setView(id, min, max)), getExtremes: () => { const v = c.getView(id); return v && { min: v.min, max: v.max, dataMin: v.dataMin, dataMax: v.dataMax }; } }; }
233
+ get xAxis() { return Object.keys(this.chart.scales).filter((k) => k.startsWith('x')).map((k) => this.axis(k)); }
234
+ get yAxis() { return Object.keys(this.chart.scales).filter((k) => k.startsWith('y')).map((k) => this.axis(k)); }
235
+ addSeries(s, redraw = true) { const ds = fromHighcharts({ ...this.options, series: [s] }).data.datasets[0]; this.chart.data.datasets.push(ds); if (redraw) this.chart.update(); }
236
+ update(o, redraw = true) { this.options = merge(this.options, o); const cfg = fromHighcharts(this.options); this.chart.config.type = cfg.type; this.chart.data = cfg.data; this.chart.options = cfg.options; if (redraw) this.chart.update(); }
237
+ setTitle(title, subtitle) { this.update({ ...(title ? { title } : {}), ...(subtitle ? { subtitle } : {}) }); }
238
+ redraw() { this.chart.update(); }
239
+ reflow() { this.chart.resize(); }
240
+ setSize(w, h) { this.chart.resize(w, h); }
241
+ getCSV() { return this.chart.toCSV(); }
242
+ getSVG() { return this.chart.toSVG(); }
243
+ exportChart({ type = 'image/png', filename = 'chart' } = {}) { return this.chart.download(type.includes('svg') ? 'svg' : type.includes('jpeg') ? 'jpeg' : 'png', filename); }
244
+ sonify(o) { return this.chart.sonify(o); }
245
+ destroy() { this.chart.destroy(); }
246
+ }
247
+ /** Highcharts's way in: Highcharts.chart(el, options), .stockChart(), .setOptions(), .getOptions(). */
248
+ export const Highcharts = {
249
+ chart: (el, options, cb) => new HighchartsChart(el, options, cb),
250
+ ganttChart: (el, options, cb) => new HighchartsChart(el, merge({ chart: { type: 'gantt' }, legend: { enabled: false } }, options), cb),
251
+ mapChart: (el, options, cb) => new HighchartsChart(el, merge({ chart: { type: 'map' } }, options), cb),
252
+ stockChart: (el, options, cb) => new HighchartsChart(el, merge({ navigator: { enabled: true }, rangeSelector: { enabled: true, selected: 1 }, xAxis: { type: 'datetime' }, tooltip: { shared: true } }, options), cb),
253
+ setOptions(o) { hcDefaults = merge(hcDefaults, o); return hcDefaults; },
254
+ getOptions: () => hcDefaults,
255
+ dateFormat: (pattern, t) => new Date(t).toISOString(),
256
+ charts: [],
257
+ };
258
+
259
+ // ── ApexCharts ──────────────────────────────────────────────────────────────────────────────────
260
+ const APEX_TYPES = { line: 'line', area: 'line', bar: 'bar', pie: 'pie', donut: 'doughnut', radialBar: 'radialBar', polarArea: 'polarArea', radar: 'radar', scatter: 'scatter', bubble: 'bubble', heatmap: 'heatmap', treemap: 'treemap', candlestick: 'candlestick', boxPlot: 'boxplot', rangeBar: 'timeline', rangeArea: 'areaRange' };
261
+ const APEX_PATTERNS = { verticalLines: 'vertical', horizontalLines: 'horizontal', slantedLines: 'diagonal', squares: 'grid', circles: 'dots' };
262
+ const apexCallback = (fn) => (typeof fn === 'function' ? function (v) { return fn(this.type === 'category' ? this.labels[v] ?? v : v); } : undefined);
263
+ function apexAxis(a, horizontal) {
264
+ if (!a) return {};
265
+ const o = {};
266
+ if (a.type === 'datetime') o.type = 'time'; else if (a.type === 'numeric') o.type = 'linear'; else if (a.logarithmic) o.type = 'logarithmic';
267
+ if (a.title?.text) o.title = { display: true, text: a.title.text };
268
+ if (a.min != null) o.min = a.min; if (a.max != null) o.max = a.max;
269
+ if (a.reversed) o.reverse = true;
270
+ if (a.opposite) o.position = horizontal ? 'top' : 'right';
271
+ if (a.show === false) o.display = false;
272
+ if (a.labels?.show === false) o.ticks = { display: false }; else if (a.labels?.formatter) o.ticks = { callback: apexCallback(a.labels.formatter) };
273
+ if (a.tickAmount) o.ticks = { ...(o.ticks ?? {}), count: a.tickAmount + 1 };
274
+ if (a.decimalsInFloat != null) o.ticks = { ...(o.ticks ?? {}), precision: a.decimalsInFloat };
275
+ return o;
276
+ }
277
+ function apexType(t, o) { if (t === 'bar' && o.plotOptions?.bar?.isFunnel) return 'funnel'; return APEX_TYPES[t] ?? t; }
278
+ /** ApexCharts options → this package's configuration. */
279
+ export function fromApex(ax = {}) {
280
+ const ch = ax.chart ?? {}, t0 = ch.type ?? 'line', type = apexType(t0, ax), po = ax.plotOptions ?? {}, options = { plugins: {} }, scales = {};
281
+ const round = ['pie', 'doughnut', 'radialBar', 'polarArea'].includes(type);
282
+ const horizontal = !!po.bar?.horizontal;
283
+ let data;
284
+ const strokeW = (k) => (Array.isArray(ax.stroke?.width) ? ax.stroke.width[k] : ax.stroke?.width);
285
+ const curve = (k) => (Array.isArray(ax.stroke?.curve) ? ax.stroke.curve[k] : ax.stroke?.curve);
286
+ if (round || type === 'funnel') {
287
+ const values = type === 'funnel' ? arr(ax.series[0]?.data) : arr(ax.series);
288
+ data = { labels: ax.labels ?? ax.xaxis?.categories ?? (type === 'funnel' ? values.map((d, i) => (isObj(d) ? d.x : ax.xaxis?.categories?.[i])) : undefined), datasets: [{ data: values.map((d) => (isObj(d) ? d.y : d)), ...(ax.colors ? { backgroundColor: ax.colors } : {}), ...(type === 'funnel' ? { shape: 'bars', label: ax.series[0]?.name } : {}) }] };
289
+ if (type === 'doughnut' && po.pie?.donut?.size) data.datasets[0].cutout = po.pie.donut.size;
290
+ if (po.pie?.startAngle != null) { data.datasets[0].rotation = po.pie.startAngle; if (po.pie.endAngle != null) data.datasets[0].circumference = po.pie.endAngle - po.pie.startAngle; }
291
+ if (type === 'radialBar') { const r = po.radialBar ?? {}; Object.assign(data.datasets[0], { startAngle: r.startAngle ?? 0, endAngle: r.endAngle ?? 360, ...(r.hollow?.size ? { hollow: r.hollow.size } : {}), ...(r.track?.background ? { track: { background: r.track.background } } : {}), ...(r.dataLabels?.total?.show ? { total: { label: r.dataLabels.total.label ?? 'Total' } } : {}) }); }
292
+ } else {
293
+ const cats = ax.xaxis?.categories ?? ax.labels;
294
+ const datasets = arr(ax.series).map((s, k) => {
295
+ const st = s.type ? apexType(s.type, ax) : type, ds = { label: s.name ?? `Series ${k + 1}` };
296
+ if (st !== type) ds.type = st;
297
+ let d = arr(s.data);
298
+ if (st === 'bubble') d = d.map((p) => (Array.isArray(p) ? { x: p[0], y: p[1], r: p[2] } : isObj(p) ? { x: p.x, y: p.y, r: p.z } : p));
299
+ if (st === 'treemap') d = d.map((p) => (isObj(p) ? { name: p.x, value: p.y, ...(p.fillColor ? { color: p.fillColor } : {}) } : p));
300
+ if (st === 'timeline' && !horizontal && t0 === 'rangeBar') { ds.type = 'bar'; data = data ?? { labels: d.map((p) => (isObj(p) ? p.x : undefined)) }; d = d.map((p) => (isObj(p) && Array.isArray(p.y) ? [p.y[0], p.y[1]] : p)); }
301
+ if (['line', 'bar', 'scatter'].includes(st) && d.length && isObj(d[0]) && typeof d[0].x === 'string' && !cats && ax.xaxis?.type !== 'datetime') { data = data ?? { labels: d.map((p) => p.x) }; d = d.map((p) => p.y); }
302
+ ds.data = d;
303
+ const c = s.color ?? ax.colors?.[k];
304
+ if (c && !po.bar?.distributed) { ds.borderColor = c; ds.backgroundColor = st === 'line' && (s.type ?? t0) === 'area' ? fill(c, ax.fill?.opacity ?? 0.35) : st === 'line' ? c : fill(c, ax.fill?.opacity ?? 1); }
305
+ if ((s.type ?? t0) === 'area') ds.fill = ch.stacked ? (k ? '-1' : 'origin') : 'origin';
306
+ const cv = curve(k);
307
+ if (cv === 'smooth') ds.tension = 0.4; else if (cv === 'stepline') ds.stepped = true; else if (cv === 'monotoneCubic') ds.cubicInterpolationMode = 'monotone';
308
+ if (strokeW(k) != null) ds.borderWidth = strokeW(k);
309
+ const da = Array.isArray(ax.stroke?.dashArray) ? ax.stroke.dashArray[k] : ax.stroke?.dashArray;
310
+ if (da) ds.borderDash = [da, da];
311
+ if (ax.markers?.size != null) ds.pointRadius = Array.isArray(ax.markers.size) ? ax.markers.size[k] : ax.markers.size; else if (st === 'line') ds.pointRadius = 0;
312
+ if (ax.fill?.type === 'gradient' || (Array.isArray(ax.fill?.type) && ax.fill.type[k] === 'gradient')) { const base = c ?? ['#3d7dd8', '#e0793a', '#2a9d8f', '#c94f7c'][k % 4], g = ax.fill.gradient ?? {}; ds.backgroundColor = { type: 'linear', angle: g.type === 'horizontal' ? 0 : 90, stops: [[0, fill(base, g.opacityFrom ?? 0.6)], [1, fill(base, g.opacityTo ?? 0.05)]] }; }
313
+ if (ax.fill?.type === 'pattern') ds.backgroundColor = { pattern: APEX_PATTERNS[arr(ax.fill.pattern?.style)[k % Math.max(1, arr(ax.fill.pattern?.style).length)]] ?? 'diagonal', color: c ?? '#3d7dd8' };
314
+ if (s.group) ds.stack = s.group;
315
+ if (st === 'candlestick' && po.candlestick?.colors) { ds.upColor = po.candlestick.colors.upward; ds.downColor = po.candlestick.colors.downward; delete ds.backgroundColor; delete ds.borderColor; }
316
+ if (st === 'boxplot' && po.boxPlot?.colors) { ds.backgroundColor = po.boxPlot.colors.upper; }
317
+ if (st === 'heatmap') ds.spacing = 2;
318
+ if (st === 'timeline' && po.bar?.distributed) ds.distributed = true;
319
+ if (po.bar?.distributed && st === 'bar') ds.backgroundColor = ax.colors ?? undefined;
320
+ if (po.bar?.borderRadius) ds.borderRadius = po.bar.borderRadius;
321
+ if (po.bar?.columnWidth && pctOf(po.bar.columnWidth)) { ds.barPercentage = 1; ds.categoryPercentage = pctOf(po.bar.columnWidth); }
322
+ if (po.bar?.barHeight && pctOf(po.bar.barHeight)) { ds.barPercentage = 1; ds.categoryPercentage = pctOf(po.bar.barHeight); }
323
+ return ds;
324
+ });
325
+ data = { ...(data ?? {}), datasets };
326
+ if (cats && !data.labels) data.labels = cats;
327
+ }
328
+ if (horizontal && type !== 'timeline') options.indexAxis = 'y';
329
+ // axes
330
+ const xa = apexAxis(ax.xaxis, !horizontal), ya = arr(ax.yaxis);
331
+ if (Object.keys(xa).length) scales[horizontal ? 'y' : 'x'] = xa;
332
+ ya.forEach((y, k) => { const o = apexAxis(y, !!horizontal); if (!Object.keys(o).length) return; scales[k ? `y${k}` : horizontal ? 'x' : 'y'] = o; });
333
+ if (ya.length > 1) ya.forEach((y, k) => { if (y.seriesName) { const ds = data.datasets.find((d) => d.label === y.seriesName); if (ds && k) ds.yAxisID = `y${k}`; } else if (k && data.datasets[k]) data.datasets[k].yAxisID = `y${k}`; });
334
+ if (ch.stacked) { const i = horizontal ? 'y' : 'x', v = horizontal ? 'x' : 'y'; scales[i] = { ...(scales[i] ?? {}), stacked: true }; scales[v] = { ...(scales[v] ?? {}), stacked: ch.stackType === '100%' ? 'percent' : true }; }
335
+ if (ax.grid?.show === false) for (const k of ['x', 'y']) scales[k] = { ...(scales[k] ?? {}), grid: { display: false } };
336
+ else if (ax.grid?.borderColor) for (const k of ['x', 'y']) scales[k] = { ...(scales[k] ?? {}), grid: { color: ax.grid.borderColor } };
337
+ if (ax.grid?.xaxis?.lines?.show === false) scales.x = { ...(scales.x ?? {}), grid: { display: false } };
338
+ if (Object.keys(scales).length && !round && !['treemap'].includes(type)) options.scales = scales;
339
+ // the rest
340
+ if (ax.title?.text) options.plugins.title = { display: true, text: ax.title.text, align: ax.title.align === 'left' ? 'start' : ax.title.align === 'right' ? 'end' : 'center' };
341
+ if (ax.subtitle?.text) options.plugins.subtitle = { display: true, text: ax.subtitle.text };
342
+ options.plugins.legend = { display: ax.legend?.show ?? (round || data.datasets.length > 1), position: ax.legend?.position ?? (round ? 'right' : 'bottom'), align: ax.legend?.horizontalAlign === 'left' ? 'start' : ax.legend?.horizontalAlign === 'right' ? 'end' : 'center' };
343
+ if (ax.colors) options.plugins.colors = { palette: ax.colors };
344
+ // as ApexCharts: labels on bars, cells and slices unless turned off; on lines only when asked for
345
+ if (ax.dataLabels?.enabled ?? ['bar', 'heatmap', 'pie', 'doughnut', 'polarArea', 'funnel'].includes(type)) options.plugins.datalabels = { display: true, ...(round ? { percent: true } : {}), ...(ax.dataLabels?.formatter ? { formatter: (v, c) => ax.dataLabels.formatter(v, { seriesIndex: c.datasetIndex, dataPointIndex: c.dataIndex, w: { config: ax } }) } : {}), ...(ax.dataLabels?.style?.colors ? { color: ax.dataLabels.style.colors[0] } : {}) };
346
+ if (ax.tooltip?.enabled === false) options.plugins.tooltip = { enabled: false };
347
+ else {
348
+ if (ax.tooltip?.shared !== false && ['line', 'area', 'bar'].includes(t0) && !horizontal) options.interaction = { mode: 'index', intersect: false };
349
+ const yf = ax.tooltip?.y?.formatter;
350
+ if (yf) options.plugins.tooltip = { callbacks: { label: (c) => `${c.dataset.label ? c.dataset.label + ': ' : ''}${yf(c.parsed.y, { seriesIndex: c.datasetIndex, dataPointIndex: c.dataIndex })}` } };
351
+ if (ax.tooltip?.x?.format && options.scales?.x?.type === 'time') options.scales.x.time = { tooltipFormat: ax.tooltip.x.format.replace(/yy\b/g, 'yyyy').replace(/dd MMM/, 'd MMM') };
352
+ }
353
+ if (ax.theme) options.theme = { mode: ax.theme.mode ?? 'light', ...(ax.theme.palette ? { palette: ax.theme.palette } : {}), ...(ax.theme.monochrome ? { monochrome: ax.theme.monochrome } : {}) };
354
+ if (ch.background && ch.background !== 'transparent') options.background = ch.background;
355
+ if (ch.foreColor) options.color = ch.foreColor;
356
+ if (ch.fontFamily) options.font = { family: ch.fontFamily };
357
+ if (ch.animations?.enabled === false) options.animation = false;
358
+ if (ch.sparkline?.enabled) options.sparkline = true;
359
+ if (ch.group) options.group = ch.group;
360
+ if (ch.id) options.id = ch.id;
361
+ const timeX = ax.xaxis?.type === 'datetime' || ax.xaxis?.type === 'numeric';
362
+ const zoomOn = ch.zoom?.enabled ?? (timeX && ['line', 'area', 'bar', 'candlestick', 'scatter', 'bubble', 'rangeArea'].includes(t0));
363
+ if (zoomOn && !ch.brush?.enabled) options.plugins.zoom = { zoom: { drag: { enabled: true }, wheel: { enabled: !!ch.zoom?.allowMouseWheelZoom }, mode: ch.zoom?.type ?? 'x' }, pan: { enabled: true, mode: ch.zoom?.type ?? 'x' } };
364
+ const showTools = ch.toolbar?.show ?? (!round && !ch.sparkline?.enabled && !ch.brush?.enabled);
365
+ if (showTools) options.plugins.toolbar = { display: true, buttons: zoomOn ? ['zoomIn', 'zoomOut', 'pan', 'reset', 'download'] : ['download'] };
366
+ if (ch.brush?.enabled) options.plugins.brush = { enabled: true, target: ch.brush.target, ...(ch.selection?.xaxis ? { selection: { min: ch.selection.xaxis.min, max: ch.selection.xaxis.max } } : {}) };
367
+ if (type === 'heatmap' && po.heatmap?.colorScale) { const cs = po.heatmap.colorScale; options.colorAxis = { ...(cs.ranges?.length ? { dataClasses: cs.ranges.map((r) => ({ from: r.from, to: r.to, color: r.color, name: r.name })) } : {}), ...(cs.min != null ? { min: cs.min } : {}), ...(cs.max != null ? { max: cs.max } : {}), ...(cs.inverse ? { reversed: true } : {}) }; }
368
+ if (ax.annotations) {
369
+ const list = [], A = ax.annotations;
370
+ for (const y of A.yaxis ?? []) list.push(y.y2 != null ? { type: 'box', yMin: y.y, yMax: y.y2, backgroundColor: fill(y.fillColor ?? '#3d7dd8', y.opacity ?? 0.15), label: y.label?.text ? { display: true, content: y.label.text, color: y.label.style?.color, backgroundColor: y.label.style?.background } : undefined } : { type: 'line', scaleID: horizontal ? 'x' : 'y', value: y.y, borderColor: y.borderColor ?? '#e0793a', borderDash: y.strokeDashArray ? [y.strokeDashArray, y.strokeDashArray] : undefined, label: y.label?.text ? { display: true, content: y.label.text, position: 'end', color: y.label.style?.color ?? '#fff', backgroundColor: y.label.style?.background ?? y.borderColor ?? '#e0793a' } : undefined });
371
+ for (const x of A.xaxis ?? []) list.push(x.x2 != null ? { type: 'box', xMin: x.x, xMax: x.x2, backgroundColor: fill(x.fillColor ?? '#3d7dd8', x.opacity ?? 0.15), label: x.label?.text ? { display: true, content: x.label.text } : undefined } : { type: 'line', scaleID: horizontal ? 'y' : 'x', value: x.x, borderColor: x.borderColor ?? '#e0793a', label: x.label?.text ? { display: true, content: x.label.text, position: 'end', backgroundColor: x.label.style?.background ?? x.borderColor ?? '#e0793a' } : undefined });
372
+ for (const p of A.points ?? []) list.push({ type: 'point', xValue: p.x, yValue: p.y, radius: p.marker?.size ?? 5, backgroundColor: p.marker?.fillColor ?? '#e0793a', borderColor: p.marker?.strokeColor ?? '#fff', label: p.label?.text ? { display: true, content: p.label.text, backgroundColor: p.label.style?.background ?? '#e0793a' } : undefined });
373
+ options.plugins.annotation = { annotations: list };
374
+ }
375
+ if (ax.responsive) options.responsive = ax.responsive.map((r) => ({ breakpoint: r.breakpoint, options: fromApex({ ...ax, ...r.options, chart: { ...ch, ...(r.options?.chart ?? {}) }, responsive: undefined }).options }));
376
+ if (ch.events?.dataPointSelection || ch.events?.click) { const f = ch.events.dataPointSelection ?? ch.events.click; options.onClick = (e, els) => { if (els[0]) f(e, null, { seriesIndex: els[0].datasetIndex, dataPointIndex: els[0].index, w: { config: ax } }); }; }
377
+ if (ch.events?.zoomed) options.plugins.zoom = merge(options.plugins.zoom ?? {}, { zoom: { onZoomComplete: ({ chart }) => { const v = chart.getView('x'); ch.events.zoomed(null, { xaxis: { min: v.min, max: v.max } }); } } });
378
+ return { type, data, options };
379
+ }
380
+
381
+ /** ApexCharts's way in: new ApexCharts(el, options).render(), and its methods. */
382
+ export class ApexCharts {
383
+ static instances = new Map();
384
+ static getChartByID(id) { return ApexCharts.instances.get(id) ?? null; }
385
+ static exec(id, fn, ...args) { const c = ApexCharts.getChartByID(id); return c?.[fn]?.(...args); }
386
+ constructor(el, options = {}) { this.el = target(el); this.opts = options; this.chart = null; }
387
+ async render() {
388
+ if (!this.el) throw new Error('[clarity-charts] new ApexCharts(el, options): no such element');
389
+ const cfg = fromApex(this.opts);
390
+ if (sizeOf(this.el, this.opts.chart?.height)) cfg.options.maintainAspectRatio = false;
391
+ this.chart = new Chart(this.el, cfg);
392
+ if (this.opts.chart?.id) ApexCharts.instances.set(this.opts.chart.id, this);
393
+ this.opts.chart?.events?.mounted?.(this, { config: this.opts });
394
+ return this;
395
+ }
396
+ _apply(redraw = true) { const cfg = fromApex(this.opts); this.chart.config.type = cfg.type; this.chart.data = cfg.data; this.chart.options = cfg.options; if (redraw) this.chart.update(); }
397
+ async updateOptions(o, redraw = true) { this.opts = merge(this.opts, o); if (o.series) this.opts.series = o.series; this._apply(redraw); return this; }
398
+ async updateSeries(series) { this.opts.series = series; this._apply(); return this; }
399
+ async appendSeries(s) { this.opts.series = [...arr(this.opts.series), s]; this._apply(); return this; }
400
+ async appendData(newData) { arr(newData).forEach((d, k) => { const s = this.opts.series?.[k]; if (s) s.data = [...arr(s.data), ...arr(d.data)]; }); this._apply(); return this; }
401
+ _index(name) { return this.chart.data.datasets.findIndex((d) => d.label === name); }
402
+ toggleSeries(name) { const i = this._index(name); if (i < 0) return; this.chart.setDatasetVisibility(i, !this.chart.isDatasetVisible(i)); this.chart.update(); return this.chart.isDatasetVisible(i); }
403
+ showSeries(name) { const i = this._index(name); if (i >= 0) this.chart.show(i); }
404
+ hideSeries(name) { const i = this._index(name); if (i >= 0) this.chart.hide(i); }
405
+ resetSeries() { this.chart.metas.forEach((m) => { m.hiddenOverride = null; }); this.chart.resetView(); }
406
+ zoomX(min, max) { this.chart.zoom({ x: [min, max] }, 'x'); }
407
+ addXaxisAnnotation(a) { this.opts.annotations = { ...(this.opts.annotations ?? {}), xaxis: [...(this.opts.annotations?.xaxis ?? []), a] }; this._apply(); }
408
+ addYaxisAnnotation(a) { this.opts.annotations = { ...(this.opts.annotations ?? {}), yaxis: [...(this.opts.annotations?.yaxis ?? []), a] }; this._apply(); }
409
+ addPointAnnotation(a) { this.opts.annotations = { ...(this.opts.annotations ?? {}), points: [...(this.opts.annotations?.points ?? []), a] }; this._apply(); }
410
+ clearAnnotations() { this.opts.annotations = {}; this._apply(); }
411
+ async dataURI({ scale = 2 } = {}) { return { imgURI: await this.chart.toImage('image/png', 1, scale) }; }
412
+ exportToCSV({ filename = 'chart' } = {}) { return this.chart.download('csv', filename); }
413
+ destroy() { this.chart?.destroy(); if (this.opts.chart?.id) ApexCharts.instances.delete(this.opts.chart.id); }
414
+ }
@@ -0,0 +1,111 @@
1
+ // @clarity-js/charts — charts in markup. <Chart type data options /> takes Chart.js's
2
+ // configuration as state: change it and the chart moves to the new values. The shorter components
3
+ // (<LineChart>, <BarChart> …) take rows and the names of their fields and make that configuration.
4
+ //
5
+ // <Chart type="line" data={ { labels, datasets: [{ label: 'Sales', data: sales }] } } options={ { plugins: { title: { display: true, text: 'Sales' } } } } />
6
+ // <LineChart data={ months } x="month" y={ ["sales", "costs"] } title="Sales and costs" />
7
+
8
+ import { _component, effect, untrack, isReactive, onDispose } from '@ozsarman/clarityjs/runtime';
9
+ import { Chart as Core, merge } from './core.js';
10
+ import { bins as binsOf } from './shape.js';
11
+ import { formatNumber } from './format.js';
12
+
13
+ const read = (v) => (isReactive(v) ? v.get() : typeof v === 'function' && v.length === 0 ? v() : v);
14
+ const callback = (v) => { if (isReactive(v)) v = v.peek(); return typeof v === 'function' ? v : null; };
15
+ const field = (f) => (typeof f === 'function' ? f : (row) => (row == null ? undefined : row[f]));
16
+
17
+ /** <Chart type="bar" data={ … } options={ … } plugins={ [ … ] } height={ 320 } renderer="svg | canvas" onCreated={ (chart) => … } /> */
18
+ export function ChartView(props = {}) {
19
+ return _component(() => {
20
+ const host = document.createElement('div');
21
+ host.className = 'clarity-chart' + (props.class ? ' ' + read(props.class) : '');
22
+ host.style.position = 'relative'; host.style.width = '100%';
23
+ let chart = null;
24
+ effect(() => {
25
+ const height = read(props.height), width = read(props.width);
26
+ const cfg = { type: read(props.type) ?? 'bar', data: read(props.data) ?? { datasets: [] }, options: read(props.options) ?? {}, plugins: read(props.plugins) ?? [] };
27
+ untrack(() => {
28
+ if (height) host.style.height = typeof height === 'number' ? height + 'px' : height;
29
+ if (width) host.style.width = typeof width === 'number' ? width + 'px' : width;
30
+ const options = height ? merge(cfg.options, { maintainAspectRatio: false }) : cfg.options;
31
+ const renderer = read(props.renderer);
32
+ if (renderer) options.renderer = renderer;
33
+ if (!chart || chart.type !== cfg.type || (renderer && (renderer === 'canvas') !== !!chart.canvas)) {
34
+ chart?.destroy();
35
+ chart = new Core(host, { ...cfg, options });
36
+ callback(props.onCreated)?.(chart);
37
+ if (props.ref && typeof props.ref === 'object' && 'current' in props.ref) props.ref.current = chart;
38
+ else if (typeof props.ref === 'function') props.ref(chart);
39
+ } else { chart.data = cfg.data; chart.options = options; chart.update(read(props.updateMode)); }
40
+ });
41
+ });
42
+ onDispose(() => chart?.destroy());
43
+ return host;
44
+ }, 'Chart');
45
+ }
46
+
47
+ // ── the short ones ─────────────────────────────────────────────────────────────
48
+ const keysOf = (y) => (Array.isArray(y) ? y : [y ?? 'y']);
49
+ function common(props, extra = {}) {
50
+ const title = read(props.title), yFormat = callback(props.yFormat), xFormat = callback(props.xFormat), onSelect = callback(props.onSelect);
51
+ return merge({
52
+ plugins: { title: { display: !!title, text: title ?? '' }, tooltip: yFormat ? { callbacks: { label: (c) => `${c.dataset.label ? c.dataset.label + ': ' : ''}${yFormat(c.parsed.y)}` } } : {} },
53
+ scales: { y: yFormat ? { ticks: { callback: (v) => yFormat(v) } } : {}, x: xFormat ? { ticks: { callback(v, i) { return xFormat(this.type === 'category' ? (this.labels[v] ?? v) : v, i); } } } : {} },
54
+ onClick: onSelect ? (e, els) => { if (els[0]) { const rows = read(props.data) ?? []; onSelect(rows[els[0].index], els[0].index); } } : undefined,
55
+ }, extra, read(props.options) ?? {});
56
+ }
57
+ function series(props, make) {
58
+ const rows = read(props.data) ?? [], labels = read(props.labels) ?? {}, colors = read(props.colors);
59
+ return keysOf(read(props.y)).map((k, i) => ({ label: labels[k] ?? (typeof k === 'string' ? k : `Series ${i + 1}`), data: rows.map((r) => field(k)(r)), ...(colors ? { borderColor: colors[i % colors.length], backgroundColor: colors[i % colors.length] } : {}), ...make(k, i) }));
60
+ }
61
+ function short(type, props, build) {
62
+ return ChartView({
63
+ ...props,
64
+ type: () => (typeof type === 'function' ? type() : type),
65
+ data: () => build.data(),
66
+ options: () => build.options(),
67
+ });
68
+ }
69
+ const curveOf = (c) => (c === 'monotone' ? { cubicInterpolationMode: 'monotone' } : c === 'step' ? { stepped: 'middle' } : c === 'smooth' ? { tension: 0.35 } : {});
70
+
71
+ /** <LineChart data x y={ key | [keys] } curve="linear | smooth | monotone | step" area dots stacked title yFormat xFormat onSelect /> */
72
+ export const LineChart = (props = {}) => short('line', props, {
73
+ data: () => { const rows = read(props.data) ?? [], many = rows.length > 40, area = !!read(props.area), stacked = !!read(props.stacked), dots = read(props.dots);
74
+ return { labels: rows.map(field(read(props.x) ?? 'x')), datasets: series(props, (k, i) => ({ ...curveOf(read(props.curve)), fill: area ? (stacked && i ? '-1' : 'origin') : false, pointRadius: dots === false || (dots == null && many) ? 0 : 3, borderWidth: 2 })) }; },
75
+ options: () => common(props, { scales: { y: { stacked: !!read(props.stacked), beginAtZero: !!read(props.zero) } }, plugins: { legend: { display: keysOf(read(props.y)).length > 1 } } }),
76
+ });
77
+ /** <AreaChart data x y stacked /> */
78
+ export const AreaChart = (props = {}) => LineChart({ ...props, area: true });
79
+ /** <BarChart data x y={ key | [keys] } stacked horizontal /> */
80
+ export const BarChart = (props = {}) => short('bar', props, {
81
+ data: () => { const rows = read(props.data) ?? []; return { labels: rows.map(field(read(props.x) ?? 'x')), datasets: series(props, () => ({ borderRadius: 3 })) }; },
82
+ options: () => { const h = !!read(props.horizontal), st = !!read(props.stacked), yf = callback(props.yFormat);
83
+ return common(props, { indexAxis: h ? 'y' : 'x', scales: { x: { stacked: st, ...(h && yf ? { ticks: { callback: (v) => yf(v) } } : {}) }, y: { stacked: st, ...(h ? { ticks: {} } : {}) } }, plugins: { legend: { display: keysOf(read(props.y)).length > 1 } } }); },
84
+ });
85
+ /** <ScatterChart data x y size /> — size: a field that sets each dot's radius (a bubble chart). */
86
+ export const ScatterChart = (props = {}) => short(() => (read(props.size) ? 'bubble' : 'scatter'), props, {
87
+ data: () => { const rows = read(props.data) ?? [], fx = field(read(props.x) ?? 'x'), size = read(props.size), max = size ? Math.max(1, ...rows.map((r) => Number(field(size)(r)) || 0)) : 1;
88
+ return { datasets: keysOf(read(props.y)).map((k, i) => ({ label: (read(props.labels) ?? {})[k] ?? k, data: rows.map((r) => ({ x: Number(fx(r)), y: Number(field(k)(r)), ...(size ? { r: 3 + 12 * Math.sqrt((Number(field(size)(r)) || 0) / max) } : {}) })), ...(read(props.colors) ? { backgroundColor: read(props.colors)[i] } : {}) })) }; },
89
+ options: () => common(props, { plugins: { legend: { display: keysOf(read(props.y)).length > 1 } } }),
90
+ });
91
+ /** <PieChart data label value donut={ 0 … 0.9 } half /> */
92
+ export const PieChart = (props = {}) => short(() => (Number(read(props.donut)) > 0 ? 'doughnut' : 'pie'), props, {
93
+ data: () => { const rows = read(props.data) ?? []; return { labels: rows.map(field(read(props.label) ?? 'label')), datasets: [{ data: rows.map((r) => Number(field(read(props.value) ?? 'value')(r)) || 0), ...(read(props.colors) ? { backgroundColor: read(props.colors) } : {}) }] }; },
94
+ options: () => { const d = Number(read(props.donut)) || 0, half = !!read(props.half);
95
+ return common(props, { ...(d > 0 ? { cutout: Math.round(d * 100) + '%' } : {}), ...(half ? { circumference: 180, rotation: -90, aspectRatio: 2 } : {}), scales: undefined }); },
96
+ });
97
+ /** <Histogram values={ numbers } bins={ 12 } /> — how many values fall in each of a row of equal ranges. */
98
+ export const Histogram = (props = {}) => short('bar', props, {
99
+ data: () => { const b = binsOf((read(props.values) ?? []).map(Number), Number(read(props.bins)) || 12);
100
+ return { labels: b.map((x) => `${formatNumber(x.x0)}–${formatNumber(x.x1)}`), datasets: [{ label: read(props.label) ?? 'Count', data: b.map((x) => x.count), barPercentage: 1, categoryPercentage: 1, borderWidth: 1, borderColor: 'var(--clarity-chart-bg, #fff)' }] }; },
101
+ options: () => common(props, { plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true, ticks: { precision: 0 } } } }),
102
+ });
103
+ /** <Sparkline values={ numbers } width={ 120 } height={ 32 } /> — a small line beside a number: no axes, no legend. */
104
+ export const Sparkline = (props = {}) => {
105
+ const node = short('line', { ...props, height: () => read(props.height) ?? 32, width: () => read(props.width) ?? 120 }, {
106
+ data: () => { const v = (read(props.values) ?? []).map(Number); return { labels: v.map((_, i) => i), datasets: [{ data: v, borderWidth: 1.5, pointRadius: v.map((_, i) => (i === v.length - 1 ? 2.5 : 0)), cubicInterpolationMode: 'monotone', ...(read(props.color) ? { borderColor: read(props.color), backgroundColor: read(props.color) } : {}) }] }; },
107
+ options: () => merge({ animation: { duration: 400 }, layout: { padding: 3 }, scales: { x: { display: false }, y: { display: false } }, plugins: { legend: { display: false }, tooltip: { enabled: false }, title: { display: false } }, events: [] }, read(props.options) ?? {}),
108
+ });
109
+ node.style.display = 'inline-block'; node.style.verticalAlign = 'middle';
110
+ return node;
111
+ };