UNPKG

one

Version:

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

538 lines (533 loc) 19.6 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, useContext, useEffect, useState } from "react"; import { SafeAreaView, ScrollView, Text, TouchableOpacity, View } 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 { SpaShellContext } from "./SpaShellContext.native.js"; import { NamedSlot } from "../views/Navigator.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 _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) return !!right[Symbol.hasInstance](left);else return left instanceof right; } 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; } 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 hasMetaCharset(children) { if (process.env.NODE_ENV === "development") { if (!children) return false; var checkElement = function (child) { if (! /* @__PURE__ */React.isValidElement(child)) return false; if (child.type === "meta") { var props = child.props; if ("charSet" in props || "charset" in props) return true; } var 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; } var { Screen, Group } = createNavigatorFactory({})(); typeof document !== "undefined" && 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) { 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); if (!(options === null || options === void 0 ? void 0 : options.onlyMatching)) ordered.push(...entries.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, ...component } = param; if (ErrorBoundary) return { default: /* @__PURE__ */React.forwardRef(function (props, ref) { return /* @__PURE__ */_jsx(Try, { catch: ErrorBoundary, children: /* @__PURE__ */React.createElement(getPageExport(component) || EmptyRoute, { ...props, ref }) }); }) }; if (process.env.NODE_ENV !== "production") { var exported = getPageExport(component); if (exported && (typeof exported === "undefined" ? "undefined" : _type_of(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) { if (process.env.NODE_ENV === "development" && false) ; if (useContext(SpaShellContext) && props.segment !== "") { var _value_children; if (!(((_value_children = value.children) === null || _value_children === void 0 ? void 0 : _value_children.length) && (value.layoutRenderMode === "ssg" || value.layoutRenderMode === "ssr"))) return /* @__PURE__ */_jsx("div", { "data-one-spa-content": "" }); } var Component = getPageExport(fromImport(value.loadRoute())); 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; } } } if (props.segment === "") return /* @__PURE__ */_jsx(RootLayoutRenderer, { LayoutComponent: Component, layoutProps: { ...props, ...slotProps }, forwardedRef: ref }); return /* @__PURE__ */_jsx(RouteErrorBoundary, { routeName: value.route, children: /* @__PURE__ */_jsx(Component, { ...props, ...slotProps, ref }) }); }); var wrapSuspense = function (children) { if (process.env.ONE_SUSPEND_ROUTES_NATIVE === "0" || globalThis.__ONE_DISABLE_SUSPENSE_ROUTES__ === true) return children; return /* @__PURE__ */_jsx(Suspense, { fallback: null, children }); }; var QualifiedRoute = /* @__PURE__ */React.forwardRef(function (param, ref) { var { route, navigation, ...props } = param; return /* @__PURE__ */_jsx(Route, { route, node: value, children: /* @__PURE__ */_jsx(_Fragment, { children: wrapSuspense(/* @__PURE__ */_jsx(ScreenComponent, { ...props, ref, segment: value.route })) }) }); }); QualifiedRoute.displayName = `Route(${value.route})`; qualifiedStore.set(value, QualifiedRoute); return /* @__PURE__ */memo(QualifiedRoute); } 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] : {}; return /* @__PURE__ */_createElement(Screen, { getId: createGetIdForRoute(route), ...props, name: route.route, key: route.route, options: function (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 () { 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}": ${_instanceof(error, 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(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: _instanceof(error, 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: [_instanceof(error, Error) ? /* @__PURE__ */_jsx(Text, { style: { color: "white", fontSize: 12, fontFamily: "monospace" }, children: error.stack }) : null, (errorInfo === null || errorInfo === void 0 ? void 0 : 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 getDerivedStateFromError(error) { return { hasError: true, error }; } }]); return RouteErrorBoundary2; }(React.Component); export { Group, Screen, createGetIdForRoute, getQualifiedRouteComponent, useSortedScreens }; //# sourceMappingURL=useScreens.native.js.map