diff --git a/docs/canary/concepts/route-groups.md b/docs/canary/concepts/route-groups.md new file mode 100644 index 00000000..56a5f1af --- /dev/null +++ b/docs/canary/concepts/route-groups.md @@ -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 +> ``` diff --git a/docs/toc.ts b/docs/toc.ts index 01cd0580..95556711 100644 --- a/docs/toc.ts +++ b/docs/toc.ts @@ -59,6 +59,7 @@ const toc: RawTableOfContents = { ["updating", "Updating Fresh", "link:latest"], ["app-wrapper", "Application wrapper", "link:latest"], ["route-layout", "Route layouts", "link:canary"], + ["route-groups", "Route groups", "link:canary"], ["server-configuration", "Server configuration", "link:latest"], ], }, diff --git a/src/server/context.ts b/src/server/context.ts index 9372a607..25db510a 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -17,6 +17,7 @@ import { BUILD_ID } from "./build_id.ts"; import DefaultErrorHandler from "./default_error_page.ts"; import { AppModule, + BaseRoute, ErrorPage, ErrorPageModule, FreshOptions, @@ -24,7 +25,6 @@ import { Island, LayoutModule, LayoutRoute, - Middleware, MiddlewareHandler, MiddlewareHandlerContext, MiddlewareModule, @@ -60,6 +60,8 @@ const DEFAULT_CONN_INFO: ServeHandlerInfo = { remoteAddr: { transport: "tcp", hostname: "localhost", port: 1234 }, }; +const ROOT_BASE_ROUTE = toBaseRoute("/"); + function isObject(value: unknown) { return typeof value === "object" && !Array.isArray(value) && @@ -244,6 +246,7 @@ export class ServerContext { }; } const route: Route = { + baseRoute: toBaseRoute(baseRoute), pattern, url, name, @@ -254,8 +257,8 @@ export class ServerContext { routes.push(route); } else if (isMiddleware) { middlewares.push({ - ...middlewarePathToPattern(baseRoute), - ...module as MiddlewareModule, + baseRoute: toBaseRoute(baseRoute), + module: module as MiddlewareModule, }); } else if ( path === "/_app.tsx" || path === "/_app.ts" || @@ -264,8 +267,8 @@ export class ServerContext { app = module as AppModule; } else if (isLayout) { layouts.push({ - ...layoutPathToPattern(baseRoute), - ...module as LayoutModule, + baseRoute: toBaseRoute(baseRoute), + module: module as LayoutModule, }); } else if ( path === "/_404.tsx" || path === "/_404.ts" || @@ -278,6 +281,7 @@ export class ServerContext { } notFound = { + baseRoute: ROOT_BASE_ROUTE, pattern: pathToPattern(baseRoute), url, name, @@ -296,6 +300,7 @@ export class ServerContext { } error = { + baseRoute: toBaseRoute("/"), pattern: pathToPattern(baseRoute), url, name, @@ -488,13 +493,16 @@ export class ServerContext { connInfo: ServeHandlerInfo, inner: router.FinalHandler, ) => { - // 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)[] = []; 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 = {}; const middlewareCtx: MiddlewareHandlerContext = { next() { @@ -574,39 +582,50 @@ export class ServerContext { const routes: router.Routes = {}; 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) { internalRoutes[REFRESH_JS_URL] = { - default: () => { - return new Response(refreshJs(ALIVE_URL, BUILD_ID), { - headers: { - "content-type": "application/javascript; charset=utf-8", - }, - }); + baseRoute: toBaseRoute(REFRESH_JS_URL), + methods: { + default: () => { + return new Response(refreshJs(ALIVE_URL, BUILD_ID), { + headers: { + "content-type": "application/javascript; charset=utf-8", + }, + }); + }, }, }; internalRoutes[ALIVE_URL] = { - default: () => { - let timerId: number | undefined = undefined; - const body = new ReadableStream({ - start(controller) { - controller.enqueue(`data: ${BUILD_ID}\nretry: 100\n\n`); - timerId = setInterval(() => { - controller.enqueue(`data: ${BUILD_ID}\n\n`); - }, 1000); - }, - cancel() { - if (timerId !== undefined) { - clearInterval(timerId); - } - }, - }); - return new Response(body.pipeThrough(new TextEncoderStream()), { - headers: { - "content-type": "text/event-stream", - }, - }); + baseRoute: toBaseRoute(ALIVE_URL), + methods: { + default: () => { + let timerId: number | undefined = undefined; + const body = new ReadableStream({ + start(controller) { + controller.enqueue(`data: ${BUILD_ID}\nretry: 100\n\n`); + timerId = setInterval(() => { + controller.enqueue(`data: ${BUILD_ID}\n\n`); + }, 1000); + }, + cancel() { + if (timerId !== undefined) { + clearInterval(timerId); + } + }, + }); + return new Response(body.pipeThrough(new TextEncoderStream()), { + headers: { + "content-type": "text/event-stream", + }, + }); + }, }, }; } @@ -620,17 +639,20 @@ export class ServerContext { ) { const route = sanitizePathToRegex(path); staticRoutes[route] = { - "HEAD": this.#staticFileHeadHandler( - size, - contentType, - etag, - ), - "GET": this.#staticFileGetHandler( - localUrl, - size, - contentType, - etag, - ), + baseRoute: toBaseRoute(route), + methods: { + "HEAD": this.#staticFileHeadHandler( + size, + contentType, + etag, + ), + "GET": this.#staticFileGetHandler( + localUrl, + size, + contentType, + etag, + ), + }, }; } @@ -656,6 +678,9 @@ export class ServerContext { headers: undefined, }); } + + const layouts = selectSharedRoutes(ROOT_BASE_ROUTE, this.#layouts); + const imports: string[] = []; const resp = await internalRender({ request: req, @@ -664,7 +689,7 @@ export class ServerContext { islands: this.#islands, plugins: this.#plugins, app: this.#app, - layouts: this.#layouts, + layouts, imports, dependenciesFn, renderFn: this.#renderFn, @@ -705,6 +730,8 @@ export class ServerContext { throw new Error("This page does not have a component to render."); } + const layouts = selectSharedRoutes(route.baseRoute, this.#layouts); + const resp = await internalRender({ request: req, context: { @@ -717,7 +744,7 @@ export class ServerContext { islands: this.#islands, plugins: this.#plugins, app: this.#app, - layouts: this.#layouts, + layouts, imports, dependenciesFn, renderFn: this.#renderFn, @@ -749,20 +776,26 @@ export class ServerContext { const createRender = genRender(route, Status.OK); if (typeof route.handler === "function") { routes[route.pattern] = { - default: (req, ctx, params) => - (route.handler as Handler)(req, { - ...ctx, - params, - render: createRender(req, params, ctx), - async renderNotFound(data: Data) { - return await renderNotFound(req, params, ctx, data); - }, - }), + baseRoute: route.baseRoute, + methods: { + default: (req, ctx, params) => + (route.handler as Handler)(req, { + ...ctx, + params, + render: createRender(req, params, ctx), + async renderNotFound(data: Data) { + return await renderNotFound(req, params, ctx, data); + }, + }), + }, }; } else { - routes[route.pattern] = {}; + routes[route.pattern] = { + baseRoute: route.baseRoute, + methods: {}, + }; 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, ctx, params, @@ -929,6 +962,7 @@ const DEFAULT_APP: AppModule = { }; const DEFAULT_NOT_FOUND: UnknownPage = { + baseRoute: toBaseRoute("/"), pattern: "", url: "", name: "_404", @@ -937,6 +971,7 @@ const DEFAULT_NOT_FOUND: UnknownPage = { }; const DEFAULT_ERROR: ErrorPage = { + baseRoute: toBaseRoute("/"), pattern: "", url: "", name: "_500", @@ -945,23 +980,23 @@ const DEFAULT_ERROR: ErrorPage = { csp: false, }; -/** - * Return a list of middlewares that needs to be applied for request url - * @param url the request url - * @param middlewares Array of middlewares handlers and their routes as path-to-regexp style - */ -export function selectMiddlewares(url: string, middlewares: MiddlewareRoute[]) { - const selectedMws: Middleware[] = []; - const reqURL = new URL(url); +export function selectSharedRoutes( + curBaseRoute: BaseRoute, + items: { baseRoute: BaseRoute; module: T }[], +): T[] { + const selected: T[] = []; - for (const { compiledPattern, handler } of middlewares) { - const res = compiledPattern.exec(reqURL); + for (const { baseRoute, module } of items) { + const res = curBaseRoute === baseRoute || + curBaseRoute.startsWith( + baseRoute.length > 1 ? baseRoute + "/" : baseRoute, + ); if (res) { - selectedMws.push({ handler }); + selected.push(module); } } - return selectedMws; + return selected; } const APP_REG = /_app\.[tj]sx?$/; @@ -1027,47 +1062,64 @@ function getRoutePathScore(char: string, nextChar: string): number { export function pathToPattern(path: string): string { const parts = path.split("/"); if (parts[parts.length - 1] === "index") { + if (parts.length === 1) { + return "/"; + } 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 - // 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.`, - ); - } + let route = ""; - // 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 i = 0; i < part.length; i++) { - const char = part[i]; - if (char === "[") { - pattern += ":"; - groupOpen++; - } else if (char === "]") { - if (--groupOpen < 0) { - throw new SyntaxError(`Invalid route pattern: "${path}"`); - } - } else { - pattern += char; + for (let i = 0; i < parts.length; i++) { + const part = parts[i]; + + // Case: /[...foo].tsx + if (part.startsWith("[...") && part.endsWith("]")) { + route += `/:${part.slice(4, part.length - 1)}*`; + continue; + } + + // Route groups like /foo/(bar) should not be included in URL + // matching. They are transparent and need to be removed here. + // Case: /foo/(bar) -> /foo + // Case: /foo/(bar)/bob -> /foo/bob + // Case: /(foo)/bar -> /bar + if (part.startsWith("(") && part.endsWith(")")) { + continue; + } + + // 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; } @@ -1118,24 +1170,21 @@ function serializeCSPDirectives(csp: ContentSecurityPolicyDirectives): string { .join("; "); } -export function layoutPathToPattern(baseRoute: string) { - baseRoute = baseRoute.slice(0, -"_layout".length); - let pattern = pathToPattern(baseRoute); - if (pattern.endsWith("/")) { - pattern = pattern.slice(0, -1) + "{/*}?"; +export function toBaseRoute(input: string): BaseRoute { + if (input.endsWith("_layout")) { + input = input.slice(0, -"_layout".length); + } else if (input.endsWith("_middleware")) { + 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) { - baseRoute = baseRoute.slice(0, -"_middleware".length); - let pattern = pathToPattern(baseRoute); - if (pattern.endsWith("/")) { - pattern = pattern.slice(0, -1) + "{/*}?"; + if (input.endsWith("/")) { + input = input.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) { diff --git a/src/server/context_test.ts b/src/server/context_test.ts index d2229e91..959c552d 100644 --- a/src/server/context_test.ts +++ b/src/server/context_test.ts @@ -1,32 +1,5 @@ import { assertEquals, assertThrows } from "$std/testing/asserts.ts"; -import { assert } from "../../tests/deps.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); -}); +import { pathToPattern } from "./context.ts"; Deno.test("pathToPattern", async (t) => { await t.step("creates pattern", () => { diff --git a/src/server/render.ts b/src/server/render.ts index be3cd144..c901f97f 100644 --- a/src/server/render.ts +++ b/src/server/render.ts @@ -15,7 +15,6 @@ import { ErrorPage, Island, LayoutModule, - LayoutRoute, Plugin, PluginRenderFunctionResult, PluginRenderResult, @@ -58,7 +57,7 @@ export interface RenderOptions { islands: Island[]; plugins: Plugin[]; app: AppModule; - layouts: LayoutRoute[]; + layouts: LayoutModule[]; imports: string[]; dependenciesFn: (path: string) => string[]; 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. * Suspense boundaries are not supported. @@ -214,13 +194,11 @@ export async function render( // deno-lint-ignore no-explicit-any let finalAppComp: VNode = vnode as any; - const layouts = selectLayouts(opts.url.toString(), opts.layouts); - - let i = layouts.length; + let i = opts.layouts.length; while (i--) { - const layout = layouts[i]; - const curComp = finalAppComp; + const layout = opts.layouts[i]; + const curComp = finalAppComp; finalAppComp = h(layout.default, { params: opts.params as Record, url: opts.url, diff --git a/src/server/router.ts b/src/server/router.ts index e056e108..c9c1ce1e 100644 --- a/src/server/router.ts +++ b/src/server/router.ts @@ -1,4 +1,4 @@ -import { ServeHandlerInfo } from "./types.ts"; +import { BaseRoute, ErrorHandlerContext, ServeHandlerInfo } from "./types.ts"; type HandlerContext = T & ServeHandlerInfo; @@ -37,13 +37,19 @@ export type MatchHandler = ( // deno-lint-ignore ban-types export interface Routes { - [key: string]: { [K in KnownMethod | "default"]?: MatchHandler }; + [key: string]: { + baseRoute: BaseRoute; + methods: { + [K in KnownMethod | "default"]?: MatchHandler; + }; + }; } export type DestinationKind = "internal" | "static" | "route" | "notFound"; // deno-lint-ignore ban-types export type InternalRoute = { + baseRoute: BaseRoute; pattern: URLPattern; methods: { [K in KnownMethod]?: MatchHandler }; default?: MatchHandler; @@ -79,7 +85,7 @@ export function defaultOtherHandler(_req: Request): Response { export function defaultErrorHandler( _req: Request, - _ctx: HandlerContext, + _ctx: ErrorHandlerContext, err: unknown, ): Response { console.error(err); @@ -107,15 +113,16 @@ function processRoutes( routes: Routes, destination: DestinationKind, ) { - for (const [path, methods] of Object.entries(routes)) { + for (const [path, def] of Object.entries(routes)) { const entry: InternalRoute = { + baseRoute: def.baseRoute, pattern: new URLPattern({ pathname: path }), methods: {}, default: undefined, destination, }; - for (const [method, handler] of Object.entries(methods)) { + for (const [method, handler] of Object.entries(def.methods)) { if (method === "default") { entry.default = handler; } else if (knownMethods.includes(method as KnownMethod)) { diff --git a/src/server/types.ts b/src/server/types.ts index f2dd50b5..f88b87d5 100644 --- a/src/server/types.ts +++ b/src/server/types.ts @@ -147,6 +147,7 @@ export type PageComponent> = // deno-lint-ignore no-explicit-any export interface Route { + baseRoute: BaseRoute; pattern: string; url: string; name: string; @@ -177,15 +178,9 @@ export interface LayoutModule { default: ComponentType; } -export interface LayoutRoute extends LayoutModule { - /** - * path-to-regexp style url path - */ - pattern: string; - /** - * URLPattern of the route - */ - compiledPattern: URLPattern; +export interface LayoutRoute { + baseRoute: BaseRoute; + module: LayoutModule; } // --- UNKNOWN PAGE --- @@ -224,6 +219,7 @@ export interface UnknownPageModule { } export interface UnknownPage { + baseRoute: BaseRoute; pattern: string; url: string; name: string; @@ -253,6 +249,9 @@ export interface ErrorHandlerContext> state: State; } +// Nominal/Branded type. Ensures that the string has the expected format +export type BaseRoute = string & { readonly __brand: unique symbol }; + export type ErrorHandler = ( req: Request, ctx: ErrorHandlerContext, @@ -265,6 +264,7 @@ export interface ErrorPageModule { } export interface ErrorPage { + baseRoute: BaseRoute; pattern: string; url: string; name: string; @@ -283,15 +283,9 @@ export interface MiddlewareHandlerContext> params: Record; } -export interface MiddlewareRoute extends Middleware { - /** - * path-to-regexp style url path - */ - pattern: string; - /** - * URLPattern of the route - */ - compiledPattern: URLPattern; +export interface MiddlewareRoute { + baseRoute: BaseRoute; + module: Middleware; } export type MiddlewareHandler> = ( diff --git a/tests/fixture/fresh.gen.ts b/tests/fixture/fresh.gen.ts index f8fbb209..0b139835 100644 --- a/tests/fixture/fresh.gen.ts +++ b/tests/fixture/fresh.gen.ts @@ -47,16 +47,23 @@ import * as $41 from "./routes/movies/[foo]@[bar].ts"; import * as $42 from "./routes/not_found.ts"; import * as $43 from "./routes/params.tsx"; import * as $44 from "./routes/props/[id].tsx"; -import * as $45 from "./routes/signal_shared.tsx"; -import * as $46 from "./routes/state-in-props/_middleware.ts"; -import * as $47 from "./routes/state-in-props/index.tsx"; -import * as $48 from "./routes/state-middleware/_middleware.ts"; -import * as $49 from "./routes/state-middleware/foo/_middleware.ts"; -import * as $50 from "./routes/state-middleware/foo/index.tsx"; -import * as $51 from "./routes/static.tsx"; -import * as $52 from "./routes/status_overwrite.tsx"; -import * as $53 from "./routes/umlaut-äöüß.tsx"; -import * as $54 from "./routes/wildcard.tsx"; +import * as $45 from "./routes/route-groups/(bar)/(baz)/_layout.tsx"; +import * as $46 from "./routes/route-groups/(bar)/(baz)/baz.tsx"; +import * as $47 from "./routes/route-groups/(bar)/_layout.tsx"; +import * as $48 from "./routes/route-groups/(bar)/bar.tsx"; +import * as $49 from "./routes/route-groups/(bar)/boof/index.tsx"; +import * as $50 from "./routes/route-groups/(foo)/_layout.tsx"; +import * as $51 from "./routes/route-groups/(foo)/index.tsx"; +import * as $52 from "./routes/signal_shared.tsx"; +import * as $53 from "./routes/state-in-props/_middleware.ts"; +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 $$1 from "./islands/MultipleCounters.tsx"; import * as $$2 from "./islands/ReturningNull.tsx"; @@ -115,16 +122,23 @@ const manifest = { "./routes/not_found.ts": $42, "./routes/params.tsx": $43, "./routes/props/[id].tsx": $44, - "./routes/signal_shared.tsx": $45, - "./routes/state-in-props/_middleware.ts": $46, - "./routes/state-in-props/index.tsx": $47, - "./routes/state-middleware/_middleware.ts": $48, - "./routes/state-middleware/foo/_middleware.ts": $49, - "./routes/state-middleware/foo/index.tsx": $50, - "./routes/static.tsx": $51, - "./routes/status_overwrite.tsx": $52, - "./routes/umlaut-äöüß.tsx": $53, - "./routes/wildcard.tsx": $54, + "./routes/route-groups/(bar)/(baz)/_layout.tsx": $45, + "./routes/route-groups/(bar)/(baz)/baz.tsx": $46, + "./routes/route-groups/(bar)/_layout.tsx": $47, + "./routes/route-groups/(bar)/bar.tsx": $48, + "./routes/route-groups/(bar)/boof/index.tsx": $49, + "./routes/route-groups/(foo)/_layout.tsx": $50, + "./routes/route-groups/(foo)/index.tsx": $51, + "./routes/signal_shared.tsx": $52, + "./routes/state-in-props/_middleware.ts": $53, + "./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/Counter.tsx": $$0, diff --git a/tests/fixture/routes/route-groups/(bar)/(baz)/_layout.tsx b/tests/fixture/routes/route-groups/(bar)/(baz)/_layout.tsx new file mode 100644 index 00000000..d408c04a --- /dev/null +++ b/tests/fixture/routes/route-groups/(bar)/(baz)/_layout.tsx @@ -0,0 +1,10 @@ +import { LayoutProps } from "$fresh/server.ts"; + +export default function BarLayout({ Component }: LayoutProps) { + return ( +
+

