@aura-react-comp/charts 0.3.1 → 0.4.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.
Files changed (68) hide show
  1. package/esm/charts/area-chart/index.js +27 -23
  2. package/esm/charts/bar-chart/index.js +17 -21
  3. package/esm/charts/candlestick-chart/index.js +242 -180
  4. package/esm/charts/combo-chart/index.js +8 -20
  5. package/esm/charts/funnel-chart/index.js +133 -108
  6. package/esm/charts/gauge-chart/index.js +102 -105
  7. package/esm/charts/graph-chart/index.js +154 -114
  8. package/esm/charts/heatmap-chart/index.js +179 -135
  9. package/esm/charts/line-chart/index.js +28 -24
  10. package/esm/charts/pie-chart/index.d.ts.map +1 -1
  11. package/esm/charts/pie-chart/index.js +198 -139
  12. package/esm/charts/radar-chart/index.d.ts.map +1 -1
  13. package/esm/charts/radar-chart/index.js +154 -128
  14. package/esm/charts/ring-progress/index.js +81 -82
  15. package/esm/charts/sankey-chart/index.js +171 -141
  16. package/esm/charts/scatter-chart/index.d.ts.map +1 -1
  17. package/esm/charts/scatter-chart/index.js +225 -159
  18. package/esm/charts/sparkline/index.js +81 -66
  19. package/esm/charts/tree-chart/index.js +128 -102
  20. package/esm/charts/treemap-chart/index.js +162 -141
  21. package/esm/charts/waterfall-chart/index.js +165 -121
  22. package/esm/components/Legend.d.ts +3 -2
  23. package/esm/components/Legend.d.ts.map +1 -1
  24. package/esm/components/Legend.js +79 -48
  25. package/esm/components/Tooltip.js +62 -71
  26. package/esm/components/chart/index.d.ts +4 -1
  27. package/esm/components/chart/index.d.ts.map +1 -1
  28. package/esm/components/chart/index.js +80 -102
  29. package/esm/components/chart.less +13 -0
  30. package/esm/core/animation.js +31 -43
  31. package/esm/core/export.d.ts +34 -0
  32. package/esm/core/export.d.ts.map +1 -0
  33. package/esm/core/export.js +390 -0
  34. package/esm/core/force.js +22 -45
  35. package/esm/core/format.js +48 -52
  36. package/esm/core/hierarchy.js +60 -92
  37. package/esm/core/layout.js +32 -50
  38. package/esm/core/sampling.js +30 -53
  39. package/esm/core/sankey.js +35 -55
  40. package/esm/core/scale.js +72 -86
  41. package/esm/core/shape.js +101 -133
  42. package/esm/core/sync.d.ts +41 -0
  43. package/esm/core/sync.d.ts.map +1 -0
  44. package/esm/core/sync.js +120 -0
  45. package/esm/hooks/useChartExport.d.ts +19 -0
  46. package/esm/hooks/useChartExport.d.ts.map +1 -0
  47. package/esm/hooks/useChartExport.js +35 -0
  48. package/esm/hooks/useChartTheme.js +17 -19
  49. package/esm/hooks/useChartTransition.js +58 -73
  50. package/esm/hooks/useElementSize.js +19 -28
  51. package/esm/hooks/usePlotPointer.d.ts +23 -0
  52. package/esm/hooks/usePlotPointer.d.ts.map +1 -0
  53. package/esm/hooks/usePlotPointer.js +94 -0
  54. package/esm/index.d.ts +6 -0
  55. package/esm/index.d.ts.map +1 -1
  56. package/esm/index.js +136 -47
  57. package/esm/internal/CartesianChart.d.ts.map +1 -1
  58. package/esm/internal/CartesianChart.js +666 -485
  59. package/esm/internal/model.js +44 -60
  60. package/esm/scene/canvas.js +100 -107
  61. package/esm/scene/svg.js +106 -99
  62. package/esm/scene/types.js +8 -15
  63. package/esm/style.css +10 -0
  64. package/esm/theme/index.js +143 -171
  65. package/esm/types.d.ts +4 -0
  66. package/esm/types.d.ts.map +1 -1
  67. package/esm/types.js +0 -1
  68. package/package.json +1 -1
@@ -1,6 +1,13 @@
1
1
  'use client';
2
- import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
3
- import { classNames, prefixCls } from '@aura-react-comp/shared';
2
+ // src/internal/CartesianChart.tsx
3
+ import {
4
+ useCallback,
5
+ useEffect,
6
+ useMemo,
7
+ useRef,
8
+ useState
9
+ } from "react";
10
+ import { classNames, prefixCls } from "@aura-react-comp/shared";
4
11
  import { SvgScene } from "../scene/svg";
5
12
  import { paintScene } from "../scene/canvas";
6
13
  import { createBandScale, createLinearScale, linearTicks } from "../core/scale";
@@ -12,24 +19,23 @@ import { withAlpha } from "../theme";
12
19
  import { useChartTheme } from "../hooks/useChartTheme";
13
20
  import { useElementSize } from "../hooks/useElementSize";
14
21
  import { useChartTransition } from "../hooks/useChartTransition";
22
+ import { usePlotPointer } from "../hooks/usePlotPointer";
15
23
  import { resolveAnimation, staggerProgress } from "../core/animation";
16
- import { applyStacking, assignDefaultStack, buildTooltipItems, resolveSeries, resolveXValues, resolveYDomain } from "./model";
24
+ import { useChartSync } from "../core/sync";
25
+ import {
26
+ applyStacking,
27
+ assignDefaultStack,
28
+ buildTooltipItems,
29
+ resolveSeries,
30
+ resolveXValues,
31
+ resolveYDomain
32
+ } from "./model";
17
33
  import { Legend } from "../components/Legend";
18
34
  import { Tooltip } from "../components/Tooltip";
