|
| 1 | +import type { AppTheme } from '../../App'; |
| 2 | + |
| 3 | +import * as echarts from 'echarts'; |
| 4 | +import { cloneDeep, merge } from 'lodash'; |
| 5 | +import React, { useCallback, useEffect, useRef, useState } from 'react'; |
| 6 | + |
| 7 | +import { useAsync, useResize, useStorage } from '@react-devui/hooks'; |
| 8 | +import { setRef } from '@react-devui/hooks/useForkRef'; |
| 9 | +import { getClassName } from '@react-devui/utils'; |
| 10 | + |
| 11 | +import { STORAGE_KEY } from '../../../config/storage'; |
| 12 | +import chartTheme from './theme.json'; |
| 13 | + |
| 14 | +echarts.registerTheme('light', chartTheme.light); |
| 15 | +echarts.registerTheme('dark', merge(cloneDeep(chartTheme.light), chartTheme.dark)); |
| 16 | + |
| 17 | +export interface AppEChartsProps<O extends echarts.EChartsOption> extends Omit<React.HTMLAttributes<HTMLDivElement>, 'children'> { |
| 18 | + aOption: O | null; |
| 19 | +} |
| 20 | + |
| 21 | +function ECharts<O extends echarts.EChartsOption>(props: AppEChartsProps<O>, ref: React.ForwardedRef<echarts.ECharts>): JSX.Element | null { |
| 22 | + const { |
| 23 | + aOption, |
| 24 | + |
| 25 | + ...restProps |
| 26 | + } = props; |
| 27 | + |
| 28 | + //#region Ref |
| 29 | + const elRef = useRef<HTMLDivElement>(null); |
| 30 | + //#endregion |
| 31 | + |
| 32 | + const dataRef = useRef<{ |
| 33 | + clearTid?: () => void; |
| 34 | + }>({}); |
| 35 | + |
| 36 | + const async = useAsync(); |
| 37 | + |
| 38 | + const themeStorage = useStorage<AppTheme>(...STORAGE_KEY.theme); |
| 39 | + |
| 40 | + const [instance, setInstance] = useState<echarts.ECharts | null>(null); |
| 41 | + const containerRef = useCallback( |
| 42 | + (el: HTMLElement | null) => { |
| 43 | + setInstance((draft) => { |
| 44 | + draft?.dispose(); |
| 45 | + const instance = el ? echarts.init(el, themeStorage.value, { renderer: 'svg' }) : null; |
| 46 | + setRef(ref, instance); |
| 47 | + return instance; |
| 48 | + }); |
| 49 | + }, |
| 50 | + [ref, themeStorage.value] |
| 51 | + ); |
| 52 | + |
| 53 | + useEffect(() => { |
| 54 | + if (instance && aOption) { |
| 55 | + instance.setOption(aOption); |
| 56 | + } |
| 57 | + }, [aOption, instance]); |
| 58 | + |
| 59 | + useResize(elRef, () => { |
| 60 | + if (instance) { |
| 61 | + dataRef.current.clearTid?.(); |
| 62 | + dataRef.current.clearTid = async.setTimeout(() => { |
| 63 | + dataRef.current.clearTid = undefined; |
| 64 | + instance.resize({ animation: { duration: 200 } }); |
| 65 | + }, 100); |
| 66 | + } |
| 67 | + }); |
| 68 | + |
| 69 | + return ( |
| 70 | + <div {...restProps} ref={elRef} className={getClassName(restProps.className, 'app-echarts')}> |
| 71 | + <div ref={containerRef} className="app-echarts__container"></div> |
| 72 | + </div> |
| 73 | + ); |
| 74 | +} |
| 75 | + |
| 76 | +export const AppECharts = React.forwardRef(ECharts); |
0 commit comments