Skip to content

Commit 295b5ee

Browse files
authored
useHiddenLocation - support web (#2872)
1 parent 4e94a10 commit 295b5ee

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import {isEqual} from 'lodash';
2+
import {useCallback, useRef, useState, RefCallback} from 'react';
3+
import {View, LayoutChangeEvent, LayoutRectangle} from 'react-native';
4+
import {Constants} from '../../commons/new';
5+
import {PanningDirectionsEnum} from '../panView';
6+
7+
type HiddenLocationRecord = Record<PanningDirectionsEnum, number>;
8+
9+
export interface HiddenLocation extends HiddenLocationRecord {
10+
wasMeasured: boolean;
11+
}
12+
13+
// Adding this for headless tests that are not triggering onLayout
14+
const wasMeasuredDefaultValue = global._UILIB_TESTING ?? false;
15+
16+
export default function useHiddenLocation<T extends View>() {
17+
const getHiddenLocation = ({
18+
wasMeasured = wasMeasuredDefaultValue
19+
}) => {
20+
return {
21+
up: -Constants.screenHeight,
22+
down: Constants.screenHeight,
23+
left: -Constants.windowWidth,
24+
right: Constants.windowWidth,
25+
wasMeasured
26+
};
27+
};
28+
29+
const [hiddenLocation, setHiddenLocation] = useState<HiddenLocation>(getHiddenLocation({}));
30+
const ref = useRef<T>();
31+
const layoutData = useRef<LayoutRectangle>();
32+
const wasMeasured = useRef(wasMeasuredDefaultValue);
33+
34+
const measure = useCallback(() => {
35+
if (ref.current) {
36+
wasMeasured.current = true;
37+
setHiddenLocation(getHiddenLocation({
38+
wasMeasured: true
39+
}));
40+
}
41+
}, []);
42+
43+
const setRef: RefCallback<T> = useCallback((node: T) => {
44+
if (node) {
45+
ref.current = node;
46+
measure();
47+
}
48+
},
49+
[measure]);
50+
51+
const onLayout = useCallback((event: LayoutChangeEvent) => {
52+
if (!isEqual(layoutData.current, event.nativeEvent.layout)) {
53+
layoutData.current = event.nativeEvent.layout;
54+
measure();
55+
}
56+
},
57+
[measure]);
58+
59+
return {setRef, onLayout, hiddenLocation};
60+
}

0 commit comments

Comments
 (0)