19
-
20
- /** Canvas 切换阈值:超过这个图元数量,SVG 的 DOM 开销会明显拖慢滚动 */
21
- import { jsx as _jsx } from "react/jsx-runtime";
22
- import { jsxs as _jsxs } from "react/jsx-runtime";
23
- const CANVAS_THRESHOLD = 2000;
24
-
25
- /** 单系列默认最大点数:超过后降采样。800 在 1000px 宽的图上约每像素 0.8 个点 */
26
- const DEFAULT_SAMPLING = 800;
27
-
28
- /**
29
- * 无障碍数据表最多渲染多少行。
30
- * 读屏器不会去听 8000 行数据,全量渲染只会让 DOM 白白膨胀。
31
- */
32
- const A11Y_ROW_LIMIT = 200;
35
+ import { jsx, jsxs } from "react/jsx-runtime";
36
+ var CANVAS_THRESHOLD = 2e3;
37
+ var DEFAULT_SAMPLING = 800;
38
+ var A11Y_ROW_LIMIT = 200;
33
39
  function CanvasScene({
34
40
  nodes,
35
41
  width,
@@ -37,35 +43,25 @@ function CanvasScene({
37
43
  }) {
38
44
  const ref = useRef(null);
39
45
  useEffect(() => {
40
- if (ref.current) paintScene(ref.current, nodes, {
41
- dpr: undefined
42
- });
46
+ if (ref.current)
47
+ paintScene(ref.current, nodes, { dpr: void 0 });
43
48
  }, [nodes, width, height]);
44
- return /*#__PURE__*/_jsx("canvas", {
45
- ref: ref,
46
- className: prefixCls('chart__canvas'),
47
- style: {
48
- width,
49
- height
49
+ return /* @__PURE__ */ jsx(
50
+ "canvas",
51
+ {
52
+ ref,
53
+ className: prefixCls("chart__canvas"),
54
+ style: { width, height },
55
+ "aria-hidden": "true"
50
56
  }
51
- // 无障碍由外层的隐藏数据表承担,canvas 本身对读屏器无意义
52
- ,
53
- "aria-hidden": "true"
54
- });
57
+ );
55
58
  }
56
-
57
- /**
58
- * 直角坐标系图表内核。
59
- *
60
- * 折线 / 柱状 / 面积 / 折柱混合全部由它渲染 —— 差异只在 series.type。
61
- * 这样组合图(一个系列折线、一个系列柱子)天然支持,无需额外组件。
62
- */
63
- export function CartesianChart(props) {
59
+ function CartesianChart(props) {
64
60
  const {
65
61
  data = [],
66
- xKey = 'x',
62
+ xKey = "x",
67
63
  series: seriesConfig = [],
68
- width = '100%',
64
+ width = "100%",
69
65
  height = 320,
70
66
  theme: themeInput,
71
67
  palette,
@@ -73,7 +69,7 @@ export function CartesianChart(props) {
73
69
  tooltip = true,
74
70
  grid = true,
75
71
  animation = true,
76
- renderer = 'auto',
72
+ renderer = "auto",
77
73
  xAxis,
78
74
  yAxis,
79
75
  yAxisRight,
@@ -85,40 +81,43 @@ export function CartesianChart(props) {
85
81
  className,
86
82
  style,
87
83
  ariaLabel,
88
- emptyText = '暂无数据',
84
+ emptyText = "暂无数据",
89
85
  onPointClick,
90
86
  valueFormatter,
87
+ syncGroup,
91
88
  defaultType,
92
89
  stack = false
93
90
  } = props;
94
91
  const theme = useChartTheme(themeInput, palette);
95
- const {
96
- ref: plotRef,
97
- size
98
- } = useElementSize();
92
+ const { ref: plotRef, size } = useElementSize();
99
93
  const [hiddenKeys, setHiddenKeys] = useState([]);
100
- const [activeIndex, setActiveIndex] = useState(null);
94
+ const [localActiveIndex, setLocalActiveIndex] = useState(null);
95
+ const {
96
+ synced: syncedPayload,
97
+ emit: emitSync,
98
+ clear: clearSync
99
+ } = useChartSync(syncGroup);
101
100
  const hiddenSet = useMemo(() => new Set(hiddenKeys), [hiddenKeys]);
102
-
103
- // ---- dataZoom 窗口 ----
104
- const [innerZoom, setInnerZoom] = useState(defaultZoom ?? [0, 1]);
101
+ const [innerZoom, setInnerZoom] = useState(
102
+ defaultZoom ?? [0, 1]
103
+ );
105
104
  const zoomRange = zoom ?? innerZoom;
106
- const zoomEnabled = dataZoom !== undefined && dataZoom !== false;
107
- const zoomOptions = typeof dataZoom === 'object' ? dataZoom : {};
105
+ const zoomEnabled = dataZoom !== void 0 && dataZoom !== false;
106
+ const zoomOptions = typeof dataZoom === "object" ? dataZoom : {};
108
107
  const allXValues = useMemo(() => resolveXValues(data, xKey), [data, xKey]);
109
108
  const windowed = useMemo(() => {
110
109
  const total = allXValues.length;
111
110
  if (!zoomEnabled || total <= 1) {
112
- return {
113
- data,
114
- xValues: allXValues,
115
- from: 0,
116
- to: Math.max(0, total - 1)
117
- };
111
+ return { data, xValues: allXValues, from: 0, to: Math.max(0, total - 1) };
118
112
  }
119
- const from = Math.min(total - 1, Math.max(0, Math.floor(zoomRange[0] * (total - 1))));
120
- // 至少保留两个点,否则折线没有意义
121
- const to = Math.min(total - 1, Math.max(from + 1, Math.ceil(zoomRange[1] * (total - 1))));
113
+ const from = Math.min(
114
+ total - 1,
115
+ Math.max(0, Math.floor(zoomRange[0] * (total - 1)))
116
+ );
117
+ const to = Math.min(
118
+ total - 1,
119
+ Math.max(from + 1, Math.ceil(zoomRange[1] * (total - 1)))
120
+ );
122
121
  return {
123
122
  data: data.slice(from, to + 1),
124
123
  xValues: allXValues.slice(from, to + 1),
@@ -126,37 +125,44 @@ export function CartesianChart(props) {
126
125
  to
127
126
  };
128
127
  }, [data, allXValues, zoomEnabled, zoomRange]);
129
-
130
- /**
131
- * 降采样:只对窗口内的点做,且多系列共用同一套下标
132
- * (各自采样会让折线错位,看起来像两列数据互相穿插)。
133
- */
134
128
  const sampledIndices = useMemo(() => {
135
129
  const threshold = sampling === false ? 0 : sampling ?? DEFAULT_SAMPLING;
136
130
  const total = windowed.xValues.length;
137
- if (!threshold || total <= threshold) return null;
138
- const matrix = seriesConfig.map(config => windowed.data.map(row => {
139
- const raw = row[config.key];
140
- return typeof raw === 'number' && Number.isFinite(raw) ? raw : null;
141
- }));
142
- return sampleSeriesIndices(matrix, threshold);
131
+ if (!threshold || total <= threshold)
132
+ return null;
133
+ const matrix2 = seriesConfig.map(
134
+ (config) => windowed.data.map((row) => {
135
+ const raw = row[config.key];
136
+ return typeof raw === "number" && Number.isFinite(raw) ? raw : null;
137
+ })
138
+ );
139
+ return sampleSeriesIndices(matrix2, threshold);
143
140
  }, [windowed, seriesConfig, sampling]);
144
- const viewData = useMemo(() => sampledIndices ? sampledIndices.map(index => windowed.data[index]) : windowed.data, [sampledIndices, windowed.data]);
145
- const xValues = useMemo(() => sampledIndices ? sampledIndices.map(index => windowed.xValues[index]) : windowed.xValues, [sampledIndices, windowed.xValues]);
146
- const applyZoom = useCallback(next => {
147
- const start = Math.max(0, Math.min(1, next[0]));
148
- const end = Math.max(0, Math.min(1, next[1]));
149
- // 最小窗口 2%,再窄就只剩一两个点,窗口本身也抓不住
150
- if (end - start < 0.02) return;
151
- if (!zoom) setInnerZoom([start, end]);
152
- onZoomChange?.([start, end]);
153
- }, [zoom, onZoomChange]);
141
+ const viewData = useMemo(
142
+ () => sampledIndices ? sampledIndices.map((index) => windowed.data[index]) : windowed.data,
143
+ [sampledIndices, windowed.data]
144
+ );
145
+ const xValues = useMemo(
146
+ () => sampledIndices ? sampledIndices.map((index) => windowed.xValues[index]) : windowed.xValues,
147
+ [sampledIndices, windowed.xValues]
148
+ );
149
+ const applyZoom = useCallback(
150
+ (next) => {
151
+ const start = Math.max(0, Math.min(1, next[0]));
152
+ const end = Math.max(0, Math.min(1, next[1]));
153
+ if (end - start < 0.02)
154
+ return;
155
+ if (!zoom)
156
+ setInnerZoom([start, end]);
157
+ onZoomChange == null ? void 0 : onZoomChange([start, end]);
158
+ },
159
+ [zoom, onZoomChange]
160
+ );
154
161
  const zoomTrackRef = useRef(null);
155
162
  const dragRef = useRef(null);
156
- // 拖拽回调里要用最新窗口,放进 ref 避免事件闭包拿到旧值
157
163
  const zoomRef = useRef(zoomRange);
158
164
  zoomRef.current = zoomRange;
159
- const beginDrag = mode => event => {
165
+ const beginDrag = (mode) => (event) => {
160
166
  event.preventDefault();
161
167
  event.stopPropagation();
162
168
  dragRef.current = {
@@ -166,19 +172,21 @@ export function CartesianChart(props) {
166
172
  };
167
173
  };
168
174
  useEffect(() => {
169
- if (!zoomEnabled) return undefined;
170
- const onMove = event => {
175
+ if (!zoomEnabled)
176
+ return void 0;
177
+ const onMove = (event) => {
171
178
  const drag = dragRef.current;
172
179
  const track = zoomTrackRef.current;
173
- if (!drag || !track) return;
174
- const width = track.getBoundingClientRect().width || 1;
175
- const delta = (event.clientX - drag.startX) / width;
180
+ if (!drag || !track)
181
+ return;
182
+ const width2 = track.getBoundingClientRect().width || 1;
183
+ const delta = (event.clientX - drag.startX) / width2;
176
184
  const [from, to] = drag.initial;
177
185
  const span = to - from;
178
- if (drag.mode === 'move') {
186
+ if (drag.mode === "move") {
179
187
  const start = Math.min(1 - span, Math.max(0, from + delta));
180
188
  applyZoom([start, start + span]);
181
- } else if (drag.mode === 'start') {
189
+ } else if (drag.mode === "start") {
182
190
  applyZoom([Math.max(0, Math.min(to - 0.02, from + delta)), to]);
183
191
  } else {
184
192
  applyZoom([from, Math.max(from + 0.02, Math.min(1, to + delta))]);
@@ -187,11 +195,11 @@ export function CartesianChart(props) {
187
195
  const onUp = () => {
188
196
  dragRef.current = null;
189
197
  };
190
- window.addEventListener('pointermove', onMove);
191
- window.addEventListener('pointerup', onUp);
198
+ window.addEventListener("pointermove", onMove);
199
+ window.addEventListener("pointerup", onUp);
192
200
  return () => {
193
- window.removeEventListener('pointermove', onMove);
194
- window.removeEventListener('pointerup', onUp);
201
+ window.removeEventListener("pointermove", onMove);
202
+ window.removeEventListener("pointerup", onUp);
195
203
  };
196
204
  }, [zoomEnabled, applyZoom]);
197
205
  const resolved = useMemo(() => {
@@ -202,132 +210,208 @@ export function CartesianChart(props) {
202
210
  defaultType,
203
211
  hidden: hiddenSet
204
212
  });
205
- if (stack) assignDefaultStack(list, true);
213
+ if (stack)
214
+ assignDefaultStack(list, true);
206
215
  applyStacking(list);
207
216
  return list;
208
217
  }, [viewData, seriesConfig, theme, defaultType, hiddenSet, stack]);
209
- const visibleSeries = useMemo(() => resolved.filter(item => item.visible), [resolved]);
218
+ const visibleSeries = useMemo(
219
+ () => resolved.filter((item) => item.visible),
220
+ [resolved]
221
+ );
210
222
  const hasVisibleSeries = visibleSeries.length > 0;
211
223
  const isEmpty = data.length === 0 || seriesConfig.length === 0;
212
-
213
- /**
214
- * 右轴配置。
215
- * 只有「显式开启 yAxisRight」且「确有系列声明了 yAxisIndex: 1」时才真正启用,
216
- * 否则多留一条空轴只会增加噪声。
217
- */
218
- // 用 useMemo 固定引用:它是 scene 的依赖,条件表达式每次渲染都会产出新对象
219
- const rightConfig = useMemo(() => !yAxisRight ? undefined : yAxisRight === true ? {} : yAxisRight, [yAxisRight]);
220
- const hasRightAxis = useMemo(() => Boolean(rightConfig) && resolved.some(item => item.visible && (item.config.yAxisIndex ?? 0) === 1), [rightConfig, resolved]);
221
-
222
- // 值域:柱状图必须含 0 基线,折线图允许裁剪
223
- const yDomain = useMemo(() => resolveYDomain(resolved, {
224
- startFromZero: yAxis?.startFromZero ?? defaultType === 'bar',
225
- min: yAxis?.min,
226
- max: yAxis?.max,
227
- includeBase: resolved.some(item => Boolean(item.stackId)),
228
- // 有右轴时,左轴只统计属于左轴的系列
229
- yAxisIndex: hasRightAxis ? 0 : undefined
230
- }), [resolved, yAxis?.startFromZero, yAxis?.min, yAxis?.max, defaultType, hasRightAxis]);
231
- const yDomainRight = useMemo(() => hasRightAxis ? resolveYDomain(resolved, {
232
- startFromZero: rightConfig?.startFromZero ?? false,
233
- min: rightConfig?.min,
234
- max: rightConfig?.max,
235
- yAxisIndex: 1
236
- }) : [0, 1], [resolved, hasRightAxis, rightConfig?.startFromZero, rightConfig?.min, rightConfig?.max]);
237
-
238
- // 刻度数量先按估算高度定,再用它算 margin —— 避免「先算布局再算刻度」的循环依赖
224
+ const rightConfig = useMemo(
225
+ () => !yAxisRight ? void 0 : yAxisRight === true ? {} : yAxisRight,
226
+ [yAxisRight]
227
+ );
228
+ const hasRightAxis = useMemo(
229
+ () => Boolean(rightConfig) && resolved.some(
230
+ (item) => item.visible && (item.config.yAxisIndex ?? 0) === 1
231
+ ),
232
+ [rightConfig, resolved]
233
+ );
234
+ const yDomain = useMemo(
235
+ () => resolveYDomain(resolved, {
236
+ startFromZero: (yAxis == null ? void 0 : yAxis.startFromZero) ?? defaultType === "bar",
237
+ min: yAxis == null ? void 0 : yAxis.min,
238
+ max: yAxis == null ? void 0 : yAxis.max,
239
+ includeBase: resolved.some(
240
+ (item) => item.visible && Boolean(item.stackId)
241
+ ),
242
+ // 有右轴时,左轴只统计属于左轴的系列
243
+ yAxisIndex: hasRightAxis ? 0 : void 0
244
+ }),
245
+ [
246
+ resolved,
247
+ yAxis == null ? void 0 : yAxis.startFromZero,
248
+ yAxis == null ? void 0 : yAxis.min,
249
+ yAxis == null ? void 0 : yAxis.max,
250
+ defaultType,
251
+ hasRightAxis
252
+ ]
253
+ );
254
+ const yDomainRight = useMemo(
255
+ () => hasRightAxis ? resolveYDomain(resolved, {
256
+ startFromZero: (rightConfig == null ? void 0 : rightConfig.startFromZero) ?? false,
257
+ min: rightConfig == null ? void 0 : rightConfig.min,
258
+ max: rightConfig == null ? void 0 : rightConfig.max,
259
+ yAxisIndex: 1
260
+ }) : [0, 1],
261
+ [
262
+ resolved,
263
+ hasRightAxis,
264
+ rightConfig == null ? void 0 : rightConfig.startFromZero,
265
+ rightConfig == null ? void 0 : rightConfig.min,
266
+ rightConfig == null ? void 0 : rightConfig.max
267
+ ]
268
+ );
239
269
  const estimatedPlotHeight = Math.max(60, height - 48);
240
- const tickCount = yAxis?.tickCount ?? suggestTickCount(estimatedPlotHeight);
241
- const yTicks = useMemo(() => linearTicks(yDomain[0], yDomain[1], tickCount), [yDomain, tickCount]);
270
+ const tickCount = (yAxis == null ? void 0 : yAxis.tickCount) ?? suggestTickCount(estimatedPlotHeight);
271
+ const yTicks = useMemo(
272
+ () => linearTicks(yDomain[0], yDomain[1], tickCount),
273
+ [yDomain, tickCount]
274
+ );
242
275
  const decimals = useMemo(() => {
243
- if (yTicks.length < 2) return 0;
276
+ if (yTicks.length < 2)
277
+ return 0;
244
278
  const step = Math.abs(yTicks[1] - yTicks[0]);
245
- if (step === 0) return 0;
279
+ if (step === 0)
280
+ return 0;
246
281
  return Math.min(4, Math.max(0, -Math.floor(Math.log10(step))));
247
282
  }, [yTicks]);
248
- const formatValue = useCallback(value => valueFormatter?.(value) ?? formatNumber(value, {
249
- decimals
250
- }), [valueFormatter, decimals]);
251
- const yLabels = useMemo(() => yTicks.map(tick => formatValue(tick)), [yTicks, formatValue]);
252
- const yTicksRight = useMemo(() => hasRightAxis ? linearTicks(yDomainRight[0], yDomainRight[1], tickCount) : [], [hasRightAxis, yDomainRight, tickCount]);
253
- const rightFormatter = rightConfig?.formatter;
254
- const yLabelsRight = useMemo(() => yTicksRight.map(tick => rightFormatter ? rightFormatter(tick) : formatNumber(tick, {
255
- decimals
256
- })), [yTicksRight, rightFormatter, decimals]);
257
- const layout = useMemo(() => computeLayout({
258
- width: Math.max(size.width, 0),
259
- height: Math.max(size.height, 0),
260
- yLabels,
261
- xLabels: xValues,
262
- theme,
263
- showXAxis: xAxis?.show !== false,
264
- showYAxis: yAxis?.show !== false,
265
- margin: hasRightAxis ? {
266
- right: Math.ceil(Math.max(0, ...yLabelsRight.map(label => estimateTextWidth(label, theme.font.size)))) + theme.axis.tickSize + 10
267
- } : undefined
268
- }), [size.width, size.height, yLabels, xValues, theme, xAxis?.show, yAxis?.show, hasRightAxis, yLabelsRight]);
269
- const {
270
- plot
271
- } = layout;
272
- const yScale = useMemo(() => createLinearScale({
273
- domain: yDomain,
274
- range: [plot.y + plot.height, plot.y]
275
- }), [yDomain, plot.y, plot.height]);
276
- const yScaleRight = useMemo(() => createLinearScale({
277
- domain: yDomainRight,
278
- range: [plot.y + plot.height, plot.y]
279
- }), [yDomainRight, plot.y, plot.height]);
280
- const hasBar = resolved.some(item => item.visible && item.type === 'bar');
281
- const xScale = useMemo(() => createBandScale({
282
- domain: xValues,
283
- range: [plot.x, plot.x + plot.width],
284
- // 柱子需要更紧的组内间距,纯折线则留更宽的呼吸空间
285
- paddingInner: hasBar ? 0.26 : 0.42,
286
- paddingOuter: 0.12
287
- }), [xValues, plot.x, plot.width, hasBar]);
288
-
289
- /** 柱子的槽位分配:堆叠组共用一个槽位,未堆叠的系列各占一个 */
283
+ const formatValue = useCallback(
284
+ (value) => (valueFormatter == null ? void 0 : valueFormatter(value)) ?? formatNumber(value, { decimals }),
285
+ [valueFormatter, decimals]
286
+ );
287
+ const yLabels = useMemo(
288
+ () => yTicks.map((tick) => formatValue(tick)),
289
+ [yTicks, formatValue]
290
+ );
291
+ const yTicksRight = useMemo(
292
+ () => hasRightAxis ? linearTicks(yDomainRight[0], yDomainRight[1], tickCount) : [],
293
+ [hasRightAxis, yDomainRight, tickCount]
294
+ );
295
+ const rightFormatter = rightConfig == null ? void 0 : rightConfig.formatter;
296
+ const yLabelsRight = useMemo(
297
+ () => yTicksRight.map(
298
+ (tick) => rightFormatter ? rightFormatter(tick) : formatNumber(tick, { decimals })
299
+ ),
300
+ [yTicksRight, rightFormatter, decimals]
301
+ );
302
+ const layout = useMemo(
303
+ () => computeLayout({
304
+ width: Math.max(size.width, 0),
305
+ height: Math.max(size.height, 0),
306
+ yLabels,
307
+ xLabels: xValues,
308
+ theme,
309
+ showXAxis: (xAxis == null ? void 0 : xAxis.show) !== false,
310
+ showYAxis: (yAxis == null ? void 0 : yAxis.show) !== false,
311
+ margin: hasRightAxis ? {
312
+ right: Math.ceil(
313
+ Math.max(
314
+ 0,
315
+ ...yLabelsRight.map(
316
+ (label) => estimateTextWidth(label, theme.font.size)
317
+ )
318
+ )
319
+ ) + theme.axis.tickSize + 10
320
+ } : void 0
321
+ }),
322
+ [
323
+ size.width,
324
+ size.height,
325
+ yLabels,
326
+ xValues,
327
+ theme,
328
+ xAxis == null ? void 0 : xAxis.show,
329
+ yAxis == null ? void 0 : yAxis.show,
330
+ hasRightAxis,
331
+ yLabelsRight
332
+ ]
333
+ );
334
+ const { plot } = layout;
335
+ const yScale = useMemo(
336
+ () => createLinearScale({
337
+ domain: yDomain,
338
+ range: [plot.y + plot.height, plot.y]
339
+ }),
340
+ [yDomain, plot.y, plot.height]
341
+ );
342
+ const yScaleRight = useMemo(
343
+ () => createLinearScale({
344
+ domain: yDomainRight,
345
+ range: [plot.y + plot.height, plot.y]
346
+ }),
347
+ [yDomainRight, plot.y, plot.height]
348
+ );
349
+ const hasBar = resolved.some((item) => item.visible && item.type === "bar");
350
+ const xScale = useMemo(
351
+ () => createBandScale({
352
+ domain: xValues,
353
+ range: [plot.x, plot.x + plot.width],
354
+ // 柱子需要更紧的组内间距,纯折线则留更宽的呼吸空间
355
+ paddingInner: hasBar ? 0.26 : 0.42,
356
+ paddingOuter: 0.12
357
+ }),
358
+ [xValues, plot.x, plot.width, hasBar]
359
+ );
290
360
  const barSlots = useMemo(() => {
291
- const map = new Map();
361
+ const map = /* @__PURE__ */ new Map();
292
362
  let count = 0;
293
363
  for (const item of resolved) {
294
- if (!item.visible || item.type !== 'bar') continue;
364
+ if (!item.visible || item.type !== "bar")
365
+ continue;
295
366
  const slotId = item.stackId ?? `__solo__${item.key}`;
296
367
  if (!map.has(slotId)) {
297
368
  map.set(slotId, count);
298
369
  count += 1;
299
370
  }
300
371
  }
301
- return {
302
- count: Math.max(1, count),
303
- map
304
- };
372
+ return { count: Math.max(1, count), map };
305
373
  }, [resolved]);
306
-
307
- // 动画配置的引用可能每次渲染都变,用序列化值做依赖避免无谓重建
308
- const animationKey = typeof animation === 'object' ? JSON.stringify(animation) : String(animation);
309
- const animConfig = useMemo(() => resolveAnimation(animation),
310
- // eslint-disable-next-line react-hooks/exhaustive-deps
311
- [animationKey]);
312
- const matrix = useMemo(() => resolved.map(item => item.top), [resolved]);
374
+ const animationKey = typeof animation === "object" ? JSON.stringify(animation) : String(animation);
375
+ const animConfig = useMemo(
376
+ () => resolveAnimation(animation),
377
+ // eslint-disable-next-line react-hooks/exhaustive-deps
378
+ [animationKey]
379
+ );
380
+ const matrix = useMemo(() => resolved.map((item) => item.top), [resolved]);
313
381
  const transition = useChartTransition(matrix, animConfig);
314
382
  const progress = transition.progress;
315
-
316
- // 动画原点:绘图区底部。所有图元由此「长」到目标位置
383
+ useEffect(() => {
384
+ if (syncedPayload && syncedPayload.index !== null) {
385
+ setLocalActiveIndex(null);
386
+ }
387
+ }, [syncedPayload]);
388
+ const syncedActiveIndex = useMemo(() => {
389
+ const payload = syncedPayload;
390
+ if (!payload || payload.index === null || xValues.length === 0)
391
+ return null;
392
+ if (payload.label !== void 0) {
393
+ const target = String(payload.label);
394
+ if (xValues[payload.index] === target)
395
+ return payload.index;
396
+ const byLabel = xValues.indexOf(target);
397
+ if (byLabel !== -1)
398
+ return byLabel;
399
+ }
400
+ return payload.index >= 0 && payload.index < xValues.length ? payload.index : null;
401
+ }, [syncedPayload, xValues]);
402
+ const activeIndex = localActiveIndex !== null ? localActiveIndex : syncedActiveIndex;
317
403
  const animBaseY = plot.y + plot.height;
318
404
  const scene = useMemo(() => {
319
- if (isEmpty || plot.width <= 0 || plot.height <= 0) return [];
405
+ if (isEmpty || plot.width <= 0 || plot.height <= 0)
406
+ return [];
320
407
  const nodes = [];
321
- /** 位置插值:local=0 贴基线,local=1 到目标位置 */
322
408
  const animY = (target, local = progress) => animBaseY + (target - animBaseY) * local;
323
-
324
- // ---- 网格线 ----
325
- if (grid !== false && yAxis?.grid !== false) {
326
- const dash = theme.grid.dash.join(' ');
409
+ if (grid !== false && (yAxis == null ? void 0 : yAxis.grid) !== false) {
410
+ const dash = theme.grid.dash.join(" ");
327
411
  for (const tick of yTicks) {
328
412
  const y = yScale.scale(tick);
329
413
  nodes.push({
330
- kind: 'line',
414
+ kind: "line",
331
415
  key: `grid-${tick}`,
332
416
  x1: plot.x,
333
417
  y1: y,
@@ -335,143 +419,135 @@ export function CartesianChart(props) {
335
419
  y2: y,
336
420
  stroke: theme.grid.line,
337
421
  strokeWidth: theme.grid.lineWidth,
338
- strokeDasharray: dash || undefined
422
+ strokeDasharray: dash || void 0
339
423
  });
340
424
  }
341
425
  }
342
-
343
- // ---- 坐标轴 ----
344
- if (xAxis?.show !== false) {
426
+ if ((xAxis == null ? void 0 : xAxis.show) !== false) {
345
427
  nodes.push({
346
- kind: 'line',
347
- key: 'x-axis-line',
428
+ kind: "line",
429
+ key: "x-axis-line",
348
430
  x1: plot.x,
349
431
  y1: plot.y + plot.height,
350
432
  x2: plot.x + plot.width,
351
433
  y2: plot.y + plot.height,
352
- stroke: xAxis?.lineColor ?? theme.axis.line,
434
+ stroke: (xAxis == null ? void 0 : xAxis.lineColor) ?? theme.axis.line,
353
435
  strokeWidth: theme.axis.lineWidth
354
436
  });
355
- const {
356
- interval,
357
- rotate,
358
- fontSize
359
- } = layout.xAxis;
437
+ const { interval, rotate, fontSize } = layout.xAxis;
360
438
  xValues.forEach((value, index) => {
361
- if (interval > 0 && index % interval !== 0) return;
439
+ if (interval > 0 && index % interval !== 0)
440
+ return;
362
441
  const cx = xScale.center(value);
363
- if (cx === undefined) return;
442
+ if (cx === void 0)
443
+ return;
364
444
  nodes.push({
365
- kind: 'text',
445
+ kind: "text",
366
446
  key: `x-label-${index}`,
367
447
  x: cx,
368
448
  y: rotate ? plot.y + plot.height + theme.axis.tickSize + fontSize + 2 : plot.y + plot.height + theme.axis.tickSize + fontSize,
369
449
  text: value,
370
- fill: xAxis?.labelColor ?? theme.axis.label,
450
+ fill: (xAxis == null ? void 0 : xAxis.labelColor) ?? theme.axis.label,
371
451
  fontSize,
372
- anchor: rotate ? 'end' : 'middle',
373
- rotate: rotate || undefined,
452
+ anchor: rotate ? "end" : "middle",
453
+ rotate: rotate || void 0,
374
454
  fontFamily: theme.font.family
375
455
  });
376
456
  });
377
457
  }
378
- if (yAxis?.show !== false) {
458
+ if ((yAxis == null ? void 0 : yAxis.show) !== false) {
379
459
  nodes.push({
380
- kind: 'line',
381
- key: 'y-axis-line',
460
+ kind: "line",
461
+ key: "y-axis-line",
382
462
  x1: plot.x,
383
463
  y1: plot.y,
384
464
  x2: plot.x,
385
465
  y2: plot.y + plot.height,
386
- stroke: yAxis?.lineColor ?? theme.axis.line,
466
+ stroke: (yAxis == null ? void 0 : yAxis.lineColor) ?? theme.axis.line,
387
467
  strokeWidth: theme.axis.lineWidth
388
468
  });
389
469
  yTicks.forEach((tick, index) => {
390
470
  nodes.push({
391
- kind: 'text',
471
+ kind: "text",
392
472
  key: `y-label-${index}`,
393
473
  x: plot.x - theme.axis.tickSize - 4,
394
474
  y: yScale.scale(tick),
395
475
  text: yLabels[index],
396
- fill: yAxis?.labelColor ?? theme.axis.label,
476
+ fill: (yAxis == null ? void 0 : yAxis.labelColor) ?? theme.axis.label,
397
477
  fontSize: theme.font.size,
398
- anchor: 'end',
399
- baseline: 'middle',
478
+ anchor: "end",
479
+ baseline: "middle",
400
480
  fontFamily: theme.font.family
401
481
  });
402
482
  });
403
483
  }
404
-
405
- // ---- 右侧第二根 y 轴 ----
406
- if (hasRightAxis && rightConfig?.show !== false) {
484
+ if (hasRightAxis && (rightConfig == null ? void 0 : rightConfig.show) !== false) {
407
485
  const axisX = plot.x + plot.width;
408
486
  nodes.push({
409
- kind: 'line',
410
- key: 'y-axis-right-line',
487
+ kind: "line",
488
+ key: "y-axis-right-line",
411
489
  x1: axisX,
412
490
  y1: plot.y,
413
491
  x2: axisX,
414
492
  y2: plot.y + plot.height,
415
- stroke: rightConfig?.lineColor ?? theme.axis.line,
493
+ stroke: (rightConfig == null ? void 0 : rightConfig.lineColor) ?? theme.axis.line,
416
494
  strokeWidth: theme.axis.lineWidth
417
495
  });
418
496
  yTicksRight.forEach((tick, index) => {
419
497
  const y = yScaleRight.scale(tick);
420
498
  nodes.push({
421
- kind: 'text',
499
+ kind: "text",
422
500
  key: `y-right-label-${index}`,
423
501
  x: axisX + theme.axis.tickSize + 4,
424
502
  y,
425
503
  text: yLabelsRight[index],
426
- fill: rightConfig?.labelColor ?? theme.axis.label,
504
+ fill: (rightConfig == null ? void 0 : rightConfig.labelColor) ?? theme.axis.label,
427
505
  fontSize: theme.font.size,
428
- anchor: 'start',
429
- baseline: 'middle',
506
+ anchor: "start",
507
+ baseline: "middle",
430
508
  fontFamily: theme.font.family
431
509
  });
432
510
  });
433
511
  }
434
-
435
- // ---- 数据图元 ----
436
512
  const barSlotWidth = barSlots.count > 0 ? xScale.bandWidth / barSlots.count : xScale.bandWidth;
437
513
  let seriesIndex = -1;
438
514
  for (const item of resolved) {
439
515
  seriesIndex += 1;
440
- if (!item.visible) continue;
441
- // 更新阶段这里是从旧值插值来的当前值;入场阶段即目标值
516
+ if (!item.visible)
517
+ continue;
442
518
  const row = transition.values[seriesIndex] ?? item.top;
443
- // 该系列归属哪根 y 轴(双轴图表里右轴系列用右轴比例尺)
444
519
  const yS = item.config.yAxisIndex === 1 && hasRightAxis ? yScaleRight : yScale;
445
- if (item.type === 'bar') {
446
- // 堆叠组内成员:用来判断某一段是不是「最远端」
447
- const stackMembers = item.stackId ? resolved.filter(other => other.visible && other.stackId === item.stackId) : [];
520
+ if (item.type === "bar") {
521
+ const stackMembers = item.stackId ? resolved.filter(
522
+ (other) => other.visible && other.stackId === item.stackId
523
+ ) : [];
448
524
  const slotId = item.stackId ?? `__solo__${item.key}`;
449
525
  const slotIndex = barSlots.map.get(slotId) ?? 0;
450
- const barWidth = Math.max(1, Math.min(barSlotWidth * 0.72, item.config.barMaxWidth ?? 48));
526
+ const barWidth = Math.max(
527
+ 1,
528
+ Math.min(barSlotWidth * 0.72, item.config.barMaxWidth ?? 48)
529
+ );
451
530
  row.forEach((value, index) => {
452
- if (value === null) return;
531
+ if (value === null)
532
+ return;
453
533
  const bandLeft = xScale.scale(xValues[index]);
454
- if (bandLeft === undefined) return;
455
-
456
- // 错峰:整排柱子从左到右依次生长,而不是同时弹起
457
- const local = staggerProgress(progress, index, xValues.length, animConfig.stagger);
534
+ if (bandLeft === void 0)
535
+ return;
536
+ const local = staggerProgress(
537
+ progress,
538
+ index,
539
+ xValues.length,
540
+ animConfig.stagger
541
+ );
458
542
  const base = item.base[index] ?? 0;
459
543
  const topY = animY(yS.scale(value), local);
460
544
  const baseY = animY(yS.scale(base), local);
461
545
  const y = Math.min(topY, baseY);
462
546
  const h = Math.max(1, Math.abs(baseY - topY));
463
547
  const x = bandLeft + barSlotWidth * slotIndex + (barSlotWidth - barWidth) / 2;
464
-
465
- /**
466
- * 圆角只加在「整柱最远端」。
467
- *
468
- * 堆叠柱每一段都圆角会在段与段之间留下月牙形缺口,
469
- * 看起来像三根柱子叠在一起而不是一根柱子。
470
- * 判断依据:有没有同组系列的基线正好落在我的顶端 ——
471
- * 有就说明上面还叠着一段,我这一端不该圆。
472
- */
473
- const hasStackedBeyond = stackMembers.some(other => {
474
- if (other === item) return false;
548
+ const hasStackedBeyond = stackMembers.some((other) => {
549
+ if (other === item)
550
+ return false;
475
551
  const otherBase = other.base[index] ?? 0;
476
552
  return Math.abs(otherBase - (item.top[index] ?? 0)) < 1e-6;
477
553
  });
@@ -479,95 +555,116 @@ export function CartesianChart(props) {
479
555
  const isPositive = value >= base;
480
556
  const radius = item.config.barMaxWidth === 0 ? 0 : theme.series.barRadius;
481
557
  nodes.push({
482
- kind: 'path',
558
+ kind: "path",
483
559
  key: `bar-${item.key}-${index}`,
484
- d: roundedRectPath(x, y, barWidth, h, radius, isPositive ? {
485
- tl: roundFarEnd,
486
- tr: roundFarEnd,
487
- bl: false,
488
- br: false
489
- } : {
490
- tl: false,
491
- tr: false,
492
- bl: roundFarEnd,
493
- br: roundFarEnd
494
- }),
560
+ d: roundedRectPath(
561
+ x,
562
+ y,
563
+ barWidth,
564
+ h,
565
+ radius,
566
+ isPositive ? { tl: roundFarEnd, tr: roundFarEnd, bl: false, br: false } : { tl: false, tr: false, bl: roundFarEnd, br: roundFarEnd }
567
+ ),
495
568
  fill: item.color,
496
569
  opacity: activeIndex === null || activeIndex === index ? 1 : 0.55,
497
- pointerEvents: 'none'
570
+ pointerEvents: "none"
498
571
  });
499
572
  });
500
573
  continue;
501
574
  }
502
- if (item.type === 'scatter') {
575
+ if (item.type === "scatter") {
503
576
  row.forEach((value, index) => {
504
- if (value === null) return;
577
+ if (value === null)
578
+ return;
505
579
  const cx = xScale.center(xValues[index]);
506
- if (cx === undefined) return;
507
- const local = staggerProgress(progress, index, xValues.length, animConfig.stagger);
580
+ if (cx === void 0)
581
+ return;
582
+ const local = staggerProgress(
583
+ progress,
584
+ index,
585
+ xValues.length,
586
+ animConfig.stagger
587
+ );
508
588
  nodes.push({
509
- kind: 'circle',
589
+ kind: "circle",
510
590
  key: `dot-${item.key}-${index}`,
511
591
  cx,
512
592
  cy: animY(yS.scale(value), local),
513
593
  r: activeIndex === index ? theme.series.symbolSize * 0.75 : theme.series.symbolSize * 0.55,
514
594
  fill: item.color,
515
595
  opacity: activeIndex === null || activeIndex === index ? 0.9 : 0.4,
516
- pointerEvents: 'none'
596
+ pointerEvents: "none"
517
597
  });
518
598
  });
519
599
  continue;
520
600
  }
521
-
522
- // line / area
523
601
  const points = row.map((value, index) => {
524
- if (value === null) return null;
602
+ if (value === null)
603
+ return null;
525
604
  const cx = xScale.center(xValues[index]);
526
- if (cx === undefined) return null;
527
- // 逐点错峰:线条像被画笔从左往右扫出来,而不是整条同时抬起
528
- const local = staggerProgress(progress, index, xValues.length, animConfig.stagger);
529
- return {
530
- x: cx,
531
- y: animY(yS.scale(value), local)
532
- };
605
+ if (cx === void 0)
606
+ return null;
607
+ const local = staggerProgress(
608
+ progress,
609
+ index,
610
+ xValues.length,
611
+ animConfig.stagger
612
+ );
613
+ return { x: cx, y: animY(yS.scale(value), local) };
533
614
  });
534
- const curve = item.config.curve ?? 'monotone';
535
- const wantArea = item.type === 'area' || item.config.area === true;
615
+ const curve = item.config.curve ?? "monotone";
616
+ const wantArea = item.type === "area" || item.config.area === true;
536
617
  if (wantArea) {
537
- const baselineY = yS.scale(Math.max((item.config.yAxisIndex === 1 ? yDomainRight : yDomain)[0], 0));
538
- const safeBaseline = Math.min(Math.max(baselineY, plot.y), plot.y + plot.height);
618
+ const baselineY = yS.scale(
619
+ Math.max(
620
+ (item.config.yAxisIndex === 1 ? yDomainRight : yDomain)[0],
621
+ 0
622
+ )
623
+ );
624
+ const safeBaseline = Math.min(
625
+ Math.max(baselineY, plot.y),
626
+ plot.y + plot.height
627
+ );
539
628
  nodes.push({
540
- kind: 'path',
629
+ kind: "path",
541
630
  key: `area-${item.key}`,
542
631
  d: areaPathOf(points, safeBaseline, curve),
543
- fill: withAlpha(item.color, item.config.areaOpacity ?? theme.series.areaOpacity),
544
- pointerEvents: 'none'
632
+ fill: withAlpha(
633
+ item.color,
634
+ item.config.areaOpacity ?? theme.series.areaOpacity
635
+ ),
636
+ pointerEvents: "none"
545
637
  });
546
638
  }
547
639
  nodes.push({
548
- kind: 'path',
640
+ kind: "path",
549
641
  key: `line-${item.key}`,
550
642
  d: linePath(points, curve),
551
- fill: 'none',
643
+ fill: "none",
552
644
  stroke: item.color,
553
645
  strokeWidth: theme.series.lineWidth,
554
- linecap: 'round',
555
- linejoin: 'round',
646
+ linecap: "round",
647
+ linejoin: "round",
556
648
  opacity: activeIndex === null ? 1 : 0.9,
557
- pointerEvents: 'none'
649
+ pointerEvents: "none"
558
650
  });
559
-
560
- // 数据点:默认在点数不多时显示,避免密集折线变成「毛毛虫」
561
651
  const showSymbol = item.config.showSymbol ?? xValues.length <= 24;
562
652
  if (showSymbol) {
563
653
  row.forEach((value, index) => {
564
- if (value === null) return;
654
+ if (value === null)
655
+ return;
565
656
  const cx = xScale.center(xValues[index]);
566
- if (cx === undefined) return;
657
+ if (cx === void 0)
658
+ return;
567
659
  const active = activeIndex === index;
568
- const local = staggerProgress(progress, index, xValues.length, animConfig.stagger);
660
+ const local = staggerProgress(
661
+ progress,
662
+ index,
663
+ xValues.length,
664
+ animConfig.stagger
665
+ );
569
666
  nodes.push({
570
- kind: 'circle',
667
+ kind: "circle",
571
668
  key: `symbol-${item.key}-${index}`,
572
669
  cx,
573
670
  cy: animY(yS.scale(value), local),
@@ -575,237 +672,321 @@ export function CartesianChart(props) {
575
672
  fill: theme.tooltip.background,
576
673
  stroke: item.color,
577
674
  strokeWidth: active ? theme.series.emphasisWidth : 2,
578
- pointerEvents: 'none'
675
+ pointerEvents: "none"
579
676
  });
580
677
  });
581
678
  }
582
679
  }
583
-
584
- // ---- 高亮指示线 ----
585
680
  if (activeIndex !== null) {
586
681
  const cx = xScale.center(xValues[activeIndex]);
587
- if (cx !== undefined) {
682
+ if (cx !== void 0) {
588
683
  nodes.push({
589
- kind: 'line',
590
- key: 'indicator',
684
+ kind: "line",
685
+ key: "indicator",
591
686
  x1: cx,
592
687
  y1: plot.y,
593
688
  x2: cx,
594
689
  y2: plot.y + plot.height,
595
690
  stroke: theme.axis.line,
596
691
  strokeWidth: 1,
597
- strokeDasharray: '3 3',
598
- pointerEvents: 'none'
692
+ strokeDasharray: "3 3",
693
+ pointerEvents: "none"
599
694
  });
600
695
  }
601
696
  }
602
697
  return nodes;
603
- }, [isEmpty, plot, yTicks, yLabels, yScale, xScale, xValues, resolved, theme, grid, xAxis, yAxis, layout.xAxis, activeIndex, barSlots, animBaseY, progress, transition.values, animConfig.stagger, yDomain, yDomainRight, yScaleRight, hasRightAxis, yTicksRight, yLabelsRight, rightConfig]);
604
-
605
- // ---- 交互 ----
606
- const indexFromClientX = useCallback(clientX => {
607
- const element = plotRef.current;
608
- if (!element) return null;
609
- const rect = element.getBoundingClientRect();
610
- const localX = clientX - rect.left;
611
- if (localX < plot.x - 8 || localX > plot.x + plot.width + 8) return null;
612
- let nearest = null;
613
- let minDistance = Infinity;
614
- xValues.forEach((value, index) => {
615
- const cx = xScale.center(value);
616
- if (cx === undefined) return;
617
- const distance = Math.abs(cx - localX);
618
- if (distance < minDistance) {
619
- minDistance = distance;
620
- nearest = index;
698
+ }, [
699
+ isEmpty,
700
+ plot,
701
+ yTicks,
702
+ yLabels,
703
+ yScale,
704
+ xScale,
705
+ xValues,
706
+ resolved,
707
+ theme,
708
+ grid,
709
+ xAxis,
710
+ yAxis,
711
+ layout.xAxis,
712
+ activeIndex,
713
+ barSlots,
714
+ animBaseY,
715
+ progress,
716
+ transition.values,
717
+ animConfig.stagger,
718
+ yDomain,
719
+ yDomainRight,
720
+ yScaleRight,
721
+ hasRightAxis,
722
+ yTicksRight,
723
+ yLabelsRight,
724
+ rightConfig
725
+ ]);
726
+ const indexFromClientX = useCallback(
727
+ (clientX) => {
728
+ const element = plotRef.current;
729
+ if (!element)
730
+ return null;
731
+ const rect = element.getBoundingClientRect();
732
+ const localX = clientX - rect.left;
733
+ if (localX < plot.x - 8 || localX > plot.x + plot.width + 8)
734
+ return null;
735
+ let nearest = null;
736
+ let minDistance = Infinity;
737
+ xValues.forEach((value, index) => {
738
+ const cx = xScale.center(value);
739
+ if (cx === void 0)
740
+ return;
741
+ const distance = Math.abs(cx - localX);
742
+ if (distance < minDistance) {
743
+ minDistance = distance;
744
+ nearest = index;
745
+ }
746
+ });
747
+ return nearest;
748
+ },
749
+ [plotRef, plot.x, plot.width, xValues, xScale]
750
+ );
751
+ const updateHighlight = useCallback(
752
+ (next) => {
753
+ setLocalActiveIndex(next);
754
+ if (next !== null) {
755
+ emitSync(next, xValues[next]);
756
+ } else {
757
+ clearSync();
621
758
  }
622
- });
623
- return nearest;
624
- }, [plotRef, plot.x, plot.width, xValues, xScale]);
625
- const handlePointerMove = useCallback(event => {
626
- if (tooltip === false || isEmpty) return;
627
- setActiveIndex(indexFromClientX(event.clientX));
628
- }, [tooltip, isEmpty, indexFromClientX]);
629
- const handlePointerLeave = useCallback(() => setActiveIndex(null), []);
630
- const handleClick = useCallback(event => {
631
- if (!onPointClick) return;
632
- const index = indexFromClientX(event.clientX);
633
- if (index === null) return;
634
- const payload = buildTooltipItems(resolved, index);
635
- const label = xValues[index] ?? '';
636
- if (payload.length === 0) return;
637
- onPointClick({
638
- label,
639
- row: data[index] ?? null,
640
- series: payload,
641
- seriesKey: payload[0].key
642
- });
643
- }, [onPointClick, indexFromClientX, resolved, xValues, data]);
759
+ },
760
+ [emitSync, clearSync, xValues]
761
+ );
762
+ const pointerHandlers = usePlotPointer({
763
+ disabled: tooltip === false && !syncGroup || isEmpty,
764
+ onMove: (clientX) => updateHighlight(indexFromClientX(clientX)),
765
+ onLeave: () => updateHighlight(null)
766
+ });
767
+ const handleClick = useCallback(
768
+ (event) => {
769
+ if (!onPointClick)
770
+ return;
771
+ const index = indexFromClientX(event.clientX);
772
+ if (index === null)
773
+ return;
774
+ const payload = buildTooltipItems(resolved, index);
775
+ const label = xValues[index] ?? "";
776
+ if (payload.length === 0)
777
+ return;
778
+ onPointClick({
779
+ label,
780
+ row: viewData[index] ?? null,
781
+ series: payload,
782
+ seriesKey: payload[0].key
783
+ });
784
+ },
785
+ [onPointClick, indexFromClientX, resolved, xValues, viewData]
786
+ );
644
787
  const tooltipPayload = useMemo(() => {
645
- if (activeIndex === null || !hasVisibleSeries) return null;
788
+ if (activeIndex === null || !hasVisibleSeries)
789
+ return null;
646
790
  return {
647
- label: xValues[activeIndex] ?? '',
648
- row: data[activeIndex] ?? null,
791
+ label: xValues[activeIndex] ?? "",
792
+ row: viewData[activeIndex] ?? null,
649
793
  series: buildTooltipItems(resolved, activeIndex)
650
794
  };
651
- }, [activeIndex, hasVisibleSeries, xValues, data, resolved]);
795
+ }, [activeIndex, hasVisibleSeries, xValues, viewData, resolved]);
652
796
  const tooltipPosition = useMemo(() => {
653
- if (activeIndex === null) return {
654
- x: 0,
655
- y: 0
656
- };
797
+ if (activeIndex === null)
798
+ return { x: 0, y: 0 };
657
799
  const cx = xScale.center(xValues[activeIndex]) ?? plot.x;
658
800
  let top = plot.y + plot.height;
659
801
  for (const item of resolved) {
660
- if (!item.visible) continue;
802
+ if (!item.visible)
803
+ continue;
661
804
  const value = item.top[activeIndex];
662
- if (value === null || value === undefined) continue;
805
+ if (value === null || value === void 0)
806
+ continue;
663
807
  const yScaleOfItem = item.config.yAxisIndex === 1 && hasRightAxis ? yScaleRight : yScale;
664
808
  top = Math.min(top, yScaleOfItem.scale(value));
665
809
  }
666
- return {
667
- x: cx,
668
- y: Math.max(top, plot.y + 8)
669
- };
670
- }, [activeIndex, xScale, xValues, plot, resolved, yScale, yScaleRight, hasRightAxis]);
671
- const totalPoints = resolved.reduce((sum, item) => sum + item.values.length, 0);
672
- const useCanvas = renderer === 'canvas' || renderer === 'auto' && totalPoints > CANVAS_THRESHOLD;
673
- const legendItems = resolved.map(item => ({
810
+ return { x: cx, y: Math.max(top, plot.y + 8) };
811
+ }, [
812
+ activeIndex,
813
+ xScale,
814
+ xValues,
815
+ plot,
816
+ resolved,
817
+ yScale,
818
+ yScaleRight,
819
+ hasRightAxis
820
+ ]);
821
+ const totalPoints = resolved.reduce(
822
+ (sum, item) => sum + item.values.length,
823
+ 0
824
+ );
825
+ const useCanvas = renderer === "canvas" || renderer === "auto" && totalPoints > CANVAS_THRESHOLD;
826
+ const legendItems = resolved.map((item) => ({
674
827
  key: item.key,
675
828
  name: item.name,
676
829
  color: item.color,
677
830
  visible: item.visible
678
831
  }));
679
- const toggleSeries = useCallback(key => {
680
- setHiddenKeys(prev => prev.includes(key) ? prev.filter(item => item !== key) : [...prev, key]);
832
+ const toggleSeries = useCallback((key) => {
833
+ setHiddenKeys(
834
+ (prev) => prev.includes(key) ? prev.filter((item) => item !== key) : [...prev, key]
835
+ );
681
836
  }, []);
682
- const autoAriaLabel = ariaLabel ?? `图表:${seriesConfig.map(item => item.name ?? item.key).join('、') || '数据'}`;
683
- return /*#__PURE__*/_jsxs("div", {
684
- className: classNames(prefixCls('chart'), className),
685
- style: {
686
- width,
687
- height,
688
- ...style
689
- },
690
- "data-aura-chart": "cartesian",
691
- children: [/*#__PURE__*/_jsx(Legend, {
692
- items: legendItems,
693
- theme: theme,
694
- config: legend,
695
- onToggle: toggleSeries
696
- }), /*#__PURE__*/_jsxs("div", {
697
- ref: plotRef,
698
- className: prefixCls('chart__plot'),
699
- onPointerMove: handlePointerMove,
700
- onPointerLeave: handlePointerLeave,
701
- onClick: handleClick,
702
- children: [isEmpty || !hasVisibleSeries ? /*#__PURE__*/_jsx("div", {
703
- className: prefixCls('chart__empty'),
704
- children: emptyText
705
- }) : size.width > 0 && size.height > 0 ? useCanvas ? /*#__PURE__*/_jsx(CanvasScene, {
706
- nodes: scene,
707
- width: size.width,
708
- height: size.height
709
- }) : /*#__PURE__*/_jsx(SvgScene, {
710
- nodes: scene,
711
- width: size.width,
712
- height: size.height,
713
- ariaLabel: autoAriaLabel
714
- }) : null, /*#__PURE__*/_jsx(Tooltip, {
715
- payload: tooltipPayload,
716
- x: tooltipPosition.x,
717
- y: tooltipPosition.y,
718
- containerWidth: size.width,
719
- containerHeight: size.height,
720
- theme: theme,
721
- config: tooltip
722
- })]
723
- }), zoomEnabled && zoomOptions.show !== false ? /*#__PURE__*/_jsx("div", {
724
- className: prefixCls('chart__zoom'),
725
- style: {
726
- height: zoomOptions.height ?? 26
727
- },
728
- children: /*#__PURE__*/_jsx("div", {
729
- ref: zoomTrackRef,
730
- className: prefixCls('chart__zoom-track'),
731
- onPointerDown: event => {
732
- // 点击轨道空白处:把窗口整体平移到点击位置并保持跨度
733
- const track = zoomTrackRef.current;
734
- if (!track) return;
735
- const rect = track.getBoundingClientRect();
736
- const ratio = (event.clientX - rect.left) / (rect.width || 1);
737
- const span = zoomRef.current[1] - zoomRef.current[0];
738
- const start = Math.min(1 - span, Math.max(0, ratio - span / 2));
739
- applyZoom([start, start + span]);
740
- },
741
- children: /*#__PURE__*/_jsxs("div", {
742
- className: prefixCls('chart__zoom-window'),
743
- style: {
744
- left: `${zoomRange[0] * 100}%`,
745
- width: `${(zoomRange[1] - zoomRange[0]) * 100}%`
746
- },
747
- onPointerDown: beginDrag('move'),
748
- children: [/*#__PURE__*/_jsx("span", {
749
- className: classNames(prefixCls('chart__zoom-handle'), prefixCls('chart__zoom-handle--start')),
750
- onPointerDown: beginDrag('start')
751
- }), /*#__PURE__*/_jsx("span", {
752
- className: classNames(prefixCls('chart__zoom-handle'), prefixCls('chart__zoom-handle--end')),
753
- onPointerDown: beginDrag('end')
754
- })]
755
- })
756
- })
757
- }) : null, /*#__PURE__*/_jsx("div", {
758
- className: prefixCls('chart__a11y'),
759
- children: /*#__PURE__*/_jsxs("table", {
760
- className: prefixCls('chart__a11y-table'),
761
- children: [/*#__PURE__*/_jsx("caption", {
762
- children: autoAriaLabel
763
- }), /*#__PURE__*/_jsx("thead", {
764
- children: /*#__PURE__*/_jsxs("tr", {
765
- children: [/*#__PURE__*/_jsx("th", {
766
- scope: "col",
767
- children: xKey
768
- }), visibleSeries.map(item => /*#__PURE__*/_jsx("th", {
769
- scope: "col",
770
- children: item.name
771
- }, item.key))]
772
- })
773
- }), /*#__PURE__*/_jsxs("tbody", {
774
- children: [viewData.slice(0, A11Y_ROW_LIMIT).map((row, rowIndex) => /*#__PURE__*/_jsxs("tr", {
775
- children: [/*#__PURE__*/_jsx("th", {
776
- scope: "row",
777
- children: xValues[rowIndex]
778
- }), visibleSeries.map(item => /*#__PURE__*/_jsx("td", {
779
- children: item.values[rowIndex] ?? '—'
780
- }, item.key))]
781
- }, rowIndex)), viewData.length > A11Y_ROW_LIMIT ? /*#__PURE__*/_jsx("tr", {
782
- children: /*#__PURE__*/_jsx("td", {
783
- colSpan: visibleSeries.length + 1,
784
- children: `另有 ${viewData.length - A11Y_ROW_LIMIT} 行数据未列出`
785
- })
786
- }) : null]
787
- })]
788
- })
789
- })]
790
- });
837
+ const autoAriaLabel = ariaLabel ?? `图表:${seriesConfig.map((item) => item.name ?? item.key).join("、") || "数据"}`;
838
+ return /* @__PURE__ */ jsxs(
839
+ "div",
840
+ {
841
+ className: classNames(prefixCls("chart"), className),
842
+ style: { width, height, ...style },
843
+ "data-aura-chart": "cartesian",
844
+ children: [
845
+ /* @__PURE__ */ jsx(
846
+ Legend,
847
+ {
848
+ items: legendItems,
849
+ theme,
850
+ config: legend,
851
+ onToggle: toggleSeries
852
+ }
853
+ ),
854
+ /* @__PURE__ */ jsxs(
855
+ "div",
856
+ {
857
+ ref: plotRef,
858
+ className: prefixCls("chart__plot"),
859
+ ...pointerHandlers,
860
+ onClick: handleClick,
861
+ children: [
862
+ isEmpty || !hasVisibleSeries ? /* @__PURE__ */ jsx("div", { className: prefixCls("chart__empty"), children: emptyText }) : size.width > 0 && size.height > 0 ? useCanvas ? /* @__PURE__ */ jsx(
863
+ CanvasScene,
864
+ {
865
+ nodes: scene,
866
+ width: size.width,
867
+ height: size.height
868
+ }
869
+ ) : /* @__PURE__ */ jsx(
870
+ SvgScene,
871
+ {
872
+ nodes: scene,
873
+ width: size.width,
874
+ height: size.height,
875
+ ariaLabel: autoAriaLabel
876
+ }
877
+ ) : null,
878
+ /* @__PURE__ */ jsx(
879
+ Tooltip,
880
+ {
881
+ payload: tooltipPayload,
882
+ x: tooltipPosition.x,
883
+ y: tooltipPosition.y,
884
+ containerWidth: size.width,
885
+ containerHeight: size.height,
886
+ theme,
887
+ config: tooltip
888
+ }
889
+ )
890
+ ]
891
+ }
892
+ ),
893
+ zoomEnabled && zoomOptions.show !== false ? /* @__PURE__ */ jsx(
894
+ "div",
895
+ {
896
+ className: prefixCls("chart__zoom"),
897
+ style: { height: zoomOptions.height ?? 26 },
898
+ children: /* @__PURE__ */ jsx(
899
+ "div",
900
+ {
901
+ ref: zoomTrackRef,
902
+ className: prefixCls("chart__zoom-track"),
903
+ onPointerDown: (event) => {
904
+ const track = zoomTrackRef.current;
905
+ if (!track)
906
+ return;
907
+ const rect = track.getBoundingClientRect();
908
+ const ratio = (event.clientX - rect.left) / (rect.width || 1);
909
+ const span = zoomRef.current[1] - zoomRef.current[0];
910
+ const start = Math.min(1 - span, Math.max(0, ratio - span / 2));
911
+ applyZoom([start, start + span]);
912
+ },
913
+ children: /* @__PURE__ */ jsxs(
914
+ "div",
915
+ {
916
+ className: prefixCls("chart__zoom-window"),
917
+ style: {
918
+ left: `${zoomRange[0] * 100}%`,
919
+ width: `${(zoomRange[1] - zoomRange[0]) * 100}%`
920
+ },
921
+ onPointerDown: beginDrag("move"),
922
+ children: [
923
+ /* @__PURE__ */ jsx(
924
+ "span",
925
+ {
926
+ className: classNames(
927
+ prefixCls("chart__zoom-handle"),
928
+ prefixCls("chart__zoom-handle--start")
929
+ ),
930
+ onPointerDown: beginDrag("start")
931
+ }
932
+ ),
933
+ /* @__PURE__ */ jsx(
934
+ "span",
935
+ {
936
+ className: classNames(
937
+ prefixCls("chart__zoom-handle"),
938
+ prefixCls("chart__zoom-handle--end")
939
+ ),
940
+ onPointerDown: beginDrag("end")
941
+ }
942
+ )
943
+ ]
944
+ }
945
+ )
946
+ }
947
+ )
948
+ }
949
+ ) : null,
950
+ /* @__PURE__ */ jsx("div", { className: prefixCls("chart__a11y"), children: /* @__PURE__ */ jsxs("table", { className: prefixCls("chart__a11y-table"), children: [
951
+ /* @__PURE__ */ jsx("caption", { children: autoAriaLabel }),
952
+ /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { children: [
953
+ /* @__PURE__ */ jsx("th", { scope: "col", children: xKey }),
954
+ visibleSeries.map((item) => /* @__PURE__ */ jsx("th", { scope: "col", children: item.name }, item.key))
955
+ ] }) }),
956
+ /* @__PURE__ */ jsxs("tbody", { children: [
957
+ viewData.slice(0, A11Y_ROW_LIMIT).map((row, rowIndex) => /* @__PURE__ */ jsxs("tr", { children: [
958
+ /* @__PURE__ */ jsx("th", { scope: "row", children: xValues[rowIndex] }),
959
+ visibleSeries.map((item) => /* @__PURE__ */ jsx("td", { children: item.values[rowIndex] ?? "—" }, item.key))
960
+ ] }, rowIndex)),
961
+ viewData.length > A11Y_ROW_LIMIT ? /* @__PURE__ */ jsx("tr", { children: /* @__PURE__ */ jsx("td", { colSpan: visibleSeries.length + 1, children: `另有 ${viewData.length - A11Y_ROW_LIMIT} 行数据未列出` }) }) : null
962
+ ] })
963
+ ] }) })
964
+ ]
965
+ }
966
+ );
791
967
  }
792
-
793
- /** 面积填充路径(支持 null 断点),与 linePath 保持同步的分段逻辑 */
794
968
  function areaPathOf(points, baseline, curve) {
795
969
  const segments = [];
796
970
  let current = [];
797
971
  for (const point of points) {
798
- if (point) current.push(point);else if (current.length) {
972
+ if (point)
973
+ current.push(point);
974
+ else if (current.length) {
799
975
  segments.push(current);
800
976
  current = [];
801
977
  }
802
978
  }
803
- if (current.length) segments.push(current);
804
- return segments.map(segment => {
805
- if (!segment.length) return '';
979
+ if (current.length)
980
+ segments.push(current);
981
+ return segments.map((segment) => {
982
+ if (!segment.length)
983
+ return "";
806
984
  const top = linePath(segment, curve);
807
985
  const last = segment[segment.length - 1];
808
986
  const first = segment[0];
809
987
  return `${top}L${last.x},${baseline}L${first.x},${baseline}Z`;
810
- }).filter(Boolean).join('');
811
- }
988
+ }).filter(Boolean).join("");
989
+ }
990
+ export {
991
+ CartesianChart
992
+ };