diff --git a/src/router/Router.ts b/src/router/Router.ts index 74e5717d..ec8dab35 100644 --- a/src/router/Router.ts +++ b/src/router/Router.ts @@ -68,9 +68,9 @@ export class Router { QWeb.addDirective(makeDirective(env)); } - navigate(dest: Destination): void { - const to = this.destToUrl(dest); - history.pushState({}, to, location.origin + to); + navigate(to: Destination): void { + const url = this.destToUrl(to); + history.pushState({}, url, location.origin + url); this.checkAndUpdateRoute(); } @@ -107,6 +107,11 @@ export class Router { let route = this.routes[routeId]; let params = this.matchRoute(route.path, currentPath); if (params) { + if (route.redirect) { + this.navigate(route.redirect); + this.checkRoute(); + return; + } this.currentRoute = route; this.currentParams = params; return; diff --git a/tests/router/router.test.ts b/tests/router/router.test.ts index b7545593..c3b473da 100644 --- a/tests/router/router.test.ts +++ b/tests/router/router.test.ts @@ -71,3 +71,27 @@ describe("match routes", () => { }); }); }); + +describe("redirect", () => { + test("can redirect to other route", () => { + router = new TestRouter(env, [ + { name: "routea", path: "/some/path" }, + { name: "routeb", path: "/some/other/path", redirect: { name: "routea" } } + ]); + + router.navigate({ name: "routeb" }); + expect(window.location.pathname).toBe("/some/path"); + expect(router.currentRouteName).toBe("routea"); + }); + + test("can redirect to other path", () => { + router = new TestRouter(env, [ + { name: "routea", path: "/some/path" }, + { name: "routeb", path: "/some/other/path", redirect: { path: "/some/path" } } + ]); + + router.navigate({ name: "routeb" }); + expect(window.location.pathname).toBe("/some/path"); + expect(router.currentRouteName).toBe("routea"); + }); +});