about summary refs log tree commit diff
path: root/src/lib/hooks/useOnMainScroll.ts
blob: 12e42aca5f2e57364ae9be4c3e3d65605d921021 (plain) (blame)
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
import {useState, useCallback, useRef} from 'react'
import {NativeSyntheticEvent, NativeScrollEvent} from 'react-native'
import {RootStoreModel} from 'state/index'
import {s} from 'lib/styles'
import {isDesktopWeb} from 'platform/detection'

const DY_LIMIT = isDesktopWeb ? 30 : 10

export type OnScrollCb = (
  event: NativeSyntheticEvent<NativeScrollEvent>,
) => void
export type ResetCb = () => void

export function useOnMainScroll(
  store: RootStoreModel,
): [OnScrollCb, boolean, ResetCb] {
  let lastY = useRef(0)
  let [isScrolledDown, setIsScrolledDown] = useState(false)
  return [
    useCallback(
      (event: NativeSyntheticEvent<NativeScrollEvent>) => {
        const y = event.nativeEvent.contentOffset.y
        const dy = y - (lastY.current || 0)
        lastY.current = y

        if (!store.shell.minimalShellMode && y > 10 && dy > DY_LIMIT) {
          store.shell.setMinimalShellMode(true)
        } else if (
          store.shell.minimalShellMode &&
          (y <= 10 || dy < DY_LIMIT * -1)
        ) {
          store.shell.setMinimalShellMode(false)
        }

        if (
          !isScrolledDown &&
          event.nativeEvent.contentOffset.y > s.window.height
        ) {
          setIsScrolledDown(true)
        } else if (
          isScrolledDown &&
          event.nativeEvent.contentOffset.y < s.window.height
        ) {
          setIsScrolledDown(false)
        }
      },
      [store, isScrolledDown],
    ),
    isScrolledDown,
    useCallback(() => {
      setIsScrolledDown(false)
      store.shell.setMinimalShellMode(false)
      lastY.current = 1e8 // NOTE we set this very high so that the onScroll logic works right -prf
    }, [store, setIsScrolledDown]),
  ]
}