Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 45 additions & 2 deletions packages/runtime/src/internal/matchRoutes.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { matchRoutes } from "./matchRoutes.js";
import type { RouteConf } from "@next-core/types";
import { matchRoutes, matchRoute } from "./matchRoutes.js";

const consoleError = jest.spyOn(console, "error").mockImplementation();

describe("matchStoryboard", () => {
describe("matchRoutes", () => {
test("handle path not string", async () => {
await expect(() =>
matchRoutes(
Expand All @@ -25,3 +26,45 @@ describe("matchStoryboard", () => {
);
});
});

describe("matchRoute", () => {
test("handle array path", () => {
const route: RouteConf = {
path: "${APP.homepage}[,/b/([^/]+)]",
exact: true,
bricks: [],
};
const homepage = "/home";

expect(matchRoute(route, homepage, "/home/b/123")).toEqual({
isExact: true,
params: {
"0": "123",
},
path: "/home/b/([^/]+)",
url: "/home/b/123",
});

expect(matchRoute(route, homepage, "/home")).toEqual({
isExact: true,
params: {},
path: "/home",
url: "/home",
});

expect(matchRoute(route, homepage, "/home/c")).toEqual(null);
expect(matchRoute(route, homepage, "/home/b/123/x")).toEqual(null);
});

test("handle not started with ${APP.homepage}", () => {
const route: RouteConf = {
path: "/home[,/b/([^/]+)]",
exact: true,
bricks: [],
};
const homepage = "/home";

expect(matchRoute(route, homepage, "/home")).toEqual(null);
expect(matchRoute(route, homepage, "/home/b/123")).toEqual(null);
});
});
22 changes: 20 additions & 2 deletions packages/runtime/src/internal/matchRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { asyncCheckIf } from "./compute/checkIf.js";
import type { RuntimeContext } from "./interfaces.js";
import { hooks } from "./Runtime.js";

const HOMEPAGE_PREFIX = "${APP.homepage}";

type MatchRoutesResult =
| {
match: MatchResult;
Expand Down Expand Up @@ -49,9 +51,25 @@ export function matchRoute(
homepage: string,
pathname: string
) {
const routePath = route.path.replace(/^\$\{APP.homepage\}/, homepage);
const path = getRoutePath(route, homepage);
return matchPath(pathname, {
path: routePath,
path,
exact: route.exact,
});
}

function getRoutePath(route: RouteConf, homepage: string): string | string[] {
if (route.path.startsWith(HOMEPAGE_PREFIX)) {
const restPath = route.path.slice(HOMEPAGE_PREFIX.length);
if (
restPath.startsWith("[") &&
restPath.endsWith("]") &&
restPath.includes(",")
) {
const paths = restPath.slice(1, -1).split(",");
return paths.map((p) => `${homepage}${p}`);
}
return `${homepage}${restPath}`;
}
return route.path;
}
Loading