import React from 'react' ; import { useComponentDidMount , useComponentWillUnmount } from "../hooks/ReactLifecycleHooks" ; import { NULL_FUNCTION } from "polar-shared/src/util/Functions" ; interface WindowOpts { readonly win ? : Window ; } export type WindowEventListenerName = 'resize' | 'scroll' | 'contextmenu' ; const listenerOpts = { capture : true , passive : true } ; param name param activity param delegate param opts export function useWindowEventListener ( name , activity , delegate , opts = { } ) { interface IWindowDescriptor { readonly win : Window ; readonly type : 'explicit' | 'default' ; } React . useEffect ( ( ) => { function computeWindowDescriptor ( ) { if ( opts . win ) { return { win : opts . win , type : 'explicit' } ; } else { return { win : window , type : 'default' } ; } } const { win , type } = computeWindowDescriptor ( ) ; if ( win ) { if ( win . closed ) { const msg = `Window ${ type } has closed for ${ name } with activity ${ activity } in useWindowEventListener.` ; console . warn ( msg , win ) ; return ; } if ( typeof win . addEventListener !== 'function' ) { const msg = `Window ${ type } has no addEventListener for ${ name } with activity ${ activity } in useWindowEventListener: ` + ( typeof win . addEventListener ) ; console . warn ( msg , win ) ; throw new Error ( msg ) ; } win . addEventListener ( name , delegate , listenerOpts ) ; return ( ) => { if ( win && typeof win . removeEventListener === 'function' ) { win . removeEventListener ( name , delegate , listenerOpts ) ; } } ; } return NULL_FUNCTION ; } , [ activity , delegate , name , opts . win ] ) ; } export function useWindowScrollEventListener ( activity , delegate , opts = { } ) { useWindowEventListener ( 'scroll' , activity , delegate , opts ) ; } export function useWindowResizeEventListener ( activity , delegate , opts = { } ) { useWindowEventListener ( 'resize' , activity , delegate , opts ) ; }