@applicaster/zapp-react-native-utils
Version:
Applicaster Zapp React Native utilities package
102 lines (81 loc) • 2.61 kB
text/typescript
import { isNotNil } from "@applicaster/zapp-react-native-utils/reactUtils/helpers";
import { find, last, pathOr, startsWith } from "ramda";
import {
QUICK_BRICK_CONTENT,
QUICK_BRICK_NAVBAR,
} from "@applicaster/quick-brick-core/const";
// run check each 300 ms
// run this check too often could lead to performance penalty on low-end devices
const HOW_OFTEN_TO_CHECK_CONDITION = 300; // ms
type Props = {
maxTimeout: number;
conditionFn: () => boolean;
};
export const waitUntil = ({ maxTimeout, conditionFn }: Props) => {
let interval;
let timeout;
return new Promise((resolve, reject) => {
// run interval check
interval = setInterval(() => {
if (conditionFn()) {
clearInterval(interval);
clearTimeout(timeout);
resolve(undefined);
}
}, HOW_OFTEN_TO_CHECK_CONDITION);
// max timeout when we need to stop interval check
timeout = setTimeout(() => {
clearInterval(interval);
clearTimeout(timeout);
const error = Error(
"Failed to wait satisfy condition. Max timeout is reached."
);
reject(error);
}, maxTimeout);
});
};
export const waitForActiveScreen = (currentRoute: string, focusableTree) => {
const isActiveScreenAvailableToFocus = (): boolean => {
const routes = focusableTree.root.children;
const route = find((route) => route.id === currentRoute, routes);
return isNotNil(route);
};
return waitUntil({
maxTimeout: HOW_OFTEN_TO_CHECK_CONDITION * 10, // ms
conditionFn: isActiveScreenAvailableToFocus,
});
};
const getActiveScreenChildren = (focusableTree) => {
return pathOr([], ["children"], last(focusableTree.root.children));
};
export const getContentNode = (focusableTree) => {
const content = find(
(child) =>
startsWith(QUICK_BRICK_CONTENT, child.id) ||
startsWith("player", child.id) ||
startsWith("/hooks", child?.parent?.id), // For startup hooks case
getActiveScreenChildren(focusableTree)
);
return content;
};
export const getNavbarNode = (focusableTree) => {
const navbar = find(
(child) => startsWith(QUICK_BRICK_NAVBAR, child.id),
getActiveScreenChildren(focusableTree)
);
return navbar;
};
export const waitForContent = (focusableTree) => {
const contentHasAnyChildren = (): boolean => {
const countOfChildren = pathOr(
0,
["children", "length"],
getContentNode(focusableTree)
);
return countOfChildren > 0;
};
return waitUntil({
maxTimeout: HOW_OFTEN_TO_CHECK_CONDITION * 10, // ms
conditionFn: contentHasAnyChildren,
});
};