@aura-react-comp/charts 0.0.0-stage → 0.2.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 (129) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +90 -2
  3. package/esm/charts/area-chart/index.d.ts +19 -0
  4. package/esm/charts/area-chart/index.d.ts.map +1 -0
  5. package/esm/charts/area-chart/index.js +30 -0
  6. package/esm/charts/bar-chart/index.d.ts +16 -0
  7. package/esm/charts/bar-chart/index.d.ts.map +1 -0
  8. package/esm/charts/bar-chart/index.js +27 -0
  9. package/esm/charts/candlestick-chart/index.d.ts +47 -0
  10. package/esm/charts/candlestick-chart/index.d.ts.map +1 -0
  11. package/esm/charts/candlestick-chart/index.js +346 -0
  12. package/esm/charts/combo-chart/index.d.ts +17 -0
  13. package/esm/charts/combo-chart/index.d.ts.map +1 -0
  14. package/esm/charts/combo-chart/index.js +25 -0
  15. package/esm/charts/funnel-chart/index.d.ts +35 -0
  16. package/esm/charts/funnel-chart/index.d.ts.map +1 -0
  17. package/esm/charts/funnel-chart/index.js +199 -0
  18. package/esm/charts/gauge-chart/index.d.ts +41 -0
  19. package/esm/charts/gauge-chart/index.d.ts.map +1 -0
  20. package/esm/charts/gauge-chart/index.js +216 -0
  21. package/esm/charts/graph-chart/index.d.ts +35 -0
  22. package/esm/charts/graph-chart/index.d.ts.map +1 -0
  23. package/esm/charts/graph-chart/index.js +223 -0
  24. package/esm/charts/heatmap-chart/index.d.ts +47 -0
  25. package/esm/charts/heatmap-chart/index.d.ts.map +1 -0
  26. package/esm/charts/heatmap-chart/index.js +280 -0
  27. package/esm/charts/line-chart/index.d.ts +23 -0
  28. package/esm/charts/line-chart/index.d.ts.map +1 -0
  29. package/esm/charts/line-chart/index.js +32 -0
  30. package/esm/charts/pie-chart/index.d.ts +38 -0
  31. package/esm/charts/pie-chart/index.d.ts.map +1 -0
  32. package/esm/charts/pie-chart/index.js +271 -0
  33. package/esm/charts/radar-chart/index.d.ts +44 -0
  34. package/esm/charts/radar-chart/index.d.ts.map +1 -0
  35. package/esm/charts/radar-chart/index.js +262 -0
  36. package/esm/charts/ring-progress/index.d.ts +38 -0
  37. package/esm/charts/ring-progress/index.d.ts.map +1 -0
  38. package/esm/charts/ring-progress/index.js +136 -0
  39. package/esm/charts/sankey-chart/index.d.ts +34 -0
  40. package/esm/charts/sankey-chart/index.d.ts.map +1 -0
  41. package/esm/charts/sankey-chart/index.js +247 -0
  42. package/esm/charts/scatter-chart/index.d.ts +34 -0
  43. package/esm/charts/scatter-chart/index.d.ts.map +1 -0
  44. package/esm/charts/scatter-chart/index.js +304 -0
  45. package/esm/charts/sparkline/index.d.ts +31 -0
  46. package/esm/charts/sparkline/index.d.ts.map +1 -0
  47. package/esm/charts/sparkline/index.js +151 -0
  48. package/esm/charts/tree-chart/index.d.ts +34 -0
  49. package/esm/charts/tree-chart/index.d.ts.map +1 -0
  50. package/esm/charts/tree-chart/index.js +199 -0
  51. package/esm/charts/treemap-chart/index.d.ts +35 -0
  52. package/esm/charts/treemap-chart/index.d.ts.map +1 -0
  53. package/esm/charts/treemap-chart/index.js +238 -0
  54. package/esm/charts/waterfall-chart/index.d.ts +41 -0
  55. package/esm/charts/waterfall-chart/index.d.ts.map +1 -0
  56. package/esm/charts/waterfall-chart/index.js +280 -0
  57. package/esm/components/Legend.d.ts +24 -0
  58. package/esm/components/Legend.d.ts.map +1 -0
  59. package/esm/components/Legend.js +49 -0
  60. package/esm/components/Tooltip.d.ts +24 -0
  61. package/esm/components/Tooltip.d.ts.map +1 -0
  62. package/esm/components/Tooltip.js +84 -0
  63. package/esm/components/chart/index.d.ts +71 -0
  64. package/esm/components/chart/index.d.ts.map +1 -0
  65. package/esm/components/chart/index.js +141 -0
  66. package/esm/components/chart.less +223 -0
  67. package/esm/core/animation.d.ts +49 -0
  68. package/esm/core/animation.d.ts.map +1 -0
  69. package/esm/core/animation.js +92 -0
  70. package/esm/core/force.d.ts +43 -0
  71. package/esm/core/force.d.ts.map +1 -0
  72. package/esm/core/force.js +133 -0
  73. package/esm/core/format.d.ts +34 -0
  74. package/esm/core/format.d.ts.map +1 -0
  75. package/esm/core/format.js +80 -0
  76. package/esm/core/hierarchy.d.ts +77 -0
  77. package/esm/core/hierarchy.d.ts.map +1 -0
  78. package/esm/core/hierarchy.js +232 -0
  79. package/esm/core/layout.d.ts +67 -0
  80. package/esm/core/layout.d.ts.map +1 -0
  81. package/esm/core/layout.js +120 -0
  82. package/esm/core/sampling.d.ts +32 -0
  83. package/esm/core/sampling.d.ts.map +1 -0
  84. package/esm/core/sampling.js +123 -0
  85. package/esm/core/sankey.d.ts +67 -0
  86. package/esm/core/sankey.d.ts.map +1 -0
  87. package/esm/core/sankey.js +135 -0
  88. package/esm/core/scale.d.ts +98 -0
  89. package/esm/core/scale.d.ts.map +1 -0
  90. package/esm/core/scale.js +206 -0
  91. package/esm/core/shape.d.ts +60 -0
  92. package/esm/core/shape.d.ts.map +1 -0
  93. package/esm/core/shape.js +245 -0
  94. package/esm/global.d.ts +6 -0
  95. package/esm/hooks/useChartTheme.d.ts +10 -0
  96. package/esm/hooks/useChartTheme.d.ts.map +1 -0
  97. package/esm/hooks/useChartTheme.js +33 -0
  98. package/esm/hooks/useChartTransition.d.ts +20 -0
  99. package/esm/hooks/useChartTransition.d.ts.map +1 -0
  100. package/esm/hooks/useChartTransition.js +119 -0
  101. package/esm/hooks/useElementSize.d.ts +17 -0
  102. package/esm/hooks/useElementSize.d.ts.map +1 -0
  103. package/esm/hooks/useElementSize.js +46 -0
  104. package/esm/index.d.ts +62 -0
  105. package/esm/index.d.ts.map +1 -0
  106. package/esm/index.js +47 -0
  107. package/esm/internal/CartesianChart.d.ts +16 -0
  108. package/esm/internal/CartesianChart.d.ts.map +1 -0
  109. package/esm/internal/CartesianChart.js +810 -0
  110. package/esm/internal/model.d.ts +67 -0
  111. package/esm/internal/model.d.ts.map +1 -0
  112. package/esm/internal/model.js +145 -0
  113. package/esm/scene/canvas.d.ts +18 -0
  114. package/esm/scene/canvas.d.ts.map +1 -0
  115. package/esm/scene/canvas.js +137 -0
  116. package/esm/scene/svg.d.ts +12 -0
  117. package/esm/scene/svg.d.ts.map +1 -0
  118. package/esm/scene/svg.js +115 -0
  119. package/esm/scene/types.d.ts +89 -0
  120. package/esm/scene/types.d.ts.map +1 -0
  121. package/esm/scene/types.js +20 -0
  122. package/esm/style.css +196 -0
  123. package/esm/theme/index.d.ts +127 -0
  124. package/esm/theme/index.d.ts.map +1 -0
  125. package/esm/theme/index.js +297 -0
  126. package/esm/types.d.ts +168 -0
  127. package/esm/types.d.ts.map +1 -0
  128. package/esm/types.js +1 -0
  129. package/package.json +64 -3
