1
- import { useRef , useEffect , useState } from 'react' ;
1
+ import { useRef , useEffect , useState , MutableRefObject } from 'react' ;
2
2
import hasPassiveEvent from 'has-passive-events' ;
3
3
4
4
export interface ScrollPosition {
@@ -28,18 +28,28 @@ const getScrollPosition = (element: HTMLElement): ScrollPosition => {
28
28
} ;
29
29
} ;
30
30
31
- export function useScrollPosition ( element ?: HTMLElement | null ) : ScrollPosition {
31
+ type Target = MutableRefObject < HTMLElement > | HTMLElement | null ;
32
+
33
+ function getTargetNode ( target ?: Target ) : HTMLElement | Document {
34
+ if ( ! target ) {
35
+ return document ;
36
+ }
37
+ if ( 'current' in target ) {
38
+ return target . current ;
39
+ }
40
+ return target ;
41
+ }
42
+
43
+ export function useScrollPosition ( target ?: Target ) : ScrollPosition {
32
44
const rafTick = useRef ( 0 ) ;
33
45
const [ position , setPosition ] = useState ( INITIAL_POSITION ) ;
34
46
useEffect (
35
47
( ) => {
36
- if ( element === null ) {
48
+ if ( target === null ) {
37
49
return ;
38
50
}
39
-
40
- const target = element ?? document ;
41
- const targetElement = element ?? document . documentElement ;
42
-
51
+ const targetNode = getTargetNode ( target ) ;
52
+ const targetElement = targetNode === document ? document . documentElement : targetNode as HTMLElement ;
43
53
setPosition ( getScrollPosition ( targetElement ) ) ;
44
54
45
55
const syncScroll = ( ) => {
@@ -54,14 +64,14 @@ export function useScrollPosition(element?: HTMLElement | null): ScrollPosition
54
64
rafTick . current = requestAnimationFrame ( callback ) ;
55
65
} ;
56
66
57
- target . addEventListener ( 'scroll' , syncScroll , EVENT_OPTIONS ) ;
67
+ targetNode . addEventListener ( 'scroll' , syncScroll , EVENT_OPTIONS ) ;
58
68
59
69
return ( ) => {
60
- target . removeEventListener ( 'scroll' , syncScroll , EVENT_OPTIONS ) ;
70
+ targetNode . removeEventListener ( 'scroll' , syncScroll , EVENT_OPTIONS ) ;
61
71
cancelAnimationFrame ( rafTick . current ) ;
62
72
} ;
63
73
} ,
64
- [ element ]
74
+ [ target ]
65
75
) ;
66
76
67
77
return position ;
0 commit comments