-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseSmartScroll.ts
More file actions
executable file
·59 lines (48 loc) · 1.5 KB
/
useSmartScroll.ts
File metadata and controls
executable file
·59 lines (48 loc) · 1.5 KB
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
import { useCallback, useMemo, useState, useEffect } from 'react'
import { ScrollViewProps, VirtualizedListProps } from 'react-native'
// type Params = Pick<
// VirtualizedListProps<any>,
// 'horizontnal' | 'onLayout' | 'onContentSizeChange'
// > &
type HandleLayoutCallback = NonNullable<ScrollViewProps['onLayout']>
type HandleContentSizeChangeCallback = NonNullable<
ScrollViewProps['onContentSizeChange']
>
export const useSmartScroll = ({
horizontal,
onSmartScrollStatusChange,
onLayout,
onContentSizeChange,
}: Params) => {
const [wrapperWidth, setWrapperWidth] = useState(0)
const [wrapperHeight, setWrapperHeight] = useState(0)
const [contentSize, setContentSize] = useState(0)
const isScrollEnabled = useMemo(
() => (horizontal ? wrapperWidth : wrapperHeight) < contentSize,
[contentSize, horizontal, wrapperHeight, wrapperWidth]
)
useEffect(() => {
onSmartScrollStatusChange?.(isScrollEnabled)
}, [isScrollEnabled, onSmartScrollStatusChange])
const handleLayout = useCallback<HandleLayoutCallback>(
(e) => {
const { width, height } = e.nativeEvent.layout
setWrapperWidth(width)
setWrapperHeight(height)
onLayout?.(e)
},
[onLayout]
)
const handleContentSizeChange = useCallback<HandleContentSizeChangeCallback>(
(w, h) => {
setContentSize(horizontal ? w : h)
onContentSizeChange?.(w, h)
},
[horizontal, onContentSizeChange]
)
return {
handleLayout,
handleContentSizeChange,
isScrollEnabled,
}
}