UNPKG

one

Version:

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

465 lines (460 loc) • 18.3 kB
import { Fragment, jsx, jsxs } from "react/jsx-runtime"; import React, { Suspense, createElement, memo, useContext } from "react"; import { createNavigatorFactory } from "@react-navigation/core"; import { getClientMatchesSnapshot } from "../useMatches.native.js"; import { getPageExport } from "../utils/getPageExport.native.js"; import { EmptyRoute } from "../views/EmptyRoute.native.js"; import { NamedSlot } from "../views/Navigator.native.js"; import { RouteErrorView } from "../views/RouteErrorView.native.js"; import { Try } from "../views/Try.native.js"; import { ScrollBehaviorRouteCommit } from "../views/ScrollBehavior.native.js"; import { getServerContext, useServerContext } from "../vite/one-server-only.native.js"; import { getReactNavigationRouteName } from "../getReactNavigationConfig.native.js"; import { filterRootHTML } from "./filterRootHTML.native.js"; import { Route, RouteParamsContext, SuspenseFallbackContext, useRouteNode } from "./Route.native.js"; import { getRouteHmrEpoch, subscribeRouteHmr } from "./routeHmr.native.js"; import { SpaShellContext } from "./SpaShellContext.native.js"; import { sortRoutesWithInitial } from "./sortRoutes.native.js"; function _assert_this_initialized(self) { if (self === void 0) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return self; } function _call_super(_this, derived, args) { derived = _get_prototype_of(derived); return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args)); } function _class_call_check(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _create_class(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _get_prototype_of(o) { _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o2) { return o2.__proto__ || Object.getPrototypeOf(o2); }; return _get_prototype_of(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) throw new TypeError("Super expression must either be null or a function"); subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _set_prototype_of(subClass, superClass); } function _is_native_reflect_construct() { try { var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {})); } catch (_) {} return (_is_native_reflect_construct = function() { return !!result; })(); } function _possible_constructor_return(self, call) { if (call && (_type_of(call) === "object" || typeof call === "function")) return call; return _assert_this_initialized(self); } function _set_prototype_of(o, p) { _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o2, p2) { o2.__proto__ = p2; return o2; }; return _set_prototype_of(o, p); } function _type_of(obj) { "@swc/helpers - typeof"; return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj; } var { Screen, Group } = createNavigatorFactory({})(); typeof document !== "undefined" && typeof document.querySelectorAll === "function" && (function() { var elements = []; document.querySelectorAll("style[id^=\"__one_css_\"], link[rel=\"stylesheet\"][data-one-css]").forEach(function(el, i) { if (el.tagName === "STYLE") elements.push(/* @__PURE__ */ jsx("style", { id: el.id, dangerouslySetInnerHTML: { __html: el.innerHTML } }, `inline-css-${i}`)); else { var href = el.getAttribute("href"); elements.push(/* @__PURE__ */ jsx("link", { rel: "stylesheet", href, "data-one-css": "" }, href)); } }); return elements; })(); function RootLayoutRenderer(param) { var { LayoutComponent, layoutProps, forwardedRef } = param; if (process.env.NODE_ENV === "development" && false); var { children, bodyProps, head, htmlProps } = filterRootHTML(LayoutComponent(layoutProps, forwardedRef)); var { children: headChildren, ...headProps } = (head === null || head === void 0 ? void 0 : head.props) || {}; useServerContext(); return children; } function getSortedChildren(children, order, initialRouteName, options) { var _ref; if (!(order === null || order === void 0 ? void 0 : order.length)) return children.sort(sortRoutesWithInitial(initialRouteName)).map(function(route) { return { route, props: {} }; }); var entries = [...children]; var ordered = order.map(function(param) { var { name, redirect, initialParams, listeners, options: _$options, getId } = param; if (!entries.length) { console.warn(`[Layout children]: Too many screens defined. Route "${name}" is extraneous.`); return null; } var matchIndex = entries.findIndex(function(child) { return child.route === name; }); if (matchIndex === -1) { console.warn(`[Layout children]: No route named "${name}" exists in nested children:`, children.map(function(param2) { var { route } = param2; return route; })); return null; } var 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: _$options, getId } }; }).filter(Boolean); var remaining = (_ref = options === null || options === void 0 ? void 0 : options.remaining) !== null && _ref !== void 0 ? _ref : "all"; if (remaining !== "none") ordered.push(...entries.filter(function(route) { return remaining === "all" || !route.generated; }).sort(sortRoutesWithInitial(initialRouteName)).map(function(route) { return { route, props: {} }; })); return ordered; } function useSortedScreens(order, options) { var node = useRouteNode(); return React.useMemo(function() { var _node_children; return ((node === null || node === void 0 ? void 0 : (_node_children = node.children) === null || _node_children === void 0 ? void 0 : _node_children.length) ? getSortedChildren(node.children, order, node.initialRouteName, options) : []).filter(function(value) { var _options_protectedScreens, _options_protectedScreens1; var routeName = value.route.route; var normalized = routeName.replace(/\/index$/, ""); return !((options === null || options === void 0 ? void 0 : (_options_protectedScreens = options.protectedScreens) === null || _options_protectedScreens === void 0 ? void 0 : _options_protectedScreens.has(routeName)) || (options === null || options === void 0 ? void 0 : (_options_protectedScreens1 = options.protectedScreens) === null || _options_protectedScreens1 === void 0 ? void 0 : _options_protectedScreens1.has(normalized))); }).map(function(value) { return routeToScreen(value.route, value.props); }); }, [ node === null || node === void 0 ? void 0 : node.children, node === null || node === void 0 ? void 0 : node.initialRouteName, order, options === null || options === void 0 ? void 0 : options.protectedScreens ]); } function fromImport(param) { var { ErrorBoundary, SuspenseFallback, ...component } = param; if (process.env.NODE_ENV !== "production") { var 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(param) { var { component: Component, route } = param; var params = useContext(RouteParamsContext); return Component ? /* @__PURE__ */ jsx(Component, { route, params: params !== null && params !== void 0 ? params : {} }) : null; } var qualifiedStore = /* @__PURE__ */ new WeakMap(); function getRouteMatchesForProps() { var _ref; var _getServerContext; var serverMatches = (_ref = (_getServerContext = getServerContext()) === null || _getServerContext === void 0 ? void 0 : _getServerContext.matches) !== null && _ref !== void 0 ? _ref : []; if (process.env.VITE_ENVIRONMENT === "ssr") return serverMatches; var clientMatches = getClientMatchesSnapshot(); return clientMatches.length ? clientMatches : serverMatches; } function getQualifiedRouteComponent(value) { if (value && qualifiedStore.has(value)) return qualifiedStore.get(value); var ScreenComponent = /* @__PURE__ */ React.forwardRef(function(props, ref) { var _value_children; if (process.env.NODE_ENV === "development" && false); if (process.env.NODE_ENV === "development" && true) React.useSyncExternalStore(subscribeRouteHmr, getRouteHmrEpoch, getRouteHmrEpoch); var isSpaShell = useContext(SpaShellContext); var InheritedSuspenseFallback = useContext(SuspenseFallbackContext); var matches = getRouteMatchesForProps(); if (isSpaShell && props.segment !== "") { var _value_children1; if (!(((_value_children1 = value.children) === null || _value_children1 === void 0 ? void 0 : _value_children1.length) && (value.layoutRenderMode === "ssg" || value.layoutRenderMode === "ssr"))) return /* @__PURE__ */ jsx("div", { "data-one-spa-content": "" }); } var res = fromImport(value.loadRoute()); var Component = res.default || EmptyRoute; var CatchBoundary = res.ErrorBoundary; var LayoutSuspenseFallback = value.type === "layout" ? res.SuspenseFallback : void 0; var match = matches.find(function(match2) { return match2.routeId === value.contextKey; }) || (!((_value_children = value.children) === null || _value_children === void 0 ? void 0 : _value_children.length) ? matches[matches.length - 1] : void 0); var 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(); } var slotProps = {}; if (value.slots && value.slots.size > 0) { var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = void 0; try { for (var _iterator = value.slots[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var [slotName] = _step.value; slotProps[slotName] = /* @__PURE__ */ jsx(NamedSlot, { name: slotName, layoutContextKey: value.contextKey }); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return != null) _iterator.return(); } finally { if (_didIteratorError) throw _iteratorError; } } } var rendered; if (props.segment === "") rendered = /* @__PURE__ */ jsx(RootLayoutRenderer, { LayoutComponent: Component, layoutProps: { ...props, ...slotProps, ...loaderDataProps }, forwardedRef: ref }); else { var 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; var providedSuspenseFallback = LayoutSuspenseFallback !== null && LayoutSuspenseFallback !== void 0 ? LayoutSuspenseFallback : InheritedSuspenseFallback; return /* @__PURE__ */ jsx(SuspenseFallbackContext.Provider, { value: providedSuspenseFallback, children: LayoutSuspenseFallback ? wrapSuspense(rendered, LayoutSuspenseFallback) : rendered }); }); var wrapSuspense = function wrapSuspense2(children, SuspenseFallback) { var fallback = /* @__PURE__ */ jsx(RouteSuspenseFallback, { component: SuspenseFallback, route: value.contextKey }); if (process.env.ONE_SUSPEND_ROUTES_NATIVE === "0" || globalThis.__ONE_DISABLE_SUSPENSE_ROUTES__ === true) return children; return /* @__PURE__ */ jsx(Suspense, { fallback, children }); }; var QualifiedRoute = /* @__PURE__ */ React.forwardRef(function(param, ref) { var { route, navigation, ...props } = param; var 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})`; var Memoized = /* @__PURE__ */ memo(QualifiedRoute); qualifiedStore.set(value, Memoized); return Memoized; } function createGetIdForRoute(route) { var include = /* @__PURE__ */ new Map(); if (route.dynamic) { var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = void 0; try { for (var _iterator = route.dynamic[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var segment = _step.value; include.set(segment.name, segment); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return != null) _iterator.return(); } finally { if (_didIteratorError) throw _iteratorError; } } } return function() { var { params = {} } = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; var _segments_join; var segments = []; var _iteratorNormalCompletion2 = true, _didIteratorError2 = false, _iteratorError2 = void 0; try { for (var _iterator2 = include.values()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var dynamic = _step2.value; var value = params === null || params === void 0 ? void 0 : 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}]`); } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return != null) _iterator2.return(); } finally { if (_didIteratorError2) throw _iteratorError2; } } return (_segments_join = segments.join("/")) !== null && _segments_join !== void 0 ? _segments_join : route.contextKey; }; } function routeToScreen(route) { var { options, ...props } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; var navigationRouteName = getReactNavigationRouteName(route); return /* @__PURE__ */ createElement(Screen, { getId: createGetIdForRoute(route), ...props, name: navigationRouteName, key: navigationRouteName, options: function options1(args) { var _route_loadRoute; var staticOptions = route.generated ? (_route_loadRoute = route.loadRoute()) === null || _route_loadRoute === void 0 ? void 0 : _route_loadRoute.getNavOptions : null; var staticResult = typeof staticOptions === "function" ? staticOptions(args) : staticOptions; var dynamicResult = typeof options === "function" ? options === null || options === void 0 ? void 0 : options(args) : options; var output = { ...staticResult, ...dynamicResult }; if (route.generated) { output.tabBarButton = function() { return null; }; output.drawerItemStyle = { height: 0, display: "none" }; } return output; }, getComponent: function getComponent() { return getQualifiedRouteComponent(route); } }); } var ROUTE_ERROR_BOUNDARY_INITIAL_STATE = { hasError: false, error: null, errorInfo: null }; var RouteErrorBoundary = /* @__PURE__ */ (function(_React_Component) { "use strict"; _inherits(RouteErrorBoundary2, _React_Component); function RouteErrorBoundary2(props) { _class_call_check(this, RouteErrorBoundary2); var _this = _call_super(this, RouteErrorBoundary2, [props]); _this.state = ROUTE_ERROR_BOUNDARY_INITIAL_STATE; return _this; } _create_class(RouteErrorBoundary2, [ { key: "componentDidCatch", value: function 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 }); } }, { key: "clearError", value: function clearError() { this.setState(ROUTE_ERROR_BOUNDARY_INITIAL_STATE); } }, { key: "render", value: function render() { if (this.state.hasError) { var { error, errorInfo } = this.state; return /* @__PURE__ */ jsx(RouteErrorView, { routeName: this.props.routeName, error, errorInfo, onRetry: this.clearError.bind(this) }); } return this.props.children; } } ], [{ key: "getDerivedStateFromError", value: function getDerivedStateFromError(error) { return { hasError: true, error }; } }]); return RouteErrorBoundary2; })(React.Component); export { Group, Screen, createGetIdForRoute, getQualifiedRouteComponent, useSortedScreens }; //# sourceMappingURL=useScreens.native.js.map