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