Import instead of code: panel forms (steps, choice lists, dates), layout, page route, GEO routes, links, section fields
- Forms: step and checkboxGroup field types (radio, date on), server validation for them, useBuilderForm (logic) + BuilderForm (unstyled default) + RenderForm (/rsc: rich text, bound action, public part of the form only — the Emails tab never reaches the browser) - Notifications: next / back / stepOf texts - createContentHelpers: getSiteShell, getFormTexts, getLinkOptions, resolveLink, resolveNav, resolvePageRedirect, one-line route handlers (llms, llms-full, md, mcp, health, indexnow, manifest) - /rsc: SiteProviders, createPageRoute, createNotFoundPage - resolveLink / resolveNav / homeSlugFrom, buildSectionHeaderField / buildSectionSettingsField - Dev sandbox frontend built on these imports; tests (unit + real Payload) Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
import type { AnalyticsProps } from '../analytics/Analytics.js'
|
||||
import type { ConsentCookieMap } from '../consent/useConsent.js'
|
||||
import type { SiteShell } from './createContentHelpers.js'
|
||||
|
||||
import { Analytics } from '../analytics/Analytics.js'
|
||||
import { ConsentProvider } from '../consent/ConsentContext.js'
|
||||
import { CookieBanner } from '../consent/CookieBanner.js'
|
||||
import { CookieButton } from '../consent/CookieButton.js'
|
||||
import { JsonLdGraph } from '../seo/JsonLdGraph.js'
|
||||
import { MediaPreconnect } from '../storage/MediaPreconnect.js'
|
||||
import { TurnstileProvider } from '../turnstile/TurnstileProvider.js'
|
||||
|
||||
export type SiteProvidersProps = {
|
||||
/** `defer` etc. for <Analytics>; `false` = no analytics tags at all. */
|
||||
analytics?: false | Omit<AnalyticsProps, keyof SiteShell['analytics']>
|
||||
/** The cookie banner. Default `<CookieBanner />`; pass your own configured one (`equalChoice`, classNames) or `false`. */
|
||||
banner?: false | ReactNode
|
||||
children: ReactNode
|
||||
/** The "cookie settings" button. Default `<CookieButton />`; your own or `false`. */
|
||||
cookieButton?: false | ReactNode
|
||||
/** Extra cookies per category to delete when consent is withdrawn. */
|
||||
cookieMap?: ConsentCookieMap
|
||||
/** More site-wide JSON-LD nodes next to shell.jsonLd (e.g. buildNavigationJsonLd). */
|
||||
jsonLd?: (null | Record<string, unknown> | undefined)[]
|
||||
/** Consent log endpoint, e.g. '/api/ipal/consent' (ipalKit consentLog: true). */
|
||||
logEndpoint?: string
|
||||
/** <link rel=preconnect> to the media origin (R2_PUBLIC_URL). Default true. */
|
||||
preconnect?: boolean
|
||||
/** getSiteShell(locale) from lib/content. */
|
||||
shell: SiteShell
|
||||
}
|
||||
|
||||
/**
|
||||
* The wiring every [locale] layout repeats — consent, Turnstile, analytics,
|
||||
* site JSON-LD, media preconnect — in the right order (Analytics inside the
|
||||
* consent provider, forms inside Turnstile). Renders no markup of its own:
|
||||
* <html>, <body>, header, footer and <main> stay in the layout.
|
||||
*
|
||||
* const shell = await getSiteShell(locale)
|
||||
* <body>
|
||||
* <SiteProviders shell={shell} logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice />}>
|
||||
* <Header … /><main>{children}</main><Footer … />
|
||||
* </SiteProviders>
|
||||
* </body>
|
||||
*
|
||||
* Every part is replaceable or switchable off; for a fully custom tree use the
|
||||
* providers themselves (consent.md, turnstile.md) — the shell data still fits.
|
||||
*/
|
||||
export function SiteProviders({
|
||||
analytics,
|
||||
banner,
|
||||
children,
|
||||
cookieButton,
|
||||
cookieMap,
|
||||
jsonLd = [],
|
||||
logEndpoint,
|
||||
preconnect = true,
|
||||
shell,
|
||||
}: SiteProvidersProps) {
|
||||
return (
|
||||
<>
|
||||
{preconnect ? <MediaPreconnect /> : null}
|
||||
<JsonLdGraph schemas={[...shell.jsonLd, ...jsonLd]} />
|
||||
<ConsentProvider cookieMap={cookieMap} logEndpoint={logEndpoint} texts={shell.consent}>
|
||||
<TurnstileProvider siteKey={shell.turnstileSiteKey}>{children}</TurnstileProvider>
|
||||
{banner === undefined ? <CookieBanner /> : banner || null}
|
||||
{cookieButton === undefined ? <CookieButton /> : cookieButton || null}
|
||||
{analytics === false ? null : <Analytics {...shell.analytics} {...analytics} />}
|
||||
</ConsentProvider>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -3,14 +3,32 @@ import type { BasePayload, SanitizedConfig } from 'payload'
|
||||
import { getPayload } from 'payload'
|
||||
import { cache } from 'react'
|
||||
|
||||
import type { AnalyticsConfig } from '../analytics/types.js'
|
||||
import type { ConsentTexts } from '../consent/texts.js'
|
||||
import type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/index.js'
|
||||
import type { I18nConfig } from '../i18n/index.js'
|
||||
import type { LinkValue, NavItem, ResolvedLink, ResolveLinkHrefOptions } from '../links/index.js'
|
||||
import type { CreateMcpRouteArgs } from '../mcp/createMcpRoute.js'
|
||||
import type { FormNotificationTexts } from '../notifications/types.js'
|
||||
import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry, SitemapStyleOptions } from '../seo/index.js'
|
||||
|
||||
import { getAnalyticsConfig } from '../analytics/getAnalyticsConfig.js'
|
||||
import { getConsentTexts } from '../consent/getConsentTexts.js'
|
||||
import { createMarkdownRoute } from '../content/createMarkdownRenderer.js'
|
||||
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js'
|
||||
import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js'
|
||||
import { resolveRedirect as resolveRedirectRaw } from '../content/resolveRedirect.js'
|
||||
import { createHealthRoute } from '../health/createHealthRoute.js'
|
||||
import { homeSlugFrom, resolveLink as resolveLinkRaw, resolveNav as resolveNavRaw } from '../links/resolveNav.js'
|
||||
import { createMcpRoute } from '../mcp/createMcpRoute.js'
|
||||
import { getNotificationTexts } from '../notifications/getNotificationTexts.js'
|
||||
import { buildOrganizationJsonLd, sameAsUrls } from '../seo/buildOrganizationJsonLd.js'
|
||||
import { buildWebPageJsonLd } from '../seo/buildWebPageJsonLd.js'
|
||||
import { buildArticleJsonLd, buildBreadcrumbJsonLd, buildFaqJsonLd, buildRobots, buildSitemapEntries, createPageMetadata, createSitemapRouteHandler } from '../seo/index.js'
|
||||
import { buildWebSiteJsonLd } from '../seo/buildWebSiteJsonLd.js'
|
||||
import { buildArticleJsonLd, buildBreadcrumbJsonLd, buildFaqJsonLd, buildRobots, buildSitemapEntries, createManifestHandler, createPageMetadata, createSitemapRouteHandler } from '../seo/index.js'
|
||||
import { createIndexNowKeyRoute } from '../seo/indexNow.js'
|
||||
import { createLlmsTxtRoute } from '../seo/routeHandlers.js'
|
||||
import { getTurnstileConfig } from '../turnstile/config.js'
|
||||
|
||||
type CreateContentHelpersArgs = {
|
||||
/**
|
||||
@@ -31,6 +49,8 @@ type CreateContentHelpersArgs = {
|
||||
* handlers — they need the locale list to emit hreflang.
|
||||
*/
|
||||
i18n?: I18nConfig
|
||||
/** Markdown route (`markdownRoute`): per-block overrides, frontmatter, layout field. */
|
||||
markdown?: { frontmatter?: boolean; layoutField?: string; overrides?: Record<string, (block: Record<string, unknown>) => string> }
|
||||
/**
|
||||
* Advertise each page's Markdown version from generatePageMetadata:
|
||||
* `<link rel="alternate" type="text/markdown" href="/md/pl/o-nas">` (GEO —
|
||||
@@ -39,10 +59,14 @@ type CreateContentHelpersArgs = {
|
||||
* (content.md). Indexable pages only.
|
||||
*/
|
||||
markdownAlternate?: boolean | string
|
||||
/** MCP route (`mcpRoute`): server name/version, rate limit, batch size. */
|
||||
mcp?: Pick<CreateMcpRouteArgs, 'clientIp' | 'maxBatch' | 'rateLimit' | 'serverName' | 'serverVersion'>
|
||||
/** Defaults for getPageJsonLd — each call can override them. */
|
||||
pageJsonLd?: PageJsonLdOptions
|
||||
/** Pages collection slug. Defaults to 'pages'. */
|
||||
pagesSlug?: string
|
||||
/** Collections checked for an old slug before a 404 (`resolvePageRedirect`). Default pages. */
|
||||
redirectCollections?: { historyField?: string; slug: string; slugField?: string }[]
|
||||
/**
|
||||
* Options for the ready-made `robots` handler, e.g.
|
||||
* `{ disallowParams: ['s', 'meter'], aiBots: 'block-training' }`, or
|
||||
@@ -51,6 +75,13 @@ type CreateContentHelpersArgs = {
|
||||
robots?: RobotsOptions
|
||||
/** SiteSettings global slug. Defaults to 'site-settings'. */
|
||||
settingsSlug?: string
|
||||
/**
|
||||
* Site-wide JSON-LD for `getSiteShell` (layout). Default: WebSite + Organization
|
||||
* from Site Settings (siteName, logo, sameAs) — skipped when the name or the
|
||||
* origin is missing, never a fallback name. A function replaces it (e.g.
|
||||
* LocalBusiness from the Company global); `false` = none.
|
||||
*/
|
||||
siteJsonLd?: ((ctx: { baseUrl: string; locale: string; settings: Record<string, unknown> }) => Promise<Record<string, unknown>[]> | Record<string, unknown>[]) | false
|
||||
/** Image URLs of a document for the sitemap (Google Images). Default: its SEO share image. */
|
||||
sitemapImages?: (doc: Record<string, unknown>) => (null | string | undefined)[]
|
||||
/**
|
||||
@@ -58,6 +89,8 @@ type CreateContentHelpersArgs = {
|
||||
* header "XML Sitemap", credit "Technology by Intecion.com". `false` = raw XML.
|
||||
*/
|
||||
sitemapStyle?: false | SitemapStyleOptions
|
||||
/** Field with the AI summary (buildSummaryField) — llms.txt and MCP prefer it. */
|
||||
summaryField?: string
|
||||
}
|
||||
|
||||
export type PageJsonLdOptions = {
|
||||
@@ -105,13 +138,18 @@ export function createContentHelpers({
|
||||
config,
|
||||
content,
|
||||
i18n,
|
||||
markdown: markdownOptions,
|
||||
markdownAlternate,
|
||||
mcp: mcpOptions,
|
||||
pageJsonLd: pageJsonLdDefaults,
|
||||
pagesSlug = 'pages',
|
||||
redirectCollections,
|
||||
robots: robotsOptions,
|
||||
settingsSlug = 'site-settings',
|
||||
siteJsonLd,
|
||||
sitemapImages,
|
||||
sitemapStyle,
|
||||
summaryField,
|
||||
}: CreateContentHelpersArgs) {
|
||||
const origin = baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? ''
|
||||
const getCachedPayload = cache(
|
||||
@@ -522,18 +560,157 @@ export function createContentHelpers({
|
||||
*/
|
||||
const sitemapRoute = createSitemapRouteHandler(sitemap, { style: sitemapStyle ?? {} })
|
||||
|
||||
const needI18n = (what: string): I18nConfig => {
|
||||
if (!i18n) {throw new Error(`[ipal] createContentHelpers: pass \`i18n\` to use ${what}.`)}
|
||||
return i18n
|
||||
}
|
||||
|
||||
// ── Links & navigation ────────────────────────────────────────────────────
|
||||
/** Homepage slug in this locale (SiteSettings.homepage) — links to it collapse to /{locale}. */
|
||||
const getHomeSlug = async (locale: string) => homeSlugFrom(await getSettings(locale))
|
||||
|
||||
/** Options for resolveLinkHref / resolveLink / RenderForm `linkOptions` in this locale. */
|
||||
const getLinkOptions = async (locale: string): Promise<ResolveLinkHrefOptions> => {
|
||||
const homeSlug = await getHomeSlug(locale)
|
||||
return { config: needI18n('getLinkOptions'), locale, ...(homeSlug ? { homeSlug } : {}) }
|
||||
}
|
||||
|
||||
/**
|
||||
* A panel link → `{ href, label, internal, newTab, targetProps, appearance }`
|
||||
* or null. The project's CMSLink only picks the element and the classes.
|
||||
*/
|
||||
const resolveLink = async (link: LinkValue | null | undefined, locale: string): Promise<null | ResolvedLink> =>
|
||||
resolveLinkRaw(link, await getLinkOptions(locale))
|
||||
|
||||
/** Menu items of a Header/Footer global → serializable NavItem[] (pass to a client MobileNav as is). */
|
||||
const resolveNav = async (items: unknown, locale: string, options: { childrenField?: string; linkField?: string } = {}): Promise<NavItem[]> =>
|
||||
resolveNavRaw(items, { ...(await getLinkOptions(locale)), ...options })
|
||||
|
||||
/** Old slug → its new URL (308), for the catch-all page before notFound(). */
|
||||
const resolvePageRedirect = async (locale: string, segments: string[] | undefined): Promise<null | string> =>
|
||||
resolveRedirectRaw({
|
||||
collections: redirectCollections,
|
||||
config: needI18n('resolvePageRedirect'),
|
||||
homeSlug: await getHomeSlug(locale),
|
||||
locale,
|
||||
payload: await getCachedPayload(),
|
||||
segments,
|
||||
})
|
||||
|
||||
// ── Layout ────────────────────────────────────────────────────────────────
|
||||
/** Notifications → form texts in this locale (BuilderForm / RenderForm `texts`). */
|
||||
const getFormTexts = cache(async (locale: string): Promise<FormNotificationTexts> =>
|
||||
(await getNotificationTexts({ locale, payload: await getCachedPayload() })).form,
|
||||
)
|
||||
|
||||
/**
|
||||
* Everything the [locale] layout reads, in one cached call: consent texts,
|
||||
* analytics IDs, Turnstile site key, site JSON-LD, form texts and Site
|
||||
* Settings. Feed it to <SiteProviders> (/rsc) — or use the pieces yourself.
|
||||
*/
|
||||
const getSiteShell = cache(async (locale: string): Promise<SiteShell> => {
|
||||
const payload = await getCachedPayload()
|
||||
const [consent, analytics, turnstile, settings, formTexts] = await Promise.all([
|
||||
getConsentTexts({ config: needI18n('getSiteShell'), locale, payload, settingsSlug }),
|
||||
getAnalyticsConfig(payload),
|
||||
getTurnstileConfig(payload),
|
||||
getSettings(locale) as Promise<Record<string, unknown>>,
|
||||
getFormTexts(locale),
|
||||
])
|
||||
let jsonLd: Record<string, unknown>[] = []
|
||||
if (typeof siteJsonLd === 'function') {
|
||||
jsonLd = await siteJsonLd({ baseUrl: origin, locale, settings: settings ?? {} })
|
||||
} else if (siteJsonLd !== false) {
|
||||
const name = typeof settings?.siteName === 'string' && settings.siteName.trim() ? settings.siteName.trim() : undefined
|
||||
if (name && origin) {
|
||||
jsonLd = [
|
||||
buildWebSiteJsonLd({ name, url: origin }),
|
||||
buildOrganizationJsonLd({ name, logo: settings.logo as never, sameAs: sameAsUrls(settings), url: origin }),
|
||||
]
|
||||
}
|
||||
}
|
||||
return {
|
||||
analytics,
|
||||
consent,
|
||||
formTexts,
|
||||
jsonLd: jsonLd.map(({ '@context': _context, ...node }) => node),
|
||||
settings: settings ?? {},
|
||||
turnstileSiteKey: turnstile.siteKey,
|
||||
}
|
||||
})
|
||||
|
||||
// ── Ready route handlers (one line per route file) ────────────────────────
|
||||
// Created on first request, so a project that doesn't use one pays nothing
|
||||
// and a missing option only fails the route that needs it.
|
||||
const lazy = <T>(make: () => T) => {
|
||||
let value: T | undefined
|
||||
return () => (value ??= make())
|
||||
}
|
||||
const llms = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsRoute'), content, getCachedPayload, pagesSlug, settingsSlug, summaryField }))
|
||||
const llmsFull = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsFullRoute'), content, full: true, getCachedPayload, pagesSlug, settingsSlug, summaryField }))
|
||||
const md = lazy(() => createMarkdownRoute({ baseUrl: origin || undefined, collection: pagesSlug, config: i18n, content, getCachedPayload, settingsSlug, ...markdownOptions }))
|
||||
const mcp = lazy(() => createMcpRoute({ baseUrl: origin, collection: pagesSlug, config: needI18n('mcpRoute'), content, getCachedPayload, settingsSlug, summaryField, ...mcpOptions }))
|
||||
const health = lazy(() => createHealthRoute({ collection: pagesSlug, getCachedPayload }))
|
||||
const indexNowKey = lazy(() => createIndexNowKeyRoute({ getCachedPayload }))
|
||||
const manifestHandler = lazy(() => createManifestHandler({ config: needI18n('manifest'), getCachedPayload, settingsSlug }))
|
||||
|
||||
/** app/llms.txt/route.ts: `export { llmsRoute as GET } from '@/lib/content'` */
|
||||
const llmsRoute = () => llms()()
|
||||
/** app/llms-full.txt/route.ts: `export { llmsFullRoute as GET } from '@/lib/content'` */
|
||||
const llmsFullRoute = () => llmsFull()()
|
||||
/** app/md/[locale]/[[...slug]]/route.ts: `export { markdownRoute as GET } from '@/lib/content'` */
|
||||
const markdownRoute = (req: Request, ctx: { params: Promise<{ locale: string; slug?: string[] }> }) => md().GET(req, ctx)
|
||||
/** app/api/mcp/route.ts: `export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'` */
|
||||
const mcpGET = () => mcp().GET()
|
||||
const mcpPOST = (req: Request) => mcp().POST(req)
|
||||
/** app/api/health/route.ts: `export { healthRoute as GET } from '@/lib/content'` */
|
||||
const healthRoute = () => health()()
|
||||
/** app/indexnow-key.txt/route.ts: `export { indexNowKeyRoute as GET } from '@/lib/content'` */
|
||||
const indexNowKeyRoute = () => indexNowKey()()
|
||||
/** app/manifest.ts: `export { manifest as default } from '@/lib/content'` */
|
||||
const manifest = () => manifestHandler()()
|
||||
|
||||
return {
|
||||
generatePageMetadata,
|
||||
generateStaticParams,
|
||||
getCachedPayload,
|
||||
getConfiguredLocales,
|
||||
getEntries,
|
||||
getFormTexts,
|
||||
getHomeSlug,
|
||||
getLinkOptions,
|
||||
getNotFoundPage,
|
||||
getPageJsonLd,
|
||||
getSettings,
|
||||
getSiteShell,
|
||||
healthRoute,
|
||||
i18n,
|
||||
indexNowKeyRoute,
|
||||
llmsFullRoute,
|
||||
llmsRoute,
|
||||
manifest,
|
||||
markdownRoute,
|
||||
mcpGET,
|
||||
mcpPOST,
|
||||
resolveLink,
|
||||
resolveNav,
|
||||
resolvePageRedirect,
|
||||
resolveRoute,
|
||||
robots,
|
||||
sitemap,
|
||||
sitemapRoute,
|
||||
}
|
||||
}
|
||||
|
||||
/** What the layout needs — getSiteShell(locale). Plain data, safe to pass to client components. */
|
||||
export type SiteShell = {
|
||||
analytics: AnalyticsConfig
|
||||
consent: ConsentTexts
|
||||
formTexts: FormNotificationTexts
|
||||
/** Site-wide nodes (WebSite, Organization…) for <JsonLdGraph>. */
|
||||
jsonLd: Record<string, unknown>[]
|
||||
settings: Record<string, unknown>
|
||||
turnstileSiteKey: null | string
|
||||
}
|
||||
|
||||
export type ContentHelpers = ReturnType<typeof createContentHelpers>
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
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 { RenderBlocks } from '../blocks/RenderBlocks.js'
|
||||
import { LocaleView } from '../pages/LocaleView.js'
|
||||
import { JsonLdGraph } from '../seo/JsonLdGraph.js'
|
||||
|
||||
type Helpers = 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`, 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
|
||||
/** 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
|
||||
/** `permanentRedirect` from 'next/navigation' (308 for an old slug). */
|
||||
permanentRedirect: (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, jsonLd = true, layoutField = 'layout', notFound, permanentRedirect, render } = options
|
||||
const localeOf = (locale: string | undefined) => {
|
||||
const l = locale ?? helpers.i18n?.defaultLocale
|
||||
if (!l) {throw new Error('[ipal] 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 Page({ params }: PageArgs) {
|
||||
const { slug, locale: param } = await params
|
||||
const locale = localeOf(param)
|
||||
const segments = slug ?? []
|
||||
const route = await helpers.resolveRoute(locale, segments, 1)
|
||||
if (!route) {
|
||||
const target = await helpers.resolvePageRedirect(locale, segments)
|
||||
return target ? permanentRedirect(target) : notFound()
|
||||
}
|
||||
const doc = route.doc
|
||||
const extra = blockProps ? await blockProps({ doc, locale }) : {}
|
||||
const rendered = (
|
||||
<RenderBlocks
|
||||
blocks={doc[layoutField] as BlockData[] | undefined}
|
||||
components={blocks}
|
||||
enhanceProps={() => ({ locale, ...extra })}
|
||||
/>
|
||||
)
|
||||
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 }
|
||||
}
|
||||
|
||||
export type NotFoundPageOptions = {
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, <LocaleView> picks the one from the URL.
|
||||
*
|
||||
* import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
|
||||
* export default createNotFoundPage(content, { blocks: blockRegistry })
|
||||
*/
|
||||
export function createNotFoundPage(helpers: Helpers, options: NotFoundPageOptions) {
|
||||
const { blockProps, blocks, fallback = null, layoutField = 'layout' } = options
|
||||
return async function NotFoundPage() {
|
||||
const configured = await helpers.getConfiguredLocales()
|
||||
const locales = configured.length ? configured : [helpers.i18n?.defaultLocale ?? '']
|
||||
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, <RenderBlocks blocks={layout} components={blocks} enhanceProps={() => ({ locale, ...extra })} key={locale} />] as const
|
||||
}),
|
||||
),
|
||||
)
|
||||
return <LocaleView defaultLocale={helpers.i18n?.defaultLocale ?? locales[0]} views={views} />
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user