From 166bf51e532ab9fde340502540201756329c6065 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Tue, 20 Oct 2026 00:46:44 +0200 Subject: [PATCH] Lazy 404: createNotFoundPage({ load }) + renderNotFoundView, NotFoundLoader Next puts a layout's not-found tree into the RSC payload of every page under it. The eager createNotFoundPage({ blocks }) rendered the panel's 404 page there in every locale, so with 404 = homepage each page shipped the homepage twice (homepage HTML 195 -> 146 KB gzip). With { load } only is in the payload; the content comes from the project's server action (renderNotFoundView, locale checked against configured locales) when a 404 shows. The eager variant is unchanged. Docs: pages.md, i18n.md, AGENT.md, PROGRAMISTA, ipal-setup, CHANGELOG. Co-Authored-By: Claude Opus 5.5 --- docs/CHANGELOG.md | 20 +++++++ docs/agent/AGENT.md | 10 ++-- docs/agent/skills/ipal-setup/SKILL.md | 3 +- docs/dev/PROGRAMISTA.md | 17 +++++- docs/dev/vibe.md | 2 +- docs/i18n.md | 4 +- docs/pages.md | 42 +++++++++++--- src/exports/client.ts | 1 + src/exports/rsc.ts | 4 +- src/modules/frontend/pageRoute.tsx | 84 +++++++++++++++++++++------ src/modules/pages/LocaleView.tsx | 6 +- src/modules/pages/NotFoundLoader.tsx | 47 +++++++++++++++ src/modules/pages/localeFromPath.ts | 8 +++ test/notFoundPage.test.ts | 67 +++++++++++++++++++++ 14 files changed, 273 insertions(+), 42 deletions(-) create mode 100644 src/modules/pages/NotFoundLoader.tsx create mode 100644 src/modules/pages/localeFromPath.ts create mode 100644 test/notFoundPage.test.ts diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index a57880c..b556fc7 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -8,6 +8,26 @@ wersji naraz przejdź po kolei wszystkie sekcje „Wymaga zmian w projekcie” o wersji, którą masz. Nowe wydanie = nowa sekcja na górze; najstarsze usuwamy dopiero powyżej 20. +## 1.12.0 + +### Nowe +- **Leniwa strona 404** — `createNotFoundPage(content, { load })` + `renderNotFoundView(content, { blocks, blockProps, + fallback }, locale)` (`/rsc`) w server action projektu; `` (`/client`). Next wkłada drzewo + `not-found` layoutu do danych RSC KAŻDEJ strony; wariant `{ blocks }` renderował tam stronę 404 z panelu w każdym + języku (404 = strona główna, 2 języki: HTML strony głównej 195 → 146 KB gzip, dane RSC −42%). Teraz w danych jest + tylko loader, treść przychodzi przy wyświetleniu 404. `renderNotFoundView` przyjmuje tylko skonfigurowane języki. + Opis: pages.md → „Strona 404”. + +### Wymaga zmian w projekcie +Nic obowiązkowego — `createNotFoundPage(content, { blocks })` działa jak dotąd. Zalecane (każdy projekt z 404 +z panelu, zwłaszcza 404 = strona główna albo kilka języków): +1. `src/app/(frontend)/[locale]/notFoundView.ts` (`.tsx`, gdy `fallback` to JSX): + `'use server'` + `export async function loadNotFoundView(locale: string) { return renderNotFoundView(content, + { blocks: blockRegistry, blockProps, fallback }, locale) }` — opcje przenieś z `not-found.tsx`. +2. `not-found.tsx`: `export default createNotFoundPage(content, { load: loadNotFoundView })`. +3. Sprawdzenie: w HTML dowolnej strony brak treści strony 404 (`self.__next_f`), a nieznany adres + (np. `/xx/test`) nadal daje 404 z treścią z panelu. + ## 1.11.1 ### Nowe diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 65ccf76..a715bc6 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -52,7 +52,7 @@ strona), **P** = test w panelu. Pełny kod: PROGRAMISTA.md §2. | # | Obszar | Co musi być (plik) | API pluginu | Kontrola | |---|---|---|---|---| -| 1 | i18n + routing | `src/proxy.ts`, `[locale]/[[...slug]]/page.tsx` = `createPageRoute(content, {…})` + literał `revalidate`, `not-found.tsx` = `createNotFoundPage(content, {…})` | `createProxy`, `createContentHelpers`, `createPageRoute`, `createNotFoundPage` (`/rsc`) | A, S | +| 1 | i18n + routing | `src/proxy.ts`, `[locale]/[[...slug]]/page.tsx` = `createPageRoute(content, {…})` + literał `revalidate`, `not-found.tsx` = `createNotFoundPage(content, { load })` + `notFoundView.ts` (`renderNotFoundView`) | `createProxy`, `createContentHelpers`, `createPageRoute`, `createNotFoundPage` (`/rsc`) | A, S | | 2 | **SEO** — meta | `generateMetadata` w każdej trasie stron; favicon i OG z Site Settings; `htmlLimitedBots` w `next.config.ts`; tab SEO + `buildNoindexField` w Pages | `generatePageMetadata`, `buildIconsMetadata`, `buildNoindexField` | A, S | | 3 | **SEO** — mapy | `src/app/sitemap.xml/route.ts`, `src/app/robots.ts`, `src/app/manifest.ts` — każdy to re-eksport z `lib/content` (`sitemapRoute`, `robots`, `manifest`) + `force-dynamic` poza robots | `sitemapRoute`, `robots`, `manifest` | A, S | | 4 | **SEO** — dane strukturalne | layout: `` daje `WebSite` + `Organization` (`sameAs`) z Site Settings; firma lokalna → `createContentHelpers({ siteJsonLd })` z `buildLocalBusinessJsonLd` (`type`, godziny → `formatOpeningHours`); nawigacja: ``; strona: `createPageRoute` dokłada `getPageJsonLd` (WebPage/BlogPosting, okruszki, FAQ — `pageJsonLd: { faq }`) | `getSiteShell`, `SiteProviders`, `build*JsonLd`, `getPageJsonLd` | A, S | @@ -285,7 +285,8 @@ src/ [locale]/ # jednojęzyczny: bez [locale] (patrz i18n.md) layout.tsx # bez ; + Header/Footer actions.ts # sendForm = createSubmitAction(…) (jedyna droga wysyłki formularzy) - not-found.tsx # createNotFoundPage(content, { blocks }) — 404 z panelu + not-found.tsx # createNotFoundPage(content, { load: loadNotFoundView }) — 404 z panelu + notFoundView.ts # 'use server' → renderNotFoundView(content, { blocks }, locale) [[...slug]]/page.tsx # PODWÓJNE nawiasy; createPageRoute(content, { blocks, … }) + revalidate (payload)/ # panel (generowany) manifest.ts # export { manifest as default } from lib/content + force-dynamic @@ -350,7 +351,8 @@ Bez skrótów (`HeroSection`, nie `HeroSec`). Nie twórz `lib/pages.ts`, statycznych — w blokach, komponentach, layoucie `[locale]` ani w `not-found.tsx` (Next 16: `Page changed from static to dynamic at runtime`). Locale do bloków → `enhanceProps`; w `not-found.tsx` (brak `params`) → - wersja na każdy język + `` (pages.md). + `createNotFoundPage(content, { load })` — język z adresu, treść z server action dopiero przy 404 + (wariant `{ blocks }` wkłada 404 w każdym języku do danych RSC KAŻDEJ strony — pages.md). 7. **`export const dynamic = 'force-dynamic'`** na trasach czytających bazę: `manifest.ts`, `sitemap.xml/route.ts`, `llms.txt`, `api/health`. Handlery pluginu mają try/catch, ale `dynamic` musi być w pliku trasy. @@ -769,7 +771,7 @@ projekcie → **ipal-plugin-gap**, nie kopia. |---|---|---| | Payload, ustawienia, języki (cache na żądanie) | `getCachedPayload`, `getSettings`, `getConfiguredLocales` | content.md | | Strona catch-all (route, 308, 404, meta, static params, JSON-LD, bloki) | `createPageRoute(content, { blocks, notFound, permanentRedirect, blockProps, render })` (`/rsc`) | pages.md | -| 404 z panelu w każdym języku | `createNotFoundPage(content, { blocks, fallback })` (`/rsc`) | pages.md | +| 404 z panelu w każdym języku | `createNotFoundPage(content, { load })` + server action `renderNotFoundView(content, { blocks, fallback }, locale)` (`/rsc`) | pages.md | | Layout: zgoda, baner, Turnstile, analityka, JSON-LD strony, preconnect | `getSiteShell(locale)` + `` (`/rsc`) | consent.md | | Własna strona / archiwum | `resolveRoute`, `getEntries`, `resolvePageRedirect`, `generatePageMetadata`, `getPageJsonLd`, `generateStaticParams` | content.md, pages.md | | Render bloków | `RenderBlocks` + mapa `registry` (nigdy `switch`) | blocks.md | diff --git a/docs/agent/skills/ipal-setup/SKILL.md b/docs/agent/skills/ipal-setup/SKILL.md index 6c2476e..40540e4 100644 --- a/docs/agent/skills/ipal-setup/SKILL.md +++ b/docs/agent/skills/ipal-setup/SKILL.md @@ -41,7 +41,8 @@ tylko, gdy użytkownik o to poprosi. Pełna budowa strony: skill **ipal-site**. (`createContentHelpers` z `markdownAlternate: true`, `summaryField`, `mcp` — PROGRAMISTA §2.7), layout bez ``: `}>`, catch-all: `createPageRoute(content, { blocks, notFound, permanentRedirect, blockProps })` + literał `revalidate`, - `not-found.tsx`: `createNotFoundPage(content, { blocks })` (PROGRAMISTA §2.6–2.8, pages.md). + `not-found.tsx`: `createNotFoundPage(content, { load: loadNotFoundView })` + `notFoundView.ts` z + `renderNotFoundView` (PROGRAMISTA §2.6–2.8, pages.md). 7. **SEO i bezpieczeństwo** — sitemap, robots, manifest, health jako re-eksporty z `lib/content` (`sitemapRoute`, `robots`, `manifest`, `healthRoute`; z `force-dynamic` poza robots; bez CSS w `public/`), `htmlLimitedBots`, `buildSecurityHeaders`, `buildUploadSecurityHeaders`, `images: buildImagesConfig()`, diff --git a/docs/dev/PROGRAMISTA.md b/docs/dev/PROGRAMISTA.md index 65b3d90..f748d29 100644 --- a/docs/dev/PROGRAMISTA.md +++ b/docs/dev/PROGRAMISTA.md @@ -303,12 +303,23 @@ export const generateStaticParams = route.generateStaticParams // SSG → 404 */ }) +export async function loadNotFoundView(locale: string) { + return renderNotFoundView(content, { blocks: blockRegistry }, locale) +} + +// src/app/(frontend)/[locale]/not-found.tsx — 404 w języku z URL, bez headers(); treść ładowana dopiero przy 404, +// a nie w danych RSC każdej strony (pages.md → „Dlaczego leniwy”) +import { createNotFoundPage } from '@intecion/ipal-kit/rsc' +import * as content from '@/lib/content' +import { loadNotFoundView } from './notFoundView' + +export default createNotFoundPage(content, { load: loadNotFoundView }) ``` ```ts diff --git a/docs/dev/vibe.md b/docs/dev/vibe.md index c065151..dc74cd2 100644 --- a/docs/dev/vibe.md +++ b/docs/dev/vibe.md @@ -171,7 +171,7 @@ Zrób zgodnie z PROGRAMISTA.md §2.6–2.8 i AGENT.md §4: (zgoda, baner equalChoice, Turnstile, Analytics, JSON-LD, preconnect — w dobrej kolejności), - [locale]/[[...slug]]/page.tsx: createPageRoute(content, { blocks, notFound, permanentRedirect }) + export const revalidate (literał), BEZ searchParams, -- [locale]/not-found.tsx: createNotFoundPage(content, { blocks }) — BEZ headers() (pages.md). +- [locale]/not-found.tsx: createNotFoundPage(content, { load: loadNotFoundView }) + notFoundView.ts ('use server', renderNotFoundView) — BEZ headers() (pages.md). Plan najpierw. ``` Sprawdź: `/` → `/`; `pnpm build` pokazuje strony jako `●`; diff --git a/docs/i18n.md b/docs/i18n.md index 5c1c2c2..37b13ce 100644 --- a/docs/i18n.md +++ b/docs/i18n.md @@ -227,8 +227,8 @@ export default route.Page export const generateMetadata = route.generateMetadata export const generateStaticParams = route.generateStaticParams // zwraca { slug } bez locale -// app/(frontend)/not-found.tsx -export default createNotFoundPage(content, { blocks: blockRegistry }) +// app/(frontend)/not-found.tsx (+ notFoundView.ts z server action — pages.md) +export default createNotFoundPage(content, { load: loadNotFoundView }) // app/md/[[...slug]]/route.ts — BEZ [locale]: /md = strona główna, /md/kontakt = kontakt export { markdownRoute as GET } from '@/lib/content' diff --git a/docs/pages.md b/docs/pages.md index de53c6f..5d72929 100644 --- a/docs/pages.md +++ b/docs/pages.md @@ -62,18 +62,44 @@ Site Settings → System Pages → **404 (Not Found)**. Edytor wybiera: - stronę główną (część klientów tak woli), **albo** - nic → projekt pokazuje wbudowany fallback z `not-found.tsx`. -Projekt — `app/(frontend)/[locale]/not-found.tsx`, jedna linia (od 1.9.2): +Projekt — dwa pliki w `app/(frontend)/[locale]/` (od 1.12.0, **wariant leniwy — zalecany**): -```tsx -import { createNotFoundPage } from '@intecion/ipal-kit/rsc' +```ts +// notFoundView.ts — server action z treścią 404 w JEDNYM języku +'use server' +import { renderNotFoundView } from '@intecion/ipal-kit/rsc' import * as content from '@/lib/content' import { blockRegistry } from '@/blocks/registry' -export default createNotFoundPage(content, { - blocks: blockRegistry, - fallback:

