diff --git a/docs/architecture/starter-experience.md b/docs/architecture/starter-experience.md index a5cfeadb..620edd09 100644 --- a/docs/architecture/starter-experience.md +++ b/docs/architecture/starter-experience.md @@ -107,6 +107,7 @@ parent, as exported string or integer literals the generator reads: | `src/features//feature-module.ts` | `FEATURE_MODULE_ID`, `FEATURE_CONTEXT_ID`, `FEATURE_MODULE` | | `src/features//feature-runtime.ts` | `FEATURE_RUNTIME` (imported only by `feature-module.ts`, dynamically) | | `src/features//context-routes.ts` | `FEATURE_CONTEXT_ROUTES` | +| `src/contexts//context-layout.tsx` (optional) | `CONTEXT_LAYOUT`, the context's own layout ("Product home and layouts") | The generator writes `src/.generated/` (git-ignored): the feature index the installed catalogs import, the context index the router loads lazily, and the @@ -162,7 +163,8 @@ selected app. Every build and check script runs it first; run it yourself with identical or more specific root: the router renders feature routes only inside the owning context. The app module refuses anything else when it loads, naming the route, feature and context - (`src/apps/deployable-app-module.ts`). + (`src/apps/deployable-app-module.ts`). A route that takes over the platform + home is the exception ("Product home and layouts"). 5. If the feature has application input, augment `ApplicationFeatureInputs` from the feature (`src/features/local-draft-feature/application/local-draft-api.ts`). 6. Run `corepack pnpm check:architecture`, `corepack pnpm check:types`, @@ -178,6 +180,7 @@ Files outside the feature directory. Everything else a feature needs is in | --- | --- | --- | | `src/.generated/*` | never by hand: every build and check script regenerates it | — | | `src/contexts//context-module.ts` | the feature needs a new context | `generate:feature-index`: `Feature belongs to undeclared context ` | +| `src/contexts//context-layout.tsx` | the context needs its own frame instead of `AppShell` (see "Product home and layouts" below) | nothing: without it the context renders in `AppShell` | | `artifacts/tests/a11y-manual/.md` | every route the feature adds. Copy a record and reset it to `Status: pending-manual-review` | `test:unit` (`tests/unit/manual-a11y-evidence.test.ts`), `verify:documentation` (names the route IDs) and FE-GATE-009 (`review:a11y-manual -- --format-only`). FE-GATE-028 requires the signed review at release | | `tests/e2e/accessibility.spec.ts` | a route path has a parameter other than `:resourceId`, or a protected page cannot render while every API answers `[]` | `test:a11y` (FE-GATE-009): the spec fills in only `:resourceId` and answers every API with `[]` | | `src/bootstrap/product-composition.ts` (product-owned) | `needs` names a capability the template does not build: augment `FeaturePlatformCapabilities` and return the capability here. `indexedDb` is built as in `recipes/frontend-capabilities/indexeddb-feature-capability.ts`. Credentials for a product auth profile are returned here too | `check:types`; at runtime `feature needs , which the host did not provide` | @@ -206,6 +209,41 @@ sample. MSW scenarios for the feature's own operations come from `createHttpScenarioHandler` (`tests/mocks/handlers/http-scenarios.ts`) with the feature's installed contract; the shared scenario catalog does not change. +### Product home and layouts + +A product whose home is a feature screen, or whose screens use a frame other +than `AppShell`, declares it. The router and the catalogs do not change. + +- **Home.** A feature takes over the platform home by declaring a route with + the id `APP_HOME` in its contract. The platform names the routes a feature + may take over (`FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS` in + `src/contracts/routes.ts`); any other platform route id is still a + duplicate. Two features declaring `APP_HOME` fail when the catalogs load, + naming both. The router mounts the route at its own path with the owning + context, whatever that context's route root. Leaving the feature out of the + build (`VITE_PRODUCT_FEATURES`) brings the platform home back; switching it + off at runtime shows the disabled-feature page at its path. +- **Layout.** A context with `src/contexts//context-layout.tsx` + exporting `CONTEXT_LAYOUT` (a component) renders under that layout instead + of `AppShell`. The generated index loads the file lazily, when one of the + context's routes is entered. The router mounts the context at each + registered path of its features under the layout, so an unknown URL still + gets the not-found page in `AppShell`. Contexts whose layout files export the + same component keep one layout instance when the user moves between them, + so several route roots can share a layout. +- **Accessibility.** The layout renders a skip link to `#main-content` and + exactly one `
` around ``. + The router moves focus there on every route change. Layout routes are + siblings of `AppShell`, never inside it. +- **Failures.** A layout chunk a deploy removed gets the reload-once recovery + of a route chunk. Route and feature boundaries work as they do in + `AppShell`. +- The route root rule of step 4 spans every layout: a root takes the URLs + under it whichever layout either context has. + +`tests/component/context-layouts.test.tsx` installs a product declared this +way (`tests/helpers/fixture-layout-product.tsx`). + ### Before shipping - Use the semantic tokens, UI primitives, and state surfaces before adding a diff --git a/scripts/generate-product-feature-index.ts b/scripts/generate-product-feature-index.ts index e5ebdac9..fc19dc2e 100644 --- a/scripts/generate-product-feature-index.ts +++ b/scripts/generate-product-feature-index.ts @@ -14,6 +14,8 @@ export type FeatureIndexEntry = FeatureImportEntry & Readonly<{ contextId: string; contextRoutePath: string; contextMaxFeatures: number; + /** 09-03. Present when the context has a `context-layout.tsx`. */ + contextLayoutImportPath?: string; }>; /** @@ -96,7 +98,10 @@ export function renderContextIndex(entries: readonly FeatureIndexEntry[]): strin const routeBindings = features .map((_, index) => `routeModule${index}`) .join(", "); - return ` defineBoundedContextModule({\n id: ${JSON.stringify(contextId)},\n features: Object.freeze([${featureRefs}]),\n budget: Object.freeze({ maxFeatures: ${first.contextMaxFeatures} }),\n route: Object.freeze({\n path: ${JSON.stringify(first.contextRoutePath)},\n async loadRoutes() {\n const [${routeBindings}] = await Promise.all([\n${routeImports}\n ]);\n return Object.freeze([\n${routeSpreads}\n ]);\n },\n }),\n }),`; + const layout = first.contextLayoutImportPath + ? ` loadLayout: async () => (await import(${JSON.stringify(first.contextLayoutImportPath)})).CONTEXT_LAYOUT,\n` + : ""; + return ` defineBoundedContextModule({\n id: ${JSON.stringify(contextId)},\n features: Object.freeze([${featureRefs}]),\n budget: Object.freeze({ maxFeatures: ${first.contextMaxFeatures} }),\n route: Object.freeze({\n path: ${JSON.stringify(first.contextRoutePath)},\n${layout} async loadRoutes() {\n const [${routeBindings}] = await Promise.all([\n${routeImports}\n ]);\n return Object.freeze([\n${routeSpreads}\n ]);\n },\n }),\n }),`; }) .join("\n"); @@ -112,6 +117,8 @@ export function renderContextIndex(entries: readonly FeatureIndexEntry[]): strin * src/apps//app-module.ts APP_MODULE_ID, APP_MAX_CONTEXTS * src/contexts//context-module.ts CONTEXT_MODULE_ID, CONTEXT_APP_ID, * CONTEXT_ROUTE_PATH, CONTEXT_MAX_FEATURES + * src/contexts//context-layout.tsx CONTEXT_LAYOUT (optional, 09-03: + * the context's own layout) * src/features//feature-module.ts FEATURE_MODULE_ID, FEATURE_CONTEXT_ID * * The generated indexes describe exactly one deployable app: the contexts it @@ -125,6 +132,7 @@ export type ContextDeclaration = Readonly<{ appId: string; routePath: string; maxFeatures: number; + layoutImportPath?: string; }>; export type FeatureDeclaration = Readonly<{ id: string; @@ -213,6 +221,9 @@ export function selectAppIndexes( contextId: context.id, contextRoutePath: context.routePath, contextMaxFeatures: context.maxFeatures, + ...(context.layoutImportPath + ? { contextLayoutImportPath: context.layoutImportPath } + : {}), }); } } @@ -316,12 +327,16 @@ export async function createFileSystemDeclarationSource( const contextsByApp = new Map(); const contextIds = new Set(); for (const declaration of await readDeclarations(resolve(root, "src/contexts"), "context-module.ts")) { - const context: ContextDeclaration = { + let context: ContextDeclaration = { id: requiredLiteral(declaration.source, "CONTEXT_MODULE_ID", declaration.file), appId: requiredLiteral(declaration.source, "CONTEXT_APP_ID", declaration.file), routePath: requiredLiteral(declaration.source, "CONTEXT_ROUTE_PATH", declaration.file), maxFeatures: requiredInteger(declaration.source, "CONTEXT_MAX_FEATURES", declaration.file), }; + const layout = `${declaration.directory}/context-layout.tsx`; + if (await readFile(resolve(root, "src/contexts", layout)).then(() => true, () => false)) { + context = { ...context, layoutImportPath: `../contexts/${layout}` }; + } if (contextIds.has(context.id)) throw new Error(`Duplicate context id: ${context.id}`); if (!apps.has(context.appId)) { throw new Error(`Context ${context.id} belongs to undeclared app ${context.appId}`); diff --git a/src/apps/deployable-app-module.ts b/src/apps/deployable-app-module.ts index c84bce0e..2a2fdbd2 100644 --- a/src/apps/deployable-app-module.ts +++ b/src/apps/deployable-app-module.ts @@ -4,6 +4,7 @@ import { contractRoutePaths, type BoundedContextModule, } from "../contexts/bounded-context-module.ts"; +import { FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS } from "../contracts/routes.ts"; import { assertWithinCardinalityBudget } from "../platform/cardinality/cardinality-budget.ts"; export type DeployableAppModule = Readonly<{ @@ -48,6 +49,12 @@ export function defineDeployableAppModule; + /** + * 09-03. The context's own layout instead of AppShell, loaded when one of + * its routes is entered. The router mounts the context at each of its + * registered paths under that layout, so an unknown URL still reaches + * AppShell's NOT_FOUND. Contexts whose layouts load the same component keep + * one layout instance when the user moves between them, so several roots + * can sit under one layout. The layout renders a skip link to + * `#main-content` and exactly one `
` + * around the ``: the router moves focus there on every route + * change. The generator reads it from `src/contexts//context-layout.tsx`. + */ + loadLayout?(): Promise; }>; export type BoundedContextModule< diff --git a/src/contracts/routes.ts b/src/contracts/routes.ts index 8318f316..8abbad36 100644 --- a/src/contracts/routes.ts +++ b/src/contracts/routes.ts @@ -96,3 +96,39 @@ export const PLATFORM_ROUTE_REGISTRY = Object.freeze({ navigationOrder: null, }), }); + +/** + * 09-03. Platform routes an installed feature may take over by declaring the + * same route id: a product whose home is a feature screen. The feature's + * definition replaces the platform's, and the router mounts it with the + * feature's context. Every other platform route id stays a collision. + */ +export const FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS: readonly string[] = + Object.freeze(["APP_HOME"]); + +/** + * A platform registry (routes, route runtime contracts) without the entries + * these features took over. Two features taking over one route fail, naming + * both. + */ +export function withoutTakenOverPlatformRoutes< + Registry extends Readonly>, +>( + registry: Registry, + contracts: readonly Readonly<{ featureId: string; routes: object }>[], +): Registry { + return Object.fromEntries( + Object.entries(registry).filter(([routeId]) => { + if (!FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS.includes(routeId)) return true; + const owners = contracts + .filter((contract) => routeId in contract.routes) + .map((contract) => contract.featureId); + if (owners.length > 1) { + throw new TypeError( + `Platform route ${routeId} is taken over by ${owners.join(", ")}`, + ); + } + return owners.length === 0; + }), + ) as Registry; +} diff --git a/src/features/installed-feature-contracts.ts b/src/features/installed-feature-contracts.ts index e11f2106..0e88e974 100644 --- a/src/features/installed-feature-contracts.ts +++ b/src/features/installed-feature-contracts.ts @@ -1,5 +1,8 @@ import { PLATFORM_ROUTE_RUNTIME_CONTRACT } from "../contracts/route-runtime-contract.ts"; -import { PLATFORM_ROUTE_REGISTRY } from "../contracts/routes.ts"; +import { + PLATFORM_ROUTE_REGISTRY, + withoutTakenOverPlatformRoutes, +} from "../contracts/routes.ts"; import { composeUniqueRecord } from "../platform/cardinality/compose-unique-record.ts"; import { INSTALLED_PRODUCT_FEATURES } from "./installed-product-manifest.ts"; @@ -17,7 +20,11 @@ export const INSTALLED_FEATURE_CONTRACTS = INSTALLED_PRODUCT_FEATURES; // kept only the route keys common to both. export const ROUTE_REGISTRY = composeUniqueRecord( [ - PLATFORM_ROUTE_REGISTRY, + // 09-03. A platform route a feature took over (its home) is the feature's. + withoutTakenOverPlatformRoutes( + PLATFORM_ROUTE_REGISTRY, + INSTALLED_FEATURE_CONTRACTS, + ), ...INSTALLED_FEATURE_CONTRACTS.map((contract) => contract.routes), ], () => "route registry", @@ -25,7 +32,10 @@ export const ROUTE_REGISTRY = composeUniqueRecord( export const ROUTE_RUNTIME_CONTRACT = composeUniqueRecord( [ - PLATFORM_ROUTE_RUNTIME_CONTRACT, + withoutTakenOverPlatformRoutes( + PLATFORM_ROUTE_RUNTIME_CONTRACT, + INSTALLED_FEATURE_CONTRACTS, + ), ...INSTALLED_FEATURE_CONTRACTS.map( (contract) => contract.routeRuntimeContracts, ), diff --git a/src/platform/routing/context-route-module.ts b/src/platform/routing/context-route-module.ts index a3791119..155dd124 100644 --- a/src/platform/routing/context-route-module.ts +++ b/src/platform/routing/context-route-module.ts @@ -1,10 +1,14 @@ import type { RouteObject } from "react-router-dom"; import type { DeployableAppModule } from "../../apps/deployable-app-module.ts"; +import type { BoundedContextRouteModule } from "../../contexts/bounded-context-module.ts"; export type ContextRouteModule = Readonly<{ id: string; path: string; loadRoutes(): Promise; + /** 09-03. The features whose registered routes this context renders. */ + featureIds: readonly string[]; + loadLayout: BoundedContextRouteModule["loadLayout"]; }>; function createCachedContextRouteLoader( @@ -46,6 +50,8 @@ export function createAppRouteModules( loadRoutes: createCachedContextRouteLoader( context.route.loadRoutes, ), + featureIds: context.features.map((feature) => feature.id), + loadLayout: context.route.loadLayout, }), ] : [], diff --git a/src/presentation/routes/app-router.tsx b/src/presentation/routes/app-router.tsx index 1fbea994..1ecff079 100644 --- a/src/presentation/routes/app-router.tsx +++ b/src/presentation/routes/app-router.tsx @@ -1,5 +1,7 @@ import { + type ComponentType, type ElementType, + lazy, type ReactNode, Suspense, useEffect, @@ -618,49 +620,102 @@ function ContextRouteGateway({ ); } -function createRegisteredRoutes(buildId: string): RouteObject[] { - const platformChildren = Object.values(PLATFORM_ROUTE_REGISTRY).map((definition) => { - const routeId = definition.routeId as RouteId; - if (definition.path === "/") { - return { - id: routeId, - index: true, - element: , - }; - } - return { - id: routeId, - path: - definition.path === "*" - ? "*" - : definition.path.replace(/^\//, ""), - element: , - }; - }); - const contextChildren = createAppRouteModules(TEMPLATE_APP_MODULE).map( - (routeModule) => ({ - id: `CONTEXT:${routeModule.id}`, - path: routeModule.path, - element: ( - // Keyed: React Router reuses the instance across sibling contexts, - // and the previous context's routes must never match the new URL. - - ), - }), +/** + * 09-03. A layout a context declared, loaded when one of its routes is + * entered. A layout chunk a deploy removed gets the reload-once recovery of a + * route chunk; any other failure reaches the layout route's error element. + */ +function ContextLayout({ + Layout, + buildId, +}: Readonly<{ Layout: ComponentType; buildId: string }>) { + const { pathname } = useLocation(); + const recovery = useApplicationRecovery(); + const diagnostics = useApplicationDiagnostics(); + return ( + + diagnostics.reportRenderFailure({ + routeId: registeredRouteIdAt(pathname) ?? "NOT_FOUND", + buildId, + boundaryName: "route", + incidentId, + }) + } + > + }> + + + ); - return [ - { - id: "APP_SHELL", - path: "/", - element: , - errorElement: , - children: [...platformChildren, ...contextChildren], - }, +} + +/** A registered path as a child of a `/` layout route: `/` is the index. */ +function registeredChild(id: string, path: string, element: ReactNode): RouteObject { + return path === "/" + ? { id, index: true, element } + : { id, path: path.replace(/^\//, ""), element }; +} + +function createRegisteredRoutes(buildId: string): RouteObject[] { + const errorElement = ; + // 09-03. A platform route a feature took over is mounted with its context. + const shellChildren = Object.values(PLATFORM_ROUTE_REGISTRY) + .filter(({ routeId }) => !ROUTE_FEATURE_OWNER[routeId]) + .map(({ routeId, path }) => + registeredChild( + routeId, + path, + , + ), + ); + const routes: RouteObject[] = [ + { id: "APP_SHELL", path: "/", element: , errorElement, children: shellChildren }, ]; + for (const routeModule of createAppRouteModules(TEMPLATE_APP_MODULE)) { + const { id, loadLayout } = routeModule; + // Keyed: React Router reuses the instance across sibling contexts, and + // the previous context's routes must never match the new URL. + const gateway = ( + + ); + let children = shellChildren; + if (loadLayout) { + // Layout routes are siblings of AppShell at `/`. Moving between two + // contexts whose layouts load the same component keeps its instance: + // React reconciles lazy types by what they resolved to. + children = []; + routes.push({ + id: `CONTEXT_LAYOUT:${id}`, + path: "/", + element: ( + ({ default: await loadLayout() }))} + buildId={buildId} + /> + ), + errorElement, + children, + }); + } else { + children.push(registeredChild(`CONTEXT:${id}`, routeModule.path, gateway)); + } + // Under a layout, the context answers its registered paths only, so an + // unknown URL still reaches AppShell's NOT_FOUND. A route that took over + // a platform route is mounted at its own path, whatever the root. + for (const { routeId, path } of Object.values(ROUTE_REGISTRY)) { + if ( + routeModule.featureIds.includes(ROUTE_FEATURE_OWNER[routeId] ?? "") && + (loadLayout || routeId in PLATFORM_ROUTE_REGISTRY) + ) { + children.push(registeredChild(`CONTEXT:${id}:${routeId}`, path, gateway)); + } + } + } + return routes; } /** diff --git a/tests/architecture/context-route-roots.test.ts b/tests/architecture/context-route-roots.test.ts index 0d4ad017..b74ebc32 100644 --- a/tests/architecture/context-route-roots.test.ts +++ b/tests/architecture/context-route-roots.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest"; import { defineDeployableAppModule } from "../../src/apps/deployable-app-module.ts"; import { defineBoundedContextModule } from "../../src/contexts/bounded-context-module.ts"; +import { withoutTakenOverPlatformRoutes } from "../../src/contracts/routes.ts"; import { defineFeatureModule } from "../../src/features/feature-module.ts"; /** @@ -32,12 +33,13 @@ function context( id: string, path: string, features: readonly ReturnType[], + loadLayout?: () => Promise<() => null>, ) { return defineBoundedContextModule({ id, features, budget: { maxFeatures: 10 }, - route: { path, loadRoutes: async () => [] }, + route: { path, loadRoutes: async () => [], ...(loadLayout ? { loadLayout } : {}) }, }); } @@ -88,6 +90,17 @@ describe("feature routes and their context route root", () => { ).toThrow(/SHOP_HOME/); }); + it("accepts the platform home a feature replaces whatever its root (09-03)", () => { + // The router mounts a replaced platform route at its own path. + expect(() => + app( + context("home-context", "home/*", [ + feature("home-feature", { APP_HOME: "/", HOME_FEED: "/home/feed" }), + ]), + ), + ).not.toThrow(); + }); + it("rejects a route whose feature belongs to a context without a route root", () => { expect(() => app( @@ -137,6 +150,69 @@ describe("feature routes and their context route root", () => { }); }); +/** + * 09-03. Several context roots may sit under one layout, and layouts are + * siblings of AppShell at `/`: a root still takes the URLs under it whatever + * layout either context has, so the rule above spans every layout. + */ +describe("context route roots under layouts", () => { + const siteLayout = async () => () => null; + const studioLayout = async () => () => null; + + it("accepts several roots under one layout and nested roots across layouts", () => { + expect(() => + app( + context("site", "*", [feature("site", { APP_HOME: "/", EXPLORE: "/explore" })], siteLayout), + context("topics", "topics/*", [feature("topics", { TOPICS: "/topics" })], siteLayout), + context("studio", "studio/*", [feature("studio", { STUDIO: "/studio" })], studioLayout), + context("shop", "shop/*", [feature("shop", { SHOP: "/shop" })]), + ), + ).not.toThrow(); + }); + + it("rejects a route another layout's root takes over", () => { + expect(() => + app( + context("site", "*", [feature("site", { DRAFTS: "/studio/drafts" })], siteLayout), + context("studio", "studio/*", [feature("studio", { STUDIO: "/studio" })], studioLayout), + ), + ).toThrow(/DRAFTS.*site.*studio \(studio\/\*\)/); + }); +}); + +/** 09-03. The platform names the routes a feature may take over; one feature may. */ +describe("replaceable platform routes", () => { + const contract = (featureId: string, ...routeIds: string[]) => ({ + featureId, + routes: Object.fromEntries(routeIds.map((routeId) => [routeId, {}])), + }); + + const platform = { APP_HOME: "platform home", NOT_FOUND: "platform not found" }; + + it("drops the platform routes a feature took over and keeps the rest", () => { + expect( + withoutTakenOverPlatformRoutes(platform, [contract("site", "APP_HOME", "EXPLORE")]), + ).toEqual({ NOT_FOUND: "platform not found" }); + expect(withoutTakenOverPlatformRoutes(platform, [contract("shop", "SHOP")])).toEqual(platform); + }); + + it("keeps a platform route the platform does not let features take over", () => { + // The registry composition then refuses the duplicate id as before. + expect( + withoutTakenOverPlatformRoutes(platform, [contract("shop", "NOT_FOUND")]), + ).toEqual(platform); + }); + + it("rejects a second feature taking over the same platform route, naming both", () => { + expect(() => + withoutTakenOverPlatformRoutes(platform, [ + contract("site", "APP_HOME"), + contract("blog", "APP_HOME"), + ]), + ).toThrow(/APP_HOME.*site.*blog/); + }); +}); + /** * 09-06 (3). The gateway renders the registered route a loaded route's handle * names. A handle no feature of the context declares in its contract fails diff --git a/tests/component/context-boundary-diagnostics.test.tsx b/tests/component/context-boundary-diagnostics.test.tsx index 079e2508..23f92f00 100644 --- a/tests/component/context-boundary-diagnostics.test.tsx +++ b/tests/component/context-boundary-diagnostics.test.tsx @@ -53,6 +53,7 @@ vi.mock("../../src/apps/template-app.ts", async () => { }), { id: "context-without-codecs", + features: [], route: { path: "fixture/items/*", loadRoutes: async () => [ @@ -66,6 +67,7 @@ vi.mock("../../src/apps/template-app.ts", async () => { }, { id: "context-with-typo", + features: [], route: { path: "fixture/items/status/*", loadRoutes: async () => [ @@ -79,6 +81,7 @@ vi.mock("../../src/apps/template-app.ts", async () => { }, { id: "context-broken", + features: [], route: { path: "fixture/items/new/*", loadRoutes: async () => { diff --git a/tests/component/context-layouts.test.tsx b/tests/component/context-layouts.test.tsx new file mode 100644 index 00000000..898c4df5 --- /dev/null +++ b/tests/component/context-layouts.test.tsx @@ -0,0 +1,122 @@ +// @vitest-environment jsdom + +import { render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, expect, it, vi } from "vitest"; + +import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx"; +import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx"; +import { AppRouter } from "../../src/presentation/routes/app-router.tsx"; +import { createTestApplication } from "../helpers/create-test-application.ts"; + +// 09-03. The product in tests/helpers/fixture-layout-product.tsx declares the +// downstream products' home and layouts; nothing here touches the router. +vi.mock("../../src/.generated/product-feature-index.ts", async () => { + const product = await import("../helpers/fixture-layout-product.tsx"); + return { + DECLARED_PRODUCT_FEATURE_IDS: product.LAYOUT_PRODUCT_FEATURE_IDS, + PRODUCT_FEATURE_MODULES: product.LAYOUT_PRODUCT_FEATURE_MODULES, + }; +}); +vi.mock("../../src/.generated/product-context-index.ts", async () => ({ + PRODUCT_CONTEXT_MODULES: (await import("../helpers/fixture-layout-product.tsx")) + .LAYOUT_PRODUCT_CONTEXT_MODULES, +})); + +function renderAt(url: string, record = vi.fn()) { + window.history.pushState({}, "", url); + render( + + + + + , + ); + return record; +} + +const APP_SHELL_NAVIGATION = { name: "주요 탐색" } as const; + +async function page(title: string) { + return screen.findByRole("heading", { name: title, level: 1 }); +} + +/** The skip link, the one `
` and the focus move every screen keeps. */ +async function expectAccessibleScreen(title: string) { + const heading = await page(title); + const mains = document.querySelectorAll("main"); + expect(mains).toHaveLength(1); + expect(mains[0]).toHaveAttribute("id", "main-content"); + expect(mains[0]).toContainElement(heading); + expect(document.querySelectorAll('a[href="#main-content"]')).toHaveLength(1); + await waitFor(() => expect(heading).toHaveFocus()); +} + +describe("context layouts and a feature-owned home (09-03)", () => { + it("renders the product home a feature took over inside its context's layout", async () => { + renderAt("/"); + + const heading = await page("Site home"); + expect(heading.closest("[data-layout]")).toHaveAttribute("data-layout", "site"); + expect(screen.queryByRole("navigation", APP_SHELL_NAVIGATION)).toBeNull(); + }); + + it("mounts each context under the layout it declares", async () => { + renderAt("/studio/documents"); + + const heading = await page("Studio documents"); + expect(heading.closest("[data-layout]")).toHaveAttribute("data-layout", "studio"); + expect(screen.queryByRole("navigation", APP_SHELL_NAVIGATION)).toBeNull(); + }); + + it("keeps one layout instance across the context roots under it", async () => { + const user = userEvent.setup(); + renderAt("/explore"); + const layout = (await page("Site explore")).closest("[data-layout]"); + + await user.click(screen.getByRole("link", { name: "Topics" })); + + const topics = await page("Site topics"); + expect(topics.closest("[data-layout]")).toBe(layout); + }); + + it("leaves unknown URLs and contexts without a layout in AppShell", async () => { + renderAt("/studio/missing"); + + expect(await page("페이지를 찾을 수 없습니다.")).toBeVisible(); + expect(screen.getByRole("navigation", APP_SHELL_NAVIGATION)).toBeVisible(); + expect(document.querySelector("[data-layout]")).toBeNull(); + }); + + it("keeps the skip link, one main and the focus move across layouts", async () => { + const user = userEvent.setup(); + renderAt("/fixture/first"); + await expectAccessibleScreen("Fixture first page"); + expect(screen.getByRole("navigation", APP_SHELL_NAVIGATION)).toBeVisible(); + + // AppShell -> site layout, through the home link the feature now owns. + await user.click(screen.getAllByRole("link", { name: "Site home" })[0]!); + await expectAccessibleScreen("Site home"); + + // site layout -> studio layout. + await user.click(screen.getByRole("link", { name: "Open the studio" })); + await expectAccessibleScreen("Studio home"); + + // studio layout -> AppShell. + await user.click(screen.getByRole("link", { name: "Back to the app shell" })); + await expectAccessibleScreen("Fixture first page"); + }); + + it("recovers a layout chunk that did not arrive like a route chunk", async () => { + const record = renderAt("/offline"); + + expect( + await screen.findByRole("heading", { name: "화면 자산을 복구하지 못했습니다." }), + ).toBeVisible(); + expect(record).toHaveBeenCalledWith({ + level: "error", + eventId: "ui.render.failed", + context: expect.objectContaining({ route_id: "OFFLINE_HOME", build_id: "build-a" }), + }); + }); +}); diff --git a/tests/component/context-route-gateway.test.tsx b/tests/component/context-route-gateway.test.tsx index ffaaf233..b4cba8d6 100644 --- a/tests/component/context-route-gateway.test.tsx +++ b/tests/component/context-route-gateway.test.tsx @@ -28,6 +28,7 @@ vi.mock("../../src/apps/template-app.ts", async () => { contexts: [ { id: "context-a", + features: [], route: { path: "fixture/items/*", loadRoutes: only("FIXTURE_ITEMS"), @@ -35,6 +36,7 @@ vi.mock("../../src/apps/template-app.ts", async () => { }, { id: "context-b", + features: [], route: { path: "fixture/items/status/*", loadRoutes: only("FIXTURE_ITEM_STATUS"), @@ -42,6 +44,7 @@ vi.mock("../../src/apps/template-app.ts", async () => { }, { id: "context-offline", + features: [], route: { path: "fixture/items/new/*", loadRoutes: async () => { diff --git a/tests/helpers/fixture-layout-product.tsx b/tests/helpers/fixture-layout-product.tsx new file mode 100644 index 00000000..0d8d15b8 --- /dev/null +++ b/tests/helpers/fixture-layout-product.tsx @@ -0,0 +1,195 @@ +import type { ComponentType } from "react"; +import { Link, Outlet, type RouteObject } from "react-router-dom"; + +import { defineBoundedContextModule } from "../../src/contexts/bounded-context-module.ts"; +import { defineFeatureModule } from "../../src/features/feature-module.ts"; +// Not the design-system barrel, for the reason fixture-feature.tsx gives. +import { PageHeader } from "../../src/presentation/components/page-header.tsx"; +import { + FIXTURE_CONTEXT_MODULE, + FIXTURE_FEATURE_MODULE, +} from "./fixture-feature.tsx"; + +/** + * 09-03. A test-only product whose screens do not live in AppShell, declared + * the way the two downstream products need it, without touching the router: + * + * context root layout routes + * site * site APP_HOME "/" (replaces the platform home), "/explore" + * topics topics/* site "/topics" (a second root under one layout) + * studio studio/* studio "/studio", "/studio/documents" + * offline offline/* offline "/offline" (its layout chunk never arrives) + * fixture fixture/* (none) the fixture feature, still under AppShell + * + * memento's bridges are `site` (its home and its own shell); tech-log's + * PUBLIC/STUDIO groups are `site` + `topics` and `studio`. Install it by + * mocking the generated indexes with the exports below. + */ +type RouteSpec = readonly [routeId: string, path: string, title: string, navigationOrder: number | null]; + +function layoutFeature(featureId: string, specs: readonly RouteSpec[]) { + const routes = Object.freeze( + Object.fromEntries( + specs.map(([routeId, path, title, navigationOrder]) => [ + routeId, + Object.freeze({ + routeId, + path, + paramsSchema: null, + searchSchema: null, + access: "public" as const, + loadingSurface: "fixture-page", + errorSurface: "route-boundary", + chunkId: `route-${routeId.toLowerCase()}`, + title, + navigationLabel: navigationOrder === null ? null : title, + navigationOrder, + }), + ]), + ), + ); + const messages = Object.freeze( + Object.fromEntries( + specs.flatMap(([routeId, , title]) => [ + [`route.${routeId}.title`, title], + [`route.${routeId}.navigation`, title], + ]), + ), + ); + const feature = defineFeatureModule({ + id: featureId, + contracts: Object.freeze({ + featureId, + routes, + routeRuntimeContracts: Object.freeze( + Object.fromEntries( + specs.map(([routeId]) => [ + routeId, + Object.freeze({ + routeId, + moduleId: `${routeId.toLowerCase()}-page`, + paramsCodec: "none", + searchCodec: "none", + }), + ]), + ), + ), + invalidation: Object.freeze({ topics: [], namespaces: [], edges: [] }), + topicVersions: Object.freeze([]), + contractPackages: Object.freeze([]), + }), + routes, + messages: Object.freeze({ "ko-KR": messages, "en-US": messages }), + loadRuntime: async () => + Object.freeze({ + featureId, + apiContract: Object.freeze({ + apiOperations: Object.freeze({}), + schemas: Object.freeze({}), + runtimeSchemas: Object.freeze({}), + mappers: Object.freeze({}), + }), + adapters: Object.freeze([]), + contractContributions: Object.freeze([]), + }), + }); + const contextRoutes: readonly RouteObject[] = specs.map(([routeId, path, title]) => ({ + id: routeId, + path, + handle: Object.freeze({ + routeId, + runtime: Object.freeze({ + moduleId: `${routeId.toLowerCase()}-page`, + Component: function FixtureLayoutPage() { + return ; + }, + }), + }), + })); + return { feature, contextRoutes }; +} + +/** A product shell: its own skip link, navigation and the one `
`. */ +function shell(name: string, links: readonly (readonly [to: string, label: string])[]): ComponentType { + return function FixtureProductLayout() { + return ( +
+ Skip to {name} content + +
+ +
+
+ ); + }; +} + +const SiteLayout = shell("site", [ + ["/topics", "Topics"], + ["/studio", "Open the studio"], +]); +const StudioLayout = shell("studio", [ + ["/", "Back to the site"], + ["/fixture/first", "Back to the app shell"], +]); + +// Each context loads its layout itself, the way generated contexts do; site +// and topics load the same component, so they share one layout instance. +const loadSiteLayout = async () => SiteLayout; +const loadTopicsLayout = async () => SiteLayout; +const loadStudioLayout = async () => StudioLayout; + +const site = layoutFeature("site-feature", [ + ["APP_HOME", "/", "Site home", 10], + ["SITE_EXPLORE", "/explore", "Site explore", null], +]); +const topics = layoutFeature("topics-feature", [["SITE_TOPICS", "/topics", "Site topics", null]]); +const studio = layoutFeature("studio-feature", [ + ["STUDIO_HOME", "/studio", "Studio home", null], + ["STUDIO_DOCUMENTS", "/studio/documents", "Studio documents", null], +]); +const offline = layoutFeature("offline-feature", [["OFFLINE_HOME", "/offline", "Offline home", null]]); + +function layoutContext( + id: string, + path: string, + { feature, contextRoutes }: ReturnType, + loadLayout: () => Promise, +) { + return defineBoundedContextModule({ + id, + features: [feature], + budget: { maxFeatures: 1 }, + route: { path, loadRoutes: async () => contextRoutes, loadLayout }, + }); +} + +export const LAYOUT_PRODUCT_FEATURE_MODULES = [ + site.feature, + topics.feature, + studio.feature, + offline.feature, + FIXTURE_FEATURE_MODULE, +] as const; + +export const LAYOUT_PRODUCT_FEATURE_IDS = LAYOUT_PRODUCT_FEATURE_MODULES.map( + (feature) => feature.id, +); + +export const LAYOUT_PRODUCT_CONTEXT_MODULES = [ + layoutContext("site", "*", site, loadSiteLayout), + layoutContext("topics", "topics/*", topics, loadTopicsLayout), + layoutContext("studio", "studio/*", studio, loadStudioLayout), + layoutContext("offline", "offline/*", offline, () => + Promise.reject( + new TypeError("Failed to fetch dynamically imported module: /assets/offline-layout.js"), + ), + ), + FIXTURE_CONTEXT_MODULE, +] as const; diff --git a/tests/scripts/generate-product-feature-index.test.ts b/tests/scripts/generate-product-feature-index.test.ts index df5387ce..4d1f05bf 100644 --- a/tests/scripts/generate-product-feature-index.test.ts +++ b/tests/scripts/generate-product-feature-index.test.ts @@ -180,6 +180,32 @@ describe("app-scoped selection from ownership declarations", () => { expect(selected.featureIndex).not.toContain("features/fb/"); expect(selected.appIndex).toContain('id: "a"'); }); + + it("loads a context's own layout lazily when it has a context-layout.tsx (09-03)", async () => { + const layout = "export const CONTEXT_LAYOUT = () => null;\n"; + const selected = await generateAppIndexes( + await repo({ + "src/apps/a/app-module.ts": app("a"), + "src/contexts/site-dir/context-module.ts": context("site", "a"), + "src/contexts/site-dir/context-layout.tsx": layout, + "src/contexts/topics/context-module.ts": context("topics", "a"), + "src/contexts/topics/context-layout.tsx": layout, + "src/contexts/shop/context-module.ts": context("shop", "a"), + "src/features/fs/feature-module.ts": feature("fs", "site"), + "src/features/ft/feature-module.ts": feature("ft", "topics"), + "src/features/fp/feature-module.ts": feature("fp", "shop"), + }), + "a", + ); + const index = selected.contextIndex; + expect(index).toContain( + 'loadLayout: async () => (await import("../contexts/site-dir/context-layout.tsx")).CONTEXT_LAYOUT,', + ); + expect(index).toContain('import("../contexts/topics/context-layout.tsx")'); + expect(index).not.toMatch(/from "\.\.\/contexts\/[^"]+\/context-layout\.tsx"/u); + // The shop context has none and stays under AppShell. + expect(index.match(/loadLayout:/gu)).toHaveLength(2); + }); }); describe("build-time product selection (09-02)", () => { diff --git a/tests/unit/product-features.test.ts b/tests/unit/product-features.test.ts index d2b353ae..2810c80c 100644 --- a/tests/unit/product-features.test.ts +++ b/tests/unit/product-features.test.ts @@ -6,6 +6,7 @@ import { selectCompiledProductFeatures, } from "../../src/contracts/product-features.ts"; import { runtimeConfigV2ArtifactSchema } from "../../src/contracts/release-artifacts.ts"; +import { FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS } from "../../src/contracts/routes.ts"; import { COMPILED_PRODUCT_FEATURE_IDS, INSTALLED_PRODUCT_FEATURE_IDS, @@ -214,10 +215,12 @@ describe("route ownership", () => { expect(Object.values(ROUTE_FEATURE_OWNER)).toContain(featureId); } // Platform routes have no owner, so disabling a feature can never withdraw - // the shell's own navigation. + // the shell's own navigation. The exception is a route the platform lets + // one feature take over (09-03: a product's home). for (const routeId of ["APP_HOME", "NOT_FOUND", "EXAMPLES_PLATFORM"]) { - expect(ROUTE_FEATURE_OWNER[routeId], routeId).toBeUndefined(); expect(Object.keys(ROUTE_REGISTRY)).toContain(routeId); + if (FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS.includes(routeId)) continue; + expect(ROUTE_FEATURE_OWNER[routeId], routeId).toBeUndefined(); } });