useECharts.ts 8.6 KB
Newer Older
P
Peter Pan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/**
 * Copyright 2020 Baidu Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

P
Peter Pan 已提交
17 18
import {MutableRefObject, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState} from 'react';
import {position, primaryColor, size} from '~/utils/style';
19

20
import type {ECharts} from 'echarts';
P
Peter Pan 已提交
21 22
import {dataURL2Blob} from '~/utils/image';
import {saveAs} from 'file-saver';
P
Peter Pan 已提交
23
import styled from 'styled-components';
P
Peter Pan 已提交
24 25
import {themes} from '~/utils/theme';
import useTheme from '~/hooks/useTheme';
26

27
export type Options = {
P
Peter Pan 已提交
28
    loading?: boolean;
29
    gl?: boolean;
P
Peter Pan 已提交
30
    zoom?: boolean;
P
Peter Pan 已提交
31
    autoFit?: boolean;
32 33 34 35 36 37 38
    onInit?: (echarts: ECharts) => unknown;
    onDispose?: (echarts: ECharts) => unknown;
};

const useECharts = <T extends HTMLElement, W extends HTMLElement = HTMLDivElement>(
    options: Options
): {
P
Peter Pan 已提交
39
    ref: MutableRefObject<T | null>;
P
Peter Pan 已提交
40 41
    wrapper: MutableRefObject<W | null>;
    echart: ECharts | null;
P
Peter Pan 已提交
42
    saveAsImage: (filename?: string) => void;
P
Peter Pan 已提交
43
} => {
44
    const ref = useRef<T | null>(null);
P
Peter Pan 已提交
45
    const [echart, setEchart] = useState<ECharts | null>(null);
P
Peter Pan 已提交
46
    const theme = useTheme();
47

48 49 50
    const onInit = useRef(options.onInit);
    const onDispose = useRef(options.onDispose);

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

53
    const createChart = useCallback(() => {
P
Peter Pan 已提交
54
        (async () => {
P
Peter Pan 已提交
55 56 57 58
            if (!ref.current) {
                return;
            }

59
            const {default: echarts} = await import('echarts');
P
Peter Pan 已提交
60 61 62
            if (options.gl) {
                await import('echarts-gl');
            }
P
Peter Pan 已提交
63 64

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

66 67
            ref.current.addEventListener('mouseleave', hideTip);

68 69
            setTimeout(() => {
                if (options.zoom) {
P
Peter Pan 已提交
70
                    echartInstance.dispatchAction({
P
Peter Pan 已提交
71 72 73 74
                        type: 'takeGlobalCursor',
                        key: 'dataZoomSelect',
                        dataZoomSelectActive: true
                    });
75 76
                }

P
Peter Pan 已提交
77 78
                if (echartInstance) {
                    onInit.current?.(echartInstance);
79 80 81
                }
            }, 0);

P
Peter Pan 已提交
82
            setEchart(echartInstance);
P
Peter Pan 已提交
83
        })();
84
    }, [options.gl, options.zoom, hideTip]);
85 86

    const destroyChart = useCallback(() => {
P
Peter Pan 已提交
87 88 89 90 91
        if (echart) {
            onDispose.current?.(echart);
            echart.dispose();
            ref.current?.removeEventListener('mouseleave', hideTip);
            setEchart(null);
92
        }
P
Peter Pan 已提交
93
    }, [hideTip, echart]);
94 95

    useEffect(() => {
96 97
        createChart();
        return destroyChart;
98 99 100
    }, [createChart, destroyChart]);

    useEffect(() => {
101
        if (options.loading) {
P
Peter Pan 已提交
102
            echart?.showLoading('default', {
103 104
                text: '',
                color: primaryColor,
P
Peter Pan 已提交
105 106
                textColor: themes[theme].textColor,
                maskColor: themes[theme].maskColor,
107 108 109
                zlevel: 0
            });
        } else {
P
Peter Pan 已提交
110
            echart?.hideLoading();
111
        }
P
Peter Pan 已提交
112
    }, [options.loading, theme, echart]);
P
Peter Pan 已提交
113 114 115

    const wrapper = useRef<W | null>(null);
    useLayoutEffect(() => {
116
        if (options.autoFit) {
P
Peter Pan 已提交
117 118 119
            const w = wrapper.current;
            if (w) {
                const observer = new ResizeObserver(() => {
P
Peter Pan 已提交
120
                    echart?.resize();
P
Peter Pan 已提交
121 122 123 124 125
                });
                observer.observe(w);
                return () => observer.unobserve(w);
            }
        }
P
Peter Pan 已提交
126
    }, [options.autoFit, echart]);
127

P
Peter Pan 已提交
128 129 130 131 132 133 134 135 136 137 138
    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};
139 140 141
};

export default useECharts;
P
Peter Pan 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160

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 已提交
161 162 163 164

export const useChartTheme = (gl?: boolean) => {
    const theme = useTheme();
    const tt = useMemo(() => themes[theme], [theme]);
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
    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 已提交
236 237 238 239 240 241 242 243 244 245 246 247 248
        return {
            title: {
                textStyle: {
                    color: tt.textColor
                }
            },
            tooltip: {
                backgroundColor: tt.tooltipBackgroundColor,
                borderColor: tt.tooltipBackgroundColor,
                textStyle: {
                    color: tt.tooltipTextColor
                }
            },
249
            xAxis: {
P
Peter Pan 已提交
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
                nameTextStyle: {
                    color: tt.textLighterColor
                },
                axisLabel: {
                    color: tt.textLighterColor
                },
                axisLine: {
                    lineStyle: {
                        color: tt.borderColor
                    }
                },
                splitLine: {
                    lineStyle: {
                        color: tt.borderColor
                    }
                }
            },
267
            yAxis: {
P
Peter Pan 已提交
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
                nameTextStyle: {
                    color: tt.textLighterColor
                },
                axisLabel: {
                    color: tt.textLighterColor
                },
                axisLine: {
                    lineStyle: {
                        color: tt.borderColor
                    }
                },
                splitLine: {
                    lineStyle: {
                        color: tt.borderColor
                    }
                }
            }
        };
286 287
    }, [tt, gl]);
    return result;
P
Peter Pan 已提交
288
};