Files
ipal-kit/src/modules/frontend/pageRoute.tsx
T

247 lines
12 KiB
TypeScript

import type { ReactNode } from 'react'
import type { BlockComponentMap, BlockData } from '../blocks/types.js'
import type { ResolvedRoute } from '../content/index.js'
import type { ContentHelpers, PageJsonLdOptions } from './createContentHelpers.js'
import { blockPosition } from '../blocks/position.js'
import { RenderBlocks } from '../blocks/RenderBlocks.js'
import { constructionNoticeHref, isPathVisibleIn } 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<ContentHelpers, 'getConstructionMode' | 'getHomeSlug' | 'getSystemLinks'>> & Pick<
ContentHelpers,
'generatePageMetadata' | 'generateStaticParams' | 'getConfiguredLocales' | 'getNotFoundPage' | 'getPageJsonLd' | 'i18n' | 'resolvePageRedirect' | 'resolveRoute'
>
type BlockPropsContext = { doc: Record<string, unknown>; locale: string }
export type PageRouteOptions = {
/**
* Props for every block on top of `locale`, `isFirst` (true for the first
* section — its heading is the page's only h1) and `firstImage` (no block before it
* shows an image — its first image is the LCP image, blockPosition), computed once per page —
* e.g. `{ formTexts, sendForm }` for form blocks.
*/
blockProps?: (ctx: BlockPropsContext) => Promise<Record<string, unknown>> | Record<string, unknown>
/** blockType → component (the project's registry). */
blocks: BlockComponentMap
/**
* The homepage opened under its own slug (/pl/home): 'redirect' (default) — 308 to the
* locale root, one URL per page (canonical already points there; Search Console reports
* the alias as a duplicate otherwise). `false` — render it like any page.
*/
homeAlias?: 'redirect' | false
/** Per-page JSON-LD (WebPage, breadcrumbs, FAQ…). Default true; options as getPageJsonLd. */
jsonLd?: boolean | PageJsonLdOptions
/** Field with the blocks. Default 'layout'. */
layoutField?: string
/** `notFound` from 'next/navigation' — injected, the plugin doesn't import next/* on the server. */
notFound: () => never
/**
* An address with no page (and no old-slug redirect):
* - 'notFound' (default) — the 404 page;
* - 'redirectHome' — 307 to the homepage in the same language (System Pages → Homepage;
* needs `redirect`). No homepage assigned, or the homepage itself missing → 404;
* - a function — your own decision, e.g. `({ locale }) => redirect(\`/${locale}/kontakt\`)`.
*/
onMissing?: 'notFound' | 'redirectHome' | ((ctx: { locale: string; segments: string[] }) => never | Promise<never>)
/** `permanentRedirect` from 'next/navigation' (308 for an old slug). */
permanentRedirect: (url: string) => never
/**
* `redirect` from 'next/navigation' — enables Site Settings → Under construction:
* pages that aren't available (and unknown addresses) go to the homepage with the notice.
*/
redirect?: (url: string) => never
/**
* Render a route yourself — an archive listing, a blog entry template.
* Return undefined to keep the default (the document's blocks).
*/
render?: (ctx: { blocks: ReactNode; locale: string; route: ResolvedRoute; segments: string[] }) => Promise<ReactNode | undefined> | ReactNode | undefined
}
type PageArgs = { params: Promise<{ locale?: string; slug?: string[] }> }
/**
* The catch-all page — route resolution, old-slug 308, 404, metadata, static
* params, per-page JSON-LD and the blocks — from one call:
*
* // src/app/(frontend)/[locale]/[[...slug]]/page.tsx
* import { notFound, permanentRedirect } from 'next/navigation'
* import { createPageRoute } from '@intecion/ipal-kit/rsc'
* import * as content from '@/lib/content'
* import { blockRegistry } from '@/blocks/registry'
*
* export const revalidate = 3600 // must stay a literal in the file (Next reads it statically)
* const route = createPageRoute(content, { blocks: blockRegistry, notFound, permanentRedirect })
* export default route.Page
* export const generateMetadata = route.generateMetadata
* export const generateStaticParams = route.generateStaticParams
*
* Archive listings / entry templates: `render`. Anything else: write the page
* yourself with the same helpers (PROGRAMISTA §2.8) — nothing here is required.
*/
export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
const { blockProps, blocks, homeAlias = 'redirect', jsonLd = true, layoutField = 'layout', notFound, onMissing = 'notFound', permanentRedirect, redirect, render } = options
if (onMissing === 'redirectHome' && !redirect) {
throw new Error("[iapl] createPageRoute: onMissing: 'redirectHome' needs `redirect` from 'next/navigation'.")
}
const localeOf = (locale: string | undefined) => {
const l = locale ?? helpers.i18n?.defaultLocale
if (!l) {throw new Error('[iapl] createPageRoute: no locale param and no i18n.defaultLocale in createContentHelpers.')}
return l
}
async function generateMetadata({ params }: PageArgs) {
const { slug, locale } = await params
return helpers.generatePageMetadata(localeOf(locale), slug)
}
async function missing(locale: string, segments: string[]): Promise<never> {
if (typeof onMissing === 'function') {return onMissing({ locale, segments })}
// segments.length: the homepage itself is missing — redirecting to it would loop.
if (onMissing === 'redirectHome' && redirect && helpers.getSystemLinks && segments.length) {
const [home] = await helpers.getSystemLinks(locale, ['homepage'])
if (home?.href) {return redirect(home.href)}
}
return notFound()
}
async function Page({ params }: PageArgs) {
const { slug, locale: param } = await params
const locale = localeOf(param)
const segments = slug ?? []
// Under construction: anything but the homepage and the chosen pages → homepage + notice
if (redirect && helpers.getConstructionMode) {
const construction = await helpers.getConstructionMode(locale)
const multilingual = (helpers.i18n?.locales.length ?? 0) > 1
const path = `/${[...(multilingual ? [locale] : []), ...segments].join('/')}`
if (!isPathVisibleIn(construction, path)) {return redirect(constructionNoticeHref(construction.homePath))}
}
const route = await helpers.resolveRoute(locale, segments, 1)
if (!route) {
const target = await helpers.resolvePageRedirect(locale, segments)
if (target) {return permanentRedirect(target)}
return missing(locale, segments)
}
if (homeAlias === 'redirect' && route.type !== 'home' && segments.length && helpers.getHomeSlug) {
const homeSlug = await helpers.getHomeSlug(locale)
if (homeSlug && segments.join('/') === homeSlug) {
const [home] = helpers.getSystemLinks ? await helpers.getSystemLinks(locale, ['homepage']) : []
const multilingual = (helpers.i18n?.locales.length ?? 0) > 1
return permanentRedirect(home?.href ?? (multilingual ? `/${locale}` : '/'))
}
}
const doc = route.doc
const extra = blockProps ? await blockProps({ doc, locale }) : {}
const rendered = (
<RenderBlocks
blocks={doc[layoutField] as BlockData[] | undefined}
components={blocks}
enhanceProps={(at) => ({ locale, ...extra, ...blockPosition(at) })}
/>
)
const custom = render ? await render({ blocks: rendered, locale, route, segments }) : undefined
const schemas = jsonLd ? await helpers.getPageJsonLd(locale, slug, jsonLd === true ? {} : jsonLd) : []
return (
<>
{schemas.length ? <JsonLdGraph schemas={schemas} /> : null}
{custom ?? rendered}
</>
)
}
return { generateMetadata, generateStaticParams: helpers.generateStaticParams, Page }
}
type NotFoundViewOptions = {
blockProps?: (ctx: BlockPropsContext) => Promise<Record<string, unknown>> | Record<string, unknown>
blocks: BlockComponentMap
/** Shown when no 404 page is assigned in Site Settings (or the DB is unreachable). Per locale or one node. */
fallback?: ((locale: string) => ReactNode) | ReactNode
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<ReactNode>
/**
* What the lazy 404 shows until its content arrives (default nothing). A block as tall as the site's 404
* content keeps the footer from moving when the content comes in (no layout shift, docs/performance.md).
*/
placeholder?: ReactNode
}
| ({ load?: undefined } & NotFoundViewOptions)
export type { NotFoundViewOptions }
type NotFoundHelpers = Pick<ContentHelpers, 'getConfiguredLocales' | 'getNotFoundPage' | 'i18n'>
async function localesOf(helpers: NotFoundHelpers): Promise<string[]> {
const configured = await helpers.getConfiguredLocales()
return configured.length ? configured : [helpers.i18n?.defaultLocale ?? '']
}
async function notFoundView(helpers: NotFoundHelpers, options: NotFoundViewOptions, locale: string): Promise<ReactNode> {
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 <RenderBlocks blocks={layout} components={blocks} enhanceProps={(at) => ({ locale, ...extra, ...blockPosition(at) })} />
}
/**
* 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<ReactNode> {
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).
*
* 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, <LocaleView> 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: NotFoundHelpers, options: NotFoundPageOptions) {
return async function NotFoundPage() {
const locales = await localesOf(helpers)
const defaultLocale = helpers.i18n?.defaultLocale ?? locales[0]
if (options.load) {
return <NotFoundLoader defaultLocale={defaultLocale} load={options.load} locales={locales} placeholder={options.placeholder} />
}
const eager = options
const views = Object.fromEntries(
await Promise.all(locales.map(async (locale) => [locale, await notFoundView(helpers, eager, locale)] as const)),
)
return <LocaleView defaultLocale={defaultLocale} views={views} />
}
}