@@ -0,0 +1,810 @@
1
+ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
2
+ import { classNames, prefixCls } from '@aura-react-comp/shared';
3
+ import { SvgScene } from "../scene/svg";
4
+ import { paintScene } from "../scene/canvas";
5
+ import { createBandScale, createLinearScale, linearTicks } from "../core/scale";
6
+ import { computeLayout, suggestTickCount } from "../core/layout";
7
+ import { estimateTextWidth, formatNumber } from "../core/format";
8
+ import { sampleSeriesIndices } from "../core/sampling";
9
+ import { linePath, roundedRectPath } from "../core/shape";
10
+ import { withAlpha } from "../theme";
11
+ import { useChartTheme } from "../hooks/useChartTheme";
12
+ import { useElementSize } from "../hooks/useElementSize";
13
+ import { useChartTransition } from "../hooks/useChartTransition";
14
+ import { resolveAnimation, staggerProgress } from "../core/animation";
15
+ import { applyStacking, assignDefaultStack, buildTooltipItems, resolveSeries, resolveXValues, resolveYDomain } from "./model";
16
+ import { Legend } from "../components/Legend";
17
+ 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;
32
+ function CanvasScene({
33
+ nodes,
34
+ width,
35
+ height
36
+ }) {
37
+ const ref = useRef(null);
38
+ useEffect(() => {
39
+ if (ref.current) paintScene(ref.current, nodes, {
40
+ dpr: undefined
41
+ });
42
+ }, [nodes, width, height]);
43
+ return /*#__PURE__*/_jsx("canvas", {
44
+ ref: ref,
45
+ className: prefixCls('chart__canvas'),
46
+ style: {
47
+ width,
48
+ height
49
+ }
50
+ // 无障碍由外层的隐藏数据表承担,canvas 本身对读屏器无意义
51
+ ,
52
+ "aria-hidden": "true"
53
+ });
54
+ }
55
+
56
+ /**
57
+ * 直角坐标系图表内核。
58
+ *
59
+ * 折线 / 柱状 / 面积 / 折柱混合全部由它渲染 —— 差异只在 series.type。
60
+ * 这样组合图(一个系列折线、一个系列柱子)天然支持,无需额外组件。
61
+ */
62
+ export function CartesianChart(props) {
63
+ const {
64
+ data = [],
65
+ xKey = 'x',
66
+ series: seriesConfig = [],
67
+ width = '100%',
68
+ height = 320,
69
+ theme: themeInput,
70
+ palette,
71
+ legend = true,
72
+ tooltip = true,
73
+ grid = true,
74
+ animation = true,
75
+ renderer = 'auto',
76
+ xAxis,
77
+ yAxis,
78
+ yAxisRight,
79
+ dataZoom,
80
+ defaultZoom,
81
+ zoom,
82
+ onZoomChange,
83
+ sampling,
84
+ className,
85
+ style,
86
+ ariaLabel,
87
+ emptyText = '暂无数据',
88
+ onPointClick,
89
+ valueFormatter,
90
+ defaultType,
91
+ stack = false
92
+ } = props;
93
+ const theme = useChartTheme(themeInput, palette);
94
+ const {
95
+ ref: plotRef,
96
+ size
97
+ } = useElementSize();
98
+ const [hiddenKeys, setHiddenKeys] = useState([]);
99
+ const [activeIndex, setActiveIndex] = useState(null);
100
+ const hiddenSet = useMemo(() => new Set(hiddenKeys), [hiddenKeys]);
101
+
102
+ // ---- dataZoom 窗口 ----
103
+ const [innerZoom, setInnerZoom] = useState(defaultZoom ?? [0, 1]);
104
+ const zoomRange = zoom ?? innerZoom;
105
+ const zoomEnabled = dataZoom !== undefined && dataZoom !== false;
106
+ const zoomOptions = typeof dataZoom === 'object' ? dataZoom : {};
107
+ const allXValues = useMemo(() => resolveXValues(data, xKey), [data, xKey]);
108
+ const windowed = useMemo(() => {
109
+ const total = allXValues.length;
110
+ if (!zoomEnabled || total <= 1) {
111
+ return {
112
+ data,
113
+ xValues: allXValues,
114
+ from: 0,
115
+ to: Math.max(0, total - 1)
116
+ };
117
+ }
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))));
121
+ return {
122
+ data: data.slice(from, to + 1),
123
+ xValues: allXValues.slice(from, to + 1),
124
+ from,
125
+ to
126
+ };
127
+ }, [data, allXValues, zoomEnabled, zoomRange]);
128
+
129
+ /**
130
+ * 降采样:只对窗口内的点做,且多系列共用同一套下标
131
+ * (各自采样会让折线错位,看起来像两列数据互相穿插)。
132
+ */
133
+ const sampledIndices = useMemo(() => {
134
+ const threshold = sampling === false ? 0 : sampling ?? DEFAULT_SAMPLING;
135
+ 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);
142
+ }, [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]);
153
+ const zoomTrackRef = useRef(null);
154
+ const dragRef = useRef(null);
155
+ // 拖拽回调里要用最新窗口,放进 ref 避免事件闭包拿到旧值
156
+ const zoomRef = useRef(zoomRange);
157
+ zoomRef.current = zoomRange;
158
+ const beginDrag = mode => event => {
159
+ event.preventDefault();
160
+ event.stopPropagation();
161
+ dragRef.current = {
162
+ mode,
163
+ startX: event.clientX,
164
+ initial: zoomRef.current
165
+ };
166
+ };
167
+ useEffect(() => {
168
+ if (!zoomEnabled) return undefined;
169
+ const onMove = event => {
170
+ const drag = dragRef.current;
171
+ const track = zoomTrackRef.current;
172
+ if (!drag || !track) return;
173
+ const width = track.getBoundingClientRect().width || 1;
174
+ const delta = (event.clientX - drag.startX) / width;
175
+ const [from, to] = drag.initial;
176
+ const span = to - from;
177
+ if (drag.mode === 'move') {
178
+ const start = Math.min(1 - span, Math.max(0, from + delta));
179
+ applyZoom([start, start + span]);
180
+ } else if (drag.mode === 'start') {
181
+ applyZoom([Math.max(0, Math.min(to - 0.02, from + delta)), to]);
182
+ } else {
183
+ applyZoom([from, Math.max(from + 0.02, Math.min(1, to + delta))]);
184
+ }
185
+ };
186
+ const onUp = () => {
187
+ dragRef.current = null;
188
+ };
189
+ window.addEventListener('pointermove', onMove);
190
+ window.addEventListener('pointerup', onUp);
191
+ return () => {
192
+ window.removeEventListener('pointermove', onMove);
193
+ window.removeEventListener('pointerup', onUp);
194
+ };
195
+ }, [zoomEnabled, applyZoom]);
196
+ const resolved = useMemo(() => {
197
+ const list = resolveSeries({
198
+ data: viewData,
199
+ series: seriesConfig,
200
+ theme,
201
+ defaultType,
202
+ hidden: hiddenSet
203
+ });
204
+ if (stack) assignDefaultStack(list, true);
205
+ applyStacking(list);
206
+ return list;
207
+ }, [viewData, seriesConfig, theme, defaultType, hiddenSet, stack]);
208
+ const visibleSeries = useMemo(() => resolved.filter(item => item.visible), [resolved]);
209
+ const hasVisibleSeries = visibleSeries.length > 0;
210
+ 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 —— 避免「先算布局再算刻度」的循环依赖
238
+ 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]);
241
+ const decimals = useMemo(() => {
242
+ if (yTicks.length < 2) return 0;
243
+ const step = Math.abs(yTicks[1] - yTicks[0]);
244
+ if (step === 0) return 0;
245
+ return Math.min(4, Math.max(0, -Math.floor(Math.log10(step))));
246
+ }, [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
+ /** 柱子的槽位分配:堆叠组共用一个槽位,未堆叠的系列各占一个 */
289
+ const barSlots = useMemo(() => {
290
+ const map = new Map();
291
+ let count = 0;
292
+ for (const item of resolved) {
293
+ if (!item.visible || item.type !== 'bar') continue;
294
+ const slotId = item.stackId ?? `__solo__${item.key}`;
295
+ if (!map.has(slotId)) {
296
+ map.set(slotId, count);
297
+ count += 1;
298
+ }
299
+ }
300
+ return {
301
+ count: Math.max(1, count),
302
+ map
303
+ };
304
+ }, [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]);
312
+ const transition = useChartTransition(matrix, animConfig);
313
+ const progress = transition.progress;
314
+
315
+ // 动画原点:绘图区底部。所有图元由此「长」到目标位置
316
+ const animBaseY = plot.y + plot.height;
317
+ const scene = useMemo(() => {
318
+ if (isEmpty || plot.width <= 0 || plot.height <= 0) return [];
319
+ const nodes = [];
320
+ /** 位置插值:local=0 贴基线,local=1 到目标位置 */
321
+ 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(' ');
326
+ for (const tick of yTicks) {
327
+ const y = yScale.scale(tick);
328
+ nodes.push({
329
+ kind: 'line',
330
+ key: `grid-${tick}`,
331
+ x1: plot.x,
332
+ y1: y,
333
+ x2: plot.x + plot.width,
334
+ y2: y,
335
+ stroke: theme.grid.line,
336
+ strokeWidth: theme.grid.lineWidth,
337
+ strokeDasharray: dash || undefined
338
+ });
339
+ }
340
+ }
341
+
342
+ // ---- 坐标轴 ----
343
+ if (xAxis?.show !== false) {
344
+ nodes.push({
345
+ kind: 'line',
346
+ key: 'x-axis-line',
347
+ x1: plot.x,
348
+ y1: plot.y + plot.height,
349
+ x2: plot.x + plot.width,
350
+ y2: plot.y + plot.height,
351
+ stroke: xAxis?.lineColor ?? theme.axis.line,
352
+ strokeWidth: theme.axis.lineWidth
353
+ });
354
+ const {
355
+ interval,
356
+ rotate,
357
+ fontSize
358
+ } = layout.xAxis;
359
+ xValues.forEach((value, index) => {
360
+ if (interval > 0 && index % interval !== 0) return;
361
+ const cx = xScale.center(value);
362
+ if (cx === undefined) return;
363
+ nodes.push({
364
+ kind: 'text',
365
+ key: `x-label-${index}`,
366
+ x: cx,
367
+ y: rotate ? plot.y + plot.height + theme.axis.tickSize + fontSize + 2 : plot.y + plot.height + theme.axis.tickSize + fontSize,
368
+ text: value,
369
+ fill: xAxis?.labelColor ?? theme.axis.label,
370
+ fontSize,
371
+ anchor: rotate ? 'end' : 'middle',
372
+ rotate: rotate || undefined,
373
+ fontFamily: theme.font.family
374
+ });
375
+ });
376
+ }
377
+ if (yAxis?.show !== false) {
378
+ nodes.push({
379
+ kind: 'line',
380
+ key: 'y-axis-line',
381
+ x1: plot.x,
382
+ y1: plot.y,
383
+ x2: plot.x,
384
+ y2: plot.y + plot.height,
385
+ stroke: yAxis?.lineColor ?? theme.axis.line,
386
+ strokeWidth: theme.axis.lineWidth
387
+ });
388
+ yTicks.forEach((tick, index) => {
389
+ nodes.push({
390
+ kind: 'text',
391
+ key: `y-label-${index}`,
392
+ x: plot.x - theme.axis.tickSize - 4,
393
+ y: yScale.scale(tick),
394
+ text: yLabels[index],
395
+ fill: yAxis?.labelColor ?? theme.axis.label,
396
+ fontSize: theme.font.size,
397
+ anchor: 'end',
398
+ baseline: 'middle',
399
+ fontFamily: theme.font.family
400
+ });
401
+ });
402
+ }
403
+
404
+ // ---- 右侧第二根 y 轴 ----
405
+ if (hasRightAxis && rightConfig?.show !== false) {
406
+ const axisX = plot.x + plot.width;
407
+ nodes.push({
408
+ kind: 'line',
409
+ key: 'y-axis-right-line',
410
+ x1: axisX,
411
+ y1: plot.y,
412
+ x2: axisX,
413
+ y2: plot.y + plot.height,
414
+ stroke: rightConfig?.lineColor ?? theme.axis.line,
415
+ strokeWidth: theme.axis.lineWidth
416
+ });
417
+ yTicksRight.forEach((tick, index) => {
418
+ const y = yScaleRight.scale(tick);
419
+ nodes.push({
420
+ kind: 'text',
421
+ key: `y-right-label-${index}`,
422
+ x: axisX + theme.axis.tickSize + 4,
423
+ y,
424
+ text: yLabelsRight[index],
425
+ fill: rightConfig?.labelColor ?? theme.axis.label,
426
+ fontSize: theme.font.size,
427
+ anchor: 'start',
428
+ baseline: 'middle',
429
+ fontFamily: theme.font.family
430
+ });
431
+ });
432
+ }
433
+
434
+ // ---- 数据图元 ----
435
+ const barSlotWidth = barSlots.count > 0 ? xScale.bandWidth / barSlots.count : xScale.bandWidth;
436
+ let seriesIndex = -1;
437
+ for (const item of resolved) {
438
+ seriesIndex += 1;
439
+ if (!item.visible) continue;
440
+ // 更新阶段这里是从旧值插值来的当前值;入场阶段即目标值
441
+ const row = transition.values[seriesIndex] ?? item.top;
442
+ // 该系列归属哪根 y 轴(双轴图表里右轴系列用右轴比例尺)
443
+ 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) : [];
447
+ const slotId = item.stackId ?? `__solo__${item.key}`;
448
+ const slotIndex = barSlots.map.get(slotId) ?? 0;
449
+ const barWidth = Math.max(1, Math.min(barSlotWidth * 0.72, item.config.barMaxWidth ?? 48));
450
+ row.forEach((value, index) => {
451
+ if (value === null) return;
452
+ const bandLeft = xScale.scale(xValues[index]);
453
+ if (bandLeft === undefined) return;
454
+
455
+ // 错峰:整排柱子从左到右依次生长,而不是同时弹起
456
+ const local = staggerProgress(progress, index, xValues.length, animConfig.stagger);
457
+ const base = item.base[index] ?? 0;
458
+ const topY = animY(yS.scale(value), local);
459
+ const baseY = animY(yS.scale(base), local);
460
+ const y = Math.min(topY, baseY);
461
+ const h = Math.max(1, Math.abs(baseY - topY));
462
+ 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;
474
+ const otherBase = other.base[index] ?? 0;
475
+ return Math.abs(otherBase - (item.top[index] ?? 0)) < 1e-6;
476
+ });
477
+ const roundFarEnd = !hasStackedBeyond;
478
+ const isPositive = value >= base;
479
+ const radius = item.config.barMaxWidth === 0 ? 0 : theme.series.barRadius;
480
+ nodes.push({
481
+ kind: 'path',
482
+ 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
+ }),
494
+ fill: item.color,
495
+ opacity: activeIndex === null || activeIndex === index ? 1 : 0.55,
496
+ pointerEvents: 'none'
497
+ });
498
+ });
499
+ continue;
500
+ }
501
+ if (item.type === 'scatter') {
502
+ row.forEach((value, index) => {
503
+ if (value === null) return;
504
+ const cx = xScale.center(xValues[index]);
505
+ if (cx === undefined) return;
506
+ const local = staggerProgress(progress, index, xValues.length, animConfig.stagger);
507
+ nodes.push({
508
+ kind: 'circle',
509
+ key: `dot-${item.key}-${index}`,
510
+ cx,
511
+ cy: animY(yS.scale(value), local),
512
+ r: activeIndex === index ? theme.series.symbolSize * 0.75 : theme.series.symbolSize * 0.55,
513
+ fill: item.color,
514
+ opacity: activeIndex === null || activeIndex === index ? 0.9 : 0.4,
515
+ pointerEvents: 'none'
516
+ });
517
+ });
518
+ continue;
519
+ }
520
+
521
+ // line / area
522
+ const points = row.map((value, index) => {
523
+ if (value === null) return null;
524
+ 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
+ };
532
+ });
533
+ const curve = item.config.curve ?? 'monotone';
534
+ const wantArea = item.type === 'area' || item.config.area === true;
535
+ 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);
538
+ nodes.push({
539
+ kind: 'path',
540
+ key: `area-${item.key}`,
541
+ d: areaPathOf(points, safeBaseline, curve),
542
+ fill: withAlpha(item.color, item.config.areaOpacity ?? theme.series.areaOpacity),
543
+ pointerEvents: 'none'
544
+ });
545
+ }
546
+ nodes.push({
547
+ kind: 'path',
548
+ key: `line-${item.key}`,
549
+ d: linePath(points, curve),
550
+ fill: 'none',
551
+ stroke: item.color,
552
+ strokeWidth: theme.series.lineWidth,
553
+ linecap: 'round',
554
+ linejoin: 'round',
555
+ opacity: activeIndex === null ? 1 : 0.9,
556
+ pointerEvents: 'none'
557
+ });
558
+
559
+ // 数据点:默认在点数不多时显示,避免密集折线变成「毛毛虫」
560
+ const showSymbol = item.config.showSymbol ?? xValues.length <= 24;
561
+ if (showSymbol) {
562
+ row.forEach((value, index) => {
563
+ if (value === null) return;
564
+ const cx = xScale.center(xValues[index]);
565
+ if (cx === undefined) return;
566
+ const active = activeIndex === index;
567
+ const local = staggerProgress(progress, index, xValues.length, animConfig.stagger);
568
+ nodes.push({
569
+ kind: 'circle',
570
+ key: `symbol-${item.key}-${index}`,
571
+ cx,
572
+ cy: animY(yS.scale(value), local),
573
+ r: active ? theme.series.symbolSize * 0.85 : theme.series.symbolSize * 0.55,
574
+ fill: theme.tooltip.background,
575
+ stroke: item.color,
576
+ strokeWidth: active ? theme.series.emphasisWidth : 2,
577
+ pointerEvents: 'none'
578
+ });
579
+ });
580
+ }
581
+ }
582
+
583
+ // ---- 高亮指示线 ----
584
+ if (activeIndex !== null) {
585
+ const cx = xScale.center(xValues[activeIndex]);
586
+ if (cx !== undefined) {
587
+ nodes.push({
588
+ kind: 'line',
589
+ key: 'indicator',
590
+ x1: cx,
591
+ y1: plot.y,
592
+ x2: cx,
593
+ y2: plot.y + plot.height,
594
+ stroke: theme.axis.line,
595
+ strokeWidth: 1,
596
+ strokeDasharray: '3 3',
597
+ pointerEvents: 'none'
598
+ });
599
+ }
600
+ }
601
+ 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;
620
+ }
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]);
643
+ const tooltipPayload = useMemo(() => {
644
+ if (activeIndex === null || !hasVisibleSeries) return null;
645
+ return {
646
+ label: xValues[activeIndex] ?? '',
647
+ row: data[activeIndex] ?? null,
648
+ series: buildTooltipItems(resolved, activeIndex)
649
+ };
650
+ }, [activeIndex, hasVisibleSeries, xValues, data, resolved]);
651
+ const tooltipPosition = useMemo(() => {
652
+ if (activeIndex === null) return {
653
+ x: 0,
654
+ y: 0
655
+ };
656
+ const cx = xScale.center(xValues[activeIndex]) ?? plot.x;
657
+ let top = plot.y + plot.height;
658
+ for (const item of resolved) {
659
+ if (!item.visible) continue;
660
+ const value = item.top[activeIndex];
661
+ if (value === null || value === undefined) continue;
662
+ const yScaleOfItem = item.config.yAxisIndex === 1 && hasRightAxis ? yScaleRight : yScale;
663
+ top = Math.min(top, yScaleOfItem.scale(value));
664
+ }
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 => ({
673
+ key: item.key,
674
+ name: item.name,
675
+ color: item.color,
676
+ visible: item.visible
677
+ }));
678
+ const toggleSeries = useCallback(key => {
679
+ setHiddenKeys(prev => prev.includes(key) ? prev.filter(item => item !== key) : [...prev, key]);
680
+ }, []);
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
+ });
790
+ }
791
+
792
+ /** 面积填充路径(支持 null 断点),与 linePath 保持同步的分段逻辑 */
793
+ function areaPathOf(points, baseline, curve) {
794
+ const segments = [];
795
+ let current = [];
796
+ for (const point of points) {
797
+ if (point) current.push(point);else if (current.length) {
798
+ segments.push(current);
799
+ current = [];
800
+ }
801
+ }
802
+ if (current.length) segments.push(current);
803
+ return segments.map(segment => {
804
+ if (!segment.length) return '';
805
+ const top = linePath(segment, curve);
806
+ const last = segment[segment.length - 1];
807
+ const first = segment[0];
808
+ return `${top}L${last.x},${baseline}L${first.x},${baseline}Z`;
809
+ }).filter(Boolean).join('');
810
+ }