404

, // gdy w panelu nie wybrano strony 404 (albo per język: (locale) => …) - // blockProps: async ({ locale }) => ({ formTexts: await content.getFormTexts(locale), sendForm }), -}) +export async function loadNotFoundView(locale: string) { + return renderNotFoundView(content, { + blocks: blockRegistry, + fallback:

404

, // gdy w panelu nie wybrano strony 404 (albo per język: (locale) => …) + // blockProps: async ({ locale }) => ({ formTexts: await content.getFormTexts(locale), sendForm }), + }, locale) +} +``` +```tsx +// not-found.tsx +import { createNotFoundPage } from '@intecion/ipal-kit/rsc' +import * as content from '@/lib/content' +import { loadNotFoundView } from './notFoundView' + +export default createNotFoundPage(content, { load: loadNotFoundView }) +``` +(`fallback` z JSX → plik `notFoundView.tsx`.) + +**Dlaczego leniwy:** Next wkłada drzewo `not-found` layoutu do danych RSC (`self.__next_f`) **każdej** strony +pod nim — router potrzebuje go do 404 po stronie klienta. Wariant natychmiastowy renderuje tam stronę 404 z panelu +w każdym języku, więc każda strona wiezie ją w HTML (404 = strona główna przy 2 językach: HTML strony głównej +195 → 146 KB gzip, strony kontaktu 153 → 104 KB). W wariancie leniwym w danych jest tylko `` +(`/client`); treść przychodzi z server action dopiero, gdy 404 się wyświetla. Język z adresu (`/en/...`); +`renderNotFoundView` przyjmuje tylko skonfigurowane języki (inne → domyślny). Status 404 bez zmian; treść +pojawia się po hydratacji (strona 404 i tak nie jest indeksowana). + +Wariant natychmiastowy (do 1.11.x jedyny) — treść już w HTML, za cenę rozmiaru każdej strony: +```tsx +export default createNotFoundPage(content, { blocks: blockRegistry, fallback:

