UNPKG

one

Version:

One is a new React Framework that makes Vite serve both native and web.

434 lines (429 loc) 16.4 kB
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime"; import { createElement as _createElement } from "react"; import { createNavigatorFactory } from "@react-navigation/core"; import { SafeAreaProviderCompat } from "@react-navigation/elements"; import React, { memo, Suspense } from "react"; import { SafeAreaView, ScrollView, View, TouchableOpacity, Text } from "react-native"; import { ServerContextScript } from "../server/ServerContextScript.native.js"; import { getPageExport } from "../utils/getPageExport.native.js"; import { EmptyRoute } from "../views/EmptyRoute.native.js"; import { Try } from "../views/Try.native.js"; import { DevHead } from "../vite/DevHead.native.js"; import { useServerContext } from "../vite/one-server-only.native.js"; import { filterRootHTML } from "./filterRootHTML.native.js"; import { Route, useRouteNode } from "./Route.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) { return derived = _get_prototype_of(derived), _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 || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } function _create_class(Constructor, protoProps, staticProps) { return protoProps && _defineProperties(Constructor.prototype, protoProps), staticProps && _defineProperties(Constructor, staticProps), Constructor; } function _get_prototype_of(o) { return _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function (o2) { return o2.__proto__ || Object.getPrototypeOf(o2); }, _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: !0, configurable: !0 } }), superClass && _set_prototype_of(subClass, superClass); } function _possible_constructor_return(self, call) { return call && (_type_of(call) === "object" || typeof call == "function") ? call : _assert_this_initialized(self); } function _set_prototype_of(o, p) { return _set_prototype_of = Object.setPrototypeOf || function (o2, p2) { return o2.__proto__ = p2, o2; }, _set_prototype_of(o, p); } function _type_of(obj) { "@swc/helpers - typeof"; return obj && typeof Symbol < "u" && obj.constructor === Symbol ? "symbol" : typeof obj; } 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; })(); } var { Screen, Group } = createNavigatorFactory({})(); function getSortedChildren(children, order, initialRouteName, options) { if (!order?.length) return children.sort(sortRoutesWithInitial(initialRouteName)).map(function (route) { return { route, props: {} }; }); var entries = [...children], ordered = order.map(function (param) { var { name, redirect, initialParams, listeners, options: _$options, getId } = param; if (!entries.length) return console.warn(`[Layout children]: Too many screens defined. Route "${name}" is extraneous.`), null; var matchIndex = entries.findIndex(function (child) { return child.route === name; }); if (matchIndex === -1) return console.warn(`[Layout children]: No route named "${name}" exists in nested children:`, children.map(function (param2) { var { route } = param2; return route; })), null; var match = entries[matchIndex]; if (entries.splice(matchIndex, 1), 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); return options?.onlyMatching || ordered.push(...entries.sort(sortRoutesWithInitial(initialRouteName)).map(function (route) { return { route, props: {} }; })), ordered; } function useSortedScreens(order, options) { var node = useRouteNode(), sortedScreens = React.useMemo(function () { var _node_children, sorted = !(node == null || (_node_children = node.children) === null || _node_children === void 0) && _node_children.length ? getSortedChildren(node.children, order, node.initialRouteName, options) : []; return sorted.map(function (value) { return routeToScreen(value.route, value.props); }); }, [node?.children, node?.initialRouteName, order]); return sortedScreens; } function fromImport(param) { var { ErrorBoundary, ...component } = param; if (ErrorBoundary) return { default: /* @__PURE__ */React.forwardRef(function (props, ref) { var children = /* @__PURE__ */React.createElement(getPageExport(component) || EmptyRoute, { ...props, ref }); return /* @__PURE__ */_jsx(Try, { catch: ErrorBoundary, children }); }) }; if (process.env.NODE_ENV !== "production") { var exported = getPageExport(component); if (exported && typeof exported == "object" && Object.keys(exported).length === 0) return { default: EmptyRoute }; } return { default: getPageExport(component) }; } var qualifiedStore = /* @__PURE__ */new WeakMap(); function getQualifiedRouteComponent(value) { if (value && qualifiedStore.has(value)) return qualifiedStore.get(value); var ScreenComponent = /* @__PURE__ */React.forwardRef(function (props, ref) { var res = value.loadRoute(), Component = getPageExport(fromImport(res)); 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()), props.segment === "") { var _serverContext_css, out = Component(props, ref), { children, bodyProps, head, htmlProps } = filterRootHTML(out), { children: headChildren, ...headProps } = head?.props || {}, serverContext = useServerContext(), finalChildren = children; return finalChildren; } return /* @__PURE__ */_jsx(RouteErrorBoundary, { routeName: value.route, children: /* @__PURE__ */_jsx(Component, { ...props, ref }) }); }), wrapSuspense = function (children) { return /* @__PURE__ */_jsx(Suspense, { fallback: null, children }); }, QualifiedRoute = /* @__PURE__ */React.forwardRef(function (param, ref) { var { // Remove these React Navigation props to // enforce usage of router hooks (where the query params are correct). route, navigation, // Pass all other props to the component ...props } = param; return /* @__PURE__ */_jsx(Route, { route, node: value, children: /* @__PURE__ */_jsx(_Fragment, { children: wrapSuspense(/* @__PURE__ */_jsx(ScreenComponent, { ...props, ref, // Expose the template segment path, e.g. `(home)`, `[foo]`, `index` // the intention is to make it possible to deduce shared routes. segment: value.route })) }) }); }); return QualifiedRoute.displayName = `Route(${value.route})`, qualifiedStore.set(value, QualifiedRoute), /* @__PURE__ */memo(QualifiedRoute); } function createGetIdForRoute(route) { var include = /* @__PURE__ */new Map(); if (route.dynamic) { var _iteratorNormalCompletion = !0, _didIteratorError = !1, _iteratorError = void 0; try { for (var _iterator = route.dynamic[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = !0) { var segment = _step.value; include.set(segment.name, segment); } } catch (err) { _didIteratorError = !0, _iteratorError = err; } finally { try { !_iteratorNormalCompletion && _iterator.return != null && _iterator.return(); } finally { if (_didIteratorError) throw _iteratorError; } } } return function () { var { params = {} } = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, segments = [], _iteratorNormalCompletion2 = !0, _didIteratorError2 = !1, _iteratorError2 = void 0; try { for (var _iterator2 = include.values()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = !0) { var dynamic = _step2.value, value = params?.[dynamic.name]; Array.isArray(value) && value.length > 0 ? segments.push(value.join("/")) : value && !Array.isArray(value) ? segments.push(value) : dynamic.deep ? segments.push(`[...${dynamic.name}]`) : segments.push(`[${dynamic.name}]`); } } catch (err) { _didIteratorError2 = !0, _iteratorError2 = err; } finally { try { !_iteratorNormalCompletion2 && _iterator2.return != null && _iterator2.return(); } finally { if (_didIteratorError2) throw _iteratorError2; } } var _segments_join; 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] : {}; return /* @__PURE__ */_createElement(Screen, { // Users can override the screen getId function. getId: createGetIdForRoute(route), ...props, name: route.route, key: route.route, options: function (args) { var _route_loadRoute, staticOptions = route.generated ? (_route_loadRoute = route.loadRoute()) === null || _route_loadRoute === void 0 ? void 0 : _route_loadRoute.getNavOptions : null, staticResult = typeof staticOptions == "function" ? staticOptions(args) : staticOptions, dynamicResult = typeof options == "function" ? options?.(args) : options, output = { ...staticResult, ...dynamicResult }; return route.generated && (output.tabBarButton = function () { return null; }, output.drawerItemStyle = { height: 0, display: "none" }), output; }, // this doesn't work, also probably better to wrap suspense only on root layout in useScreens // but it doesnt seem to pick up our startTransitions which i wrapped in a few places. // now i thought this was due to our use of useSyncExternalStore, but i replaced that with // `use-sync-external-store/shim` and i also replaced the one in react-navigation that does // `use-sync-external-store/with-selector` to `use-sync-external-store/shim/with-selector` // but still it seems something else must be updating state outside a transition. // layout={({ children }) => { // console.log('route.contextKey', route.contextKey) // if (route.contextKey === '') { // return <Suspense fallback={null}>{children}</Suspense> // } // return children // }} getComponent: function () { return getQualifiedRouteComponent(route); } }); } var ROUTE_ERROR_BOUNDARY_INITIAL_STATE = { hasError: !1, error: null, errorInfo: null }, RouteErrorBoundary = /* @__PURE__ */function (_React_Component) { "use strict"; _inherits(RouteErrorBoundary2, _React_Component); function RouteErrorBoundary2(props) { _class_call_check(this, RouteErrorBoundary2); var _this; return _this = _call_super(this, RouteErrorBoundary2, [props]), _this.state = ROUTE_ERROR_BOUNDARY_INITIAL_STATE, _this; } return _create_class(RouteErrorBoundary2, [{ key: "componentDidCatch", value: function (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 () { this.setState(ROUTE_ERROR_BOUNDARY_INITIAL_STATE); } }, { key: "render", value: function () { if (this.state.hasError) { var { error, errorInfo } = this.state; return /* @__PURE__ */_jsx(SafeAreaView, { style: { backgroundColor: "#000" }, children: /* @__PURE__ */_jsxs(View, { style: { margin: 16, gap: 16 }, children: [/* @__PURE__ */_jsxs(Text, { style: { alignSelf: "flex-start", padding: 5, margin: -5, backgroundColor: "red", color: "white", fontSize: 20, fontFamily: "monospace" }, children: ['Error on route "', this.props.routeName, '"'] }), /* @__PURE__ */_jsx(Text, { style: { color: "white", fontSize: 16, fontFamily: "monospace" }, children: error instanceof Error ? error.message : error }), /* @__PURE__ */_jsx(TouchableOpacity, { onPress: this.clearError.bind(this), children: /* @__PURE__ */_jsx(Text, { style: { alignSelf: "flex-start", margin: -6, padding: 6, backgroundColor: "white", color: "black", fontSize: 14, fontFamily: "monospace" }, children: "Retry" }) }), /* @__PURE__ */_jsxs(ScrollView, { contentContainerStyle: { gap: 12 }, children: [error instanceof Error ? /* @__PURE__ */_jsx(Text, { style: { color: "white", fontSize: 12, fontFamily: "monospace" }, children: error.stack }) : null, errorInfo?.componentStack ? /* @__PURE__ */_jsxs(Text, { style: { color: "white", fontSize: 12, fontFamily: "monospace" }, children: ["Component Stack: ", errorInfo.componentStack] }) : null] })] }) }); } return this.props.children; } }], [{ key: "getDerivedStateFromError", value: function (error) { return { hasError: !0, error }; } }]), RouteErrorBoundary2; }(React.Component); export { Group, Screen, createGetIdForRoute, getQualifiedRouteComponent, useSortedScreens }; //# sourceMappingURL=useScreens.native.js.map