one
Version:
One is a React framework for web, iOS, and Android apps.
391 lines (386 loc) • 14.6 kB
JavaScript
import { createNavigatorFactory } from "@react-navigation/core";
import React, { Suspense, createElement, memo, useContext, useEffect, useState } from "react";
import { SafeAreaProvider } from "../safe-area-context/index.mjs";
import { ServerContextScript } from "../server/ServerContextScript.mjs";
import { checkSkewAndReload } from "../skewProtection.mjs";
import { getClientMatchesSnapshot } from "../useMatches.mjs";
import { handleSkewError, isChunkLoadError } from "../utils/dynamicImport.mjs";
import { getPageExport } from "../utils/getPageExport.mjs";
import { EmptyRoute } from "../views/EmptyRoute.mjs";
import { NamedSlot } from "../views/Navigator.mjs";
import { RouteErrorView } from "../views/RouteErrorView.mjs";
import { Try } from "../views/Try.mjs";
import { ScrollBehaviorRouteCommit } from "../views/ScrollBehavior.mjs";
import { DevHead } from "../vite/DevHead.mjs";
import { getServerContext, useServerContext } from "../vite/one-server-only.mjs";
import { getReactNavigationRouteName } from "../getReactNavigationConfig.mjs";
import { filterRootHTML } from "./filterRootHTML.mjs";
import { Route, RouteParamsContext, SuspenseFallbackContext, useRouteNode } from "./Route.mjs";
import { SpaShellContext } from "./SpaShellContext.mjs";
import { sortRoutesWithInitial } from "./sortRoutes.mjs";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
function hasMetaCharset(children) {
if (process.env.NODE_ENV === "development") {
if (!children) return false;
const checkElement = (child) => {
if (!React.isValidElement(child)) return false;
if (child.type === "meta") {
const props = child.props;
if ("charSet" in props || "charset" in props) return true;
}
const childProps = child.props;
if (childProps.children) return hasMetaCharset(childProps.children);
return false;
};
if (Array.isArray(children)) return children.some(checkElement);
return checkElement(children);
}
return true;
}
const { Screen, Group } = createNavigatorFactory({})();
const cachedInlineCSSElements = typeof document !== "undefined" && typeof document.querySelectorAll === "function" ? (() => {
const elements = [];
document.querySelectorAll("style[id^=\"__one_css_\"], link[rel=\"stylesheet\"][data-one-css]").forEach((el, i) => {
if (el.tagName === "STYLE") elements.push(/* @__PURE__ */ jsx("style", {
id: el.id,
dangerouslySetInnerHTML: { __html: el.innerHTML }
}, `inline-css-${i}`));
else {
const href = el.getAttribute("href");
elements.push(/* @__PURE__ */ jsx("link", {
rel: "stylesheet",
href,
"data-one-css": ""
}, href));
}
});
return elements;
})() : [];
const SSR_SAFE_METRICS = {
frame: {
x: 0,
y: 0,
width: 0,
height: 0
},
insets: {
top: 0,
left: 0,
right: 0,
bottom: 0
}
};
function RootLayoutRenderer({ LayoutComponent, layoutProps, forwardedRef }) {
if (process.env.NODE_ENV === "development" && true) {
const [, setHmrKey] = useState(0);
useEffect(() => {
const handler = () => setHmrKey((k) => k + 1);
window.addEventListener("one-hmr-update", handler);
return () => window.removeEventListener("one-hmr-update", handler);
}, []);
}
const { children, bodyProps, head, htmlProps } = filterRootHTML(LayoutComponent(layoutProps, forwardedRef));
const { children: headChildren, ...headProps } = head?.props || {};
const serverContext = useServerContext();
let finalChildren = children;
if (process.env.NODE_ENV === "development") {
if (!hasMetaCharset(headChildren)) console.warn(`[one] Missing <meta charSet="utf-8" /> in your root _layout.tsx <head>. This can cause React hydration issues due to encoding mismatch. Add it as the first element in your <head> tag.`);
}
finalChildren = /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("head", {
...headProps,
children: [
/* @__PURE__ */ jsx(DevHead, {}),
/* @__PURE__ */ jsx("script", { dangerouslySetInnerHTML: { __html: `globalThis['global'] = globalThis` } }),
serverContext?.cssContents?.length || serverContext?.cssInlineCount ? serverContext?.cssContents ? serverContext.cssContents.map((content, i) => content ? /* @__PURE__ */ jsx("style", {
id: `__one_css_${i}`,
dangerouslySetInnerHTML: { __html: content }
}, `inline-css-${i}`) : serverContext.css?.[i] ? /* @__PURE__ */ jsx("link", {
rel: "stylesheet",
href: serverContext.css[i]
}, serverContext.css[i]) : null) : cachedInlineCSSElements : serverContext?.css?.map((file) => /* @__PURE__ */ jsx("link", {
rel: "stylesheet",
href: file
}, file)),
/* @__PURE__ */ jsx(ServerContextScript, {}),
headChildren
]
}, "head"), /* @__PURE__ */ jsx("body", {
suppressHydrationWarning: true,
...bodyProps,
children: /* @__PURE__ */ jsx(SafeAreaProvider, {
initialMetrics: SSR_SAFE_METRICS,
children: finalChildren
})
}, "body")] });
return /* @__PURE__ */ jsx("html", {
suppressHydrationWarning: true,
lang: "en-US",
...htmlProps,
children: finalChildren
});
}
function getSortedChildren(children, order, initialRouteName, options) {
if (!order?.length) return children.sort(sortRoutesWithInitial(initialRouteName)).map((route) => ({
route,
props: {}
}));
const entries = [...children];
const ordered = order.map(({ name, redirect, initialParams, listeners, options: options2, getId }) => {
if (!entries.length) {
console.warn(`[Layout children]: Too many screens defined. Route "${name}" is extraneous.`);
return null;
}
const matchIndex = entries.findIndex((child) => child.route === name);
if (matchIndex === -1) {
console.warn(`[Layout children]: No route named "${name}" exists in nested children:`, children.map(({ route }) => route));
return null;
}
const match = entries[matchIndex];
entries.splice(matchIndex, 1);
if (redirect) {
if (typeof redirect === "string") throw new Error(`Redirecting to a specific route is not supported yet.`);
return null;
}
return {
route: match,
props: {
initialParams,
listeners,
options: options2,
getId
}
};
}).filter(Boolean);
const remaining = options?.remaining ?? "all";
if (remaining !== "none") ordered.push(...entries.filter((route) => remaining === "all" || !route.generated).sort(sortRoutesWithInitial(initialRouteName)).map((route) => ({
route,
props: {}
})));
return ordered;
}
function useSortedScreens(order, options) {
const node = useRouteNode();
return React.useMemo(() => {
return (node?.children?.length ? getSortedChildren(node.children, order, node.initialRouteName, options) : []).filter((value) => {
const routeName = value.route.route;
const normalized = routeName.replace(/\/index$/, "");
return !(options?.protectedScreens?.has(routeName) || options?.protectedScreens?.has(normalized));
}).map((value) => routeToScreen(value.route, value.props));
}, [
node?.children,
node?.initialRouteName,
order,
options?.protectedScreens
]);
}
function fromImport({ ErrorBoundary, SuspenseFallback, ...component }) {
if (process.env.NODE_ENV !== "production") {
const exported = getPageExport(component);
if (exported && typeof exported === "object" && Object.keys(exported).length === 0) return {
default: EmptyRoute,
ErrorBoundary,
SuspenseFallback
};
}
return {
default: getPageExport(component),
ErrorBoundary,
SuspenseFallback
};
}
function RouteSuspenseFallback({ component: Component, route }) {
const params = useContext(RouteParamsContext);
return Component ? /* @__PURE__ */ jsx(Component, {
route,
params: params ?? {}
}) : null;
}
const qualifiedStore = /* @__PURE__ */ new WeakMap();
function getRouteMatchesForProps() {
const serverMatches = getServerContext()?.matches ?? [];
if (process.env.VITE_ENVIRONMENT === "ssr") return serverMatches;
const clientMatches = getClientMatchesSnapshot();
return clientMatches.length ? clientMatches : serverMatches;
}
function getQualifiedRouteComponent(value) {
if (value && qualifiedStore.has(value)) return qualifiedStore.get(value);
const ScreenComponent = React.forwardRef((props, ref) => {
if (process.env.NODE_ENV === "development" && true) {
const [, setHmrKey] = useState(0);
useEffect(() => {
const handler = () => setHmrKey((k) => k + 1);
window.addEventListener("one-hmr-update", handler);
return () => window.removeEventListener("one-hmr-update", handler);
}, []);
}
if (process.env.NODE_ENV === "development" && false);
const isSpaShell = useContext(SpaShellContext);
const InheritedSuspenseFallback = useContext(SuspenseFallbackContext);
const matches = getRouteMatchesForProps();
if (isSpaShell && props.segment !== "") {
if (!(value.children?.length && (value.layoutRenderMode === "ssg" || value.layoutRenderMode === "ssr"))) return /* @__PURE__ */ jsx("div", { "data-one-spa-content": "" });
}
const res = fromImport(value.loadRoute());
const Component = res.default || EmptyRoute;
const CatchBoundary = res.ErrorBoundary;
const LayoutSuspenseFallback = value.type === "layout" ? res.SuspenseFallback : void 0;
const match = matches.find((match2) => match2.routeId === value.contextKey) || (!value.children?.length ? matches[matches.length - 1] : void 0);
const loaderDataProps = match && "loaderData" in match ? { loaderData: match.loaderData } : {};
if (process.env.NODE_ENV === "development" && process.env.DEBUG === "one") {
console.groupCollapsed(`Render ${props.key} ${props.segment}`);
console.info(`value`, value);
console.info(`Component`, Component);
console.groupEnd();
}
const slotProps = {};
if (value.slots && value.slots.size > 0) for (const [slotName] of value.slots) slotProps[slotName] = /* @__PURE__ */ jsx(NamedSlot, {
name: slotName,
layoutContextKey: value.contextKey
});
let rendered;
if (props.segment === "") rendered = /* @__PURE__ */ jsx(RootLayoutRenderer, {
LayoutComponent: Component,
layoutProps: {
...props,
...slotProps,
...loaderDataProps
},
forwardedRef: ref
});
else {
const page = /* @__PURE__ */ jsx(Component, {
...props,
...slotProps,
...loaderDataProps,
ref
});
rendered = /* @__PURE__ */ jsx(RouteErrorBoundary, {
routeName: value.route,
children: CatchBoundary ? /* @__PURE__ */ jsx(Try, {
catch: CatchBoundary,
children: page
}) : page
});
}
if (value.type !== "layout") return rendered;
const providedSuspenseFallback = LayoutSuspenseFallback ?? InheritedSuspenseFallback;
return /* @__PURE__ */ jsx(SuspenseFallbackContext.Provider, {
value: providedSuspenseFallback,
children: LayoutSuspenseFallback ? wrapSuspense(rendered, LayoutSuspenseFallback) : rendered
});
});
const wrapSuspense = (children, SuspenseFallback) => {
const fallback = /* @__PURE__ */ jsx(RouteSuspenseFallback, {
component: SuspenseFallback,
route: value.contextKey
});
if (process.env.ONE_SUSPEND_ROUTES === "1" && globalThis.__ONE_DISABLE_SUSPENSE_ROUTES__ !== true) return /* @__PURE__ */ jsx(Suspense, {
fallback,
children
});
return children;
};
const QualifiedRoute = React.forwardRef(({ route, navigation, ...props }, ref) => {
const InheritedSuspenseFallback = useContext(SuspenseFallbackContext);
return /* @__PURE__ */ jsx(Route, {
route,
node: value,
children: /* @__PURE__ */ jsx(Fragment, { children: wrapSuspense(/* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(ScreenComponent, {
...props,
ref,
segment: value.route
}), process.env.VITE_ENVIRONMENT === "client" && value.type !== "layout" && navigation && /* @__PURE__ */ jsx(ScrollBehaviorRouteCommit, {})] }), InheritedSuspenseFallback) })
});
});
QualifiedRoute.displayName = `Route(${value.route})`;
const Memoized = memo(QualifiedRoute);
qualifiedStore.set(value, Memoized);
return Memoized;
}
function createGetIdForRoute(route) {
const include = /* @__PURE__ */ new Map();
if (route.dynamic) for (const segment of route.dynamic) include.set(segment.name, segment);
return ({ params = {} } = {}) => {
const segments = [];
for (const dynamic of include.values()) {
const value = params?.[dynamic.name];
if (Array.isArray(value) && value.length > 0) segments.push(value.join("/"));
else if (value && !Array.isArray(value)) segments.push(value);
else if (dynamic.deep) segments.push(`[...${dynamic.name}]`);
else segments.push(`[${dynamic.name}]`);
}
return segments.join("/") ?? route.contextKey;
};
}
function routeToScreen(route, { options, ...props } = {}) {
const navigationRouteName = getReactNavigationRouteName(route);
return /* @__PURE__ */ createElement(Screen, {
getId: createGetIdForRoute(route),
...props,
name: navigationRouteName,
key: navigationRouteName,
options: (args) => {
const staticOptions = route.generated ? route.loadRoute()?.getNavOptions : null;
const staticResult = typeof staticOptions === "function" ? staticOptions(args) : staticOptions;
const dynamicResult = typeof options === "function" ? options?.(args) : options;
const output = {
...staticResult,
...dynamicResult
};
if (route.generated) {
output.tabBarButton = () => null;
output.drawerItemStyle = {
height: 0,
display: "none"
};
}
return output;
},
getComponent: () => {
return getQualifiedRouteComponent(route);
}
});
}
const ROUTE_ERROR_BOUNDARY_INITIAL_STATE = {
hasError: false,
error: null,
errorInfo: null
};
var RouteErrorBoundary = class extends React.Component {
constructor(props) {
super(props);
this.state = ROUTE_ERROR_BOUNDARY_INITIAL_STATE;
}
static getDerivedStateFromError(error) {
return {
hasError: true,
error
};
}
componentDidCatch(error, errorInfo) {
console.error(`Error occurred while running route "${this.props.routeName}": ${error instanceof Error ? error.message : error}
${error.stack}
Component Stack:
${errorInfo.componentStack}`);
this.setState({ errorInfo });
if (process.env.NODE_ENV === "production" && process.env.ONE_SKEW_PROTECTION !== "false") if (isChunkLoadError(error)) handleSkewError();
else checkSkewAndReload();
}
clearError() {
this.setState(ROUTE_ERROR_BOUNDARY_INITIAL_STATE);
}
render() {
if (this.state.hasError) {
const { error, errorInfo } = this.state;
return /* @__PURE__ */ jsx(RouteErrorView, {
routeName: this.props.routeName,
error,
errorInfo,
onRetry: this.clearError.bind(this)
});
}
return this.props.children;
}
};
export { Group, Screen, createGetIdForRoute, getQualifiedRouteComponent, useSortedScreens };
//# sourceMappingURL=useScreens.mjs.map