useECharts.ts 8.0 KB
Newer Older
P
Peter Pan 已提交
1 2
import {MutableRefObject, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState} from 'react';
import {position, primaryColor, size} from '~/utils/style';
3

4
import type {ECharts} from 'echarts';
P
Peter Pan 已提交
5 6
import {dataURL2Blob} from '~/utils/image';
import {saveAs} from 'file-saver';
P
Peter Pan 已提交
7
import styled from 'styled-components';
P
Peter Pan 已提交
8 9
import {themes} from '~/utils/theme';
import useTheme from '~/hooks/useTheme';
10

11
export type Options = {
P
Peter Pan 已提交
12
    loading?: boolean;
13
    gl?: boolean;
P
Peter Pan 已提交
14
    zoom?: boolean;
P
Peter Pan 已提交
15
    autoFit?: boolean;
16 17 18 19 20 21 22
    onInit?: (echarts: ECharts) => unknown;
    onDispose?: (echarts: ECharts) => unknown;
};

const useECharts = <T extends HTMLElement, W extends HTMLElement = HTMLDivElement>(
    options: Options
): {
P
Peter Pan 已提交
23
    ref: MutableRefObject<T | null>;
P
Peter Pan 已提交
24 25
    wrapper: MutableRefObject<W | null>;
    echart: ECharts | null;
P
Peter Pan 已提交
26
    saveAsImage: (filename?: string) => void;
P
Peter Pan 已提交
27
} => {
28
    const ref = useRef<T | null>(null);
P
Peter Pan 已提交
29
    const [echart, setEchart] = useState<ECharts | null>(null);
P
Peter Pan 已提交
30
    const theme = useTheme();
31

32 33 34
    const onInit = useRef(options.onInit);
    const onDispose = useRef(options.onDispose);

P
Peter Pan 已提交
35
    const hideTip = useCallback(() => echart?.dispatchAction({type: 'hideTip'}), [echart]);
36

37
    const createChart = useCallback(() => {
P
Peter Pan 已提交
38
        (async () => {
P
Peter Pan 已提交
39 40 41 42
            if (!ref.current) {
                return;
            }

43
            const {default: echarts} = await import('echarts');
P
Peter Pan 已提交
44 45 46
            if (options.gl) {
                await import('echarts-gl');
            }
P
Peter Pan 已提交
47 48

            const echartInstance = echarts.init((ref.current as unknown) as HTMLDivElement);
49

50 51
            ref.current.addEventListener('mouseleave', hideTip);

52 53
            setTimeout(() => {
                if (options.zoom) {
P
Peter Pan 已提交
54
                    echartInstance.dispatchAction({
P
Peter Pan 已提交
55 56 57 58
                        type: 'takeGlobalCursor',
                        key: 'dataZoomSelect',
                        dataZoomSelectActive: true
                    });
59 60
                }

P
Peter Pan 已提交
61 62
                if (echartInstance) {
                    onInit.current?.(echartInstance);
63 64 65
                }
            }, 0);

P
Peter Pan 已提交
66
            setEchart(echartInstance);
P
Peter Pan 已提交
67
        })();
68
    }, [options.gl, options.zoom, hideTip]);
69 70

    const destroyChart = useCallback(() => {
P
Peter Pan 已提交
71 72 73 74 75
        if (echart) {
            onDispose.current?.(echart);
            echart.dispose();
            ref.current?.removeEventListener('mouseleave', hideTip);
            setEchart(null);
76
        }
P
Peter Pan 已提交
77
    }, [hideTip, echart]);
78 79

    useEffect(() => {
80 81
        createChart();
        return destroyChart;
82 83 84
    }, [createChart, destroyChart]);

    useEffect(() => {
85
        if (options.loading) {
P
Peter Pan 已提交
86
            echart?.showLoading('default', {
87 88
                text: '',
                color: primaryColor,
P
Peter Pan 已提交
89 90
                textColor: themes[theme].textColor,
                maskColor: themes[theme].maskColor,
91 92 93
                zlevel: 0
            });
        } else {
P
Peter Pan 已提交
94
            echart?.hideLoading();
95
        }
P
Peter Pan 已提交
96
    }, [options.loading, theme, echart]);
P
Peter Pan 已提交
97 98 99

    const wrapper = useRef<W | null>(null);
    useLayoutEffect(() => {
100
        if (options.autoFit) {
P
Peter Pan 已提交
101 102 103
            const w = wrapper.current;
            if (w) {
                const observer = new ResizeObserver(() => {
P
Peter Pan 已提交
104
                    echart?.resize();
P
Peter Pan 已提交
105 106 107 108 109
                });
                observer.observe(w);
                return () => observer.unobserve(w);
            }
        }
P
Peter Pan 已提交
110
    }, [options.autoFit, echart]);
111

P
Peter Pan 已提交
112 113 114 115 116 117 118 119 120 121 122
    const saveAsImage = useCallback(
        (filename?: string) => {
            if (echart) {
                const blob = dataURL2Blob(echart.getDataURL({type: 'png', pixelRatio: 2, backgroundColor: '#FFF'}));
                saveAs(blob, `${filename?.replace(/[/\\?%*:|"<>]/g, '_') || 'chart'}.png`);
            }
        },
        [echart]
    );

    return {ref, echart, wrapper, saveAsImage};
123 124 125
};

