one
Version:
One is a React framework for web, iOS, and Android apps.
73 lines (70 loc) • 2.71 kB
JavaScript
import React, { createContext, useContext } from "react";
import { isNative } from "../constants.mjs";
import { findFocusedRoute } from "../fork/findFocusedRoute.mjs";
import { getResolvedLinking } from "./linkingConfig.mjs";
import { getContextKey } from "./matchers.mjs";
import { mergeDynamicParams } from "./params.mjs";
import { getPathWithRecoveredDynamicSegment } from "./path.mjs";
import { routeInfo } from "./router.mjs";
import { RouteInfoContextProvider } from "./RouteInfoContext.mjs";
import { jsx } from "react/jsx-runtime";
const RouteParamsContext = createContext({});
const CurrentRouteContext = React.createContext([]);
const SuspenseFallbackContext = createContext(void 0);
if (process.env.NODE_ENV !== "production") {
CurrentRouteContext.displayName = "RouteNode";
SuspenseFallbackContext.displayName = "SuspenseFallback";
}
function useRouteNode() {
const nodes = useContext(CurrentRouteContext);
return nodes[nodes.length - 1] ?? null;
}
function useRouteNodes() {
return useContext(CurrentRouteContext);
}
function useContextKey() {
const node = useRouteNode();
if (node == null) {
throw new Error("No filename found. This is likely a bug in router.");
}
return getContextKey(node.contextKey);
}
function getParamsFromCurrentUrl(route) {
const linking = getResolvedLinking();
if (!linking?.getStateFromPath) return void 0;
const path = getPathWithRecoveredDynamicSegment([routeInfo?.unstable_globalHref, route?.path]);
if (!path) return void 0;
const state = linking.getStateFromPath(path, linking.config);
if (!state) return void 0;
const focused = findFocusedRoute(state);
return focused?.params;
}
function Route({ children, node, route }) {
const parentParams = useContext(RouteParamsContext);
const parentRouteNodes = useContext(CurrentRouteContext);
const routeNodes = React.useMemo(() => [...parentRouteNodes, node], [node, parentRouteNodes]);
const resolvedParams = React.useMemo(() => {
const rp = route?.params;
const ownParams = !isNative && node.dynamic?.length ? mergeDynamicParams(rp, node.dynamic, getParamsFromCurrentUrl(route)) : rp;
if (!parentParams) return ownParams;
if (!ownParams) return parentParams;
return {
...parentParams,
...ownParams
};
}, [
node,
parentParams,
route,
routeInfo?.unstable_globalHref
]);
return /* @__PURE__ */ jsx(RouteParamsContext.Provider, {
value: resolvedParams,
children: /* @__PURE__ */ jsx(CurrentRouteContext.Provider, {
value: routeNodes,
children: /* @__PURE__ */ jsx(RouteInfoContextProvider, { children })
})
});
}
export { Route, RouteParamsContext, SuspenseFallbackContext, useContextKey, useRouteNode, useRouteNodes };
//# sourceMappingURL=Route.mjs.map