@applicaster/zapp-react-native-utils
Version:
Applicaster Zapp React Native utilities package
61 lines (48 loc) • 1.82 kB
text/typescript
import { useCallback, useEffect, useMemo, useState } from "react";
import { useScreenTrackedViewPositionsContext } from "@applicaster/zapp-react-native-ui-components/Contexts/ScreenTrackedViewPositionsContext";
import { useDimensions } from "@applicaster/zapp-react-native-utils/reactHooks/layout";
import { findTrackedView } from "./utils/findTrackedView";
const getNormalizedRect = (rect, componentId, screenWidth, screenHeight) => {
if (!rect) {
return null;
}
const { left, right, top, bottom } = rect;
return {
left: left / screenWidth,
right: right / screenWidth,
top: top / screenHeight,
bottom: bottom / screenHeight,
centerX: (left + right) / 2 / screenWidth,
centerY: (top + bottom) / 2 / screenHeight,
componentId,
};
};
export const useTrackedView = (componentId: string) => {
const [inViewPort, setInViewPort] = useState(false);
const { updateComponentsPositions } = useScreenTrackedViewPositionsContext();
const { width: screenWidth, height: screenHeight } = useDimensions("screen", {
fullDimensions: true,
});
const normalizedRect = useCallback(
(componentId, rect) =>
getNormalizedRect(rect, componentId, screenWidth, screenHeight),
[screenWidth, screenHeight, componentId]
);
const onPositionUpdated = useCallback(
({ rect }) => {
const currentPosition = normalizedRect(componentId, rect);
updateComponentsPositions(componentId, currentPosition as any);
setInViewPort(!!currentPosition);
},
[findTrackedView, normalizedRect, componentId, updateComponentsPositions]
);
useEffect(() => {
return () => {
updateComponentsPositions(componentId, null);
};
}, []);
return useMemo(
() => ({ inViewPort, onPositionUpdated }),
[inViewPort, onPositionUpdated]
);
};