feat: add support for route groups (#1563)

This commit is contained in:
Marvin Hagemeister
2023-08-02 09:51:20 +02:00
committed by GitHub
parent 4b28e2e269
commit e4d797ae4e
17 changed files with 384 additions and 218 deletions
+58
View File
@@ -0,0 +1,58 @@
---
description: |
Route groups allow you to organize your route segments into groups and share layout or middleware code without affecting the URL structure.
---
When working with [route layouts](/docs/canary/concepts/route-layout) or
[route middlewares](/docs/canary/concepts/middleware) you'll sometimes come
across a situation where you want your routes to inherit from a different layout
than another route that's in the same URL segment.
Let's illustrate that with an example:
```txt
/about -> layout A
/career -> layout A
/archive -> layout B
/contact -> layout B
```
Without any way to group routes this is a problem because every route segment
can only have one `_layout` file.
```txt
/routes
/_layout.tsx <-- applies to all routes here :(
/about.tsx
/career.tsx
/archive.tsx
/contact.tsx
```
We can solve this problem with route groups. A route group is a folder which has
a name that is wrapped in braces. For example `(pages)` would be considered a
route and so would be `(marketing)`. This enables us to group related routes in
a folder and use a different `_layout` file for each group.
```txt
/routes
/(marketing)
/_layout.tsx <-- only applies to about.tsx and career.tsx
/about.tsx
/career.tsx
/(info)
/_layout.tsx <-- only applies to archive.tsx and contact.tsx
/archive.tsx
/contact.tsx
```
> ℹ️ Be careful about routes in different groups which match to the same URL.
> Such scenarios will lead to ambiguity as to which route file should be picked.
>
> ```txt
> /routes
> /(group-1)
> /about.tsx <-- Bad: Both routes map to the same `/about` url
> /(group-2)
> /about.tsx <-- Bad: Both routes map to the same `/about` url
> ```
+1
View File
@@ -59,6 +59,7 @@ const toc: RawTableOfContents = {
["updating", "Updating Fresh", "link:latest"], ["updating", "Updating Fresh", "link:latest"],
["app-wrapper", "Application wrapper", "link:latest"], ["app-wrapper", "Application wrapper", "link:latest"],
["route-layout", "Route layouts", "link:canary"], ["route-layout", "Route layouts", "link:canary"],
["route-groups", "Route groups", "link:canary"],
["server-configuration", "Server configuration", "link:latest"], ["server-configuration", "Server configuration", "link:latest"],
], ],
}, },
+170 -121
View File
@@ -17,6 +17,7 @@ import { BUILD_ID } from "./build_id.ts";
import DefaultErrorHandler from "./default_error_page.ts"; import DefaultErrorHandler from "./default_error_page.ts";
import { import {
AppModule, AppModule,
BaseRoute,
ErrorPage, ErrorPage,
ErrorPageModule, ErrorPageModule,
FreshOptions, FreshOptions,
@@ -24,7 +25,6 @@ import {
Island, Island,
LayoutModule, LayoutModule,
LayoutRoute, LayoutRoute,
Middleware,
MiddlewareHandler, MiddlewareHandler,
MiddlewareHandlerContext, MiddlewareHandlerContext,
MiddlewareModule, MiddlewareModule,
@@ -60,6 +60,8 @@ const DEFAULT_CONN_INFO: ServeHandlerInfo = {
remoteAddr: { transport: "tcp", hostname: "localhost", port: 1234 }, remoteAddr: { transport: "tcp", hostname: "localhost", port: 1234 },
}; };
const ROOT_BASE_ROUTE = toBaseRoute("/");
function isObject(value: unknown) { function isObject(value: unknown) {
return typeof value === "object" && return typeof value === "object" &&
!Array.isArray(value) && !Array.isArray(value) &&
@@ -244,6 +246,7 @@ export class ServerContext {
}; };
} }
const route: Route = { const route: Route = {
baseRoute: toBaseRoute(baseRoute),
pattern, pattern,
url, url,
name, name,
@@ -254,8 +257,8 @@ export class ServerContext {
routes.push(route); routes.push(route);
} else if (isMiddleware) { } else if (isMiddleware) {
middlewares.push({ middlewares.push({
...middlewarePathToPattern(baseRoute), baseRoute: toBaseRoute(baseRoute),
...module as MiddlewareModule, module: module as MiddlewareModule,
}); });
} else if ( } else if (
path === "/_app.tsx" || path === "/_app.ts" || path === "/_app.tsx" || path === "/_app.ts" ||
@@ -264,8 +267,8 @@ export class ServerContext {
app = module as AppModule; app = module as AppModule;
} else if (isLayout) { } else if (isLayout) {
layouts.push({ layouts.push({
...layoutPathToPattern(baseRoute), baseRoute: toBaseRoute(baseRoute),
...module as LayoutModule, module: module as LayoutModule,
}); });
} else if ( } else if (
path === "/_404.tsx" || path === "/_404.ts" || path === "/_404.tsx" || path === "/_404.ts" ||
@@ -278,6 +281,7 @@ export class ServerContext {
} }
notFound = { notFound = {
baseRoute: ROOT_BASE_ROUTE,
pattern: pathToPattern(baseRoute), pattern: pathToPattern(baseRoute),
url, url,
name, name,
@@ -296,6 +300,7 @@ export class ServerContext {
} }
error = { error = {
baseRoute: toBaseRoute("/"),
pattern: pathToPattern(baseRoute), pattern: pathToPattern(baseRoute),
url, url,
name, name,
@@ -488,13 +493,16 @@ export class ServerContext {
connInfo: ServeHandlerInfo, connInfo: ServeHandlerInfo,
inner: router.FinalHandler<RouterState>, inner: router.FinalHandler<RouterState>,
) => { ) => {
// identify middlewares to apply, if any.
// middlewares should be already sorted from deepest to shallow layer
const mws = selectMiddlewares(req.url, middlewares);
const handlers: (() => Response | Promise<Response>)[] = []; const handlers: (() => Response | Promise<Response>)[] = [];
const paramsAndRouteResult = paramsAndRoute(req.url); const paramsAndRouteResult = paramsAndRoute(req.url);
// identify middlewares to apply, if any.
// middlewares should be already sorted from deepest to shallow layer
const mws = selectSharedRoutes(
paramsAndRouteResult.route?.baseRoute ?? ROOT_BASE_ROUTE,
middlewares,
);
let state: Record<string, unknown> = {}; let state: Record<string, unknown> = {};
const middlewareCtx: MiddlewareHandlerContext = { const middlewareCtx: MiddlewareHandlerContext = {
next() { next() {
@@ -574,39 +582,50 @@ export class ServerContext {
const routes: router.Routes<RouterState> = {}; const routes: router.Routes<RouterState> = {};
internalRoutes[`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`] = { internalRoutes[`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`] = {
default: this.#bundleAssetRoute(), baseRoute: toBaseRoute(
`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`,
),
methods: {
default: this.#bundleAssetRoute(),
},
}; };
if (this.#dev) { if (this.#dev) {
internalRoutes[REFRESH_JS_URL] = { internalRoutes[REFRESH_JS_URL] = {
default: () => { baseRoute: toBaseRoute(REFRESH_JS_URL),
return new Response(refreshJs(ALIVE_URL, BUILD_ID), { methods: {
headers: { default: () => {
"content-type": "application/javascript; charset=utf-8", return new Response(refreshJs(ALIVE_URL, BUILD_ID), {
}, headers: {
}); "content-type": "application/javascript; charset=utf-8",
},
});
},
}, },
}; };
internalRoutes[ALIVE_URL] = { internalRoutes[ALIVE_URL] = {
default: () => { baseRoute: toBaseRoute(ALIVE_URL),
let timerId: number | undefined = undefined; methods: {
const body = new ReadableStream({ default: () => {
start(controller) { let timerId: number | undefined = undefined;
controller.enqueue(`data: ${BUILD_ID}\nretry: 100\n\n`); const body = new ReadableStream({
timerId = setInterval(() => { start(controller) {
controller.enqueue(`data: ${BUILD_ID}\n\n`); controller.enqueue(`data: ${BUILD_ID}\nretry: 100\n\n`);
}, 1000); timerId = setInterval(() => {
}, controller.enqueue(`data: ${BUILD_ID}\n\n`);
cancel() { }, 1000);
if (timerId !== undefined) { },
clearInterval(timerId); cancel() {
} if (timerId !== undefined) {
}, clearInterval(timerId);
}); }
return new Response(body.pipeThrough(new TextEncoderStream()), { },
headers: { });
"content-type": "text/event-stream", return new Response(body.pipeThrough(new TextEncoderStream()), {
}, headers: {
}); "content-type": "text/event-stream",
},
});
},
}, },
}; };
} }
@@ -620,17 +639,20 @@ export class ServerContext {
) { ) {
const route = sanitizePathToRegex(path); const route = sanitizePathToRegex(path);
staticRoutes[route] = { staticRoutes[route] = {
"HEAD": this.#staticFileHeadHandler( baseRoute: toBaseRoute(route),
size, methods: {
contentType, "HEAD": this.#staticFileHeadHandler(
etag, size,
), contentType,
"GET": this.#staticFileGetHandler( etag,
localUrl, ),
size, "GET": this.#staticFileGetHandler(
contentType, localUrl,
etag, size,
), contentType,
etag,
),
},
}; };
} }
@@ -656,6 +678,9 @@ export class ServerContext {
headers: undefined, headers: undefined,
}); });
} }
const layouts = selectSharedRoutes(ROOT_BASE_ROUTE, this.#layouts);
const imports: string[] = []; const imports: string[] = [];
const resp = await internalRender({ const resp = await internalRender({
request: req, request: req,
@@ -664,7 +689,7 @@ export class ServerContext {
islands: this.#islands, islands: this.#islands,
plugins: this.#plugins, plugins: this.#plugins,
app: this.#app, app: this.#app,
layouts: this.#layouts, layouts,
imports, imports,
dependenciesFn, dependenciesFn,
renderFn: this.#renderFn, renderFn: this.#renderFn,
@@ -705,6 +730,8 @@ export class ServerContext {
throw new Error("This page does not have a component to render."); throw new Error("This page does not have a component to render.");
} }
const layouts = selectSharedRoutes(route.baseRoute, this.#layouts);
const resp = await internalRender({ const resp = await internalRender({
request: req, request: req,
context: { context: {
@@ -717,7 +744,7 @@ export class ServerContext {
islands: this.#islands, islands: this.#islands,
plugins: this.#plugins, plugins: this.#plugins,
app: this.#app, app: this.#app,
layouts: this.#layouts, layouts,
imports, imports,
dependenciesFn, dependenciesFn,
renderFn: this.#renderFn, renderFn: this.#renderFn,
@@ -749,20 +776,26 @@ export class ServerContext {
const createRender = genRender(route, Status.OK); const createRender = genRender(route, Status.OK);
if (typeof route.handler === "function") { if (typeof route.handler === "function") {
routes[route.pattern] = { routes[route.pattern] = {
default: (req, ctx, params) => baseRoute: route.baseRoute,
(route.handler as Handler)(req, { methods: {
...ctx, default: (req, ctx, params) =>
params, (route.handler as Handler)(req, {
render: createRender(req, params, ctx), ...ctx,
async renderNotFound<Data = undefined>(data: Data) { params,
return await renderNotFound(req, params, ctx, data); render: createRender(req, params, ctx),
}, async renderNotFound<Data = undefined>(data: Data) {
}), return await renderNotFound(req, params, ctx, data);
},
}),
},
}; };
} else { } else {
routes[route.pattern] = {}; routes[route.pattern] = {
baseRoute: route.baseRoute,
methods: {},
};
for (const [method, handler] of Object.entries(route.handler)) { for (const [method, handler] of Object.entries(route.handler)) {
routes[route.pattern][method as router.KnownMethod] = ( routes[route.pattern].methods[method as router.KnownMethod] = (
req, req,
ctx, ctx,
params, params,
@@ -929,6 +962,7 @@ const DEFAULT_APP: AppModule = {
}; };
const DEFAULT_NOT_FOUND: UnknownPage = { const DEFAULT_NOT_FOUND: UnknownPage = {
baseRoute: toBaseRoute("/"),
pattern: "", pattern: "",
url: "", url: "",
name: "_404", name: "_404",
@@ -937,6 +971,7 @@ const DEFAULT_NOT_FOUND: UnknownPage = {
}; };
const DEFAULT_ERROR: ErrorPage = { const DEFAULT_ERROR: ErrorPage = {
baseRoute: toBaseRoute("/"),
pattern: "", pattern: "",
url: "", url: "",
name: "_500", name: "_500",
@@ -945,23 +980,23 @@ const DEFAULT_ERROR: ErrorPage = {
csp: false, csp: false,
}; };
/** export function selectSharedRoutes<T>(
* Return a list of middlewares that needs to be applied for request url curBaseRoute: BaseRoute,
* @param url the request url items: { baseRoute: BaseRoute; module: T }[],
* @param middlewares Array of middlewares handlers and their routes as path-to-regexp style ): T[] {
*/ const selected: T[] = [];
export function selectMiddlewares(url: string, middlewares: MiddlewareRoute[]) {
const selectedMws: Middleware[] = [];
const reqURL = new URL(url);
for (const { compiledPattern, handler } of middlewares) { for (const { baseRoute, module } of items) {
const res = compiledPattern.exec(reqURL); const res = curBaseRoute === baseRoute ||
curBaseRoute.startsWith(
baseRoute.length > 1 ? baseRoute + "/" : baseRoute,
);
if (res) { if (res) {
selectedMws.push({ handler }); selected.push(module);
} }
} }
return selectedMws; return selected;
} }
const APP_REG = /_app\.[tj]sx?$/; const APP_REG = /_app\.[tj]sx?$/;
@@ -1027,47 +1062,64 @@ function getRoutePathScore(char: string, nextChar: string): number {
export function pathToPattern(path: string): string { export function pathToPattern(path: string): string {
const parts = path.split("/"); const parts = path.split("/");
if (parts[parts.length - 1] === "index") { if (parts[parts.length - 1] === "index") {
if (parts.length === 1) {
return "/";
}
parts.pop(); parts.pop();
} }
const route = "/" + parts
.map((part) => {
// Case: /[...foo].tsx
if (part.startsWith("[...") && part.endsWith("]")) {
return `:${part.slice(4, part.length - 1)}*`;
}
// Disallow neighbouring params like `/[id][bar].tsx` because let route = "";
// it's ambiguous where the `id` param ends and `bar` begins.
if (part.includes("][")) {
throw new SyntaxError(
`Invalid route pattern: "${path}". A parameter cannot be followed by another parameter without any characters in between.`,
);
}
// Case: /[id].tsx for (let i = 0; i < parts.length; i++) {
// Case: /[id]@[bar].tsx const part = parts[i];
// Case: /[id]-asdf.tsx
// Case: /[id]-asdf[bar].tsx // Case: /[...foo].tsx
// Case: /asdf[bar].tsx if (part.startsWith("[...") && part.endsWith("]")) {
let pattern = ""; route += `/:${part.slice(4, part.length - 1)}*`;
let groupOpen = 0; continue;
for (let i = 0; i < part.length; i++) { }
const char = part[i];
if (char === "[") { // Route groups like /foo/(bar) should not be included in URL
pattern += ":"; // matching. They are transparent and need to be removed here.
groupOpen++; // Case: /foo/(bar) -> /foo
} else if (char === "]") { // Case: /foo/(bar)/bob -> /foo/bob
if (--groupOpen < 0) { // Case: /(foo)/bar -> /bar
throw new SyntaxError(`Invalid route pattern: "${path}"`); if (part.startsWith("(") && part.endsWith(")")) {
} continue;
} else { }
pattern += char;
// Disallow neighbouring params like `/[id][bar].tsx` because
// it's ambiguous where the `id` param ends and `bar` begins.
if (part.includes("][")) {
throw new SyntaxError(
`Invalid route pattern: "${path}". A parameter cannot be followed by another parameter without any characters in between.`,
);
}
// Case: /[id].tsx
// Case: /[id]@[bar].tsx
// Case: /[id]-asdf.tsx
// Case: /[id]-asdf[bar].tsx
// Case: /asdf[bar].tsx
let pattern = "";
let groupOpen = 0;
for (let j = 0; j < part.length; j++) {
const char = part[j];
if (char === "[") {
pattern += ":";
groupOpen++;
} else if (char === "]") {
if (--groupOpen < 0) {
throw new SyntaxError(`Invalid route pattern: "${path}"`);
} }
} else {
pattern += char;
} }
}
route += "/" + pattern;
}
return pattern;
})
.join("/");
return route; return route;
} }
@@ -1118,24 +1170,21 @@ function serializeCSPDirectives(csp: ContentSecurityPolicyDirectives): string {
.join("; "); .join("; ");
} }
export function layoutPathToPattern(baseRoute: string) { export function toBaseRoute(input: string): BaseRoute {
baseRoute = baseRoute.slice(0, -"_layout".length); if (input.endsWith("_layout")) {
let pattern = pathToPattern(baseRoute); input = input.slice(0, -"_layout".length);
if (pattern.endsWith("/")) { } else if (input.endsWith("_middleware")) {
pattern = pattern.slice(0, -1) + "{/*}?"; input = input.slice(0, -"_middleware".length);
} else if (input.endsWith("index")) {
input = input.slice(0, -"index".length);
} }
const compiledPattern = new URLPattern({ pathname: pattern });
return { pattern, compiledPattern };
}
export function middlewarePathToPattern(baseRoute: string) { if (input.endsWith("/")) {
baseRoute = baseRoute.slice(0, -"_middleware".length); input = input.slice(0, -1);
let pattern = pathToPattern(baseRoute);
if (pattern.endsWith("/")) {
pattern = pattern.slice(0, -1) + "{/*}?";
} }
const compiledPattern = new URLPattern({ pathname: pattern });
return { pattern, compiledPattern }; const suffix = !input.startsWith("/") ? "/" : "";
return (suffix + input) as BaseRoute;
} }
function refreshJs(aliveUrl: string, buildId: string) { function refreshJs(aliveUrl: string, buildId: string) {
+1 -28
View File
@@ -1,32 +1,5 @@
import { assertEquals, assertThrows } from "$std/testing/asserts.ts"; import { assertEquals, assertThrows } from "$std/testing/asserts.ts";
import { assert } from "../../tests/deps.ts"; import { pathToPattern } from "./context.ts";
import {
middlewarePathToPattern,
pathToPattern,
selectMiddlewares,
} from "./context.ts";
import { MiddlewareRoute } from "./types.ts";
Deno.test("selectMiddlewares", () => {
const url = "https://fresh.deno.dev/api/abc/def";
const middlewaresPath = [
// should select
"_middleware",
"api/_middleware",
"api/[id]/_middleware",
"api/[id]/[path]/_middleware",
// should not select
"api/xyz/_middleware",
"api/[id]/xyz/_middleware",
"api/[id]/[path]/foo/_middleware",
];
const mwRoutes = middlewaresPath.map((path) =>
middlewarePathToPattern(path)
) as MiddlewareRoute[];
const mws = selectMiddlewares(url, mwRoutes);
assert(mws.length === 4);
});
Deno.test("pathToPattern", async (t) => { Deno.test("pathToPattern", async (t) => {
await t.step("creates pattern", () => { await t.step("creates pattern", () => {
+4 -26
View File
@@ -15,7 +15,6 @@ import {
ErrorPage, ErrorPage,
Island, Island,
LayoutModule, LayoutModule,
LayoutRoute,
Plugin, Plugin,
PluginRenderFunctionResult, PluginRenderFunctionResult,
PluginRenderResult, PluginRenderResult,
@@ -58,7 +57,7 @@ export interface RenderOptions<Data> {
islands: Island[]; islands: Island[];
plugins: Plugin[]; plugins: Plugin[];
app: AppModule; app: AppModule;
layouts: LayoutRoute[]; layouts: LayoutModule[];
imports: string[]; imports: string[];
dependenciesFn: (path: string) => string[]; dependenciesFn: (path: string) => string[];
url: URL; url: URL;
@@ -138,25 +137,6 @@ function defaultCsp() {
}; };
} }
/**
* Return a list of layouts that needs to be applied for request url
* @param url the request url
* @param layouts Array of layouts handlers and their routes as path-to-regexp style
*/
export function selectLayouts(url: string, layouts: LayoutRoute[]) {
const selectedLayouts: LayoutModule[] = [];
const reqURL = new URL(url);
for (const layout of layouts) {
const res = layout.compiledPattern.exec(reqURL);
if (res) {
selectedLayouts.push(layout);
}
}
return selectedLayouts;
}
/** /**
* This function renders out a page. Rendering is synchronous and non streaming. * This function renders out a page. Rendering is synchronous and non streaming.
* Suspense boundaries are not supported. * Suspense boundaries are not supported.
@@ -214,13 +194,11 @@ export async function render<Data>(
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
let finalAppComp: VNode<any> = vnode as any; let finalAppComp: VNode<any> = vnode as any;
const layouts = selectLayouts(opts.url.toString(), opts.layouts); let i = opts.layouts.length;
let i = layouts.length;
while (i--) { while (i--) {
const layout = layouts[i]; const layout = opts.layouts[i];
const curComp = finalAppComp;
const curComp = finalAppComp;
finalAppComp = h(layout.default, { finalAppComp = h(layout.default, {
params: opts.params as Record<string, string>, params: opts.params as Record<string, string>,
url: opts.url, url: opts.url,
+12 -5
View File
@@ -1,4 +1,4 @@
import { ServeHandlerInfo } from "./types.ts"; import { BaseRoute, ErrorHandlerContext, ServeHandlerInfo } from "./types.ts";
type HandlerContext<T = unknown> = T & ServeHandlerInfo; type HandlerContext<T = unknown> = T & ServeHandlerInfo;
@@ -37,13 +37,19 @@ export type MatchHandler<T = unknown> = (
// deno-lint-ignore ban-types // deno-lint-ignore ban-types
export interface Routes<T = {}> { export interface Routes<T = {}> {
[key: string]: { [K in KnownMethod | "default"]?: MatchHandler<T> }; [key: string]: {
baseRoute: BaseRoute;
methods: {
[K in KnownMethod | "default"]?: MatchHandler<T>;
};
};
} }
export type DestinationKind = "internal" | "static" | "route" | "notFound"; export type DestinationKind = "internal" | "static" | "route" | "notFound";
// deno-lint-ignore ban-types // deno-lint-ignore ban-types
export type InternalRoute<T = {}> = { export type InternalRoute<T = {}> = {
baseRoute: BaseRoute;
pattern: URLPattern; pattern: URLPattern;
methods: { [K in KnownMethod]?: MatchHandler<T> }; methods: { [K in KnownMethod]?: MatchHandler<T> };
default?: MatchHandler<T>; default?: MatchHandler<T>;
@@ -79,7 +85,7 @@ export function defaultOtherHandler(_req: Request): Response {
export function defaultErrorHandler( export function defaultErrorHandler(
_req: Request, _req: Request,
_ctx: HandlerContext, _ctx: ErrorHandlerContext,
err: unknown, err: unknown,
): Response { ): Response {
console.error(err); console.error(err);
@@ -107,15 +113,16 @@ function processRoutes<T>(
routes: Routes<T>, routes: Routes<T>,
destination: DestinationKind, destination: DestinationKind,
) { ) {
for (const [path, methods] of Object.entries(routes)) { for (const [path, def] of Object.entries(routes)) {
const entry: InternalRoute<T> = { const entry: InternalRoute<T> = {
baseRoute: def.baseRoute,
pattern: new URLPattern({ pathname: path }), pattern: new URLPattern({ pathname: path }),
methods: {}, methods: {},
default: undefined, default: undefined,
destination, destination,
}; };
for (const [method, handler] of Object.entries(methods)) { for (const [method, handler] of Object.entries(def.methods)) {
if (method === "default") { if (method === "default") {
entry.default = handler; entry.default = handler;
} else if (knownMethods.includes(method as KnownMethod)) { } else if (knownMethods.includes(method as KnownMethod)) {
+12 -18
View File
@@ -147,6 +147,7 @@ export type PageComponent<T = any, S = Record<string, unknown>> =
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
export interface Route<Data = any> { export interface Route<Data = any> {
baseRoute: BaseRoute;
pattern: string; pattern: string;
url: string; url: string;
name: string; name: string;
@@ -177,15 +178,9 @@ export interface LayoutModule {
default: ComponentType<LayoutProps>; default: ComponentType<LayoutProps>;
} }
export interface LayoutRoute extends LayoutModule { export interface LayoutRoute {
/** baseRoute: BaseRoute;
* path-to-regexp style url path module: LayoutModule;
*/
pattern: string;
/**
* URLPattern of the route
*/
compiledPattern: URLPattern;
} }
// --- UNKNOWN PAGE --- // --- UNKNOWN PAGE ---
@@ -224,6 +219,7 @@ export interface UnknownPageModule {
} }
export interface UnknownPage { export interface UnknownPage {
baseRoute: BaseRoute;
pattern: string; pattern: string;
url: string; url: string;
name: string; name: string;
@@ -253,6 +249,9 @@ export interface ErrorHandlerContext<State = Record<string, unknown>>
state: State; state: State;
} }
// Nominal/Branded type. Ensures that the string has the expected format
export type BaseRoute = string & { readonly __brand: unique symbol };
export type ErrorHandler = ( export type ErrorHandler = (
req: Request, req: Request,
ctx: ErrorHandlerContext, ctx: ErrorHandlerContext,
@@ -265,6 +264,7 @@ export interface ErrorPageModule {
} }
export interface ErrorPage { export interface ErrorPage {
baseRoute: BaseRoute;
pattern: string; pattern: string;
url: string; url: string;
name: string; name: string;
@@ -283,15 +283,9 @@ export interface MiddlewareHandlerContext<State = Record<string, unknown>>
params: Record<string, string>; params: Record<string, string>;
} }
export interface MiddlewareRoute extends Middleware { export interface MiddlewareRoute {
/** baseRoute: BaseRoute;
* path-to-regexp style url path module: Middleware;
*/
pattern: string;
/**
* URLPattern of the route
*/
compiledPattern: URLPattern;
} }
export type MiddlewareHandler<State = Record<string, unknown>> = ( export type MiddlewareHandler<State = Record<string, unknown>> = (
+34 -20
View File
@@ -47,16 +47,23 @@ import * as $41 from "./routes/movies/[foo]@[bar].ts";
import * as $42 from "./routes/not_found.ts"; import * as $42 from "./routes/not_found.ts";
import * as $43 from "./routes/params.tsx"; import * as $43 from "./routes/params.tsx";
import * as $44 from "./routes/props/[id].tsx"; import * as $44 from "./routes/props/[id].tsx";
import * as $45 from "./routes/signal_shared.tsx"; import * as $45 from "./routes/route-groups/(bar)/(baz)/_layout.tsx";
import * as $46 from "./routes/state-in-props/_middleware.ts"; import * as $46 from "./routes/route-groups/(bar)/(baz)/baz.tsx";
import * as $47 from "./routes/state-in-props/index.tsx"; import * as $47 from "./routes/route-groups/(bar)/_layout.tsx";
import * as $48 from "./routes/state-middleware/_middleware.ts"; import * as $48 from "./routes/route-groups/(bar)/bar.tsx";
import * as $49 from "./routes/state-middleware/foo/_middleware.ts"; import * as $49 from "./routes/route-groups/(bar)/boof/index.tsx";
import * as $50 from "./routes/state-middleware/foo/index.tsx"; import * as $50 from "./routes/route-groups/(foo)/_layout.tsx";
import * as $51 from "./routes/static.tsx"; import * as $51 from "./routes/route-groups/(foo)/index.tsx";
import * as $52 from "./routes/status_overwrite.tsx"; import * as $52 from "./routes/signal_shared.tsx";
import * as $53 from "./routes/umlaut-äöüß.tsx"; import * as $53 from "./routes/state-in-props/_middleware.ts";
import * as $54 from "./routes/wildcard.tsx"; import * as $54 from "./routes/state-in-props/index.tsx";
import * as $55 from "./routes/state-middleware/_middleware.ts";
import * as $56 from "./routes/state-middleware/foo/_middleware.ts";
import * as $57 from "./routes/state-middleware/foo/index.tsx";
import * as $58 from "./routes/static.tsx";
import * as $59 from "./routes/status_overwrite.tsx";
import * as $60 from "./routes/umlaut-äöüß.tsx";
import * as $61 from "./routes/wildcard.tsx";
import * as $$0 from "./islands/Counter.tsx"; import * as $$0 from "./islands/Counter.tsx";
import * as $$1 from "./islands/MultipleCounters.tsx"; import * as $$1 from "./islands/MultipleCounters.tsx";
import * as $$2 from "./islands/ReturningNull.tsx"; import * as $$2 from "./islands/ReturningNull.tsx";
@@ -115,16 +122,23 @@ const manifest = {
"./routes/not_found.ts": $42, "./routes/not_found.ts": $42,
"./routes/params.tsx": $43, "./routes/params.tsx": $43,
"./routes/props/[id].tsx": $44, "./routes/props/[id].tsx": $44,
"./routes/signal_shared.tsx": $45, "./routes/route-groups/(bar)/(baz)/_layout.tsx": $45,
"./routes/state-in-props/_middleware.ts": $46, "./routes/route-groups/(bar)/(baz)/baz.tsx": $46,
"./routes/state-in-props/index.tsx": $47, "./routes/route-groups/(bar)/_layout.tsx": $47,
"./routes/state-middleware/_middleware.ts": $48, "./routes/route-groups/(bar)/bar.tsx": $48,
"./routes/state-middleware/foo/_middleware.ts": $49, "./routes/route-groups/(bar)/boof/index.tsx": $49,
"./routes/state-middleware/foo/index.tsx": $50, "./routes/route-groups/(foo)/_layout.tsx": $50,
"./routes/static.tsx": $51, "./routes/route-groups/(foo)/index.tsx": $51,
"./routes/status_overwrite.tsx": $52, "./routes/signal_shared.tsx": $52,
"./routes/umlaut-äöüß.tsx": $53, "./routes/state-in-props/_middleware.ts": $53,
"./routes/wildcard.tsx": $54, "./routes/state-in-props/index.tsx": $54,
"./routes/state-middleware/_middleware.ts": $55,
"./routes/state-middleware/foo/_middleware.ts": $56,
"./routes/state-middleware/foo/index.tsx": $57,
"./routes/static.tsx": $58,
"./routes/status_overwrite.tsx": $59,
"./routes/umlaut-äöüß.tsx": $60,
"./routes/wildcard.tsx": $61,
}, },
islands: { islands: {
"./islands/Counter.tsx": $$0, "./islands/Counter.tsx": $$0,
@@ -0,0 +1,10 @@
import { LayoutProps } from "$fresh/server.ts";
export default function BarLayout({ Component }: LayoutProps) {
return (
<div>
<p class="baz-layout">Baz layout</p>
<Component />
</div>
);
}
@@ -0,0 +1,3 @@
export default function BazPage() {
return <p class="baz-page">Baz page</p>;
}
@@ -0,0 +1,10 @@
import { LayoutProps } from "$fresh/server.ts";
export default function BarLayout({ Component }: LayoutProps) {
return (
<div>
<p class="bar-layout">Bar layout</p>
<Component />
</div>
);
}
@@ -0,0 +1,3 @@
export default function BarPage() {
return <p class="bar-page">Bar page</p>;
}
@@ -0,0 +1,3 @@
export default function Boof() {
return <p class="boof">Boof Page</p>;
}
@@ -0,0 +1,10 @@
import { LayoutProps } from "$fresh/server.ts";
export default function FooLayout({ Component }: LayoutProps) {
return (
<div>
<p class="foo-layout">Foo layout</p>
<Component />
</div>
);
}
@@ -0,0 +1,3 @@
export default function FooPage() {
return <p class="foo-page">Foo page</p>;
}
+32
View File
@@ -0,0 +1,32 @@
import { assertTextMany, fetchHtml, withFresh } from "./test_utils.ts";
Deno.test("applies only _layout file of one group", async () => {
await withFresh(
"./tests/fixture/main.ts",
async (address) => {
const doc = await fetchHtml(`${address}/route-groups`);
assertTextMany(doc, "p", ["Foo layout", "Foo page"]);
},
);
});
Deno.test("applies only _layout files in parent groups", async () => {
await withFresh(
"./tests/fixture/main.ts",
async (address) => {
const doc = await fetchHtml(`${address}/route-groups/baz`);
assertTextMany(doc, "p", ["Bar layout", "Baz layout", "Baz page"]);
},
);
});
Deno.test("applies only _layout files in parent groups #2", async () => {
await withFresh(
"./tests/fixture/main.ts",
async (address) => {
const doc = await fetchHtml(`${address}/route-groups/boof`);
assertTextMany(doc, "p", ["Bar layout", "Boof Page"]);
},
);
});
+18
View File
@@ -1,5 +1,6 @@
import { colors } from "$fresh/src/server/deps.ts"; import { colors } from "$fresh/src/server/deps.ts";
import { import {
assertEquals,
delay, delay,
DOMParser, DOMParser,
HTMLElement, HTMLElement,
@@ -39,6 +40,23 @@ export function assertSelector(doc: Document, selector: string) {
} }
} }
export function assertTextMany(
doc: Document,
selector: string,
expected: string[],
) {
const texts = Array.from(doc.querySelectorAll(selector)).map((el) =>
el.textContent
);
try {
assertEquals(texts, expected);
} catch (err) {
const html = "\n\n" + prettyDom(doc);
throw new err.constructor(err.message += html, { cause: err });
}
}
export const VOID_ELEMENTS = export const VOID_ELEMENTS =
/^(?:area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)$/; /^(?:area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)$/;
function prettyDom(doc: Document) { function prettyDom(doc: Document) {