@agions/taroviz 1.9.0 → 1.10.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.
@@ -0,0 +1,273 @@
1
+ /**
2
+ * useChartHistory - 图表 Undo/Redo Hook
3
+ * 追踪图表配置历史,支持撤销/重做操作和键盘快捷键
4
+ *
5
+ * 特性:
6
+ * - 最多保存 50 条历史记录(可配置)
7
+ * - 自动绑定 Ctrl+Z / Ctrl+Y 键盘快捷键
8
+ * - 支持 ignoreKeys 忽略特定配置字段(如动画、时间戳)
9
+ * - 暴露 canUndo / canRedo 状态
10
+ */
11
+ import { useEffect, useRef, useCallback, useState } from 'react';
12
+ import type { ChartInstance } from './index';
13
+ import type { EChartsOption } from 'echarts';
14
+
15
+ // ============================================================================
16
+ // 类型定义
17
+ // ============================================================================
18
+
19
+ export interface UseChartHistoryOptions {
20
+ /** 最大历史记录数,默认 50 */
21
+ maxHistorySize?: number;
22
+ /** 忽略的顶层配置键(不计入历史),默认 ['animation', 'animationDuration', 'animationEasing', 'animationFrame'] */
23
+ ignoreKeys?: string[];
24
+ /** 是否自动绑定键盘快捷键,默认 true */
25
+ enableKeyboard?: boolean;
26
+ /** 是否在组件卸载时自动清空历史,默认 false */
27
+ clearOnUnmount?: boolean;
28
+ }
29
+
30
+ export interface UseChartHistoryReturn {
31
+ /** 是否可撤销 */
32
+ canUndo: boolean;
33
+ /** 是否可重做 */
34
+ canRedo: boolean;
35
+ /** 当前历史索引 */
36
+ currentIndex: number;
37
+ /** 历史总数 */
38
+ historyCount: number;
39
+ /** 撤销一步 */
40
+ undo: () => void;
41
+ /** 重做一步 */
42
+ redo: () => void;
43
+ /** 跳转到指定历史索引 */
44
+ goTo: (index: number) => void;
45
+ /** 手动推送一条历史记录 */
46
+ push: (option: EChartsOption) => void;
47
+ /** 清空历史记录 */
48
+ clear: () => void;
49
+ }
50
+
51
+ // ============================================================================
52
+ // 工具函数
53
+ // ============================================================================
54
+
55
+ /** 深度省略指定键后比较两个配置是否相等 */
56
+ function omitAndCompare(
57
+ a: unknown,
58
+ b: unknown,
59
+ ignoreKeys: Set<string>
60
+ ): boolean {
61
+ if (a === b) return true;
62
+ if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) {
63
+ return a === b;
64
+ }
65
+
66
+ const aObj = a as Record<string, unknown>;
67
+ const bObj = b as Record<string, unknown>;
68
+ const aKeys = Object.keys(aObj).filter((k) => !ignoreKeys.has(k));
69
+ const bKeys = Object.keys(bObj).filter((k) => !ignoreKeys.has(k));
70
+
71
+ if (aKeys.length !== bKeys.length) return false;
72
+
73
+ for (const key of aKeys) {
74
+ if (!bObj.hasOwnProperty(key)) return false;
75
+ if (!omitAndCompare(aObj[key], bObj[key], ignoreKeys)) return false;
76
+ }
77
+
78
+ return true;
79
+ }
80
+
81
+ // ============================================================================
82
+ // Hook 实现
83
+ // ============================================================================
84
+
85
+ /**
86
+ * 使用图表历史记录(Undo/Redo)
87
+ * @param chartInstance 图表实例
88
+ * @param options 配置选项
89
+ * @returns 历史记录控制接口
90
+ */
91
+ export function useChartHistory(
92
+ chartInstance: ChartInstance | null,
93
+ options: UseChartHistoryOptions = {}
94
+ ): UseChartHistoryReturn {
95
+ const {
96
+ maxHistorySize = 50,
97
+ ignoreKeys = [
98
+ 'animation',
99
+ 'animationDuration',
100
+ 'animationEasing',
101
+ 'animationFrame',
102
+ ],
103
+ enableKeyboard = true,
104
+ clearOnUnmount = false,
105
+ } = options;
106
+
107
+ // 忽略键集合
108
+ const ignoreKeySet = useRef(new Set<string>(ignoreKeys));
109
+
110
+ // 历史栈(每次 setOption 快照)
111
+ const historyStack = useRef<EChartsOption[]>([]);
112
+
113
+ // 当前索引
114
+ const [currentIndex, setCurrentIndex] = useState(-1);
115
+
116
+ // Chart instance ref
117
+ const chartRef = useRef<ChartInstance | null>(null);
118
+ chartRef.current = chartInstance;
119
+
120
+ // 是否正在执行 undo/redo(避免 push 时重复记录)
121
+ const isApplyingRef = useRef(false);
122
+
123
+ // 拦截 chart.setOption,记录历史
124
+ useEffect(() => {
125
+ const chart = chartRef.current;
126
+ if (!chart) return;
127
+
128
+ const originalSetOption = chart.setOption.bind(chart);
129
+
130
+ chart.setOption = (
131
+ option: EChartsOption,
132
+ notMerge?: boolean,
133
+ lazyUpdate?: boolean
134
+ ) => {
135
+ // 如果正在执行 undo/redo,跳过历史记录
136
+ if (isApplyingRef.current) {
137
+ return originalSetOption(option, notMerge, lazyUpdate);
138
+ }
139
+
140
+ const stack = historyStack.current;
141
+ const idx = currentIndex;
142
+
143
+ // 如果当前索引不在栈顶,丢弃redo历史(类似 Git 行为)
144
+ const newStack = idx < stack.length - 1 ? stack.slice(0, idx + 1) : [...stack];
145
+
146
+ // 检查是否与上一次配置相同(忽略动画字段)
147
+ const lastOption = newStack[newStack.length - 1];
148
+ if (lastOption && omitAndCompare(lastOption, option, ignoreKeySet.current)) {
149
+ // 配置没变,直接应用
150
+ return originalSetOption(option, notMerge, lazyUpdate);
151
+ }
152
+
153
+ // 入栈
154
+ newStack.push(option);
155
+
156
+ // 裁剪超出 maxHistorySize
157
+ if (newStack.length > maxHistorySize) {
158
+ newStack.shift();
159
+ } else {
160
+ // 更新索引
161
+ setCurrentIndex(newStack.length - 1);
162
+ }
163
+
164
+ historyStack.current = newStack;
165
+ return originalSetOption(option, notMerge, lazyUpdate);
166
+ };
167
+
168
+ return () => {
169
+ // 恢复原始 setOption
170
+ chart.setOption = originalSetOption;
171
+ };
172
+ }, [chartInstance, currentIndex, maxHistorySize]);
173
+
174
+ // 键盘快捷键:Ctrl+Z 撤销,Ctrl+Y / Ctrl+Shift+Z 重做
175
+ useEffect(() => {
176
+ if (!enableKeyboard) return;
177
+
178
+ const handleKeyDown = (e: KeyboardEvent) => {
179
+ const isMod = e.ctrlKey || e.metaKey;
180
+ if (!isMod) return;
181
+
182
+ if (e.key === 'z' && !e.shiftKey) {
183
+ e.preventDefault();
184
+ undo();
185
+ } else if (e.key === 'y' || (e.key === 'z' && e.shiftKey)) {
186
+ e.preventDefault();
187
+ redo();
188
+ }
189
+ };
190
+
191
+ window.addEventListener('keydown', handleKeyDown);
192
+ return () => window.removeEventListener('keydown', handleKeyDown);
193
+ }, [enableKeyboard]); // eslint-disable-line react-hooks/exhaustive-deps
194
+
195
+ // 组件卸载时清空
196
+ useEffect(() => {
197
+ return () => {
198
+ if (clearOnUnmount) {
199
+ historyStack.current = [];
200
+ setCurrentIndex(-1);
201
+ }
202
+ };
203
+ }, [clearOnUnmount]);
204
+
205
+ // ─── Public API ───────────────────────────────────────────────────────────
206
+
207
+ const undo = useCallback(() => {
208
+ const chart = chartRef.current;
209
+ if (!chart || currentIndex <= 0) return;
210
+
211
+ const idx = currentIndex - 1;
212
+ isApplyingRef.current = true;
213
+ chart.setOption(historyStack.current[idx], true, true);
214
+ isApplyingRef.current = false;
215
+ setCurrentIndex(idx);
216
+ }, [currentIndex]);
217
+
218
+ const redo = useCallback(() => {
219
+ const chart = chartRef.current;
220
+ if (!chart || currentIndex >= historyStack.current.length - 1) return;
221
+
222
+ const idx = currentIndex + 1;
223
+ isApplyingRef.current = true;
224
+ chart.setOption(historyStack.current[idx], true, true);
225
+ isApplyingRef.current = false;
226
+ setCurrentIndex(idx);
227
+ }, [currentIndex]);
228
+
229
+ const goTo = useCallback(
230
+ (index: number) => {
231
+ const chart = chartRef.current;
232
+ if (!chart) return;
233
+ if (index < 0 || index >= historyStack.current.length) return;
234
+ if (index === currentIndex) return;
235
+
236
+ isApplyingRef.current = true;
237
+ chart.setOption(historyStack.current[index], true, true);
238
+ isApplyingRef.current = false;
239
+ setCurrentIndex(index);
240
+ },
241
+ [currentIndex]
242
+ );
243
+
244
+ const push = useCallback((option: EChartsOption) => {
245
+ const stack = historyStack.current;
246
+ const idx = currentIndex;
247
+
248
+ const newStack = idx < stack.length - 1 ? stack.slice(0, idx + 1) : [...stack];
249
+ newStack.push(option);
250
+ if (newStack.length > maxHistorySize) newStack.shift();
251
+ historyStack.current = newStack;
252
+ setCurrentIndex(newStack.length - 1);
253
+ }, [currentIndex, maxHistorySize]);
254
+
255
+ const clear = useCallback(() => {
256
+ historyStack.current = [];
257
+ setCurrentIndex(-1);
258
+ }, []);
259
+
260
+ return {
261
+ canUndo: currentIndex > 0,
262
+ canRedo: currentIndex < historyStack.current.length - 1,
263
+ currentIndex,
264
+ historyCount: historyStack.current.length,
265
+ undo,
266
+ redo,
267
+ goTo,
268
+ push,
269
+ clear,
270
+ };
271
+ }
272
+
273
+ export default useChartHistory;
@@ -0,0 +1,350 @@
1
+ /**
2
+ * useChartSelection - 图表数据点选择/高亮 Hook
3
+ * 支持单个/批量选择、反选、清除选择,配合 ECharts select 事件
4
+ *
5
+ * 特性:
6
+ * - 支持按 seriesIndex + dataIndex 选择
7
+ * - 支持按 dataIndex 跨系列批量选择
8
+ * - 支持反选(invertSelection)
9
+ * - 支持多选模式(multi)
10
+ * - 自动绑定图表 select/unselect 事件
11
+ */
12
+ import { useEffect, useRef, useCallback, useState } from 'react';
13
+ import type { ChartInstance } from './index';
14
+
15
+ // ============================================================================
16
+ // 类型定义
17
+ // ============================================================================
18
+
19
+ /** 单个数据点的选择键 */
20
+ export interface DataPointKey {
21
+ seriesIndex: number;
22
+ dataIndex: number;
23
+ }
24
+
25
+ /** 选择模式 */
26
+ export type SelectionMode = 'single' | 'multiple';
27
+
28
+ /** 选择事件参数 */
29
+ export interface SelectionEvent {
30
+ /** 被选中的数据点 */
31
+ selected: DataPointKey[];
32
+ /** 取消选择的数据点 */
33
+ unselected: DataPointKey[];
34
+ }
35
+
36
+ /** 选择配置选项 */
37
+ export interface UseChartSelectionOptions {
38
+ /** 选择模式:'single' 单选,'multiple' 多选,默认 'multiple' */
39
+ mode?: SelectionMode;
40
+ /** 是否在组件卸载时清除所有选择,默认 true */
41
+ clearOnUnmount?: boolean;
42
+ /** 是否启用 Ctrl+Click 多选,默认 true */
43
+ enableCtrlMultiSelect?: boolean;
44
+ /** 是否启用 Shift+Click 范围选择,默认 true */
45
+ enableShiftRangeSelect?: boolean;
46
+ /** 选择变化时的回调 */
47
+ onSelectionChange?: (event: SelectionEvent) => void;
48
+ }
49
+
50
+ /** 选择返回值 */
51
+ export interface UseChartSelectionReturn {
52
+ /** 当前选中的数据点 */
53
+ selectedPoints: DataPointKey[];
54
+ /** 是否存在选中 */
55
+ hasSelection: boolean;
56
+ /** 选中数量 */
57
+ selectionCount: number;
58
+ /** 选中指定数据点 */
59
+ select: (key: DataPointKey) => void;
60
+ /** 取消选中指定数据点 */
61
+ deselect: (key: DataPointKey) => void;
62
+ /** 批量选中 */
63
+ selectMultiple: (keys: DataPointKey[]) => void;
64
+ /** 批量取消选中 */
65
+ deselectMultiple: (keys: DataPointKey[]) => void;
66
+ /** 切换选中状态 */
67
+ toggle: (key: DataPointKey) => void;
68
+ /** 反选 */
69
+ invertSelection: (seriesIndex: number, dataIndices: number[]) => void;
70
+ /** 全选指定系列 */
71
+ selectAll: (seriesIndex: number, dataIndices: number[]) => void;
72
+ /** 清除所有选择 */
73
+ clearSelection: () => void;
74
+ /** 判断某点是否被选中 */
75
+ isSelected: (key: DataPointKey) => boolean;
76
+ }
77
+
78
+ // ============================================================================
79
+ // 工具函数
80
+ // ============================================================================
81
+
82
+ /** 生成唯一键字符串 */
83
+ function keyToString(key: DataPointKey): string {
84
+ return `${key.seriesIndex}:${key.dataIndex}`;
85
+ }
86
+
87
+ function stringToKey(str: string): DataPointKey {
88
+ const [seriesIndex, dataIndex] = str.split(':').map(Number);
89
+ return { seriesIndex, dataIndex };
90
+ }
91
+
92
+ // ============================================================================
93
+ // Hook 实现
94
+ // ============================================================================
95
+
96
+ /**
97
+ * 使用图表数据点选择功能
98
+ * @param chartInstance 图表实例
99
+ * @param options 配置选项
100
+ * @returns 选择控制接口
101
+ */
102
+ export function useChartSelection(
103
+ chartInstance: ChartInstance | null,
104
+ options: UseChartSelectionOptions = {}
105
+ ): UseChartSelectionReturn {
106
+ const {
107
+ mode = 'multiple',
108
+ clearOnUnmount = true,
109
+ enableCtrlMultiSelect = true,
110
+ enableShiftRangeSelect = true,
111
+ onSelectionChange,
112
+ } = options;
113
+
114
+ // 选中点集合(字符串键)
115
+ const [selectedPoints, setSelectedPoints] = useState<DataPointKey[]>([]);
116
+
117
+ // Chart instance ref
118
+ const chartRef = useRef<ChartInstance | null>(null);
119
+ chartRef.current = chartInstance;
120
+
121
+ // 上一次 shift+click 的数据索引(用于范围选择)
122
+ const lastShiftIndexRef = useRef<number | null>(null);
123
+
124
+ // 当前模式 ref(用于事件处理)
125
+ const modeRef = useRef(mode);
126
+ modeRef.current = mode;
127
+
128
+ // 绑定图表 select/unselect 事件
129
+ useEffect(() => {
130
+ const chart = chartRef.current;
131
+ if (!chart || !chart.on) return;
132
+
133
+ const handleSelect = (params: { selected: Record<string, boolean>; type: string }) => {
134
+ // ECharts 内置 select 会同步更新 legend
135
+ // 这里我们用 dispatchAction 来实现纯数据点选择
136
+ };
137
+
138
+ // 单击 legend 时清除数据点选择(保持一致性)
139
+ const handleLegendSelectChanged = (params: { name?: string; selected?: Record<string, boolean> }) => {
140
+ // 清除选择时的视觉反馈
141
+ };
142
+
143
+ chart.on('selectchanged', (params: unknown) => {
144
+ // 当图表内部选择变化时同步状态
145
+ const p = params as {
146
+ isFromClick?: boolean;
147
+ selected?: Record<string, boolean>;
148
+ notSelected?: Record<string, boolean>;
149
+ };
150
+ if (p.isFromClick) {
151
+ // 用户点击了图例,清除所有数据点选择
152
+ setSelectedPoints([]);
153
+ onSelectionChange?.({ selected: [], unselected: [] });
154
+ }
155
+ });
156
+
157
+ return () => {
158
+ if (chart.off) {
159
+ chart.off('selectchanged');
160
+ }
161
+ };
162
+ }, [onSelectionChange]);
163
+
164
+ // 组件卸载时清除选择
165
+ useEffect(() => {
166
+ return () => {
167
+ if (clearOnUnmount) {
168
+ const chart = chartRef.current;
169
+ if (chart?.dispatchAction) {
170
+ // 清除所有系列的选择状态
171
+ chart.dispatchAction({ type: 'unselect' });
172
+ }
173
+ }
174
+ };
175
+ }, [clearOnUnmount]);
176
+
177
+ // ─── 私有方法 ───────────────────────────────────────────────────────────────
178
+
179
+ /** 触发选择变化回调 */
180
+ const notifyChange = useCallback(
181
+ (selected: DataPointKey[], unselected: DataPointKey[]) => {
182
+ onSelectionChange?.({ selected, unselected });
183
+ },
184
+ [onSelectionChange]
185
+ );
186
+
187
+ /** 执行 ECharts dispatchAction */
188
+ const dispatchSelect = useCallback(
189
+ (key: DataPointKey, select: boolean) => {
190
+ const chart = chartRef.current;
191
+ if (!chart?.dispatchAction) return;
192
+ chart.dispatchAction({
193
+ type: select ? 'select' : 'unselect',
194
+ seriesIndex: key.seriesIndex,
195
+ dataIndex: key.dataIndex,
196
+ });
197
+ },
198
+ []
199
+ );
200
+
201
+ // ─── Public API ───────────────────────────────────────────────────────────
202
+
203
+ const select = useCallback(
204
+ (key: DataPointKey) => {
205
+ setSelectedPoints((prev) => {
206
+ const str = keyToString(key);
207
+ if (prev.some((p) => keyToString(p) === str)) return prev;
208
+ const next = mode === 'single' ? [key] : [...prev, key];
209
+ notifyChange(next, []);
210
+ return next;
211
+ });
212
+ dispatchSelect(key, true);
213
+ },
214
+ [mode, notifyChange, dispatchSelect]
215
+ );
216
+
217
+ const deselect = useCallback(
218
+ (key: DataPointKey) => {
219
+ setSelectedPoints((prev) => {
220
+ const str = keyToString(key);
221
+ const removed = prev.filter((p) => keyToString(p) !== str);
222
+ notifyChange([], removed);
223
+ return removed;
224
+ });
225
+ dispatchSelect(key, false);
226
+ },
227
+ [notifyChange, dispatchSelect]
228
+ );
229
+
230
+ const toggle = useCallback(
231
+ (key: DataPointKey) => {
232
+ const str = keyToString(key);
233
+ if (selectedPoints.some((p) => keyToString(p) === str)) {
234
+ deselect(key);
235
+ } else {
236
+ select(key);
237
+ }
238
+ },
239
+ [selectedPoints, select, deselect]
240
+ );
241
+
242
+ const selectMultiple = useCallback(
243
+ (keys: DataPointKey[]) => {
244
+ setSelectedPoints((prev) => {
245
+ const newPoints = mode === 'single' ? keys : [...prev, ...keys.filter(
246
+ (k) => !prev.some((p) => keyToString(p) === keyToString(k))
247
+ )];
248
+ notifyChange(newPoints, []);
249
+ return newPoints;
250
+ });
251
+ keys.forEach((key) => dispatchSelect(key, true));
252
+ },
253
+ [mode, notifyChange, dispatchSelect]
254
+ );
255
+
256
+ const deselectMultiple = useCallback(
257
+ (keys: DataPointKey[]) => {
258
+ setSelectedPoints((prev) => {
259
+ const keySet = new Set(keys.map(keyToString));
260
+ const removed = prev.filter((p) => keySet.has(keyToString(p)));
261
+ const remaining = prev.filter((p) => !keySet.has(keyToString(p)));
262
+ notifyChange([], removed);
263
+ return remaining;
264
+ });
265
+ keys.forEach((key) => dispatchSelect(key, false));
266
+ },
267
+ [notifyChange, dispatchSelect]
268
+ );
269
+
270
+ const invertSelection = useCallback(
271
+ (seriesIndex: number, dataIndices: number[]) => {
272
+ setSelectedPoints((prev) => {
273
+ const selectedSet = new Set(prev.filter((p) => p.seriesIndex === seriesIndex).map((p) => p.dataIndex));
274
+ const toSelect: DataPointKey[] = [];
275
+ const toDeselect: DataPointKey[] = [];
276
+
277
+ dataIndices.forEach((dataIndex) => {
278
+ const key = { seriesIndex, dataIndex };
279
+ const str = keyToString(key);
280
+ if (selectedSet.has(dataIndex)) {
281
+ toDeselect.push(key);
282
+ } else {
283
+ toSelect.push(key);
284
+ }
285
+ });
286
+
287
+ toDeselect.forEach((k) => dispatchSelect(k, false));
288
+ toSelect.forEach((k) => dispatchSelect(k, true));
289
+
290
+ const newSelected = prev.filter(
291
+ (p) => !(p.seriesIndex === seriesIndex && selectedSet.has(p.dataIndex))
292
+ ).concat(toSelect);
293
+
294
+ notifyChange(toSelect, toDeselect);
295
+ return newSelected;
296
+ });
297
+ },
298
+ [notifyChange, dispatchSelect]
299
+ );
300
+
301
+ const selectAll = useCallback(
302
+ (seriesIndex: number, dataIndices: number[]) => {
303
+ const keys = dataIndices.map((dataIndex) => ({ seriesIndex, dataIndex }));
304
+ setSelectedPoints((prev) => {
305
+ const newPoints = mode === 'single' ? keys : [...prev, ...keys.filter(
306
+ (k) => !prev.some((p) => keyToString(p) === keyToString(k))
307
+ )];
308
+ notifyChange(newPoints, []);
309
+ return newPoints;
310
+ });
311
+ keys.forEach((key) => dispatchSelect(key, true));
312
+ },
313
+ [mode, notifyChange, dispatchSelect]
314
+ );
315
+
316
+ const clearSelection = useCallback(() => {
317
+ const chart = chartRef.current;
318
+ if (chart?.dispatchAction) {
319
+ chart.dispatchAction({ type: 'unselect' });
320
+ }
321
+ const prev = selectedPoints;
322
+ setSelectedPoints([]);
323
+ notifyChange([], prev);
324
+ }, [selectedPoints, notifyChange]);
325
+
326
+ const isSelected = useCallback(
327
+ (key: DataPointKey) => {
328
+ const str = keyToString(key);
329
+ return selectedPoints.some((p) => keyToString(p) === str);
330
+ },
331
+ [selectedPoints]
332
+ );
333
+
334
+ return {
335
+ selectedPoints,
336
+ hasSelection: selectedPoints.length > 0,
337
+ selectionCount: selectedPoints.length,
338
+ select,
339
+ deselect,
340
+ selectMultiple,
341
+ deselectMultiple,
342
+ toggle,
343
+ invertSelection,
344
+ selectAll,
345
+ clearSelection,
346
+ isSelected,
347
+ };
348
+ }
349
+
350
+ export default useChartSelection;