one
Version:
One is a new React Framework that makes Vite serve both native and web.
487 lines (481 loc) • 19.6 kB
JavaScript
;
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf,
__hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all) __defProp(target, name, {
get: all[name],
enumerable: !0
});
},
__copyProps = (to, from, except, desc) => {
if (from && typeof from == "object" || typeof from == "function") for (let key of __getOwnPropNames(from)) !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, {
get: () => from[key],
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: !0
}) : target, mod)),
__toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
value: !0
}), mod);
var useScreens_exports = {};
__export(useScreens_exports, {
Group: () => Group,
Screen: () => Screen,
createGetIdForRoute: () => createGetIdForRoute,
getQualifiedRouteComponent: () => getQualifiedRouteComponent,
useSortedScreens: () => useSortedScreens
});
module.exports = __toCommonJS(useScreens_exports);
var import_jsx_runtime = require("react/jsx-runtime"),
import_react = require("react"),
import_core = require("@react-navigation/core"),
import_elements = require("@react-navigation/elements"),
import_react2 = __toESM(require("react"), 1),
import_react_native = require("react-native"),
import_ServerContextScript = require("../server/ServerContextScript.native.js"),
import_getPageExport = require("../utils/getPageExport.native.js"),
import_EmptyRoute = require("../views/EmptyRoute.native.js"),
import_Try = require("../views/Try.native.js"),
import_DevHead = require("../vite/DevHead.native.js"),
import_one_server_only = require("../vite/one-server-only.native.js"),
import_filterRootHTML = require("./filterRootHTML.native.js"),
import_Route = require("./Route.native.js"),
import_sortRoutes = require("./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 _instanceof(left, right) {
return right != null && typeof Symbol < "u" && right[Symbol.hasInstance] ? !!right[Symbol.hasInstance](left) : left instanceof right;
}
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
} = (0, import_core.createNavigatorFactory)({})(),
cachedInlineCSSElements = typeof document < "u" ? Array.from(document.querySelectorAll('style[id^="__one_css_"]')).map(function (el, i) {
return /* @__PURE__ */(0, import_jsx_runtime.jsx)("style", {
id: el.id,
dangerouslySetInnerHTML: {
__html: el.innerHTML
}
}, `inline-css-${i}`);
}) : [];
function getSortedChildren(children, order, initialRouteName, options) {
if (!order?.length) return children.sort((0, import_sortRoutes.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((0, import_sortRoutes.sortRoutesWithInitial)(initialRouteName)).map(function (route) {
return {
route,
props: {}
};
})), ordered;
}
function useSortedScreens(order, options) {
var node = (0, import_Route.useRouteNode)(),
sortedScreens = import_react2.default.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__ */import_react2.default.forwardRef(function (props, ref) {
var children = /* @__PURE__ */import_react2.default.createElement((0, import_getPageExport.getPageExport)(component) || import_EmptyRoute.EmptyRoute, {
...props,
ref
});
return /* @__PURE__ */(0, import_jsx_runtime.jsx)(import_Try.Try, {
catch: ErrorBoundary,
children
});
})
};
if (process.env.NODE_ENV !== "production") {
var exported = (0, import_getPageExport.getPageExport)(component);
if (exported && (typeof exported > "u" ? "undefined" : _type_of(exported)) === "object" && Object.keys(exported).length === 0) return {
default: import_EmptyRoute.EmptyRoute
};
}
return {
default: (0, import_getPageExport.getPageExport)(component)
};
}
var qualifiedStore = /* @__PURE__ */new WeakMap();
function getQualifiedRouteComponent(value) {
if (value && qualifiedStore.has(value)) return qualifiedStore.get(value);
var ScreenComponent = /* @__PURE__ */import_react2.default.forwardRef(function (props, ref) {
var res = value.loadRoute(),
Component = (0, import_getPageExport.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_cssContents,
_serverContext_css,
out = Component(props, ref),
{
children,
bodyProps,
head,
htmlProps
} = (0, import_filterRootHTML.filterRootHTML)(out),
{
children: headChildren,
...headProps
} = head?.props || {},
serverContext = (0, import_one_server_only.useServerContext)(),
finalChildren = children;
return finalChildren;
}
return /* @__PURE__ */(0, import_jsx_runtime.jsx)(RouteErrorBoundary, {
routeName: value.route,
children: /* @__PURE__ */(0, import_jsx_runtime.jsx)(Component, {
...props,
ref
})
});
}),
wrapSuspense = function (children) {
return /* @__PURE__ */(0, import_jsx_runtime.jsx)(import_react2.Suspense, {
fallback: null,
children
});
},
QualifiedRoute = /* @__PURE__ */import_react2.default.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__ */(0, import_jsx_runtime.jsx)(import_Route.Route, {
route,
node: value,
children: /* @__PURE__ */(0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, {
children: wrapSuspense(/* @__PURE__ */(0, import_jsx_runtime.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__ */(0, import_react2.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__ */(0, import_react.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}": ${_instanceof(error, 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__ */(0, import_jsx_runtime.jsx)(import_react_native.SafeAreaView, {
style: {
backgroundColor: "#000"
},
children: /* @__PURE__ */(0, import_jsx_runtime.jsxs)(import_react_native.View, {
style: {
margin: 16,
gap: 16
},
children: [/* @__PURE__ */(0, import_jsx_runtime.jsxs)(import_react_native.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__ */(0, import_jsx_runtime.jsx)(import_react_native.Text, {
style: {
color: "white",
fontSize: 16,
fontFamily: "monospace"
},
children: _instanceof(error, Error) ? error.message : error
}), /* @__PURE__ */(0, import_jsx_runtime.jsx)(import_react_native.TouchableOpacity, {
onPress: this.clearError.bind(this),
children: /* @__PURE__ */(0, import_jsx_runtime.jsx)(import_react_native.Text, {
style: {
alignSelf: "flex-start",
margin: -6,
padding: 6,
backgroundColor: "white",
color: "black",
fontSize: 14,
fontFamily: "monospace"
},
children: "Retry"
})
}), /* @__PURE__ */(0, import_jsx_runtime.jsxs)(import_react_native.ScrollView, {
contentContainerStyle: {
gap: 12
},
children: [_instanceof(error, Error) ? /* @__PURE__ */(0, import_jsx_runtime.jsx)(import_react_native.Text, {
style: {
color: "white",
fontSize: 12,
fontFamily: "monospace"
},
children: error.stack
}) : null, errorInfo?.componentStack ? /* @__PURE__ */(0, import_jsx_runtime.jsxs)(import_react_native.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;
}(import_react2.default.Component);
//# sourceMappingURL=useScreens.native.js.map