useECharts.ts 7.6 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 29
    const ref = useRef<T | null>(null);
    const echartInstance = useRef<ECharts | null>(null);
P
Peter Pan 已提交
30
    const [echart, setEchart] = useState<ECharts | null>(null);
P
Peter Pan 已提交
31
    const theme = useTheme();
32

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

36 37
    const hideTip = useCallback(() => echartInstance.current?.dispatchAction({type: 'hideTip'}), []);

38
    const createChart = useCallback(() => {
P
Peter Pan 已提交
39
        (async () => {
40
            const {default: echarts} = await import('echarts');
P
Peter Pan 已提交
41 42 43
            if (options.gl) {
                await import('echarts-gl');
            }
44 45 46
            if (!ref.current) {
                return;
            }
P
Peter Pan 已提交
47
            echartInstance.current = echarts.init((ref.current as unknown) as HTMLDivElement);
48

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

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

                if (echartInstance.current) {
                    onInit.current?.(echartInstance.current);
                }
            }, 0);

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

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

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

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

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

P
Peter Pan 已提交
111 112 113 114 115 116 117 118 119 120 121
    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};
122 123 124
};

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

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 已提交
144 145 146 147 148 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 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268

export const useChartTheme = (gl?: boolean) => {
    const theme = useTheme();
    const tt = useMemo(() => themes[theme], [theme]);
    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
                    }
                }
            }
        };
    }
    return {
        title: {
            textStyle: {
                color: tt.textColor
            }
        },
        tooltip: {
            backgroundColor: tt.tooltipBackgroundColor,
            borderColor: tt.tooltipBackgroundColor,
            textStyle: {
                color: tt.tooltipTextColor
            }
        },
        xAxis: {
            nameTextStyle: {
                color: tt.textLighterColor
            },
            axisLabel: {
                color: tt.textLighterColor
            },
            axisLine: {
                lineStyle: {
                    color: tt.borderColor
                }
            },
            splitLine: {
                lineStyle: {
                    color: tt.borderColor
                }
            }
        },
        yAxis: {
            nameTextStyle: {
                color: tt.textLighterColor
            },
            axisLabel: {
                color: tt.textLighterColor
            },
            axisLine: {
                lineStyle: {
                    color: tt.borderColor
                }
            },
            splitLine: {
                lineStyle: {
                    color: tt.borderColor
                }
            }
        }
    };
};