forked from Expensify/App
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
50 lines (43 loc) · 1.93 KB
/
index.ts
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
import {useCallback, useEffect, useRef, useState} from 'react';
import * as Browser from '@libs/Browser';
import addViewportResizeListener from '@libs/VisualViewport';
/**
* A hook that returns the offset of the top edge of the visual viewport
*/
export default function useViewportOffsetTop(shouldAdjustScrollView = false): number {
const [viewportOffsetTop, setViewportOffsetTop] = useState(0);
const cachedDefaultOffsetTop = useRef<number>(0);
const updateOffsetTop = useCallback(
(event?: Event) => {
let targetOffsetTop = window.visualViewport?.offsetTop ?? 0;
if (event?.target instanceof VisualViewport) {
targetOffsetTop = event.target.offsetTop;
}
if (Browser.isMobileSafari() && shouldAdjustScrollView && window.visualViewport) {
const clientHeight = document.body.clientHeight;
const adjustScrollY = clientHeight - window.visualViewport.height;
if (cachedDefaultOffsetTop.current === 0) {
cachedDefaultOffsetTop.current = targetOffsetTop;
}
if (adjustScrollY > targetOffsetTop) {
setViewportOffsetTop(adjustScrollY);
} else if (targetOffsetTop !== 0 && adjustScrollY === targetOffsetTop) {
setViewportOffsetTop(cachedDefaultOffsetTop.current);
} else {
setViewportOffsetTop(targetOffsetTop);
}
} else {
setViewportOffsetTop(targetOffsetTop);
}
},
[shouldAdjustScrollView],
);
useEffect(() => addViewportResizeListener(updateOffsetTop), [updateOffsetTop]);
useEffect(() => {
if (!shouldAdjustScrollView) {
return;
}
window.scrollTo({top: viewportOffsetTop, behavior: 'smooth'});
}, [shouldAdjustScrollView, viewportOffsetTop]);
return viewportOffsetTop;
}