forked from FedericoDiRosa/react-window-scroller
/
index.jsx
73 lines (63 loc) · 2.01 KB
/
index.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { useRef, useEffect, useCallback } from 'react'
import throttle from 'lodash.throttle'
const windowScrollPositionKey = {
y: 'pageYOffset',
x: 'pageXOffset'
}
const documentScrollPositionKey = {
y: 'scrollTop',
x: 'scrollLeft'
}
const getScrollPosition = (axis) =>
window[windowScrollPositionKey[axis]] ||
document.documentElement[documentScrollPositionKey[axis]] ||
document.body[documentScrollPositionKey[axis]] ||
0
export const ReactWindowScroller = ({
children,
throttleTime = 10,
isGrid = false
}) => {
const ref = useRef()
const outerRef = useRef()
useEffect(() => {
const handleWindowScroll = throttle(() => {
const { offsetTop = 0, offsetLeft = 0 } = outerRef.current || {}
const scrollTop = getScrollPosition('y') - offsetTop
const scrollLeft = getScrollPosition('x') - offsetLeft
if (isGrid) ref.current && ref.current.scrollTo({ scrollLeft, scrollTop })
if (!isGrid) ref.current && ref.current.scrollTo(scrollTop)
}, throttleTime)
window.addEventListener('scroll', handleWindowScroll)
return () => {
handleWindowScroll.cancel()
window.removeEventListener('scroll', handleWindowScroll)
}
}, [isGrid])
const onScroll = useCallback(
({ scrollLeft, scrollTop, scrollOffset, scrollUpdateWasRequested }) => {
if (!scrollUpdateWasRequested) return
const top = getScrollPosition('y')
const left = getScrollPosition('x')
const { offsetTop = 0, offsetLeft = 0 } = outerRef.current || {}
scrollOffset += Math.min(top, offsetTop)
scrollTop += Math.min(top, offsetTop)
scrollLeft += Math.min(left, offsetLeft)
if (!isGrid && scrollOffset !== top) window.scrollTo(0, scrollOffset)
if (isGrid && (scrollTop !== top || scrollLeft !== left)) {
window.scrollTo(scrollLeft, scrollTop)
}
},
[isGrid]
)
return children({
ref,
outerRef,
style: {
width: isGrid ? 'auto' : '100%',
height: '100%',
display: 'inline-block'
},
onScroll
})
}