mobx-react-routing
Version:
MobX react-router-dom integration
84 lines (83 loc) • 3 kB
JavaScript
import { withViewModel, } from 'mobx-view-model';
import { loadable } from 'react-simple-loadable';
import { withRouteBlocker } from './hoc/index.js';
import { VMPayloadTransferHOC } from './hoc/vm-payload-transfer.js';
const NoopComponent = () => null;
export const createRoute = ({ declaration, router, factory, createChildRoute = createRoute, parentPath, index, }) => {
const { Model, Component, path, id: origId, loader, fallback = router?.fallbackComponent, children, errorBoundary = router?.errorBoundaryComponent, index: isIndexRoute, element, } = declaration;
const treePath = [...parentPath, index];
const factoryFn = factory
? (config) => factory(config, config.ctx.routeDeclaration)
: undefined;
const id = origId ??
(process.env.NODE_ENV === 'production'
? `route-${treePath.join('-')}`
: `route-${treePath.join('-')}(path:${path ?? '-'})`);
declaration.id = id;
if (!Model && !loader) {
return {
id,
children: children?.map((declaration, index) => createChildRoute({
declaration,
router,
factory,
createChildRoute,
parentPath: treePath,
index,
})),
Component: VMPayloadTransferHOC(Component),
path,
index: isIndexRoute,
element,
ErrorBoundary: errorBoundary,
};
}
let WrappedComponent;
if (loader) {
WrappedComponent = withRouteBlocker(router, loadable(async () => {
const { Model, Component } = await loader();
const UsageComponent = Component || NoopComponent;
return Model
? withViewModel(Model, {
id,
fallback,
ctx: {
routeDeclaration: declaration,
...declaration.ctx,
},
factory: factoryFn,
})(UsageComponent)
: UsageComponent;
}, fallback), fallback);
}
else {
const UsageComponent = Component || NoopComponent;
WrappedComponent = withRouteBlocker(router, Model
? withViewModel(Model, {
id,
fallback,
ctx: {
routeDeclaration: declaration,
...declaration.ctx,
},
factory: factoryFn,
})(UsageComponent)
: UsageComponent, fallback);
}
return {
id,
children: children?.map((route, index) => createChildRoute({
declaration: route,
router,
factory,
createChildRoute,
parentPath: treePath,
index,
})),
Component: VMPayloadTransferHOC(WrappedComponent),
path,
index: isIndexRoute,
element,
ErrorBoundary: errorBoundary,
};
};