Baz layout

+ +
+ ); +} diff --git a/tests/fixture/routes/route-groups/(bar)/(baz)/baz.tsx b/tests/fixture/routes/route-groups/(bar)/(baz)/baz.tsx new file mode 100644 index 00000000..95045329 --- /dev/null +++ b/tests/fixture/routes/route-groups/(bar)/(baz)/baz.tsx @@ -0,0 +1,3 @@ +export default function BazPage() { + return

Baz page

; +} diff --git a/tests/fixture/routes/route-groups/(bar)/_layout.tsx b/tests/fixture/routes/route-groups/(bar)/_layout.tsx new file mode 100644 index 00000000..b5bc0417 --- /dev/null +++ b/tests/fixture/routes/route-groups/(bar)/_layout.tsx @@ -0,0 +1,10 @@ +import { LayoutProps } from "$fresh/server.ts"; + +export default function BarLayout({ Component }: LayoutProps) { + return ( +
+

Bar layout

+ +
+ ); +} diff --git a/tests/fixture/routes/route-groups/(bar)/bar.tsx b/tests/fixture/routes/route-groups/(bar)/bar.tsx new file mode 100644 index 00000000..b4ce304b --- /dev/null +++ b/tests/fixture/routes/route-groups/(bar)/bar.tsx @@ -0,0 +1,3 @@ +export default function BarPage() { + return

Bar page

; +} diff --git a/tests/fixture/routes/route-groups/(bar)/boof/index.tsx b/tests/fixture/routes/route-groups/(bar)/boof/index.tsx new file mode 100644 index 00000000..b466aebe --- /dev/null +++ b/tests/fixture/routes/route-groups/(bar)/boof/index.tsx @@ -0,0 +1,3 @@ +export default function Boof() { + return

Boof Page

; +} diff --git a/tests/fixture/routes/route-groups/(foo)/_layout.tsx b/tests/fixture/routes/route-groups/(foo)/_layout.tsx new file mode 100644 index 00000000..13b10bb7 --- /dev/null +++ b/tests/fixture/routes/route-groups/(foo)/_layout.tsx @@ -0,0 +1,10 @@ +import { LayoutProps } from "$fresh/server.ts"; + +export default function FooLayout({ Component }: LayoutProps) { + return ( +
+

Foo layout

+ +
+ ); +} diff --git a/tests/fixture/routes/route-groups/(foo)/index.tsx b/tests/fixture/routes/route-groups/(foo)/index.tsx new file mode 100644 index 00000000..c575ed9a --- /dev/null +++ b/tests/fixture/routes/route-groups/(foo)/index.tsx @@ -0,0 +1,3 @@ +export default function FooPage() { + return

Foo page

; +} diff --git a/tests/route_groups_test.ts b/tests/route_groups_test.ts new file mode 100644 index 00000000..dfc74fc4 --- /dev/null +++ b/tests/route_groups_test.ts @@ -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"]); + }, + ); +}); diff --git a/tests/test_utils.ts b/tests/test_utils.ts index f8a80ca2..be95d8cc 100644 --- a/tests/test_utils.ts +++ b/tests/test_utils.ts @@ -1,5 +1,6 @@ import { colors } from "$fresh/src/server/deps.ts"; import { + assertEquals, delay, DOMParser, 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 = /^(?:area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)$/; function prettyDom(doc: Document) {