fix: CSS modules not working in _app/_layout/_error and across routes in non-island components (#3781)

This commit is contained in:
Hajime-san
2026-05-27 08:32:41 +02:00
committed by GitHub
parent 072d09297e
commit 3afaaf4f78
30 changed files with 464 additions and 39 deletions
+8 -7
View File
@@ -1,4 +1,3 @@
import { setAdditionalStyles } from "./context.ts";
import { HttpError } from "./error.ts";
import { isHandlerByMethod, type PageResponse } from "./handlers.ts";
import {
@@ -74,11 +73,13 @@ export function newErrorCmd<State>(
export interface AppCommand<State> {
type: CommandType.App;
component: RouteComponent<State>;
css?: string[];
}
export function newAppCmd<State>(
component: RouteComponent<State>,
css?: string[],
): AppCommand<State> {
return { type: CommandType.App, component };
return { type: CommandType.App, component, css };
}
export interface LayoutCommand<State> {
@@ -86,6 +87,7 @@ export interface LayoutCommand<State> {
pattern: string;
component: RouteComponent<State>;
config?: LayoutConfig;
css?: string[];
includeLastSegment: boolean;
}
export function newLayoutCmd<State>(
@@ -93,12 +95,14 @@ export function newLayoutCmd<State>(
component: RouteComponent<State>,
config: LayoutConfig | undefined,
includeLastSegment: boolean,
css?: string[],
): LayoutCommand<State> {
return {
type: CommandType.Layout,
pattern,
component,
config,
css,
includeLastSegment,
};
}
@@ -253,7 +257,7 @@ function applyCommandsInner<State>(
break;
}
case CommandType.App: {
root.app = cmd.component;
root.app = { component: cmd.component, css: cmd.css ?? null };
break;
}
case CommandType.Layout: {
@@ -265,6 +269,7 @@ function applyCommandsInner<State>(
segment.layout = {
component: cmd.component,
config: cmd.config ?? null,
css: cmd.css ?? null,
};
break;
}
@@ -290,10 +295,6 @@ function applyCommandsInner<State>(
def = await route();
}
if (def.css !== undefined) {
setAdditionalStyles(ctx, def.css);
}
return renderRoute(ctx, def);
});
+34 -8
View File
@@ -120,8 +120,11 @@ export type ServerIslandRegistry = Map<ComponentType, Island>;
export const internals: unique symbol = Symbol("fresh_internal");
export interface UiTree<Data, State> {
app: AnyComponent<PageProps<Data, State>> | null;
layouts: ComponentDef<Data, State>[];
app: {
component: AnyComponent<PageProps<Data, State>>;
css: string[] | null;
} | null;
layouts: (ComponentDef<Data, State> & { css: string[] | null })[];
}
/**
@@ -131,7 +134,10 @@ export type FreshContext<State = unknown> = Context<State>;
export let getBuildCache: <T>(ctx: Context<T>) => BuildCache<T>;
export let getInternals: <T>(ctx: Context<T>) => UiTree<unknown, T>;
export let setAdditionalStyles: <T>(ctx: Context<T>, css: string[]) => void;
export let setAdditionalStyles: <T>(
ctx: Context<T>,
css: string[] | null | undefined,
) => void;
/**
* The context passed to every middleware. It is unique for every request.
@@ -204,8 +210,23 @@ export class Context<State> {
// deno-lint-ignore no-explicit-any
getInternals = <T>(ctx: Context<T>) => ctx.#internal as any;
getBuildCache = <T>(ctx: Context<T>) => ctx.#buildCache;
setAdditionalStyles = <T>(ctx: Context<T>, css: string[]) =>
ctx.#additionalStyles = css;
setAdditionalStyles = <T>(
ctx: Context<T>,
css: string[] | null | undefined,
) => {
if (css == null) return;
if (ctx.#additionalStyles === null) {
ctx.#additionalStyles = css.slice();
return;
}
for (const href of css) {
if (!ctx.#additionalStyles.includes(href)) {
ctx.#additionalStyles.push(href);
}
}
};
}
constructor(
@@ -305,6 +326,7 @@ export class Context<State> {
props.Component = () => child;
const def = defs[i];
setAdditionalStyles(this, def.css);
const result = await renderRouteComponent(this, def, () => child);
if (result instanceof Response) {
@@ -320,16 +342,20 @@ export class Context<State> {
let hasApp = true;
if (isAsyncAnyComponent(appDef)) {
if (appDef !== null) {
setAdditionalStyles(this, appDef.css);
}
if (appDef !== null && isAsyncAnyComponent(appDef.component)) {
props.Component = () => appChild;
const result = await renderAsyncAnyComponent(appDef, props);
const result = await renderAsyncAnyComponent(appDef.component, props);
if (result instanceof Response) {
return result;
}
appVNode = result;
} else if (appDef !== null) {
appVNode = h(appDef, {
appVNode = h(appDef.component, {
Component: () => appChild,
config: this.config,
data: null,
+1 -1
View File
@@ -20,7 +20,7 @@ const WINDOWS_SEPARATOR = pathWin32.SEPARATOR;
/** Normalize a path to use forward slashes so that generated files
* are portable across operating systems (e.g. build on Windows,
* deploy on Linux). */
function toPosix(p: string): string {
export function toPosix(p: string): string {
return p.replaceAll(WINDOWS_SEPARATOR, "/");
}
+2 -2
View File
@@ -1,6 +1,6 @@
import { type FsAdapter, fsAdapter } from "../fs.ts";
import type { WalkEntry } from "@std/fs/walk";
import type { FsRouteFileNoMod } from "./dev_build_cache.ts";
import { type FsRouteFileNoMod, toPosix } from "./dev_build_cache.ts";
import * as path from "@std/path";
import { pathToPattern } from "../router.ts";
import { CommandType } from "../commands.ts";
@@ -86,7 +86,7 @@ export async function crawlRouteDir<State>(
files.push({
id,
filePath: entry.path,
filePath: toPosix(entry.path),
type,
pattern,
routePattern,
+23 -1
View File
@@ -1,6 +1,6 @@
import { expect } from "@std/expect/expect";
import { createFakeFs } from "../test_utils.ts";
import { walkDir } from "./fs_crawl.ts";
import { crawlRouteDir, walkDir } from "./fs_crawl.ts";
Deno.test("walkDir - ", async () => {
const fs = createFakeFs({
@@ -43,3 +43,25 @@ Deno.test("walkDir - respects skip patterns", async () => {
"routes/api/users.ts",
]);
});
Deno.test({
name: "crawlRouteDir.filePath - normalized Windows paths",
ignore: Deno.build.os !== "windows",
fn: async () => {
const fs = createFakeFs({
"foo\\bar\\baz.txt": "foo",
"D:\\foo\\bar.tsx": "foo",
});
const rawFiles = await crawlRouteDir(fs, "foo", [], () => {});
expect(rawFiles).toEqual(expect.arrayContaining([
expect.objectContaining({
filePath: "foo/bar/baz.txt",
}),
expect.objectContaining({
filePath: "D:/foo/bar.tsx",
}),
]));
},
});
+6 -2
View File
@@ -106,7 +106,9 @@ export function fsItemsToCommands<State>(
}
if (!mod.default) continue;
commands.push(newLayoutCmd(pattern, mod.default, mod.config, true));
commands.push(
newLayoutCmd(pattern, mod.default, mod.config, true, mod.css),
);
continue;
}
case CommandType.Error: {
@@ -116,6 +118,7 @@ export function fsItemsToCommands<State>(
{
component: mod.default ?? undefined,
config: mod.config ?? undefined,
css: mod.css,
// deno-lint-ignore no-explicit-any
handler: (handlers as any) ?? undefined,
},
@@ -128,6 +131,7 @@ export function fsItemsToCommands<State>(
commands.push(newNotFoundCmd({
config: mod.config,
component: mod.default,
css: mod.css,
// deno-lint-ignore no-explicit-any
handler: handlers as any ?? undefined,
}));
@@ -137,7 +141,7 @@ export function fsItemsToCommands<State>(
const { mod } = validateFsMod<State>(filePath, rawMod, type);
if (mod.default === undefined) continue;
commands.push(newAppCmd(mod.default));
commands.push(newAppCmd(mod.default, mod.css));
continue;
}
case CommandType.Route: {
+1
View File
@@ -7,6 +7,7 @@ export {
type IslandModChunk,
type PendingStaticFile,
prepareStaticFile,
toPosix,
writeCompiledEntry,
} from "./dev/dev_build_cache.ts";
export { specToName } from "./dev/builder.ts";
+13 -3
View File
@@ -2,7 +2,7 @@ import type { AnyComponent } from "preact";
import type { MaybeLazyMiddleware, Middleware } from "./middlewares/mod.ts";
import { type Method, patternToSegments } from "./router.ts";
import type { LayoutConfig, Route } from "./types.ts";
import { type Context, getInternals } from "./context.ts";
import { type Context, getInternals, setAdditionalStyles } from "./context.ts";
import { recordSpanError, tracer } from "./otel.ts";
import { type HandlerFn, isHandlerByMethod } from "./handlers.ts";
import {
@@ -22,10 +22,14 @@ export interface Segment<State> {
layout: {
component: RouteComponent<State>;
config: LayoutConfig | null;
css: string[] | null;
} | null;
errorRoute: Route<State> | null;
notFound: Middleware<State> | null;
app: RouteComponent<State> | null;
app: {
component: RouteComponent<State>;
css: string[] | null;
} | null;
children: Map<string, Segment<State>>;
parent: Segment<State> | null;
}
@@ -105,7 +109,11 @@ export function segmentToMiddlewares<State>(
internals.app = null;
}
const def = { props: null, component: layout.component };
const def = {
props: null,
component: layout.component,
css: layout.css,
};
if (layout.config?.skipInheritedLayouts) {
internals.layouts = [def];
} else {
@@ -145,6 +153,8 @@ export async function renderRoute<State>(
route: Route<State>,
status = 200,
): Promise<Response> {
setAdditionalStyles(ctx, route.css);
const internals = getInternals(ctx);
if (route.config?.skipAppWrapper) {
internals.app = null;
+5 -1
View File
@@ -7,6 +7,7 @@ import { DEFAULT_CONN_INFO } from "./app.ts";
import type { Command } from "./commands.ts";
import { fsItemsToCommands, type FsRouteFile } from "./fs_routes.ts";
import * as path from "@std/path";
import { toPosix } from "./dev/dev_build_cache.ts";
const STUB = {} as unknown as Deno.ServeHandlerInfo;
@@ -123,7 +124,10 @@ export function createFakeFs(files: Record<string, unknown>): FsAdapter {
},
// deno-lint-ignore require-await
async isDirectory(dir) {
return Object.keys(files).some((file) => file.startsWith(dir + "/"));
return Object.keys(files).some((file) =>
// normalize path to posix before comparing
toPosix(file).startsWith(dir + "/")
);
},
async mkdirp(_dir: string) {
},