import { hasDocument , hasWindow , isDocumentVisibility } from './helper' ; function useSubscribe ( ) { const fns = [ ] ; const off = ( fn ) => { const index = fns . indexOf ( fn ) ; if ( index !== - 1 ) fns . splice ( index , 1 ) ; } ; const on = ( fn ) => { fns . push ( fn ) ; return { off : ( ) => off ( fn ) , } ; } ; const trigger = ( ... args ) => { fns . forEach ( ( fn ) => fn ( ... args ) ) ; } ; return { on , trigger , } ; } let online = true ; const hasWin = hasWindow ( ) ; const hasDoc = hasDocument ( ) ; function createFocusEvent ( eventHook ) { if ( hasWin && window . addEventListener ) { window . addEventListener ( 'focus' , eventHook . trigger ) ; } return ( ) => { window . removeEventListener ( 'focus' , eventHook . trigger ) ; } ; } function createVisibilityEvent ( eventHook ) { if ( hasDoc && document . addEventListener ) { document . addEventListener ( 'visibilitychange' , ( ) => eventHook . trigger ( isDocumentVisibility ( ) ) ) ; } return ( ) => { document . removeEventListener ( 'visibilitychange' , ( ) => eventHook . trigger ( isDocumentVisibility ( ) ) ) ; } ; } function createReconnectEvent ( eventHook ) { const onOnline = ( ) => { online = true ; eventHook . trigger ( online ) ; } ; const onOffline = ( ) => { online = false ; eventHook . trigger ( online ) ; } ; if ( hasWin && window . addEventListener ) { window . addEventListener ( 'online' , onOnline ) ; window . addEventListener ( 'offline' , onOffline ) ; } return ( ) => { window . removeEventListener ( 'online' , onOnline ) ; window . removeEventListener ( 'offline' , onOffline ) ; } ; } export function createEvents ( ) { const conditionEvent = useSubscribe ( ) ; const responseEvent = useSubscribe ( ) ; const errorEvent = useSubscribe ( ) ; const finallyEvent = useSubscribe ( ) ; const focusEvent = useSubscribe ( ) ; const visibilityEvent = useSubscribe ( ) ; const reconnectEvent = useSubscribe ( ) ; const stopFocusEvent = createFocusEvent ( focusEvent ) ; const stopVisibilityEvent = createVisibilityEvent ( visibilityEvent ) ; const stopReconnectEvent = createReconnectEvent ( reconnectEvent ) ; return { conditionEvent , responseEvent , errorEvent , finallyEvent , focusEvent , reconnectEvent , visibilityEvent , stopFocusEvent , stopReconnectEvent , stopVisibilityEvent , } ; }