Added richtext support, and helpers for proxy, llms route

This commit is contained in:
2026-10-09 16:44:28 +02:00
parent cca2b20c3d
commit c738435fe0
51 changed files with 934 additions and 11 deletions
+6
View File
@@ -4,6 +4,7 @@ import { useEffect, useState } from 'react'
import { CONSENT_CATEGORIES, type ConsentCategory } from './categories.js'
import { useConsentContext } from './ConsentContext.js'
import { useIsMounted } from './useIsMounted.js'
/**
* Optional class overrides — for when tokens aren't enough, e.g. turning the
@@ -53,6 +54,7 @@ const mutedText =
'text-[var(--ipal-text-muted,#737373)] dark:text-[var(--ipal-text-muted-dark,#a3a3a3)]'
export function CookieBanner({ classNames }: { classNames?: CookieBannerClassNames } = {}) {
const isMounted = useIsMounted()
const { acceptAll, decided, rejectAll, savePreferences, state, texts } = useConsentContext()
const [showSettings, setShowSettings] = useState(false)
const [choices, setChoices] = useState<Record<ConsentCategory, boolean>>(state)
@@ -61,6 +63,10 @@ export function CookieBanner({ classNames }: { classNames?: CookieBannerClassNam
setChoices(state)
}, [state])
// Render nothing until mounted — avoids the React 19 hydration mismatch that
// projects used to work around with a setTimeout ConsentWrapper. No wrapper
// needed now.
if (!isMounted) {return null}
if (decided) {return null}
const toggle = (cat: ConsentCategory) => {
+5
View File
@@ -2,6 +2,7 @@
import { Cookie } from 'lucide-react'
import { useConsentContext } from './ConsentContext.js'
import { useIsMounted } from './useIsMounted.js'
/**
* Floating "cookie settings" button — lets visitors reopen the consent panel
@@ -14,8 +15,12 @@ import { useConsentContext } from './ConsentContext.js'
* replace the styling outright.
*/
export function CookieButton({ className }: { className?: string } = {}) {
const isMounted = useIsMounted()
const { decided, reopen } = useConsentContext()
// Render nothing until mounted — prevents hydration mismatch (no project
// ConsentWrapper workaround needed).
if (!isMounted) {return null}
if (!decided) {return null}
const cls =
+1
View File
@@ -18,3 +18,4 @@ export {
serializeConsent,
} from './storage.js'
export type { ConsentTexts } from './texts.js'
export { useIsMounted } from './useIsMounted.js'
+17
View File
@@ -0,0 +1,17 @@
'use client'
import { useEffect, useState } from 'react'
/**
* Returns true only after the component has mounted on the client. Used to gate
* consent UI (CookieBanner, CookieButton) so it renders nothing during SSR /
* first paint — preventing the React 19 / Next hydration mismatch that projects
* were working around with their own setTimeout-based ConsentWrapper. Built into
* the components now, so no project wrapper is needed.
*/
export function useIsMounted(): boolean {
const [mounted, setMounted] = useState(false)
useEffect(() => {
setMounted(true)
}, [])
return mounted
}
+92
View File
@@ -0,0 +1,92 @@
import type { I18nConfig } from './types.js'
import { isValidLocale } from './helpers.js'
import { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMiddleware.js'
/** Re-exported so the project's proxy.ts config uses the plugin's matcher. */
export const DEFAULT_PROXY_MATCHER = DEFAULT_MIDDLEWARE_MATCHER
/**
* Minimal structural types — the plugin does NOT import next/server (it's a peer
* dep not present at the plugin's own build time, which would cause TS2307).
* Next's real NextRequest / NextResponse satisfy these shapes at the call site.
*/
type ProxyRequest = {
cookies: { get: (name: string) => { value: string } | undefined }
// Matches localeMiddleware's MiddlewareRequest shape; a real NextRequest
// satisfies all of this structurally.
headers: Headers
nextUrl: { clone: () => URL; pathname: string; search: string }
url: string
}
type ProxyResponse = {
cookies: { set: (name: string, value: string, opts?: Record<string, unknown>) => void }
}
/**
* Next's NextResponse constructor, injected by the project (which has next/server
* in scope). The plugin stays free of a next/server import.
*/
type NextResponseLike = {
next: (init?: { request?: { headers: Headers } }) => ProxyResponse
redirect: (url: string | URL) => ProxyResponse
}
type CreateProxyOptions = {
consentCategory?: 'functional' | 'necessary'
consentCookieName?: string
cookieName?: string
/** Expose x-locale / x-pathname request headers to RSC. Default true. */
exposeHeaders?: boolean
}
/**
* Ready-made Next 16 proxy (the former middleware). Wraps the plugin's locale
* logic AND the per-project boilerplate (NextResponse, x-locale / x-pathname
* headers, locale cookie, redirect). The project's proxy.ts becomes a few lines.
*
* `NextResponse` is INJECTED (the plugin never imports next/server — it's a peer
* dep absent at the plugin's build time). The project passes it:
*
* // proxy.ts (Next 16 — NOT middleware.ts)
* import { NextResponse } from 'next/server'
* import { createProxy, DEFAULT_PROXY_MATCHER } from '@intecion/ipal-kit'
* import { i18nConfig } from '@/i18n.config'
* export const proxy = createProxy(i18nConfig, { NextResponse })
* export const config = { matcher: DEFAULT_PROXY_MATCHER }
*/
export function createProxy(
config: I18nConfig,
deps: { NextResponse: NextResponseLike } & CreateProxyOptions,
): (request: ProxyRequest) => ProxyResponse {
const { exposeHeaders = true, NextResponse, ...mwOptions } = deps
const run = createLocaleMiddleware({ config, ...mwOptions })
return (request: ProxyRequest): ProxyResponse => {
const result = run(request)
const requestHeaders = new Headers(request.headers)
if (exposeHeaders) {
const { pathname } = request.nextUrl
const seg = pathname.split('/').filter(Boolean)[0] ?? ''
const locale = isValidLocale(seg, config) ? seg : config.defaultLocale
requestHeaders.set('x-locale', locale)
requestHeaders.set('x-pathname', pathname)
}
const response =
result.type === 'redirect'
? NextResponse.redirect(new URL(result.location, request.url))
: NextResponse.next({ request: { headers: requestHeaders } })
if (result.cookie) {
response.cookies.set(result.cookie.name, result.cookie.value, {
path: '/',
sameSite: 'lax',
})
}
return response
}
}
+1
View File
@@ -1,3 +1,4 @@
export { createProxy, DEFAULT_PROXY_MATCHER } from './createProxy.js'
export { getLocalizedSlugs } from './getLocalizedSlugs.js'
export { getDefaultLocale, getLocaleCodes, getLocaleDefinition, isValidLocale } from './helpers.js'
export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } from './localeMiddleware.js'
+55
View File
@@ -0,0 +1,55 @@
import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical'
import type { JSXConvertersFunction } from '@payloadcms/richtext-lexical/react'
import { RichText as PayloadRichText } from '@payloadcms/richtext-lexical/react'
export type RenderRichTextProps = {
/** Wrapper class (e.g. Tailwind prose classes). */
className?: string
/**
* Override the JSX for specific node types to apply the project's own
* styling. Receives Payload's defaultConverters; return the merged map.
* This is where a project puts its Tailwind classes per node (headings,
* paragraphs, links, …) — the design stays in the project, the parsing in
* the plugin's wrapper over Payload's official converter.
*/
converters?: JSXConvertersFunction
/**
* Lexical editor state from a Payload richText field. Already localized —
* Payload returns the current locale's value, so NO per-locale key handling
* is needed here (unlike hand-rolled renderers that hardcode `.pl`).
*/
data: null | SerializedEditorState | undefined
}
/**
* Renders a Payload Lexical richText field to React — a thin wrapper over
* Payload's OFFICIAL converter (@payloadcms/richtext-lexical/react).
*
* Why not hand-roll it: parsing Lexical by hand (node.type switch, node.format
* bit flags) duplicates what Payload already does, misses node types, drifts
* on Lexical updates, and tempts shortcuts like dangerouslySetInnerHTML (XSS)
* or a hardcoded `.pl` locale. The official converter handles every node,
* stays in sync, and is safe. This is the RenderBlocks of rich text: the
* plugin owns the engine, the project owns the look via `converters`.
*
* // project — a Server Component
* import { RenderRichText } from '@intecion/ipal-kit/rsc'
* <RenderRichText data={page.content} className="prose" />
*
* // with project styling per node:
* const converters: JSXConvertersFunction = ({ defaultConverters }) => ({
* ...defaultConverters,
* heading: ({ node, nodesToJSX }) => {
* const children = nodesToJSX({ nodes: node.children })
* const cls = { h2: 'text-2xl font-semibold mt-10', h3: 'text-xl mt-7' }[node.tag] ?? ''
* const Tag = node.tag as 'h1'|'h2'|'h3'|'h4'
* return <Tag className={cls}>{children}</Tag>
* },
* })
* <RenderRichText data={page.content} converters={converters} />
*/
export function RenderRichText({ className, converters, data }: RenderRichTextProps) {
if (!data) {return null}
return <PayloadRichText className={className} converters={converters} data={data} />
}
+2
View File
@@ -0,0 +1,2 @@
export { RenderRichText } from './RenderRichText.js'
export type { RenderRichTextProps } from './RenderRichText.js'
+90
View File
@@ -0,0 +1,90 @@
import type { BasePayload } from 'payload'
import type { I18nConfig } from '../i18n/index.js'
import { getDefaultLocale } from '../i18n/index.js'
type MediaLike =
| { height?: null | number; mimeType?: null | string; url?: null | string; width?: null | number }
| null
| undefined
type ManifestIcon = { sizes?: string; src: string; type?: string }
type Manifest = {
background_color?: string
display: 'standalone'
icons: ManifestIcon[]
name?: string
short_name?: string
start_url: string
theme_color?: string
}
type SettingsShape = {
backgroundColor?: null | string
favicon?: MediaLike
logo?: MediaLike
siteName?: null | string
themeColor?: null | string
}
/**
* Builds a Next Web App Manifest from SiteSettings — replaces the ~50 lines of
* icon/mimeType parsing copied into every project's manifest.ts. Values come
* from the panel; missing fields are omitted (no hardcoded client data).
*
* // app/manifest.ts
* import { createManifestHandler } from '@intecion/ipal-kit'
* import { getCachedPayload } from '@/lib/content'
* import { i18nConfig } from '@/i18n.config'
* export default createManifestHandler({ getCachedPayload, config: i18nConfig })
*/
export function createManifestHandler(opts: {
config: I18nConfig
getCachedPayload: () => Promise<BasePayload>
settingsSlug?: string
}): () => Promise<Manifest> {
return async () => {
const defaultLocale = getDefaultLocale(opts.config)
const payload = await opts.getCachedPayload()
const settings = (await payload
.findGlobal({
slug: (opts.settingsSlug ?? 'site-settings') as never,
depth: 1,
locale: defaultLocale as never,
})
.catch(() => null)) as null | SettingsShape
const start_url = `/${defaultLocale}`
if (!settings) {
return { display: 'standalone', icons: [], start_url }
}
const iconSource = settings.favicon ?? settings.logo
const icons: ManifestIcon[] = []
if (iconSource?.url) {
const type =
iconSource.mimeType ?? (iconSource.url.endsWith('.svg') ? 'image/svg+xml' : undefined)
const isSvg = type === 'image/svg+xml'
const size =
iconSource.width && iconSource.height
? `${iconSource.width}x${iconSource.height}`
: undefined
icons.push({
src: iconSource.url,
...(isSvg ? { sizes: 'any' } : size ? { sizes: size } : {}),
...(type ? { type } : {}),
})
}
return {
...(settings.siteName ? { name: settings.siteName, short_name: settings.siteName } : {}),
display: 'standalone',
start_url,
...(settings.backgroundColor ? { background_color: settings.backgroundColor } : {}),
...(settings.themeColor ? { theme_color: settings.themeColor } : {}),
icons,
}
}
}
+2
View File
@@ -6,6 +6,7 @@ export { buildFaqJsonLd } from './buildFaqJsonLd.js'
export { buildIconsMetadata } from './buildIconsMetadata.js'
export { buildLlmsTxt } from './buildLlmsTxt.js'
export { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js'
export { createManifestHandler } from './buildManifest.js'
export { buildMetadata } from './buildMetadata.js'
export type { PageMetadata } from './buildMetadata.js'
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'
@@ -26,6 +27,7 @@ export { injectAutoFillMeta } from './injectAutoFillMeta.js'
export { injectSeoTabs } from './injectSeoTabs.js'
export { readSiteMetaConfig } from './readSiteMetaConfig.js'
export type { SiteMetaConfig } from './readSiteMetaConfig.js'
export { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js'
export { buildSeoPlugin } from './seoPluginConfig.js'
export { slugsAcrossLocales } from './slugsAcrossLocales.js'
export type { SeoMeta, SeoOption } from './types.js'
+89
View File
@@ -0,0 +1,89 @@
import type { BasePayload } from 'payload'
import type { I18nConfig } from '../i18n/index.js'
import type { SitemapEntry } from './buildSitemapEntries.js'
import { buildLlmsTxt } from './buildLlmsTxt.js'
import { buildSitemapXml } from './buildSitemapXml.js'
/**
* Ready-made Next route handler for /llms.txt. Replaces the ~60-line try/catch
* every project was copying. buildLlmsTxt already handles collections without
* drafts, so no workaround is needed here.
*
* // app/llms.txt/route.ts
* import { createLlmsTxtRoute } from '@intecion/ipal-kit'
* import { getCachedPayload } from '@/lib/content'
* import { i18nConfig } from '@/i18n.config'
* export const dynamic = 'force-dynamic'
* export const GET = createLlmsTxtRoute({ getCachedPayload, config: i18nConfig,
* baseUrl: process.env.NEXT_PUBLIC_SERVER_URL! })
*/
export function createLlmsTxtRoute(opts: {
baseUrl: string
config: I18nConfig
getCachedPayload: () => Promise<BasePayload>
pagesSlug?: string
settingsSlug?: string
}): () => Promise<Response> {
return async () => {
try {
const payload = await opts.getCachedPayload()
const body = await buildLlmsTxt({
baseUrl: opts.baseUrl,
config: opts.config,
pagesSlug: opts.pagesSlug,
payload,
settingsSlug: opts.settingsSlug,
})
return new Response(body, {
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
})
} catch (err) {
// DB unreachable at build (container) — return a minimal valid file so the
// route doesn't 500; it fills in at runtime. No per-project try/catch.
console.warn('[ipal] createLlmsTxtRoute: could not build llms.txt:', err)
return new Response('# llms.txt\n', {
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
})
}
}
}
/**
* Ready-made Next route handler for /sitemap.xml with the CSS stylesheet.
* Replaces the hand-written route in every project. Pass the project's `sitemap`
* helper (from createContentHelpers) and optionally a cssUrl.
*
* // app/sitemap.xml/route.ts
* import { createSitemapRouteHandler } from '@intecion/ipal-kit'
* import { sitemap } from '@/lib/content'
* export const dynamic = 'force-dynamic'
* export const GET = createSitemapRouteHandler(sitemap, { cssUrl: '/sitemap.css' })
*
* Remember: if you use this, DON'T also keep app/sitemap.ts (two sitemaps
* confuse crawlers).
*/
export function createSitemapRouteHandler(
sitemap: () => Promise<SitemapEntry[]>,
opts: { cssUrl?: string } = {},
): () => Promise<Response> {
return async () => {
try {
const entries = await sitemap()
const xml = buildSitemapXml(entries, { cssUrl: opts.cssUrl })
return new Response(xml, {
headers: { 'Content-Type': 'application/xml; charset=utf-8' },
})
} catch (err) {
console.warn('[ipal] createSitemapRouteHandler: could not build sitemap:', err)
// Valid empty urlset so the route doesn't 500 during a DB-less build.
const empty =
'<?xml version="1.0" encoding="UTF-8"?>\n' +
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>'
return new Response(empty, {
headers: { 'Content-Type': 'application/xml; charset=utf-8' },
})
}
}
}