export default useECharts;
P
Peter Pan 已提交
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144

export const Wrapper = styled.div`
    position: relative;
    display: flex;
    justify-content: center;
    align-items: stretch;

    > .echarts {
        width: 100%;
    }

    > .loading {
        ${size('100%')}
        ${position('absolute', 0, null, null, 0)}
        display: flex;
        justify-content: center;
        align-items: center;
    }
`;
P
Peter Pan 已提交
145 146 147 148

export const useChartTheme = (gl?: boolean) => {
    const theme = useTheme();
    const tt = useMemo(() => themes[theme], [theme]);
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
    const result = useMemo(() => {
        if (gl) {
            return {
                title: {
                    textStyle: {
                        color: tt.textColor
                    }
                },
                tooltip: {
                    backgroundColor: tt.tooltipBackgroundColor,
                    borderColor: tt.tooltipBackgroundColor,
                    textStyle: {
                        color: tt.tooltipTextColor
                    }
                },
                xAxis3D: {
                    nameTextStyle: {
                        color: tt.textLighterColor
                    },
                    axisLabel: {
                        color: tt.textLighterColor
                    },
                    axisLine: {
                        lineStyle: {
                            color: tt.borderColor
                        }
                    },
                    splitLine: {
                        lineStyle: {
                            color: tt.borderColor
                        }
                    }
                },
                yAxis3D: {
                    nameTextStyle: {
                        color: tt.textLighterColor
                    },
                    axisLabel: {
                        color: tt.textLighterColor
                    },
                    axisLine: {
                        lineStyle: {
                            color: tt.borderColor
                        }
                    },
                    splitLine: {
                        lineStyle: {
                            color: tt.borderColor
                        }
                    }
                },
                zAxis3D: {
                    nameTextStyle: {
                        color: tt.textLighterColor
                    },
                    axisLabel: {
                        color: tt.textLighterColor
                    },
                    axisLine: {
                        lineStyle: {
                            color: tt.borderColor
                        }
                    },
                    splitLine: {
                        lineStyle: {
                            color: tt.borderColor
                        }
                    }
                }
            };
        }
P
Peter Pan 已提交
220 221 222 223 224 225 226 227 228 229 230 231 232
        return {
            title: {
                textStyle: {
                    color: tt.textColor
                }
            },
            tooltip: {
                backgroundColor: tt.tooltipBackgroundColor,
                borderColor: tt.tooltipBackgroundColor,
                textStyle: {
                    color: tt.tooltipTextColor
                }
            },
233
            xAxis: {
P
Peter Pan 已提交
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
                nameTextStyle: {
                    color: tt.textLighterColor
                },
                axisLabel: {
                    color: tt.textLighterColor
                },
                axisLine: {
                    lineStyle: {
                        color: tt.borderColor
                    }
                },
                splitLine: {
                    lineStyle: {
                        color: tt.borderColor
                    }
                }
            },
251
            yAxis: {
P
Peter Pan 已提交
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
                nameTextStyle: {
                    color: tt.textLighterColor
                },
                axisLabel: {
                    color: tt.textLighterColor
                },
                axisLine: {
                    lineStyle: {
                        color: tt.borderColor
                    }
                },
                splitLine: {
                    lineStyle: {
                        color: tt.borderColor
                    }
                }
            }
        };
270 271
    }, [tt, gl]);
    return result;
P
Peter Pan 已提交
272
};