@shopgate/pwa-common
Version:
Common library for the Shopgate Connect PWA.
97 lines (94 loc) • 3.11 kB
JavaScript
import _createClass from "@babel/runtime/helpers/createClass";
import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose";
import React, { Suspense } from 'react';
import PropTypes from 'prop-types';
import { router } from '@virtuous/conductor';
import { RouteContext, RouterContext } from '@virtuous/react-conductor';
import Loading from "../Loading";
import ErrorBoundary from "../ErrorBoundary";
import RouteNotFound from "./RouteNotFound";
/**
* The Route component.
*/
import { jsx as _jsx } from "react/jsx-runtime";
let Route = /*#__PURE__*/function (_React$Component) {
/**
* @param {Object} props The component props.
*/
function Route(props) {
var _this;
_this = _React$Component.call(this, props) || this;
router.register(props.pattern, props.transform);
return _this;
}
/**
* TODO: Move to router
*/
_inheritsLoose(Route, _React$Component);
var _proto = Route.prototype;
/**
* @returns {JSX}
*/
_proto.render = function render() {
const {
cache,
component: Component,
pattern
} = this.props;
let matches = [];
// If the current pattern does not match the whitelist but matches the current route
// then add the current route as the only match.
if (!cache && pattern === this.currentRoute.pattern) {
matches = [[this.currentRoute.id, this.currentRoute]];
} else if (cache) {
const subset = this.context.stack.slice(0, router.routeIndex + 1);
// Find matching patterns.
matches = subset.filter(([, route]) => route.pattern === pattern);
}
if (!matches.length) {
return null;
}
return matches.map(([, route]) => {
const {
setPattern,
...context
} = route;
context.open = true;
context.visible = route.id === this.currentRoute.id;
/**
* When a route is "replaced" the router doesn't assign a new route id to the old route
* stack entry. This can cause issues when a route is replaced by itself, since the content
* will not remount out of the box.
*
* The "replaceRouteId" state prop is injected by the "historyReplace" action. It's used
* to enforce re-remounting routes which where replaced by itself.
*/
const replaceRouteId = context?.state?.replaceRouteId || '';
return /*#__PURE__*/_jsx(ErrorBoundary, {
children: /*#__PURE__*/_jsx(RouteContext.Provider, {
value: context,
children: /*#__PURE__*/_jsx(Suspense, {
fallback: /*#__PURE__*/_jsx(Loading, {}),
children: /*#__PURE__*/_jsx(Component, {})
})
}, `${route.id}_${replaceRouteId}`)
}, `error.${route.id}_${replaceRouteId}`);
});
};
return _createClass(Route, [{
key: "currentRoute",
get: function () {
const {
[router.routeIndex]: [, route]
} = this.context.stack;
return route;
}
}]);
}(React.Component);
Route.contextType = RouterContext;
Route.NotFound = RouteNotFound;
Route.defaultProps = {
cache: false,
transform: null
};
export default Route;