@@ -7,27 +7,37 @@ type EventHandler<T extends Event = Event> = (e: T) => void;
77
88type WindowEventHook = {
99 < K extends keyof WindowEventMap > (
10- eventName : K ,
10+ value : K | [ K , AddEventListenerOptions ] ,
1111 handler : EventHandler < WindowEventMap [ K ] > ,
12- options ?: boolean | ( AddEventListenerOptions & { disable ?: boolean } ) ,
12+ dependencies ?: any [ ] ,
1313 ) : void ;
1414} ;
1515
16- export const useWindowEvent : WindowEventHook = ( eventName , handler , options ) => {
16+ const unpackValue = < K extends keyof WindowEventMap > (
17+ value : K | [ K , AddEventListenerOptions ] ,
18+ ) : [ K , AddEventListenerOptions ] => {
19+ if ( typeof value === "string" ) {
20+ return [ value , { } ] ;
21+ }
22+ return value ;
23+ } ;
24+
25+ export const useWindowEvent : WindowEventHook = ( value , handler , dependencies = [ ] ) => {
1726 const didUnmount = useRef ( false ) ;
1827 useWillUnmount ( ( ) => ( didUnmount . current = true ) ) ;
1928
20- const isClient = getIsClient ( ) ;
21-
2229 useDidUpdate (
2330 ( ) => {
24- const { disable = false , ...windowOptions } = typeof options === "object" ? options : { } ;
25- if ( ! isClient || disable ) return ;
31+ const isClient = getIsClient ( ) ;
32+ if ( ! isClient ) return ;
33+
34+ const [ name , options ] = unpackValue ( value ) ;
35+ const windowOptions = typeof options === "object" ? options : { } ;
2636
27- window . addEventListener ( eventName , handler , windowOptions ) ;
28- return ( ) => window . removeEventListener ( eventName , handler , windowOptions ) ;
37+ window . addEventListener ( name , handler , windowOptions ) ;
38+ return ( ) => window . removeEventListener ( name , handler , windowOptions ) ;
2939 } ,
30- [ eventName , options ] ,
40+ [ JSON . stringify ( value ) , ... dependencies ] ,
3141 true ,
3242 ) ;
3343} ;
0 commit comments