Skip to content

Commit 084bf89

Browse files
committed
feat(projects): support add parent when add route
1 parent 3493583 commit 084bf89

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

packages/simple-router/src/router.tsx

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ class CreateRouter {
3232
reactRoutes: RouteObject[] = [];
3333
initRoute = false;
3434
reactRouter: RemixRouter;
35-
listeners: (() => void)[] = [];
35+
private listeners: (() => void)[] = [];
3636
initReactRoutes: RouteObject[] = [];
3737
private matcher: CreateRouterMatcher;
3838
currentRoute = START_LOCATION_NORMALIZED;
@@ -79,24 +79,29 @@ class CreateRouter {
7979
*
8080
* @param routes - An array of elegant constant routes.
8181
*/
82-
addReactRoutes(routes: ElegantConstRoute[]) {
82+
addReactRoutes(parentOrRoute: ElegantConstRoute[] | string, elegantRoutes?: ElegantConstRoute[]) {
8383
// Flatten nested routes
84-
const flattenRoutes = routes.flat();
84+
let parent: string | null = null;
85+
let routes: ElegantConstRoute;
86+
if (typeof parentOrRoute === 'string') {
87+
parent = parentOrRoute;
88+
routes = elegantRoutes;
89+
} else {
90+
routes = parentOrRoute;
91+
}
8592

86-
flattenRoutes.forEach(route => {
87-
const matcher = this.matcher.getRecordMatcher(route.name);
88-
if (matcher) return;
93+
const flattenRoutes = routes.flat();
8994

95+
const reactRoutes = flattenRoutes.map(route => {
9096
// Add route
9197
this.#addRoute(route);
9298
// Transform to react-router route
9399
const reactRoute = this.getReactRoutes(route);
94-
// Add to react-router's routes
95100
this.reactRoutes.push(reactRoute);
101+
return reactRoute;
96102
});
97-
98-
// Update react-router's routes
99-
this.#changeRoutes();
103+
// Add to react-router's routes
104+
this.reactRouter.patchRoutes(parent, reactRoutes);
100105
}
101106

102107
#changeRoutes() {
@@ -113,6 +118,7 @@ class CreateRouter {
113118
removeRoute(name: string) {
114119
const matched = this.matcher.getRecordMatcher(name);
115120
if (!matched) return;
121+
116122
if (matched.parent) {
117123
const parentNames = findParentNames(matched.parent);
118124
let routes = this.reactRoutes;
@@ -286,6 +292,7 @@ class CreateRouter {
286292
this.reactRoutes.length = 0;
287293
// Resets the route matcher so it can begin matching new routes again.
288294
this.matcher.resetMatcher();
295+
this.#changeRoutes();
289296
}
290297

291298
/**

0 commit comments

Comments
 (0)