UNPKG

one

Version:

One is a React framework for web, iOS, and Android apps.

80 lines (77 loc) • 2.8 kB
import { useNavigation as useNavigation$1 } from "@react-navigation/native"; import React from "react"; import { getReactNavigationRouteName } from "../getReactNavigationConfig.mjs"; import { getContextKey, getNameFromFilePath } from "./matchers.mjs"; import { useContextKey, useRouteNodes } from "./Route.mjs"; function useNavigation(parent) { const navigation = useNavigation$1(); const contextKey = useContextKey(); const routeNodes = useRouteNodes(); const normalizedParent = React.useMemo(() => { if (!parent) { return null; } return resolveParentRouteName(routeNodes, contextKey, parent); }, [ contextKey, parent, routeNodes ]); if (parent && normalizedParent === void 0) { throw new Error(`Could not find parent navigation with route "${parent}". (normalized context: ${resolveParentId(contextKey, parent)})`); } if (normalizedParent != null) { if (normalizedParent === "") { let rootNavigation = navigation; let nextNavigation = rootNavigation.getParent(); while (nextNavigation) { rootNavigation = nextNavigation; nextNavigation = rootNavigation.getParent(); } return rootNavigation; } const parentNavigation = navigation.getParent(normalizedParent); if (!parentNavigation) { throw new Error(`Could not find parent navigation with route "${parent}".` + (normalizedParent !== parent ? ` (normalized: ${normalizedParent})` : "")); } return parentNavigation; } return navigation; } function resolveParentId(contextKey, parentId) { if (!parentId) { return null; } if (parentId.startsWith(".")) { return normalizeContextPath(relativePaths(contextKey, parentId)); } return normalizeContextPath(parentId); } function resolveParentRouteName(routeNodes, contextKey, parentId) { const parentContextKey = resolveParentId(contextKey, parentId); if (parentContextKey == null) return null; if (parentContextKey === "/") return ""; const parentRoute = routeNodes.find((node) => getContextKey(node.contextKey) === parentContextKey); return parentRoute ? getReactNavigationRouteName(parentRoute) : void 0; } function normalizeContextPath(path) { const normalized = getNameFromFilePath(path).replace(/^\/+|\/+$/g, "").replace(/\/_layout$/, ""); return normalized ? `/${normalized}` : "/"; } function relativePaths(from, to) { const fromParts = from.split("/").filter(Boolean); const toParts = to.split("/").filter(Boolean); for (const part of toParts) { if (part === "..") { if (fromParts.length === 0) { throw new Error(`Cannot resolve path "${to}" relative to "${from}"`); } fromParts.pop(); } else if (part === ".") {} else { fromParts.push(part); } } return "/" + fromParts.join("/"); } export { resolveParentId, resolveParentRouteName, useNavigation }; //# sourceMappingURL=useNavigation.mjs.map