Skip to content

Commit

Permalink
feat(projects): support add parent when add route
Browse files Browse the repository at this point in the history
  • Loading branch information
mufeng889 committed Sep 8, 2024
1 parent 3493583 commit 084bf89
Showing 1 changed file with 17 additions and 10 deletions.
27 changes: 17 additions & 10 deletions packages/simple-router/src/router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ class CreateRouter {
reactRoutes: RouteObject[] = [];
initRoute = false;
reactRouter: RemixRouter;
listeners: (() => void)[] = [];
private listeners: (() => void)[] = [];
initReactRoutes: RouteObject[] = [];
private matcher: CreateRouterMatcher;
currentRoute = START_LOCATION_NORMALIZED;
Expand Down Expand Up @@ -79,24 +79,29 @@ class CreateRouter {
*
* @param routes - An array of elegant constant routes.
*/
addReactRoutes(routes: ElegantConstRoute[]) {
addReactRoutes(parentOrRoute: ElegantConstRoute[] | string, elegantRoutes?: ElegantConstRoute[]) {
// Flatten nested routes
const flattenRoutes = routes.flat();
let parent: string | null = null;
let routes: ElegantConstRoute;
if (typeof parentOrRoute === 'string') {
parent = parentOrRoute;
routes = elegantRoutes;
} else {
routes = parentOrRoute;
}

flattenRoutes.forEach(route => {
const matcher = this.matcher.getRecordMatcher(route.name);
if (matcher) return;
const flattenRoutes = routes.flat();

const reactRoutes = flattenRoutes.map(route => {
// Add route
this.#addRoute(route);
// Transform to react-router route
const reactRoute = this.getReactRoutes(route);
// Add to react-router's routes
this.reactRoutes.push(reactRoute);
return reactRoute;
});

// Update react-router's routes
this.#changeRoutes();
// Add to react-router's routes
this.reactRouter.patchRoutes(parent, reactRoutes);
}

#changeRoutes() {
Expand All @@ -113,6 +118,7 @@ class CreateRouter {
removeRoute(name: string) {
const matched = this.matcher.getRecordMatcher(name);
if (!matched) return;

if (matched.parent) {
const parentNames = findParentNames(matched.parent);
let routes = this.reactRoutes;
Expand Down Expand Up @@ -286,6 +292,7 @@ class CreateRouter {
this.reactRoutes.length = 0;
// Resets the route matcher so it can begin matching new routes again.
this.matcher.resetMatcher();
this.#changeRoutes();
}

/**
Expand Down

0 comments on commit 084bf89

Please sign in to comment.