import { Fn , isClient , isString , MaybeRef , noop , unRef } from '@react-hooks-library/shared' ; import { useEffect , useRef } from 'react' ; import { _window } from '../_ssr.config' ; interface InferEventTarget < Events > { addEventListener ( event , fn ? , options ? ) : any ; removeEventListener ( event , fn ? , options ? ) : any ; } export type WindowEventName = keyof WindowEventMap ; export type DocumentEventName = keyof DocumentEventMap ; export type GeneralEventListener < E = Event > = { ( evt ) : void ; } ; see https param event param listener param options returns export function useEventListener < E extends keyof WindowEventMap > ( event , listener , options ? ) ; see https param target param event param listener param options returns export function useEventListener < E extends keyof WindowEventMap > ( target , event , listener , options ? ) ; see https param target param event param listener param options returns export function useEventListener < E extends keyof DocumentEventMap > ( target , event , listener , options ? ) ; see https param target param event param listener param options returns export function useEventListener < Names extends string , EventType = Event > ( target , event , listener , options ? ) ; see https param target param event param listener param options returns export function useEventListener < EventType = Event > ( target , event , listener , options ? ) ; export function useEventListener ( ... args ) { let target = _window ; let event ; let listener ; let options ; isString ( args [ 0 ] ) ? ( [ event , listener , options ] = args ) : ( [ target , event , listener , options ] = args ) ; const savedListener = useRef < EventListener > ( listener ) ; const cleanup = useRef ( noop ) ; useEffect ( ( ) => { savedListener . current = listener ; } , [ listener ] ) ; useEffect ( ( ) => { const el = unRef ( target ) ; if ( ! isClient || ! el ) return ; el . addEventListener ( event , savedListener . current , options ) ; cleanup . current = ( ) => { el . removeEventListener ( event , savedListener . current , options ) ; } ; return cleanup . current ; } , [ event , target , options ] ) ; return cleanup . current ; }