404

}) ``` Robi dokładnie to, co pełny plik poniżej (widok dla każdego języka + `LocaleView`, bez `headers()`). diff --git a/src/exports/client.ts b/src/exports/client.ts index 11e7a6a..45d9c74 100644 --- a/src/exports/client.ts +++ b/src/exports/client.ts @@ -76,6 +76,7 @@ export { } from '../modules/i18n/index.js' export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js' export { LocaleView } from '../modules/pages/LocaleView.js' +export { NotFoundLoader } from '../modules/pages/NotFoundLoader.js' export { TableOfContents } from '../modules/richtext/TableOfContents.js' export type { TableOfContentsClassNames, TableOfContentsProps } from '../modules/richtext/TableOfContents.js' export { YouTubeEmbed } from '../modules/storage/YouTubeEmbed.js' diff --git a/src/exports/rsc.ts b/src/exports/rsc.ts index a4a7ecf..92e3a7b 100644 --- a/src/exports/rsc.ts +++ b/src/exports/rsc.ts @@ -18,8 +18,8 @@ export { prepareBuilderForm, publicForm, RenderForm } from '../modules/forms/Ren export type { PrepareBuilderFormArgs, PreparedBuilderForm, RenderFormProps, SendFormAction } from '../modules/forms/RenderForm.js' // Layout wiring + catch-all page + 404 from lib/content helpers (optional — the // pieces stay available for a project that composes them itself). -export { createNotFoundPage, createPageRoute } from '../modules/frontend/pageRoute.js' -export type { NotFoundPageOptions, PageRouteOptions } from '../modules/frontend/pageRoute.js' +export { createNotFoundPage, createPageRoute, renderNotFoundView } from '../modules/frontend/pageRoute.js' +export type { NotFoundPageOptions, NotFoundViewOptions, PageRouteOptions } from '../modules/frontend/pageRoute.js' export { SiteProviders } from '../modules/frontend/SiteProviders.js' export type { SiteProvidersProps } from '../modules/frontend/SiteProviders.js' export { extractHeadings } from '../modules/richtext/headings.js' diff --git a/src/modules/frontend/pageRoute.tsx b/src/modules/frontend/pageRoute.tsx index cfc61b1..7f9fff7 100644 --- a/src/modules/frontend/pageRoute.tsx +++ b/src/modules/frontend/pageRoute.tsx @@ -7,6 +7,7 @@ import type { ContentHelpers, PageJsonLdOptions } from './createContentHelpers.j import { RenderBlocks } from '../blocks/RenderBlocks.js' import { constructionNoticeHref, isPathAllowed } from '../construction/logic.js' import { LocaleView } from '../pages/LocaleView.js' +import { NotFoundLoader } from '../pages/NotFoundLoader.js' import { JsonLdGraph } from '../seo/JsonLdGraph.js' type Helpers = Partial> & Pick< @@ -139,7 +140,7 @@ export function createPageRoute(helpers: Helpers, options: PageRouteOptions) { return { generateMetadata, generateStaticParams: helpers.generateStaticParams, Page } } -export type NotFoundPageOptions = { +type NotFoundViewOptions = { blockProps?: (ctx: BlockPropsContext) => Promise> | Record blocks: BlockComponentMap /** Shown when no 404 page is assigned in Site Settings (or the DB is unreachable). Per locale or one node. */ @@ -147,31 +148,78 @@ export type NotFoundPageOptions = { layoutField?: string } +export type NotFoundPageOptions = + | { + /** + * Lazy 404 (recommended): the project's server action returning + * `renderNotFoundView(content, options, locale)`. Next puts the not-found tree + * into the RSC payload of EVERY page; with `load` that tree is a small loader + * and the content is fetched only when a 404 is shown. Without it every page + * carries the whole 404 page in every locale. + */ + load: (locale: string) => Promise + } + | ({ load?: undefined } & NotFoundViewOptions) + +export type { NotFoundViewOptions } + +type NotFoundHelpers = Pick + +async function localesOf(helpers: NotFoundHelpers): Promise { + const configured = await helpers.getConfiguredLocales() + return configured.length ? configured : [helpers.i18n?.defaultLocale ?? ''] +} + +async function notFoundView(helpers: NotFoundHelpers, options: NotFoundViewOptions, locale: string): Promise { + const { blockProps, blocks, fallback = null, layoutField = 'layout' } = options + const doc = await helpers.getNotFoundPage(locale) + const layout = doc?.[layoutField] as BlockData[] | undefined + if (!doc || !layout?.length) {return typeof fallback === 'function' ? fallback(locale) : fallback} + const extra = blockProps ? await blockProps({ doc, locale }) : {} + return ({ locale, ...extra, isFirst: index === 0 })} /> +} + +/** + * The 404 page from the panel in ONE locale — for the server action behind + * `createNotFoundPage(content, { load })`. The locale comes from the browser, + * so it is checked against the configured locales (anything else → default). + * + * // src/app/(frontend)/[locale]/notFoundView.ts + * 'use server' + * export async function loadNotFoundView(locale: string) { + * return renderNotFoundView(content, { blocks: blockRegistry }, locale) + * } + */ +export async function renderNotFoundView(helpers: NotFoundHelpers, options: NotFoundViewOptions, locale: unknown): Promise { + const locales = await localesOf(helpers) + const safe = typeof locale === 'string' && locales.includes(locale) ? locale : (helpers.i18n?.defaultLocale ?? locales[0]) + return notFoundView(helpers, options, safe) +} + /** * app/(frontend)/[locale]/not-found.tsx — the 404 page from the panel, in the - * visitor's language, WITHOUT headers() (the route stays static): one view per - * locale rendered here, picks the one from the URL. + * visitor's language, WITHOUT headers() (the route stays static). * + * Lazy (recommended) — the content is fetched only when a 404 is shown: * import { createNotFoundPage } from '@intecion/ipal-kit/rsc' + * import { loadNotFoundView } from './notFoundView' + * export default createNotFoundPage(content, { load: loadNotFoundView }) + * + * Eager — one view per locale rendered here, picks the one from the + * URL; Next ships all of them in the payload of every page: * export default createNotFoundPage(content, { blocks: blockRegistry }) */ -export function createNotFoundPage(helpers: Helpers, options: NotFoundPageOptions) { - const { blockProps, blocks, fallback = null, layoutField = 'layout' } = options +export function createNotFoundPage(helpers: NotFoundHelpers, options: NotFoundPageOptions) { return async function NotFoundPage() { - const configured = await helpers.getConfiguredLocales() - const locales = configured.length ? configured : [helpers.i18n?.defaultLocale ?? ''] + const locales = await localesOf(helpers) + const defaultLocale = helpers.i18n?.defaultLocale ?? locales[0] + if (options.load) { + return + } + const eager = options const views = Object.fromEntries( - await Promise.all( - locales.map(async (locale) => { - const doc = await helpers.getNotFoundPage(locale) - const layout = doc?.[layoutField] as BlockData[] | undefined - const fb = typeof fallback === 'function' ? fallback(locale) : fallback - if (!doc || !layout?.length) {return [locale, fb] as const} - const extra = blockProps ? await blockProps({ doc, locale }) : {} - return [locale, ({ locale, ...extra, isFirst: index === 0 })} key={locale} />] as const - }), - ), + await Promise.all(locales.map(async (locale) => [locale, await notFoundView(helpers, eager, locale)] as const)), ) - return + return } } diff --git a/src/modules/pages/LocaleView.tsx b/src/modules/pages/LocaleView.tsx index 3c60882..493dc05 100644 --- a/src/modules/pages/LocaleView.tsx +++ b/src/modules/pages/LocaleView.tsx @@ -5,6 +5,8 @@ import type { ReactNode } from 'react' // Bundlers in the project resolve the same file either way. import { usePathname } from 'next/navigation.js' +import { localeFromPath } from './localeFromPath.js' + type LocaleViewProps = { /** Used when the URL has no locale segment (single-locale site) or an unknown one. */ defaultLocale: string @@ -25,8 +27,6 @@ type LocaleViewProps = { * it also runs during SSR, so the HTML already contains the right language. */ export function LocaleView({ defaultLocale, views }: LocaleViewProps) { - const pathname = usePathname() ?? '' - const segment = pathname.split('/').filter(Boolean)[0] ?? '' - const locale = segment in views ? segment : defaultLocale + const locale = localeFromPath(usePathname() ?? '', Object.keys(views), defaultLocale) return <>{views[locale] ?? views[defaultLocale] ?? null} } diff --git a/src/modules/pages/NotFoundLoader.tsx b/src/modules/pages/NotFoundLoader.tsx new file mode 100644 index 0000000..4bec4a3 --- /dev/null +++ b/src/modules/pages/NotFoundLoader.tsx @@ -0,0 +1,47 @@ +'use client' +import type { ReactNode } from 'react' + +// '.js' is required: `next` has no package.json "exports" (see LocaleView.tsx). +import { usePathname } from 'next/navigation.js' +import { useEffect, useState } from 'react' + +import { localeFromPath } from './localeFromPath.js' + +type NotFoundLoaderProps = { + defaultLocale: string + /** The project's server action: `(locale) => renderNotFoundView(content, options, locale)`. */ + load: (locale: string) => Promise + locales: string[] +} + +/** + * The 404 content, fetched only when the 404 is actually shown. + * + * Next puts the `not-found` tree of a layout into the RSC payload of EVERY page + * under it (the router needs it for a client-side 404). A 404 page with real + * content (often the homepage) rendered there in every locale multiplied the + * size of each page. Here only this small component is in the payload; the + * content comes from a server action on mount. + */ +export function NotFoundLoader({ defaultLocale, load, locales }: NotFoundLoaderProps) { + const pathname = usePathname() ?? '' + const locale = localeFromPath(pathname, locales, defaultLocale) + const [view, setView] = useState<{ locale: string; node: ReactNode } | null>(null) + + useEffect(() => { + let active = true + load(locale) + .then((node) => { + if (active) {setView({ locale, node })} + }) + .catch((error: unknown) => { + // the status is already 404 — without the content the page stays empty, the error goes to the console + console.error('[ipal] NotFoundLoader: the 404 content could not be loaded', error) + }) + return () => { + active = false + } + }, [load, locale]) + + return <>{view?.locale === locale ? view.node : null} +} diff --git a/src/modules/pages/localeFromPath.ts b/src/modules/pages/localeFromPath.ts new file mode 100644 index 0000000..93317fd --- /dev/null +++ b/src/modules/pages/localeFromPath.ts @@ -0,0 +1,8 @@ +/** + * The locale from the first URL segment (`/en/...` → `en`), or `defaultLocale` + * when the segment isn't one of `locales` (single-locale site, unknown prefix). + */ +export function localeFromPath(pathname: string, locales: readonly string[], defaultLocale: string): string { + const segment = pathname.split('/').filter(Boolean)[0] ?? '' + return locales.includes(segment) ? segment : defaultLocale +} diff --git a/test/notFoundPage.test.ts b/test/notFoundPage.test.ts new file mode 100644 index 0000000..a738a84 --- /dev/null +++ b/test/notFoundPage.test.ts @@ -0,0 +1,67 @@ +import { isValidElement, type ReactElement } from 'react' +import { describe, expect, test, vi } from 'vitest' + +vi.mock('next/navigation.js', () => ({ usePathname: () => '/en/missing' })) + +import { createNotFoundPage, renderNotFoundView } from '../src/modules/frontend/pageRoute.js' +import { localeFromPath } from '../src/modules/pages/localeFromPath.js' +import { LocaleView } from '../src/modules/pages/LocaleView.js' +import { NotFoundLoader } from '../src/modules/pages/NotFoundLoader.js' + +const layout = [{ id: '1', blockType: 'hero' }] +const helpers = () => + ({ + getConfiguredLocales: vi.fn(async () => ['pl', 'en']), + getNotFoundPage: vi.fn(async (locale: string) => ({ layout, locale })), + i18n: { defaultLocale: 'pl', locales: [{ code: 'pl' }, { code: 'en' }] }, + }) as never as { getNotFoundPage: ReturnType } & Parameters[0] + +describe('localeFromPath', () => { + test('first segment when it is a locale, default otherwise', () => { + expect(localeFromPath('/en/missing', ['pl', 'en'], 'pl')).toBe('en') + expect(localeFromPath('/de/missing', ['pl', 'en'], 'pl')).toBe('pl') + expect(localeFromPath('', ['pl'], 'pl')).toBe('pl') + }) +}) + +describe('createNotFoundPage', () => { + test('lazy (load): only the loader goes into the payload — no 404 page is read or rendered', async () => { + const h = helpers() + const load = vi.fn(async () => null) + const element = (await createNotFoundPage(h, { load })()) as ReactElement<{ load: unknown; locales: string[] }> + expect(element.type).toBe(NotFoundLoader) + expect(element.props.locales).toEqual(['pl', 'en']) + expect(element.props.load).toBe(load) + expect(h.getNotFoundPage).not.toHaveBeenCalled() + }) + + test('eager (blocks): one view per locale in LocaleView', async () => { + const h = helpers() + const element = (await createNotFoundPage(h, { blocks: {} })()) as ReactElement<{ views: Record }> + expect(element.type).toBe(LocaleView) + expect(Object.keys(element.props.views)).toEqual(['pl', 'en']) + expect(h.getNotFoundPage).toHaveBeenCalledTimes(2) + }) +}) + +describe('renderNotFoundView', () => { + test('renders the requested configured locale', async () => { + const h = helpers() + const node = await renderNotFoundView(h, { blocks: {} }, 'en') + expect(isValidElement(node)).toBe(true) + expect(h.getNotFoundPage).toHaveBeenCalledWith('en') + }) + + test('a locale from the browser outside the configured ones → default locale', async () => { + const h = helpers() + await renderNotFoundView(h, { blocks: {} }, '../admin') + await renderNotFoundView(h, { blocks: {} }, 42) + expect(h.getNotFoundPage.mock.calls).toEqual([['pl'], ['pl']]) + }) + + test('no 404 page in the panel → fallback for that locale', async () => { + const h = helpers() + h.getNotFoundPage.mockResolvedValueOnce(null) + expect(await renderNotFoundView(h, { blocks: {}, fallback: (locale) => `missing:${locale}` }, 'en')).toBe('missing:en') + }) +})