Skip to content

Instantly share code, notes, and snippets.

@davidmz
Last active August 28, 2018 10:56
Show Gist options
  • Save davidmz/148101963b980ddcd164770b2e428f62 to your computer and use it in GitHub Desktop.
Save davidmz/148101963b980ddcd164770b2e428f62 to your computer and use it in GitHub Desktop.
Nested routes for mobx-state-router
import { Route as PlainRoute, RouterStore, RouterState } from 'mobx-state-router';
import { TransitionHook } from 'mobx-state-router/dist/types/router-store';
export interface Route extends PlainRoute {
children?: Route[];
}
type KeysOfType<A extends object, B> = { [K in keyof A]: A[K] extends B ? K : never }[keyof A];
type HookKey = Exclude<KeysOfType<PlainRoute, TransitionHook | undefined>, undefined>;
const enterHooks: HookKey[] = ['beforeEnter', 'onEnter'];
const exitHooks: HookKey[] = ['beforeExit', 'onExit'];
export function flatten(tree: Route[], parent?: Route): PlainRoute[] {
const result: PlainRoute[] = [];
for (const route of tree) {
const r: PlainRoute = {
name: [parent ? parent.name : '', route.name].filter(Boolean).join('.'),
pattern: (parent ? parent.pattern : '') + route.pattern,
};
for (const hk of [...enterHooks, ...exitHooks]) {
if (route[hk]) {
r[hk] = route[hk];
}
}
for (const hk of enterHooks) {
if (parent && parent[hk]) {
r[hk] = async (fromState: RouterState, toState: RouterState, routerStore: RouterStore) => {
parent[hk] && (await parent[hk]!(fromState, toState, routerStore));
route[hk] && (await route[hk]!(fromState, toState, routerStore));
};
}
}
for (const hk of exitHooks) {
if (parent && parent[hk]) {
r[hk] = async (fromState: RouterState, toState: RouterState, routerStore: RouterStore) => {
route[hk] && (await route[hk]!(fromState, toState, routerStore));
parent[hk] && (await parent[hk]!(fromState, toState, routerStore));
};
}
}
if (route.children) {
result.push(...flatten(route.children, r));
} else {
result.push(r);
}
}
return result;
}
import { flatten, Route } from '../ui/utils/nested-routes';
export const routes: Route[] = flatten([
{
name: 'home',
pattern: '/',
},
{
name: 'about',
pattern: '/about',
children: [
{
name: 'index',
pattern: '',
},
{
name: 'team',
pattern: '/team',
},
],
},
{
name: 'notFound',
pattern: '/not-found',
},
]);
import { Route } from 'mobx-state-router';
export const routes: Route[] = [
{
name: 'home',
pattern: '/',
},
{
name: 'about.index',
pattern: '/about',
},
{
name: 'about.team',
pattern: '/about/team',
},
{
name: 'notFound',
pattern: '/not-found',
},
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment