import React , { useState , useCallback , ComponentPropsWithoutRef , useEffect } from 'react' ; import { Chartisan , ChartisanOptions , Controller , ControllerOptions } from '@chartisan/echarts' ; export interface ChartisanProps < Meta > extends Omit < ChartisanOptions < Meta > , 'element' > { attributes : ComponentPropsWithoutRef < 'div' > ; } export function useChart < Meta = unknown > ( options ? ) { const [ chartisan , setChartisan ] = useState < Chartisan < Meta > | undefined > ( undefined ) ; const [ isInitiated , setIsInitiated ] = useState < boolean | undefined > ( undefined ) ; const [ isLoading , setIsLoading ] = useState < boolean | undefined > ( undefined ) ; const [ isOnline , setIsOnline ] = useState < boolean | undefined > ( undefined ) ; const [ isOffline , setIsOffline ] = useState < boolean | undefined > ( undefined ) ; const [ isSubscribed , setIsSubscribed ] = useState < boolean | undefined > ( undefined ) ; const [ controller , _setController ] = useState < Controller < Meta > > ( new Controller < Meta > ( { ... options , onAttach : ( chartisan ) => setChartisan ( chartisan ) , } ) ) ; useEffect ( ( ) => { const subscribers = [ controller . on ( 'initialized' , ( ) => setIsInitiated ( chartisan ?. isInitiated ( ) ) ) , controller . on ( 'created' , ( ) => setIsInitiated ( chartisan ?. isInitiated ( ) ) ) , controller . on ( 'updated' , ( ) => setIsInitiated ( chartisan ?. isInitiated ( ) ) ) , controller . on ( 'deleted' , ( ) => setIsInitiated ( chartisan ?. isInitiated ( ) ) ) , controller . on ( 'loading-enabled' , ( ) => setIsLoading ( chartisan ?. isLoading ( ) ) ) , controller . on ( 'loading-disabled' , ( ) => setIsLoading ( chartisan ?. isLoading ( ) ) ) , controller . on ( 'options-changed' , ( ) => setIsOnline ( chartisan ?. isOnline ( ) ) ) , controller . on ( 'options-changed' , ( ) => setIsOffline ( chartisan ?. isOffline ( ) ) ) , controller . on ( 'subscribed' , ( ) => setIsSubscribed ( chartisan ?. isSubscribed ( ) ) ) , controller . on ( 'unsubscribed' , ( ) => setIsSubscribed ( chartisan ?. isSubscribed ( ) ) ) , ] ; return ( ) => subscribers . forEach ( ( unsubscribe ) => unsubscribe ( ) ) ; } , [ chartisan , controller ] ) ; return { controller , chartisan , isInitiated , isLoading , isOnline , isOffline , isSubscribed } ; } export function Chart < Meta = unknown > ( { attributes , ... props } ) { const [ chartisan , setChartisan ] = useState < Chartisan < Meta > | undefined > ( undefined ) ; const ref = useCallback ( ( element ) => { setChartisan ( new Chartisan ( { element , ... props } ) ) ; } , [ ] ) ; useEffect ( ( ) => { chartisan ?. update ( { url : props . url } ) ; } , [ chartisan , props . url ] ) ; useEffect ( ( ) => { chartisan ?. update ( { chart : props . chart } ) ; } , [ chartisan , props . chart ] ) ; return < div ref = { ref } { ... attributes } />; }