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:
2026-10-16 11:32:46 +02:00
co-authored by Claude Opus 5.5
parent 0cfd846dd1
commit 412bf953a8
44 changed files with 2015 additions and 20 deletions
@@ -0,0 +1,18 @@
import { notFound, permanentRedirect } from 'next/navigation.js'
import { createPageRoute } from '@intecion/ipal-kit/rsc'
import { FormBlock } from '../../../../blocks/FormBlock.js'
import * as content from '../../../../lib/content.js'
import { sendForm } from '../actions.js'
export const revalidate = 3600
const route = createPageRoute(content, {
blockProps: async ({ locale }) => ({ formTexts: await content.getFormTexts(locale), sendForm }),
blocks: { formBlock: FormBlock },
notFound,
permanentRedirect,
})
export default route.Page
export const generateMetadata = route.generateMetadata
export const generateStaticParams = route.generateStaticParams
+7
View File
@@ -0,0 +1,7 @@
'use server'
import { headers } from 'next/headers.js'
import { createSubmitAction } from '@intecion/ipal-kit/server'
import { getCachedPayload } from '../../../lib/content.js'
export const sendForm = createSubmitAction({ getCachedPayload, headers })
+22
View File
@@ -0,0 +1,22 @@
import { notFound } from 'next/navigation.js'
import { CookieBanner } from '@intecion/ipal-kit/client'
import { SiteProviders } from '@intecion/ipal-kit/rsc'
import { getConfiguredLocales, getSiteShell } from '../../../lib/content.js'
import './styles.css'
type Props = { children: React.ReactNode; params: Promise<{ locale: string }> }
export default async function LocaleLayout({ children, params }: Props) {
const { locale } = await params
if (!(await getConfiguredLocales()).includes(locale)) notFound()
return (
<html lang={locale}>
<body>
<SiteProviders banner={<CookieBanner equalChoice />} logEndpoint="/api/ipal/consent" shell={await getSiteShell(locale)}>
<main>{children}</main>
</SiteProviders>
</body>
</html>
)
}
@@ -0,0 +1,6 @@
import { createNotFoundPage } from '@intecion/ipal-kit/rsc'
import { FormBlock } from '../../../blocks/FormBlock.js'
import * as content from '../../../lib/content.js'
export default createNotFoundPage(content, { blocks: { formBlock: FormBlock }, fallback: <h1>404</h1> })
+10
View File
@@ -0,0 +1,10 @@
/* Sandbox look — in a project this is the design system. */
body { font-family: system-ui, sans-serif; margin: 0 auto; max-width: 40rem; padding: 1rem; }
.grid { display: grid; gap: 1rem; grid-template-columns: repeat(2, 1fr); }
.field { grid-column: span 2; } .half { grid-column: span 1; }
.label, legend { display: block; font-weight: 600; margin-bottom: .25rem; }
.input { border: 1px solid #999; border-radius: 6px; box-sizing: border-box; padding: .5rem; width: 100%; }
.choices { border: 0; display: grid; gap: .25rem; margin: 0; padding: 0; } .choice { display: flex; gap: .5rem; }
.error { color: #b00020; } .progress { color: #555; } .step-title { font-size: 1.25rem; font-weight: 700; }
.actions { display: flex; gap: .5rem; margin-top: 1rem; } .btn { background: #111; border: 0; border-radius: 6px; color: #fff; padding: .6rem 1rem; }
.btn-secondary { background: #ddd; color: #111; } .success { background: #e7f7ec; padding: 1rem; }
+2
View File
@@ -0,0 +1,2 @@
export { mcpGET as GET, mcpPOST as POST } from '../../../lib/content.js'
export const dynamic = 'force-dynamic'
+2
View File
@@ -0,0 +1,2 @@
export { llmsRoute as GET } from '../../lib/content.js'
export const dynamic = 'force-dynamic'
+16
View File
@@ -0,0 +1,16 @@
import type { FormNotificationTexts } from '@intecion/ipal-kit'
import { RenderForm, type SendFormAction } from '@intecion/ipal-kit/rsc'
// Classes set once per project — here plain names the sandbox CSS styles.
const formClasses = {
actions: 'actions', back: 'btn btn-secondary', choice: 'choice', choices: 'choices', error: 'error', field: 'field',
fieldHalf: 'half', fields: 'grid', form: 'form', formError: 'error', input: 'input', label: 'label', progress: 'progress',
select: 'input', stepTitle: 'step-title', submit: 'btn', success: 'success', textarea: 'input',
}
type Props = { form?: unknown; formTexts?: FormNotificationTexts; locale: string; sendForm?: SendFormAction }
export function FormBlock({ form, formTexts, locale, sendForm }: Props) {
if (!formTexts || !sendForm) return null
return <RenderForm action={sendForm} classNames={formClasses} form={form as never} locale={locale} requiredMark=" *" texts={formTexts} />
}
+7
View File
@@ -0,0 +1,7 @@
export const i18nConfig = {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
} as const
+11
View File
@@ -0,0 +1,11 @@
// Sandbox data layer — the same one line every project has (PROGRAMISTA §2.7).
import config from '@payload-config'
import { createContentHelpers } from '@intecion/ipal-kit'
import { i18nConfig } from '../i18n.config.js'
export const {
generatePageMetadata, generateStaticParams, getCachedPayload, getConfiguredLocales, getFormTexts, getLinkOptions,
getNotFoundPage, getPageJsonLd, getSettings, getSiteShell, healthRoute, i18n, llmsRoute, mcpGET, mcpPOST,
resolveNav, resolvePageRedirect, resolveRoute,
} = createContentHelpers({ baseUrl: 'http://localhost:3000', config, i18n: i18nConfig, mcp: { serverName: 'ipal-sandbox' } })
+11 -8
View File
@@ -7,6 +7,7 @@ import sharp from 'sharp'
import { fileURLToPath } from 'url'
import { testEmailAdapter } from './helpers/testEmailAdapter.js'
import { i18nConfig } from './i18n.config.js'
import { seed } from './seed.js'
const filename = fileURLToPath(import.meta.url)
@@ -30,7 +31,15 @@ export default buildConfig({
},
{
slug: 'pages',
fields: [{ name: 'title', type: 'text' }],
fields: [
{ name: 'title', type: 'text', localized: true },
{ name: 'slug', type: 'text', index: true, localized: true },
{
name: 'layout',
type: 'blocks',
blocks: [{ slug: 'formBlock', fields: [{ name: 'form', type: 'relationship', relationTo: 'forms' }] }],
},
],
},
{
slug: 'posts',
@@ -56,13 +65,7 @@ export default buildConfig({
plugins: [
ipalKit({
access: { authCollection: 'users' },
i18n: {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
},
i18n: i18nConfig,
consentLog: true,
forms: {},
seo: { collections: ['posts', 'pages'] },
+46
View File
@@ -22,4 +22,50 @@ export const seed = async (payload: Payload) => {
},
})
}
await seedContactPage(payload)
}
const text = (t: string) => ({
root: {
children: [{ children: [{ detail: 0, format: 0, mode: 'normal', style: '', text: t, type: 'text', version: 1 }], direction: null, format: '', indent: 0, type: 'paragraph', version: 1 }],
direction: null,
format: '',
indent: 0,
type: 'root',
version: 1,
},
})
/** A step-by-step quote form on /pl/kontakt — exercises RenderForm, steps, choice lists, dates. */
async function seedContactPage(payload: Payload) {
const { totalDocs } = await payload.count({ collection: 'pages', where: { slug: { equals: 'kontakt' } } })
if (totalDocs) {return}
const form = await payload.create({
collection: 'forms',
data: {
confirmationMessage: text('Dziękujemy! Odezwiemy się w ciągu 24 godzin.'),
confirmationType: 'message',
fields: [
{ blockType: 'step', title: 'Kontakt' },
{ name: 'name', blockType: 'text', label: 'Imię i nazwisko', required: true, width: 50 },
{ name: 'email', blockType: 'email', label: 'E-mail', required: true, width: 50 },
{ blockType: 'step', description: 'Zaznacz, czego potrzebujesz.', title: 'Projekt' },
{ name: 'services', blockType: 'checkboxGroup', label: 'Usługi', options: [{ label: 'Strona WWW', value: 'www' }, { label: 'SEO', value: 'seo' }, { label: 'Kampanie', value: 'ads' }], required: true },
{ name: 'budget', blockType: 'radio', label: 'Budżet', options: [{ label: 'do 10 tys.', value: 's' }, { label: 'powyżej 10 tys.', value: 'l' }], required: true },
{ name: 'deadline', blockType: 'date', label: 'Termin' },
{ blockType: 'message', message: text('Dane przetwarzamy wyłącznie w celu przygotowania wyceny.') },
{ name: 'consent', blockType: 'checkbox', label: 'Zgadzam się na przetwarzanie danych.', required: true },
],
submitButtonLabel: 'Wyślij zapytanie',
title: 'Wycena',
} as never,
})
const page = await payload.create({
collection: 'pages',
data: { layout: [{ blockType: 'formBlock', form: form.id }], slug: 'kontakt', title: 'Kontakt' } as never,
})
await payload.updateGlobal({ slug: 'site-settings' as never, data: { siteName: 'Sandbox' } as never })
payload.logger.info(`[seed] /pl/kontakt (page ${page.id}, form ${form.id})`)
}
+14 -1
View File
@@ -24,9 +24,22 @@ export {
useConsentContext,
} from '../modules/consent/client.js'
export type { CookieBannerClassNames } from '../modules/consent/client.js'
export { BuilderForm } from '../modules/forms/BuilderForm.js'
export type { BuilderFieldRenderArgs, BuilderFormClassNames, BuilderFormProps } from '../modules/forms/BuilderForm.js'
export { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from '../modules/forms/builderLogic.js'
export type {
BuilderField,
BuilderFormAction,
BuilderFormDoc,
BuilderFormTexts,
BuilderOption,
BuilderStep,
} from '../modules/forms/builderTypes.js'
export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'
export type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js'
export { useBuilderForm } from '../modules/forms/useBuilderForm.js'
export type { BuilderFormApi, UseBuilderFormOptions } from '../modules/forms/useBuilderForm.js'
export { useContactForm } from '../modules/forms/useContactForm.js'
export type { ContactFormErrors, ContactFormValues, SubmitAction } from '../modules/forms/useContactForm.js'
export { useForm } from '../modules/forms/useForm.js'
@@ -64,5 +77,5 @@ export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStat
export { LocaleView } from '../modules/pages/LocaleView.js'
export { YouTubeEmbed } from '../modules/storage/YouTubeEmbed.js'
export { Turnstile } from '../modules/turnstile/client.js'
export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'
export { TurnstileProvider, useOptionalTurnstile, useTurnstile } from '../modules/turnstile/client.js'
export type { TurnstileProps } from '../modules/turnstile/client.js'
+8
View File
@@ -14,6 +14,14 @@ export type {
} from '../modules/blocks/index.js'
export { CookieTable } from '../modules/consent/CookieTable.js'
export type { CookieTableLabels } from '../modules/consent/CookieTable.js'
export { RenderForm } from '../modules/forms/RenderForm.js'
export type { 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 { SiteProviders } from '../modules/frontend/SiteProviders.js'
export type { SiteProvidersProps } from '../modules/frontend/SiteProviders.js'
export { RenderRichText } from '../modules/richtext/index.js'
export type { RenderRichTextProps } from '../modules/richtext/index.js'
export { JsonLdGraph } from '../modules/seo/index.js'
+23
View File
@@ -69,6 +69,29 @@ export const notificationsFields: Field[] = [
admin: { placeholder: 'This form is no longer available.' },
localized: true,
},
{
type: 'row',
fields: [
{
name: 'next',
type: 'text',
admin: { description: 'Step-by-step forms: button to the next step.', placeholder: 'Next', width: '33%' },
localized: true,
},
{
name: 'back',
type: 'text',
admin: { description: 'Step-by-step forms: button to the previous step.', placeholder: 'Back', width: '33%' },
localized: true,
},
{
name: 'stepOf',
type: 'text',
admin: { description: 'Progress — {current} and {total} are replaced.', placeholder: 'Step {current} of {total}', width: '34%' },
localized: true,
},
],
},
],
label: 'Form messages',
},
+11 -2
View File
@@ -19,6 +19,9 @@ export { rowLabel } from './modules/admin-ui/index.js'
export type { RowLabelProps } from './modules/admin-ui/index.js'
export type { AnalyticsConfig } from './modules/analytics/index.js'
export { getAnalyticsConfig } from './modules/analytics/index.js'
// Shared section fields (header: eyebrow/heading/intro, settings: anchor/background).
export { buildSectionHeaderField, buildSectionSettingsField } from './modules/blocks/sectionFields.js'
export type { SectionHeaderFieldOptions, SectionSettingsFieldOptions } from './modules/blocks/sectionFields.js'
export {
ACCEPT_ALL_CONSENT,
buildConsentLogCollection,
@@ -74,6 +77,9 @@ export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'
// Boot-time environment validation (fail fast on misconfigured deploys).
export { assertEnv, ipalEnvRules } from './modules/env/index.js'
export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js'
export { checkboxGroupBlock, stepBlock } from './modules/forms/builderBlocks.js'
export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from './modules/forms/builderLogic.js'
export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep } from './modules/forms/builderTypes.js'
// Panel-managed form analytics (config-time field builder).
export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
@@ -99,7 +105,7 @@ export {
required,
} from './modules/forms/validators.js'
export type { Rule } from './modules/forms/validators.js'
export type { PageJsonLdOptions } from './modules/frontend/createContentHelpers.js'
export type { ContentHelpers, PageJsonLdOptions, SiteShell } from './modules/frontend/createContentHelpers.js'
export { createContentHelpers } from './modules/frontend/index.js'
// Healthcheck route (Coolify/Docker liveness with a real DB round-trip).
export { createHealthRoute } from './modules/health/index.js'
@@ -126,13 +132,16 @@ export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'
export { resolveLocalized } from './modules/i18n/index.js'
export { buildIntegrationStatusBanner, buildIntegrationStatusField, recordIntegrationStatus } from './modules/integrations/index.js'
export type { IntegrationState, IntegrationStatus } from './modules/integrations/index.js'
export { buildLinkField, buildLinksField, resolveLinkHref, safeHref } from './modules/links/index.js'
export { buildLinkField, buildLinksField, homeSlugFrom, resolveLink, resolveLinkHref, resolveNav, safeHref } from './modules/links/index.js'
export type {
BuildLinkFieldOptions,
BuildLinksFieldOptions,
LinkAppearance,
LinkValue,
NavItem,
ResolvedLink,
ResolveLinkHrefOptions,
ResolveNavOptions,
} from './modules/links/index.js'
// Read-only MCP server (Claude/agents connect to the site and query it).
export { createMcpRoute } from './modules/mcp/index.js'
+2
View File
@@ -1,3 +1,5 @@
export { RenderBlocks } from './RenderBlocks.js'
export type { RenderBlocksProps } from './RenderBlocks.js'
export { buildSectionHeaderField, buildSectionSettingsField } from './sectionFields.js'
export type { SectionHeaderFieldOptions, SectionSettingsFieldOptions } from './sectionFields.js'
export type { BlockComponentMap, BlockData, EnhanceProps } from './types.js'
+82
View File
@@ -0,0 +1,82 @@
import type { Field, GroupField } from 'payload'
/**
* The two field groups every section block shares — same panel, same data
* shape in every project, so the shared <Section>/<SectionHeader> components
* work on every block. Everything is overridable: names, options, extra fields.
*
* fields: [buildSectionHeaderField(), …the block's own fields…, buildSectionSettingsField()]
* fields: [buildSectionSettingsField({ backgrounds: [{ label: 'Brand', value: 'brand' }] })]
*/
export type SectionHeaderFieldOptions = {
/** Extra fields inside the group (e.g. a heading level select). */
fields?: Field[]
/** Generated TS type name. Default 'SectionHeaderData'. */
interfaceName?: string
/** Default 'header'. */
name?: string
}
/** eyebrow + heading + intro, localized — rendered by the project's <SectionHeader>. */
export function buildSectionHeaderField({ name = 'header', fields = [], interfaceName = 'SectionHeaderData' }: SectionHeaderFieldOptions = {}): GroupField {
return {
name,
type: 'group',
fields: [
{ name: 'eyebrow', type: 'text', admin: { description: 'Small line above the heading. Optional.' }, localized: true },
{ name: 'heading', type: 'text', localized: true },
{ name: 'intro', type: 'textarea', admin: { rows: 3 }, localized: true },
...fields,
],
interfaceName,
}
}
export type SectionSettingsFieldOptions = {
/** Section #id for anchor links and a section nav. Default true. */
anchor?: boolean
/**
* Background choices — values map to the project's own classes in <Section>.
* Default Default / Muted / Inverted (dark). `false` → no background select.
*/
backgrounds?: { label: string; value: string }[] | false
/** Extra settings (e.g. spacing, width). */
fields?: Field[]
/** Generated TS type name. Default 'SectionSettings'. */
interfaceName?: string
/** Default 'settings'. */
name?: string
}
const DEFAULT_BACKGROUNDS = [
{ label: 'Default', value: 'default' },
{ label: 'Muted', value: 'muted' },
{ label: 'Inverted (dark)', value: 'inverted' },
]
/** Sidebar group: anchor + background (+ your own) — instead of bgColor / sectionId per block. */
export function buildSectionSettingsField({
name = 'settings',
anchor = true,
backgrounds = DEFAULT_BACKGROUNDS,
fields = [],
interfaceName = 'SectionSettings',
}: SectionSettingsFieldOptions = {}): GroupField {
return {
name,
type: 'group',
admin: { position: 'sidebar' },
fields: [
...(anchor
? [{ name: 'anchor', type: 'text', admin: { description: 'Section id for #links and section nav, e.g. "pricing".' } } as Field]
: []),
...(backgrounds && backgrounds.length
? [{ name: 'background', type: 'select', defaultValue: backgrounds[0].value, options: backgrounds } as Field]
: []),
...fields,
],
interfaceName,
label: 'Section settings',
}
}
+219
View File
@@ -0,0 +1,219 @@
'use client'
import type { ReactNode } from 'react'
import { useEffect, useRef } from 'react'
import type { BuilderField } from './builderTypes.js'
import type { BuilderFormApi, UseBuilderFormOptions } from './useBuilderForm.js'
import { honeypotInputProps } from './honeypot.js'
import { useBuilderForm } from './useBuilderForm.js'
/**
* Class names for every element — the plugin ships none. Set them once in the
* project (e.g. src/components/forms/formClasses.ts) and every panel form looks
* the same. Plain strings, so a server component can pass them.
*/
export type BuilderFormClassNames = Partial<
Record<
| 'actions' | 'back' | 'checkbox' | 'checkboxLabel' | 'choice' | 'choiceInput' | 'choiceLabel' | 'choices'
| 'error' | 'field' | 'fieldFull' | 'fieldHalf' | 'fields' | 'form' | 'formError' | 'input' | 'label'
| 'legend' | 'message' | 'next' | 'progress' | 'required' | 'select' | 'step' | 'stepDescription'
| 'stepTitle' | 'submit' | 'success' | 'textarea' | 'turnstile',
string
>
>
export type BuilderFieldRenderArgs = {
/** The default markup for this field — return it to keep it, or wrap it. */
defaultRender: () => ReactNode
field: BuilderField
form: BuilderFormApi
/** Position in the panel's field list (key of `messages`). */
index: number
}
export type BuilderFormProps = {
classNames?: BuilderFormClassNames
/** Shown after success instead of the form (the form's confirmation message, rendered by RenderForm). */
confirmation?: ReactNode
/** Rendered `message` blocks, keyed by their index in form.fields (RenderForm fills it). */
messages?: Record<number, ReactNode>
/**
* Client-side only (use BuilderForm from a 'use client' file): replace the
* markup of chosen fields — a project's own field type, option cards, a
* slider. Return undefined to keep the default.
*/
renderField?: (args: BuilderFieldRenderArgs) => ReactNode | undefined
/** Appended to required labels, e.g. "*". Default: nothing. */
requiredMark?: ReactNode
turnstileTheme?: 'auto' | 'dark' | 'light'
} & UseBuilderFormOptions
const cx = (...c: (false | null | string | undefined)[]) => c.filter(Boolean).join(' ') || undefined
/**
* Renders ANY panel form — single screen or step-by-step, text, e-mail, number,
* date, select, radio, checkbox, checkbox group, message blocks — with plain,
* accessible HTML and no styles. Look: `classNames` (+ `data-*` hooks:
* data-ipal="form", data-type, data-width, data-step). Different markup:
* `renderField`, or your own component on useBuilderForm.
*
* In a block, use RenderForm (/rsc) — it renders the rich text, binds the
* action and passes only the public part of the form to the browser.
*/
export function BuilderForm({
classNames: cn = {},
confirmation,
messages = {},
renderField,
requiredMark,
turnstileTheme,
...options
}: BuilderFormProps) {
const f = useBuilderForm(options)
const stepRef = useRef<HTMLDivElement>(null)
const firstRender = useRef(true)
// Moving between steps: focus the new step, so keyboard and screen-reader users land on it.
useEffect(() => {
if (firstRender.current) {
firstRender.current = false
return
}
const el = stepRef.current
const target = el?.querySelector<HTMLElement>('[aria-invalid="true"], input, select, textarea') ?? el
target?.focus()
}, [f.stepIndex])
if (f.isSuccess && options.form.confirmationType !== 'redirect') {
return (
<div className={cn.success} data-ipal="form-success" role="status">
{confirmation ?? f.resultMessage ?? options.texts.success}
</div>
)
}
const label = (field: BuilderField) => (
<>
{field.label}
{field.required && requiredMark ? <span aria-hidden className={cn.required}>{requiredMark}</span> : null}
</>
)
const errorOf = (field: BuilderField) => {
const error = field.name ? f.errors[field.name] : undefined
return error ? <p className={cn.error} id={f.errorId(field)}>{error}</p> : null
}
const defaultField = (field: BuilderField, index: number): ReactNode => {
if (field.blockType === 'message') {return <div className={cn.message}>{messages[index]}</div>}
switch (field.blockType) {
case 'checkbox': {
const props = f.getInputProps(field)
return (
<>
<label className={cn.checkboxLabel} htmlFor={props.id}>
<input {...props} className={cn.checkbox} />
<span>{label(field)}</span>
</label>
{errorOf(field)}
</>
)
}
case 'checkboxGroup':
case 'radio':
return (
<fieldset
aria-describedby={f.getFieldProps(field)['aria-describedby']}
aria-invalid={f.getFieldProps(field)['aria-invalid']}
className={cn.choices}
id={f.fieldId(field)}
>
<legend className={cn.legend}>{label(field)}</legend>
{(field.options ?? []).map((option, i) => {
const o = f.getOptionProps(field, option, i)
return (
<label className={cn.choice} htmlFor={o.id} key={option.value}>
<input {...o} className={cn.choiceInput} />
<span className={cn.choiceLabel}>{option.label ?? option.value}</span>
</label>
)
})}
{errorOf(field)}
</fieldset>
)
case 'select': {
const props = f.getSelectProps(field)
return (
<>
<label className={cn.label} htmlFor={props.id}>{label(field)}</label>
<select {...props} className={cn.select}>
<option value="">{field.placeholder ?? ''}</option>
{(field.options ?? []).map((o) => <option key={o.value} value={o.value}>{o.label ?? o.value}</option>)}
</select>
{errorOf(field)}
</>
)
}
case 'textarea': {
const props = f.getTextareaProps(field)
return (
<>
<label className={cn.label} htmlFor={props.id}>{label(field)}</label>
<textarea {...props} className={cn.textarea} rows={5} />
{errorOf(field)}
</>
)
}
default: {
const props = f.getInputProps(field)
return (
<>
<label className={cn.label} htmlFor={props.id}>{label(field)}</label>
<input {...props} className={cn.input} />
{errorOf(field)}
</>
)
}
}
}
const { step } = f
const progress = options.texts.stepOf?.replace('{current}', String(f.stepIndex + 1)).replace('{total}', String(f.total))
return (
<form className={cn.form} data-ipal="form" data-step={f.stepIndex + 1} noValidate onSubmit={f.submit}>
<input {...honeypotInputProps()} />
{f.total > 1 && progress ? <p aria-live="polite" className={cn.progress}>{progress}</p> : null}
<div className={cn.step} data-ipal="form-step" ref={stepRef} tabIndex={-1}>
{step.title ? <p className={cn.stepTitle}>{step.title}</p> : null}
{step.description ? <p className={cn.stepDescription}>{step.description}</p> : null}
<div className={cn.fields}>
{step.fields.map(({ field, index }) => {
const half = typeof field.width === 'number' && field.width <= 50
const content = renderField?.({ defaultRender: () => defaultField(field, index), field, form: f, index }) ?? defaultField(field, index)
return (
<div
className={cx(cn.field, half ? cn.fieldHalf : cn.fieldFull)}
data-type={field.blockType}
data-width={field.width ?? 100}
key={field.id ?? `${field.blockType}-${index}`}
>
{content}
</div>
)
})}
</div>
</div>
{f.isLast ? <div className={cn.turnstile}><f.TurnstileWidget theme={turnstileTheme} /></div> : null}
{f.errorMessage ? <p className={cn.formError} role="alert">{f.errorMessage}</p> : null}
<div className={cn.actions}>
{!f.isFirst ? <button className={cn.back} onClick={f.back} type="button">{options.texts.back ?? 'Back'}</button> : null}
<button className={f.isLast ? cn.submit : (cn.next ?? cn.submit)} disabled={f.isSubmitting} type="submit">
{f.isLast ? options.form.submitButtonLabel || 'Send' : options.texts.next ?? 'Next'}
</button>
</div>
</form>
)
}
+109
View File
@@ -0,0 +1,109 @@
import type { SerializedEditorState } from '@payloadcms/richtext-lexical/lexical'
import type { JSXConvertersFunction } from '@payloadcms/richtext-lexical/react'
import type { ReactNode } from 'react'
import type { ResolveLinkHrefOptions } from '../links/resolveLinkHref.js'
import type { BuilderFormClassNames } from './BuilderForm.js'
import type { BuilderField, BuilderFormDoc, BuilderFormTexts } from './builderTypes.js'
import type { SubmitActionResult } from './createSubmitAction.js'
import { resolveLinkHref, safeHref } from '../links/resolveLinkHref.js'
import { RenderRichText } from '../richtext/RenderRichText.js'
import { BuilderForm } from './BuilderForm.js'
/** The action from createSubmitAction — `sendForm(formId, locale, values, token?)`. */
export type SendFormAction = (
formId: string,
locale: string,
values: Record<string, unknown>,
turnstileToken?: string,
) => Promise<SubmitActionResult>
export type RenderFormProps = {
/** The project's `sendForm` server action (createSubmitAction). */
action: SendFormAction
classNames?: BuilderFormClassNames
/** Rich text styling for message blocks and the confirmation (same as RenderRichText). */
converters?: JSXConvertersFunction
/** The `form` relationship of the block, populated (page query depth ≥ 1). An id or null renders nothing. */
form: BuilderFormDoc | null | number | string | undefined
/**
* For redirect forms pointing at a page: `{ config: i18nConfig, homeSlug }`
* (locale is added). Without it only a custom URL redirect works.
*/
linkOptions?: Omit<ResolveLinkHrefOptions, 'locale'>
locale: string
requiredMark?: ReactNode
richTextClassName?: string
/** Notifications → form texts in this locale (getNotificationTexts(...).form). */
texts: BuilderFormTexts
turnstileTheme?: 'auto' | 'dark' | 'light'
}
/** Only what the browser needs. The Local API reads with overrideAccess, so the
* document still carries Emails (recipient addresses) — those never leave the server. */
function publicForm(form: BuilderFormDoc): BuilderFormDoc {
return {
id: form.id,
analytics: form.analytics,
confirmationType: form.confirmationType,
fields: (form.fields ?? []).map(({ message: _message, ...field }: BuilderField) => field),
redirect: form.redirect?.type === 'custom' || form.redirect?.url ? { url: safeHref(form.redirect?.url) } : null,
submitButtonLabel: form.submitButtonLabel,
title: form.title,
}
}
/**
* A panel form inside a block, in one line — server part of BuilderForm:
*
* <RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />
*
* Renders `message` blocks and the confirmation with RenderRichText, binds the
* action to the form and locale, resolves the redirect target, and passes the
* client only the public part of the form (never the Emails tab).
*/
export function RenderForm({
action,
classNames,
converters,
form,
linkOptions,
locale,
requiredMark,
richTextClassName,
texts,
turnstileTheme,
}: RenderFormProps) {
if (!form || typeof form !== 'object') {return null} // never a placeholder form
const rich = (data: unknown) =>
data ? <RenderRichText className={richTextClassName} converters={converters} data={data as SerializedEditorState} /> : null
const messages: Record<number, ReactNode> = {}
form.fields?.forEach((field, i) => {
if (field.blockType === 'message' && field.message) {messages[i] = rich(field.message)}
})
const page = form.redirect?.type === 'reference' ? (form.redirect.reference as { value?: unknown } | null)?.value : undefined
const redirectHref =
form.confirmationType === 'redirect'
? page && linkOptions
? resolveLinkHref({ type: 'internal', page }, { ...linkOptions, locale })
: safeHref(form.redirect?.url)
: null
return (
<BuilderForm
action={action.bind(null, String(form.id), locale)}
classNames={classNames}
confirmation={rich(form.confirmationMessage)}
form={publicForm(form)}
messages={messages}
redirectHref={redirectHref}
requiredMark={requiredMark}
texts={texts}
turnstileTheme={turnstileTheme}
/>
)
}
+74
View File
@@ -0,0 +1,74 @@
import type { Block, Field } from 'payload'
/**
* Extra form-builder field types — what the built-in set can't express:
*
* - `step` — a divider: fields below it (until the next Step) are one
* screen of a step-by-step form, with Next / Back buttons.
* Carries no value.
* - `checkboxGroup` — a list of options where the visitor ticks several
* ("Services you're interested in"). Value: string[].
*
* Plain English labels (the panel is EN). Rendered by BuilderForm /
* useBuilderForm, validated by submitForm like every other field.
*/
const name: Field = {
name: 'name',
type: 'text',
admin: { description: 'Technical name, e.g. "services" — no spaces.', width: '50%' },
label: 'Name (lowercase, no special characters)',
required: true,
}
const label: Field = { name: 'label', type: 'text', admin: { width: '50%' }, label: 'Label', localized: true }
const width: Field = { name: 'width', type: 'number', admin: { width: '50%' }, label: 'Field width (percentage)' }
const required: Field = { name: 'required', type: 'checkbox', admin: { width: '50%' }, label: 'Required' }
export const stepBlock: Block = {
slug: 'step',
fields: [
{
name: 'title',
type: 'text',
admin: {
description:
'Starts a new step: the fields below it (until the next Step) are shown together, with Next / Back buttons. Leave the form without Steps for a single-screen form.',
},
label: 'Step title',
localized: true,
},
{ name: 'description', type: 'textarea', admin: { rows: 2 }, label: 'Step description', localized: true },
],
labels: { plural: 'Steps', singular: 'Step' },
}
export const checkboxGroupBlock: Block = {
slug: 'checkboxGroup',
fields: [
{ type: 'row', fields: [name, label] },
{ type: 'row', fields: [width, required] },
{
name: 'options',
type: 'array',
fields: [
{
type: 'row',
fields: [
{ name: 'label', type: 'text', admin: { width: '50%' }, label: 'Label', localized: true, required: true },
{ name: 'value', type: 'text', admin: { width: '50%' }, label: 'Value', required: true },
],
},
],
labels: { plural: 'Options', singular: 'Option' },
minRows: 1,
},
{
type: 'row',
fields: [
{ name: 'minSelected', type: 'number', admin: { description: 'Empty = no minimum (Required = at least one).', width: '50%' }, label: 'Minimum selected', min: 0 },
{ name: 'maxSelected', type: 'number', admin: { description: 'Empty = no limit.', width: '50%' }, label: 'Maximum selected', min: 1 },
],
},
],
labels: { plural: 'Checkbox groups', singular: 'Checkbox group' },
}
+96
View File
@@ -0,0 +1,96 @@
import type { BuilderField, BuilderFormTexts, BuilderStep } from './builderTypes.js'
import { NON_INPUT_TYPES } from './builderTypes.js'
import { isEmail } from './validators.js'
/**
* Pure logic of a panel form — steps, initial values, validation. No React, so
* it's shared by useBuilderForm and tested on its own. The server re-checks
* everything (validateSubmission); this is only for instant feedback.
*/
/** Fields that hold a value (have a name and aren't message/step). */
export function inputFields(fields: BuilderField[] | null | undefined): ({ name: string } & BuilderField)[] {
return (fields ?? []).filter(
(f): f is { name: string } & BuilderField => typeof f.name === 'string' && f.name !== '' && !NON_INPUT_TYPES.has(f.blockType),
)
}
/**
* Splits the field list at `step` blocks. Fields before the first Step form
* the first screen; a form without Steps is one screen.
*/
export function splitSteps(fields: BuilderField[] | null | undefined): BuilderStep[] {
const steps: BuilderStep[] = []
let current: BuilderStep | null = null
;(fields ?? []).forEach((field, index) => {
if (field.blockType === 'step') {
current = { description: field.description ?? undefined, fields: [], index: steps.length, title: field.title ?? undefined }
steps.push(current)
return
}
if (!current) {
current = { fields: [], index: 0 }
steps.push(current)
}
current.fields.push({ field, index })
})
// Drop screens a trailing / doubled Step left empty.
const kept = steps.filter((s) => s.fields.length > 0)
return (kept.length ? kept : [{ fields: [], index: 0 }]).map((s, i) => ({ ...s, index: i }))
}
/** Starting values: checkbox → boolean, checkboxGroup → string[], the rest → string. */
export function initialBuilderValues(fields: BuilderField[] | null | undefined): Record<string, unknown> {
return Object.fromEntries(
inputFields(fields).map((f) => {
if (f.blockType === 'checkbox') {return [f.name, f.defaultValue === true]}
if (f.blockType === 'checkboxGroup') {return [f.name, Array.isArray(f.defaultValue) ? f.defaultValue : []]}
const v = f.defaultValue
return [f.name, typeof v === 'string' || typeof v === 'number' ? String(v) : '']
}),
)
}
const isBlank = (v: unknown) =>
v == null || v === false || (typeof v === 'string' && v.trim() === '') || (Array.isArray(v) && v.length === 0)
/** Errors for the given fields (one message per field), empty object = valid. */
export function validateBuilderFields(
fields: BuilderField[],
values: Record<string, unknown>,
texts: Pick<BuilderFormTexts, 'validation'>,
): Record<string, string> {
const errors: Record<string, string> = {}
for (const f of inputFields(fields)) {
const v = values[f.name]
const msg = texts.validation.replace('{field}', f.label || f.name)
if (isBlank(v)) {
if (f.required) {errors[f.name] = msg}
continue
}
if (f.blockType === 'email' && !isEmail(v)) {errors[f.name] = msg}
else if (f.blockType === 'number' && !Number.isFinite(Number(v))) {errors[f.name] = msg}
else if (f.blockType === 'checkboxGroup' && Array.isArray(v)) {
if ((f.minSelected && v.length < f.minSelected) || (f.maxSelected && v.length > f.maxSelected)) {errors[f.name] = msg}
}
}
return errors
}
/** Index of the step holding a field — to jump back to it after a failed submit. */
export function stepOfField(steps: BuilderStep[], name: string): number {
const i = steps.findIndex((s) => s.fields.some(({ field }) => field.name === name))
return i < 0 ? 0 : i
}
/** Browser autofill hint from the field type / a conventional name. */
export function autoCompleteFor(field: BuilderField): string | undefined {
if (field.blockType === 'email') {return 'email'}
if (field.blockType === 'country') {return 'country-name'}
const n = (field.name ?? '').toLowerCase()
if (/^(?:full_?)?name$|^imie/.test(n)) {return 'name'}
if (/phone|tel/.test(n)) {return 'tel'}
if (/company|organi[sz]ation|firma/.test(n)) {return 'organization'}
return undefined
}
+69
View File
@@ -0,0 +1,69 @@
import type { FormAnalyticsConfig } from './formAnalytics.js'
/**
* Shapes of a panel form as the frontend receives it (form-builder + ipal's
* step / checkboxGroup). Loose on purpose — the project's generated types fit.
*/
export type BuilderOption = { label?: null | string; value: string }
export type BuilderField = {
blockName?: null | string
/** text · textarea · email · number · date · select · radio · checkbox · checkboxGroup · country · state · message · step · a project's own type */
blockType: string
defaultValue?: unknown
/** step */
description?: null | string
id?: null | string
label?: null | string
maxSelected?: null | number
/** message — rich text, rendered on the server (RenderForm) */
message?: unknown
minSelected?: null | number
name?: null | string
options?: BuilderOption[] | null
placeholder?: null | string
required?: boolean | null
/** step */
title?: null | string
width?: null | number
}
export type BuilderFormDoc = {
analytics?: FormAnalyticsConfig
confirmationMessage?: unknown
confirmationType?: 'message' | 'redirect' | null
fields?: BuilderField[] | null
id: number | string
redirect?: { reference?: unknown; type?: 'custom' | 'reference' | null; url?: null | string } | null
submitButtonLabel?: null | string
title?: null | string
}
/** Texts the form needs — Notifications → form (getNotificationTexts) fits. */
export type BuilderFormTexts = {
back?: string
error?: string
next?: string
/** "Step {current} of {total}" */
stepOf?: string
success?: string
/** "Please check the {field} field" */
validation: string
}
/** The bound server action: createSubmitAction(...) bound to formId + locale (RenderForm does it). */
export type BuilderFormAction = (
values: Record<string, unknown>,
turnstileToken?: string,
) => Promise<{ field?: string; message?: string; reason?: string; success: boolean }>
export type BuilderStep = {
description?: string
/** Every field of the step, `message` blocks included, in panel order. */
fields: { field: BuilderField; index: number }[]
index: number
title?: string
}
/** Field types that carry no value. */
export const NON_INPUT_TYPES = new Set(['message', 'step'])
+11 -1
View File
@@ -5,6 +5,7 @@ import { formBuilderPlugin } from '@payloadcms/plugin-form-builder'
import type { FormsOption } from './types.js'
import { hasMinimumRole, isAdmin } from '../access/predicates.js'
import { checkboxGroupBlock, stepBlock } from './builderBlocks.js'
type AccessArgs = { req: { user?: unknown } }
@@ -52,16 +53,25 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
const adminGroup = forms.adminGroup === undefined ? 'Forms' : forms.adminGroup
const group = adminGroup ? { group: adminGroup } : {}
return formBuilderPlugin({
// Built-in types + ipal's `step` and `checkboxGroup` (builderBlocks). All are
// panel choices only — a form uses what the editor adds, nothing changes on
// existing forms. Switch any off with forms.fields.<type>: false.
fields: {
checkbox: true,
checkboxGroup: forms.fields?.checkboxGroup === false ? false : checkboxGroupBlock,
date: true,
email: true,
message: true,
number: true,
payment: false,
radio: true,
select: true,
step: forms.fields?.step === false ? false : stepBlock,
text: true,
textarea: true,
...forms.fields,
...Object.fromEntries(
Object.entries(forms.fields ?? {}).filter(([k]) => k !== 'checkboxGroup' && k !== 'step'),
),
},
...(forms.redirectRelationships
? { redirectRelationships: forms.redirectRelationships }
+5
View File
@@ -1,3 +1,8 @@
// Panel field types: step-by-step forms + multiple choice (enabled by default).
export { checkboxGroupBlock, stepBlock } from './builderBlocks.js'
// Pure panel-form logic (steps, values, validation) — the engine of useBuilderForm.
export { initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from './builderLogic.js'
export type { BuilderField, BuilderFormDoc, BuilderFormTexts, BuilderStep } from './builderTypes.js'
export { formAnalyticsOnSuccess } from './formAnalytics.js'
export type { FormAnalyticsConfig } from './formAnalytics.js'
// Panel-managed form analytics: fields (config-time) + onSuccess helper (client).
+2 -1
View File
@@ -147,7 +147,8 @@ export async function submitForm({
form: formId,
submissionData: Object.entries(validation.cleaned).map(([field, value]) => ({
field,
value: value == null ? '' : typeof value === 'object' ? JSON.stringify(value) : String(value as boolean | number | string),
// checkboxGroup → "a, b" (readable in the panel and in {{field}} e-mails)
value: value == null ? '' : Array.isArray(value) ? value.join(', ') : typeof value === 'object' ? JSON.stringify(value) : String(value as boolean | number | string),
})),
} as never,
})
+9
View File
@@ -34,11 +34,20 @@ export type FormsOption = {
/** Field types available in the form builder. Sensible defaults applied. */
fields?: {
checkbox?: boolean
/** Multiple choice from a list (ipal). Default on. */
checkboxGroup?: boolean
country?: boolean
date?: boolean
email?: boolean
message?: boolean
number?: boolean
payment?: boolean
/** Single choice from a list. Default on. */
radio?: boolean
select?: boolean
state?: boolean
/** Step-by-step forms: divider between screens (ipal). Default on. */
step?: boolean
text?: boolean
textarea?: boolean
}
+268
View File
@@ -0,0 +1,268 @@
'use client'
import type { ChangeEvent } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import type { BuilderField, BuilderFormAction, BuilderFormDoc, BuilderFormTexts, BuilderOption } from './builderTypes.js'
import { safeHref } from '../links/resolveLinkHref.js'
import { useOptionalTurnstile } from '../turnstile/TurnstileProvider.js'
import { autoCompleteFor, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields } from './builderLogic.js'
import { formAnalyticsOnSuccess } from './formAnalytics.js'
import { useForm } from './useForm.js'
export type UseBuilderFormOptions = {
/** Bound server action (RenderForm binds createSubmitAction to formId + locale). */
action: BuilderFormAction
form: BuilderFormDoc
/** Router navigation for redirect forms (e.g. router.push). Default: window.location.assign. */
navigate?: (href: string) => void
/** After a successful submit — on top of the panel's analytics event. */
onSuccess?: (values: Record<string, unknown>) => void
/** Redirect target resolved on the server (RenderForm). Falls back to the form's custom URL. */
redirectHref?: null | string
texts: BuilderFormTexts
}
/**
* Engine of every panel form: steps, values, per-step validation, Turnstile,
* submit through the server action, field errors from the server, redirect,
* analytics — and NO markup. <BuilderForm> renders a default on top of it; a
* form that looks or behaves differently (cards to pick from, a summary step,
* a custom field type) builds its own markup on the same hook:
*
* const f = useBuilderForm({ form, action, texts })
* <form onSubmit={f.submit}>
* {f.step.fields.map(({ field }) => <input key={field.name} {...f.getInputProps(field)} />)} // getTextareaProps, getSelectProps, getOptionProps
* <f.TurnstileWidget />
* {!f.isFirst && <button type="button" onClick={f.back}>{texts.back}</button>}
* <button type="submit">{f.isLast ? form.submitButtonLabel : texts.next}</button>
* </form>
*/
export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref, texts }: UseBuilderFormOptions) {
const fields = useMemo(() => form.fields ?? [], [form.fields])
const steps = useMemo(() => splitSteps(fields), [fields])
const inputs = useMemo(() => inputFields(fields), [fields])
const [stepIndex, setStepIndex] = useState(0)
const [resultMessage, setResultMessage] = useState<null | string>(null)
const ts = useOptionalTurnstile()
// A field error returned by the server (e.g. "email invalid") — applied after useForm records the failure.
const serverFieldError = useRef<{ field: string; message: string } | null>(null)
const submitAction = useCallback(
async (values: Record<string, unknown>, token?: string) => {
const result = await action(values, token)
if (result.success) {setResultMessage(result.message ?? null)}
else if (result.field) {serverFieldError.current = { field: result.field, message: result.message ?? texts.validation.replace('{field}', result.field) }}
return result
},
[action, texts.validation],
)
const validate = useCallback((values: Record<string, unknown>) => validateBuilderFields(inputs, values, texts), [inputs, texts])
const f = useForm<Record<string, unknown>>({
errorFallback: texts.error,
initialValues: initialBuilderValues(fields),
onSuccess: (_result, values) => {
formAnalyticsOnSuccess(form.analytics)(_result, values)
onSuccess?.(values)
if (form.confirmationType === 'redirect') {
const href = redirectHref ?? safeHref(form.redirect?.url)
if (href) {(navigate ?? ((h: string) => window.location.assign(h)))(href)}
}
},
requireTurnstile: ts.enabled,
submitAction,
validate,
})
const { setErrors, setTurnstileToken } = f
// Turnstile token lives in the provider; the engine needs it at submit.
useEffect(() => setTurnstileToken(ts.token), [ts.token, setTurnstileToken])
useEffect(() => {
if (!f.errorMessage) {return}
ts.reset()
const fieldError = serverFieldError.current
serverFieldError.current = null
if (fieldError) {
setErrors({ [fieldError.field]: fieldError.message })
setStepIndex(stepOfField(steps, fieldError.field))
}
}, [f.errorMessage])
const step = steps[Math.min(stepIndex, steps.length - 1)]
const isFirst = stepIndex === 0
const isLast = stepIndex >= steps.length - 1
/** Validates the current step and moves on. Returns false when the step has errors. */
const next = useCallback(() => {
const errors = validateBuilderFields(step.fields.map(({ field }) => field), f.values, texts)
setErrors(errors)
if (Object.keys(errors).length) {return false}
setStepIndex((i) => Math.min(i + 1, steps.length - 1))
return true
}, [step, f.values, texts, setErrors, steps.length])
const back = useCallback(() => setStepIndex((i) => Math.max(i - 1, 0)), [])
/** Jump to a step that's already been passed (a clickable progress bar). Forward jumps validate on the way. */
const goTo = useCallback(
(target: number) => {
if (target <= stepIndex) {return setStepIndex(Math.max(target, 0))}
for (let i = stepIndex; i < target; i++) {
const errors = validateBuilderFields(steps[i].fields.map(({ field }) => field), f.values, texts)
if (Object.keys(errors).length) {
setErrors(errors)
return setStepIndex(i)
}
}
setStepIndex(Math.min(target, steps.length - 1))
},
[stepIndex, steps, f.values, texts, setErrors],
)
/** onSubmit of the <form>: Next on earlier steps, send on the last one. */
const submit = useCallback(
(e?: { preventDefault?: () => void }) => {
e?.preventDefault?.()
if (!isLast) {return void next()}
const errors = validate(f.values)
if (Object.keys(errors).length) {
setErrors(errors)
return setStepIndex(stepOfField(steps, Object.keys(errors)[0]))
}
void f.handleSubmit()
},
[isLast, next, validate, f, setErrors, steps],
)
const fieldId = useCallback((field: BuilderField) => `ipal-f-${String(form.id)}-${field.name ?? ''}`, [form.id])
const errorId = useCallback((field: BuilderField) => `${fieldId(field)}-error`, [fieldId])
/** id, name, required and aria for any field's control (or its fieldset). */
const getFieldProps = useCallback(
(field: BuilderField) => {
const error = field.name ? f.errors[field.name] : undefined
return {
id: fieldId(field),
name: field.name ?? undefined,
'aria-describedby': error ? errorId(field) : undefined,
'aria-invalid': error ? true : undefined,
required: Boolean(field.required),
}
},
[f.errors, errorId, fieldId],
)
const textValue = useCallback((name: string) => {
const value = f.values[name]
return typeof value === 'string' ? value : value == null ? '' : String(value as number)
}, [f.values])
/** Everything an <input> needs, by field type: text · email · number · date · tel · checkbox. */
const getInputProps = useCallback(
(field: BuilderField) => {
const name = field.name ?? ''
const base = { ...getFieldProps(field), autoComplete: autoCompleteFor(field) }
if (field.blockType === 'checkbox') {
return { ...base, type: 'checkbox', checked: f.values[name] === true, onChange: (e: ChangeEvent<HTMLInputElement>) => f.setField(name, e.target.checked) }
}
const type =
field.blockType === 'email' ? 'email'
: field.blockType === 'number' ? 'number'
: field.blockType === 'date' ? 'date'
: base.autoComplete === 'tel' ? 'tel'
: 'text'
return {
...base,
...(type === 'number' ? { inputMode: 'decimal' as const } : {}),
type,
onChange: (e: ChangeEvent<HTMLInputElement>) => f.setField(name, e.target.value),
placeholder: field.placeholder ?? undefined,
value: textValue(name),
}
},
[f, getFieldProps, textValue],
)
/** Props of a <textarea>. */
const getTextareaProps = useCallback(
(field: BuilderField) => ({
...getFieldProps(field),
onChange: (e: ChangeEvent<HTMLTextAreaElement>) => f.setField(field.name ?? '', e.target.value),
placeholder: field.placeholder ?? undefined,
value: textValue(field.name ?? ''),
}),
[f, getFieldProps, textValue],
)
/** Props of a <select> (render the options yourself — field.options). */
const getSelectProps = useCallback(
(field: BuilderField) => ({
...getFieldProps(field),
autoComplete: autoCompleteFor(field),
onChange: (e: ChangeEvent<HTMLSelectElement>) => f.setField(field.name ?? '', e.target.value),
value: textValue(field.name ?? ''),
}),
[f, getFieldProps, textValue],
)
/** Props of one option's input in a radio group or checkboxGroup. */
const getOptionProps = useCallback(
(field: BuilderField, option: BuilderOption, i: number) => {
const name = field.name ?? ''
const id = `${fieldId(field)}-${i}`
if (field.blockType === 'checkboxGroup') {
const picked = Array.isArray(f.values[name]) ? (f.values[name] as string[]) : []
return {
id,
name,
type: 'checkbox',
checked: picked.includes(option.value),
onChange: (e: ChangeEvent<HTMLInputElement>) =>
f.setField(name, e.target.checked ? [...picked, option.value] : picked.filter((v) => v !== option.value)),
value: option.value,
}
}
return {
id,
name,
type: 'radio',
checked: f.values[name] === option.value,
onChange: () => f.setField(name, option.value),
required: Boolean(field.required) && i === 0,
value: option.value,
}
},
[f, fieldId],
)
return {
...f,
back,
errorId,
fieldId,
form,
getFieldProps,
getInputProps,
getOptionProps,
getSelectProps,
getTextareaProps,
goTo,
isFirst,
isLast,
next,
/** Message the server returned on success (Notifications → success). */
resultMessage,
step,
stepIndex,
steps,
submit,
total: steps.length,
TurnstileWidget: ts.TurnstileWidget,
}
}
export type BuilderFormApi = ReturnType<typeof useBuilderForm>
+30 -4
View File
@@ -4,8 +4,11 @@ import type { BasePayload } from 'payload'
type FormField = {
blockType?: string
label?: string
/** checkboxGroup limits. */
maxSelected?: null | number
minSelected?: null | number
name?: string
/** select / radio choices defined in the panel. */
/** select / radio / checkboxGroup choices defined in the panel. */
options?: { value?: unknown }[] | null
required?: boolean | null
}
@@ -35,7 +38,10 @@ export type FormValidationResult =
| { ok: false; reason: 'not_found' }
/** Field block types that don't carry a submittable value. */
const NON_DATA_BLOCKS = new Set(['message'])
const NON_DATA_BLOCKS = new Set(['message', 'step'])
/** YYYY-MM-DD (a date input) or a full ISO timestamp. */
const DATE = /^\d{4}-\d{2}-\d{2}(?:T[\d:.]+(?:Z|[+-]\d{2}:?\d{2})?)?$/
/**
* Keys injected by the captcha widget itself, not by the form definition.
@@ -63,7 +69,7 @@ const MAX_EMAIL_LENGTH = 254
// eslint-disable-next-line no-control-regex
const CONTROL = /[\u0000-\u0008\v\f\u000E-\u001F\u007F\u202A-\u202E\u2066-\u2069]/g
type Checked = { error?: 'invalid_format'; value?: unknown }
type Checked = { error?: 'invalid_format' | 'required'; value?: unknown }
/**
* Type-checks one value against its field's block type, as defined in the
@@ -76,6 +82,23 @@ function checkValue(field: FormField, value: unknown): Checked {
switch (field.blockType) {
case 'checkbox':
return typeof value === 'boolean' ? { value } : { error: 'invalid_format' }
case 'checkboxGroup': {
// string[] of distinct option values, within the panel's min/max.
if (!Array.isArray(value) || value.some((v) => typeof v !== 'string')) {return { error: 'invalid_format' }}
const picked = [...new Set(value as string[])]
const allowed = new Set((field.options ?? []).map((o) => String(o?.value)))
if (picked.some((v) => !allowed.has(v))) {return { error: 'invalid_format' }}
if (picked.length === 0) {return { value: undefined }}
if (field.minSelected && picked.length < field.minSelected) {return { error: 'required' }}
if (field.maxSelected && picked.length > field.maxSelected) {return { error: 'invalid_format' }}
return { value: picked }
}
case 'date': {
if (typeof value !== 'string' || !DATE.test(value.trim()) || Number.isNaN(Date.parse(value.trim()))) {
return { error: 'invalid_format' }
}
return { value: value.trim() }
}
case 'email': {
if (typeof value !== 'string') {return { error: 'invalid_format' }}
const email = value.trim()
@@ -154,7 +177,10 @@ export async function validateSubmission(
for (const field of fields) {
const value = data[field.name]
const isBlank =
value == null || (typeof value === 'string' && value.trim() === '') || value === false
value == null ||
(typeof value === 'string' && value.trim() === '') ||
value === false ||
(Array.isArray(value) && value.length === 0)
// GDPR consent gate: a field matching the consent name must be truthy
// (checked). Enforced independently of `required`, so it can't be weakened
+74
View File
@@ -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>
</>
)
}
+178 -1
View File
@@ -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>
+138
View File
@@ -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} />
}
}
+2
View File
@@ -2,3 +2,5 @@ export { buildLinkField, buildLinksField } from './buildLinkField.js'
export type { BuildLinkFieldOptions, BuildLinksFieldOptions, LinkAppearance } from './buildLinkField.js'
export { resolveLinkHref, safeHref } from './resolveLinkHref.js'
export type { LinkValue, ResolveLinkHrefOptions } from './resolveLinkHref.js'
export { homeSlugFrom, resolveLink, resolveNav } from './resolveNav.js'
export type { NavItem, ResolvedLink, ResolveNavOptions } from './resolveNav.js'
+77
View File
@@ -0,0 +1,77 @@
import type { LinkValue, ResolveLinkHrefOptions } from './resolveLinkHref.js'
import { resolveLinkHref } from './resolveLinkHref.js'
/**
* Everything an <a>/<Link> needs for a panel link — the project keeps the
* element and the classes (Button variants), the plugin decides the rest:
* href, new tab (files always open in one), rel, and whether it's internal
* (render next/link) or not (plain <a>).
*/
export type ResolvedLink = {
/** `link.appearance` from the panel (primary / secondary / link) — map it to your Button classes. */
appearance?: string
href: string
/** Internal page → next/link; external URL / file / mailto → <a>. */
internal: boolean
label: string
newTab: boolean
/** Spread on the element: target + rel for a new tab, nothing otherwise. */
targetProps: { rel: string; target: '_blank' } | Record<string, never>
}
/** A panel link → ResolvedLink, or null when it leads nowhere in this locale (no page, no file, unsafe URL). */
export function resolveLink(link: LinkValue | null | undefined, options: ResolveLinkHrefOptions): null | ResolvedLink {
const href = resolveLinkHref(link, options)
if (!link || !href) {return null}
const newTab = Boolean(link.newTab) || link.type === 'file'
return {
...(link.appearance ? { appearance: link.appearance } : {}),
href,
internal: (link.type ?? 'internal') === 'internal',
label: link.label ?? '',
newTab,
targetProps: newTab ? { rel: 'noopener noreferrer', target: '_blank' } : {},
}
}
export type NavItem = {
/** Nested items (dropdown), already resolved. */
children: NavItem[]
} & ResolvedLink
export type ResolveNavOptions = {
/** Field with the nested items inside an item. Default 'subItems'. */
childrenField?: string
/** Field with the link inside an item. Default 'link'. */
linkField?: string
} & ResolveLinkHrefOptions
/**
* Menu items from a Header/Footer global → plain, serializable items (safe to
* pass to a client MobileNav). Items whose link leads nowhere in this locale
* — a deleted or untranslated page — are dropped instead of rendering "#".
*
* const items = resolveNav(header.navItems, { locale, config: i18nConfig, homeSlug })
* // [{ href, label, newTab, internal, targetProps, children: [...] }]
*
* Any depth; the item shape is configurable (linkField, childrenField).
*/
export function resolveNav(items: unknown, options: ResolveNavOptions): NavItem[] {
const { childrenField = 'subItems', linkField = 'link', ...linkOptions } = options
if (!Array.isArray(items)) {return []}
return items.flatMap((item) => {
if (!item || typeof item !== 'object') {return []}
const record = item as Record<string, unknown>
const link = resolveLink(record[linkField] as LinkValue, linkOptions)
if (!link || !link.label) {return []}
return [{ ...link, children: resolveNav(record[childrenField], options) }]
})
}
/** Homepage slug from SiteSettings (`homepage` relationship, populated) — for links that collapse to /{locale}. */
export function homeSlugFrom(settings: unknown, field = 'homepage'): string | undefined {
const home = settings && typeof settings === 'object' ? (settings as Record<string, unknown>)[field] : undefined
const slug = home && typeof home === 'object' ? (home as { slug?: unknown }).slug : undefined
return typeof slug === 'string' && slug ? slug : undefined
}
+1 -1
View File
@@ -46,7 +46,7 @@ import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit
const DEFAULT_PROTOCOL = '2025-06-18'
type CreateMcpRouteArgs = {
export type CreateMcpRouteArgs = {
/** Absolute origin for building result URLs. */
baseUrl?: string
/** How to read the client IP for the rate limit — see clientIp(). */
+3
View File
@@ -7,10 +7,13 @@ import type { NotificationTexts } from './types.js'
*/
export const NOTIFICATION_FALLBACK: NotificationTexts = {
form: {
back: 'Back',
consent: 'Please accept the privacy policy to continue.',
error: 'Something went wrong. Please try again later.',
next: 'Next',
notFound: 'This form is no longer available.',
rateLimited: 'Too many attempts. Please wait a moment and try again.',
stepOf: 'Step {current} of {total}',
success: 'Thank you — your message has been sent.',
turnstile: 'Captcha verification failed. Please try again.',
validation: 'Please check the {field} field and try again.',
@@ -28,10 +28,13 @@ export async function getNotificationTexts({
return {
form: {
back: f.back || fb.back,
consent: f.consent || fb.consent,
error: f.error || fb.error,
next: f.next || fb.next,
notFound: f.notFound || fb.notFound,
rateLimited: f.rateLimited || fb.rateLimited,
stepOf: f.stepOf || fb.stepOf,
success: f.success || fb.success,
turnstile: f.turnstile || fb.turnstile,
validation: f.validation || fb.validation,
+6
View File
@@ -3,11 +3,17 @@
* `form` maps submitForm result codes to user-facing messages.
*/
export type FormNotificationTexts = {
/** Step-by-step forms: "Back" button. */
back: string
/** Shown when a required GDPR consent checkbox was left unchecked. */
consent: string
error: string
/** Step-by-step forms: "Next" button. */
next: string
notFound: string
rateLimited: string
/** Step-by-step forms: progress, with {current} and {total}. */
stepOf: string
success: string
turnstile: string
/** May contain the {field} placeholder — resolve with resolveValidationText. */
@@ -64,6 +64,21 @@ export function useTurnstile(): {
if (!ctx) {
throw new Error('useTurnstile must be used within <TurnstileProvider>')
}
return useTurnstileFrom(ctx)
}
const NO_PROVIDER: TurnstileContextValue = { setToken: () => {}, siteKey: null, token: null }
/**
* useTurnstile without the provider requirement: outside <TurnstileProvider>
* it reports `enabled: false` (no widget, no token) instead of throwing. For
* shared components (BuilderForm) that must not crash a page missing the provider.
*/
export function useOptionalTurnstile(): ReturnType<typeof useTurnstile> {
return useTurnstileFrom(use(TurnstileContext) ?? NO_PROVIDER)
}
function useTurnstileFrom(ctx: TurnstileContextValue): ReturnType<typeof useTurnstile> {
const { setToken, siteKey, token } = ctx
const reset = useCallback(() => setToken(null), [setToken])
+1 -1
View File
@@ -3,4 +3,4 @@
// the server-only verify never leaks into a browser bundle.
export { Turnstile } from './Turnstile.js'
export type { TurnstileProps } from './Turnstile.js'
export { TurnstileProvider, useTurnstile } from './TurnstileProvider.js'
export { TurnstileProvider, useOptionalTurnstile, useTurnstile } from './TurnstileProvider.js'
+133
View File
@@ -0,0 +1,133 @@
import { createElement, isValidElement } from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, test, vi } from 'vitest'
import type { BuilderField, BuilderFormDoc } from '../src/modules/forms/builderTypes.js'
import { BuilderForm } from '../src/modules/forms/BuilderForm.js'
import { autoCompleteFor, initialBuilderValues, splitSteps, stepOfField, validateBuilderFields } from '../src/modules/forms/builderLogic.js'
import { RenderForm } from '../src/modules/forms/RenderForm.js'
vi.mock('server-only', () => ({}))
const fields: BuilderField[] = [
{ name: 'name', blockType: 'text', label: 'Imię', required: true },
{ name: 'email', blockType: 'email', label: 'E-mail', required: true },
{ blockType: 'step', title: 'Szczegóły' },
{ name: 'budget', blockType: 'radio', label: 'Budżet', options: [{ label: 'Mały', value: 's' }, { label: 'Duży', value: 'l' }], required: true },
{ name: 'services', blockType: 'checkboxGroup', label: 'Usługi', maxSelected: 2, options: [{ value: 'www' }, { value: 'seo' }, { value: 'ads' }] },
{ blockType: 'message', message: { root: {} } },
{ name: 'deadline', blockType: 'date', label: 'Termin' },
{ name: 'consent', blockType: 'checkbox', label: 'Zgoda', required: true },
]
const texts = { back: 'Wstecz', next: 'Dalej', stepOf: 'Krok {current} z {total}', validation: 'Sprawdź pole {field}' }
describe('panel form logic', () => {
test('Step blocks split the form into screens; fields before the first Step are screen 1', () => {
const steps = splitSteps(fields)
expect(steps.map((s) => ({ names: s.fields.map(({ field }) => field.name ?? field.blockType), title: s.title }))).toEqual([
{ names: ['name', 'email'], title: undefined },
{ names: ['budget', 'services', 'message', 'deadline', 'consent'], title: 'Szczegóły' },
])
expect(stepOfField(steps, 'consent')).toBe(1)
})
test('no Steps → one screen; trailing or doubled Steps leave no empty screens', () => {
expect(splitSteps(fields.filter((f) => f.blockType !== 'step'))).toHaveLength(1)
expect(splitSteps([{ blockType: 'step' }, { blockType: 'step' }, { name: 'a', blockType: 'text' }, { blockType: 'step' }])).toHaveLength(1)
})
test('initial values by type', () => {
expect(initialBuilderValues(fields)).toEqual({ name: '', budget: '', consent: false, deadline: '', email: '', services: [] })
})
test('validation: required, e-mail, choice limits — only for the fields given (one step)', () => {
const values = { ...initialBuilderValues(fields), email: 'zły', services: ['www', 'seo', 'ads'] }
expect(validateBuilderFields(splitSteps(fields)[0].fields.map(({ field }) => field), values, texts)).toEqual({
name: 'Sprawdź pole Imię',
email: 'Sprawdź pole E-mail',
})
expect(validateBuilderFields(fields, values, texts)).toMatchObject({ budget: expect.any(String), consent: expect.any(String), services: expect.any(String) })
})
test('autofill hints', () => {
expect(autoCompleteFor({ name: 'phone', blockType: 'text' })).toBe('tel')
expect(autoCompleteFor({ name: 'x', blockType: 'email' })).toBe('email')
expect(autoCompleteFor({ name: 'message', blockType: 'text' })).toBeUndefined()
})
})
const form: BuilderFormDoc = { id: 7, fields, submitButtonLabel: 'Wyślij' }
const action = async () => ({ success: true })
describe('BuilderForm markup', () => {
test('unstyled by default: no class attributes, data hooks, honeypot, progress and Next on step 1', () => {
const html = renderToStaticMarkup(createElement(BuilderForm, { action, form, texts }))
expect(html).not.toMatch(/class="/)
expect(html).toContain('data-ipal="form"')
expect(html).toContain('name="company_url"')
expect(html).toContain('Krok 1 z 2')
expect(html).toContain('>Dalej</button>')
expect(html).not.toContain('Wyślij')
expect(html).toMatch(/<label for="ipal-f-7-name">Imię<\/label><input[^>]*id="ipal-f-7-name"[^>]*required=""/)
expect(html).toContain('autoComplete="email"')
})
test('classNames go where they belong; a single-screen form shows the submit label', () => {
const html = renderToStaticMarkup(
createElement(BuilderForm, {
action,
classNames: { fieldHalf: 'half', form: 'f', input: 'in', submit: 'btn' },
form: { ...form, fields: [{ name: 'a', blockType: 'text', label: 'A', width: 50 }] },
texts,
}),
)
expect(html).toContain('<form class="f"')
expect(html).toContain('class="half"')
expect(html).toContain('class="in"')
expect(html).toContain('<button class="btn" type="submit">Wyślij</button>')
expect(html).not.toContain('Krok')
})
test('radio and checkbox groups are fieldsets with a legend', () => {
const html = renderToStaticMarkup(
createElement(BuilderForm, { action, form: { ...form, fields: fields.slice(3, 5) }, texts }),
)
expect(html).toMatch(/<fieldset[^>]*id="ipal-f-7-budget"><legend>Budżet<\/legend>/)
expect(html).toMatch(/type="radio"[^>]*value="s"|value="s"[^>]*type="radio"/)
expect(html).toMatch(/<fieldset[^>]*id="ipal-f-7-services"><legend>Usługi<\/legend>/)
})
test('renderField replaces chosen fields and can reuse the default', () => {
const html = renderToStaticMarkup(
createElement(BuilderForm, {
action,
form: { ...form, fields: fields.slice(0, 2) },
renderField: ({ defaultRender, field }) => (field.name === 'email' ? createElement('div', { 'data-x': 'wrap' }, defaultRender()) : undefined),
texts,
}),
)
expect(html).toMatch(/<div data-x="wrap"><label for="ipal-f-7-email">/)
})
})
describe('RenderForm', () => {
test('passes only the public part of the form to the browser — never the Emails tab', () => {
const doc = {
...form,
confirmationType: 'redirect' as const,
emails: [{ emailTo: '[email protected]' }],
redirect: { type: 'custom' as const, url: 'javascript:alert(1)' },
}
const el = RenderForm({ action: async () => ({ message: '', success: true }), form: doc, locale: 'pl', texts })
expect(isValidElement(el)).toBe(true)
const props = (el as { props: { form: Record<string, unknown>; redirectHref: unknown } }).props
expect(JSON.stringify(props.form)).not.toContain('[email protected]')
expect(props.form).not.toHaveProperty('emails')
expect(props.redirectHref).toBeNull() // unsafe scheme dropped
})
test('a bare id or null renders nothing (no placeholder form)', () => {
expect(RenderForm({ action: async () => ({ message: '', success: true }), form: 5, locale: 'pl', texts })).toBeNull()
})
})
+35
View File
@@ -65,3 +65,38 @@ describe('form validation — injection and abuse', () => {
expect(await check({ count: ' 42 ' })).toMatchObject({ cleaned: { count: 42 }, ok: true })
})
})
describe('form validation — choice lists and dates', () => {
const { payload: p } = fakePayload({
forms: {
g: {
fields: [
{ name: 'services', blockType: 'checkboxGroup', maxSelected: 2, minSelected: 1, options: [{ value: 'www' }, { value: 'seo' }, { value: 'ads' }] },
{ name: 'size', blockType: 'radio', options: [{ value: 's' }, { value: 'l' }] },
{ name: 'deadline', blockType: 'date' },
{ blockType: 'step' },
],
},
},
})
const v = (data: Record<string, unknown>) => validateSubmission(p, 'g', data)
test('checkbox group: only configured values, deduplicated, within min/max', async () => {
expect(await v({ services: ['www', 'seo', 'www'] })).toMatchObject({ cleaned: { services: ['www', 'seo'] }, ok: true })
expect(await v({ services: ['www', '<b>x</b>'] })).toMatchObject({ field: 'services', kind: 'invalid_format' })
expect(await v({ services: ['www', 'seo', 'ads'] })).toMatchObject({ field: 'services', kind: 'invalid_format' })
expect(await v({ services: 'www' })).toMatchObject({ field: 'services', kind: 'invalid_format' })
expect(await v({ services: [{ $ne: 1 }] })).toMatchObject({ field: 'services', kind: 'invalid_format' })
})
test('radio accepts only its options; date must be a real date', async () => {
expect(await v({ deadline: '2026-11-30', size: 'l' })).toMatchObject({ cleaned: { deadline: '2026-11-30', size: 'l' }, ok: true })
expect(await v({ size: 'xl' })).toMatchObject({ field: 'size', kind: 'invalid_format' })
expect(await v({ deadline: 'jutro' })).toMatchObject({ field: 'deadline', kind: 'invalid_format' })
expect(await v({ deadline: '2026-13-45' })).toMatchObject({ field: 'deadline', kind: 'invalid_format' })
})
test('a Step block carries no value and is not an unknown field', async () => {
expect(await v({})).toMatchObject({ ok: true })
})
})
+81
View File
@@ -16,6 +16,7 @@ import { buildConsentLogEndpoint } from '../src/modules/consent/consentLog.js'
import { getCookieTable } from '../src/modules/consent/getConsentTexts.js'
import { submitForm } from '../src/modules/forms/submitForm.js'
import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js'
import { createPageRoute } from '../src/modules/frontend/pageRoute.js'
import { ipalKit } from '../src/plugin.js'
vi.mock('server-only', () => ({}))
@@ -117,6 +118,41 @@ describe('forms against a real Payload', () => {
expect(await send({ name: 'Ala', consent: true, role: 'admin' })).toMatchObject({ kind: 'unknown_fields' })
})
test('step-by-step form with a checkbox group, radio and date: built in the panel, stored readable', async () => {
const multi = await payload.create({
collection: 'forms' as never,
data: {
confirmationType: 'redirect',
fields: [
{ name: 'name', blockType: 'text', label: 'Imię', required: true },
{ blockType: 'step', title: 'Szczegóły' },
{ name: 'services', blockType: 'checkboxGroup', label: 'Usługi', options: [{ label: 'Strona', value: 'www' }, { label: 'SEO', value: 'seo' }], required: true },
{ name: 'size', blockType: 'radio', label: 'Wielkość', options: [{ label: 'Mała', value: 's' }, { label: 'Duża', value: 'l' }] },
{ name: 'deadline', blockType: 'date', label: 'Termin' },
],
redirect: { url: '/dziekujemy' },
title: 'Wycena',
} as never,
})
const result = await submitForm({
data: { name: 'Ala', deadline: '2026-12-01', services: ['www', 'seo'], size: 'l' },
formId: String(multi.id),
ip: '10.7.0.9',
payload,
})
expect(result).toMatchObject({ success: true })
if (!result.success) {return}
const stored = (await payload.findByID({ id: result.submissionId, collection: 'form-submissions' as never, depth: 0 })) as unknown as {
submissionData: { field: string; value: string }[]
}
expect(stored.submissionData.map(({ field, value }) => [field, value])).toEqual([
['name', 'Ala'],
['services', 'www, seo'],
['size', 'l'],
['deadline', '2026-12-01'],
])
})
test('REST/anonymous creation of submissions is closed (only submitForm writes)', async () => {
await expect(
payload.create({
@@ -178,6 +214,51 @@ describe('getPageJsonLd', () => {
})
})
describe('one-call helpers — layout, page, GEO routes', () => {
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } as const
const h = () => createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n, mcp: { serverName: 'acme-site' } })
test('getSiteShell: consent, analytics, Turnstile, form texts and site JSON-LD in one call', async () => {
await payload.updateGlobal({ slug: 'site-settings' as never, data: { siteName: 'Acme' } as never })
const shell = await h().getSiteShell('pl')
expect(shell.turnstileSiteKey).toBeNull()
expect(shell.consent.buttons.acceptAll).toEqual(expect.any(String))
expect(shell.formTexts).toMatchObject({ next: 'Next', stepOf: 'Step {current} of {total}' })
expect(shell.jsonLd.map((n) => n['@type'])).toEqual(['WebSite', 'Organization'])
expect(shell.jsonLd.every((n) => !('@context' in n))).toBe(true)
const custom = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n, siteJsonLd: false })
expect((await custom.getSiteShell('pl')).jsonLd).toEqual([])
})
test('createPageRoute: renders a page with its JSON-LD, 404s an unknown slug', async () => {
await payload.create({ collection: 'pages' as never, data: { slug: 'uslugi', title: 'Usługi' } as never })
const notFound = vi.fn(() => {
throw new Error('NEXT_NOT_FOUND')
}) as unknown as () => never
const permanentRedirect = vi.fn() as unknown as (url: string) => never
const route = createPageRoute(h(), { blocks: {}, notFound, permanentRedirect })
const el = (await route.Page({ params: Promise.resolve({ slug: ['uslugi'] }) })) as { props: { children: unknown[] } }
expect(JSON.stringify(el.props.children[0])).toContain('Usługi')
await expect(route.Page({ params: Promise.resolve({ slug: ['nie-ma'] }) })).rejects.toThrow('NEXT_NOT_FOUND')
expect((await route.generateMetadata({ params: Promise.resolve({ slug: ['uslugi'] }) })).alternates?.canonical).toBe('https://acme.pl/uslugi')
})
test('route handlers answer without per-file configuration', async () => {
const helpers = h()
const llms = await helpers.llmsRoute()
expect(llms.status).toBe(200)
expect(await llms.text()).toContain('https://acme.pl/uslugi')
expect((await helpers.healthRoute()).status).toBe(200)
expect((await helpers.indexNowKeyRoute()).status).toBe(404) // no key configured
const mcp = await helpers.mcpPOST(
new Request('https://acme.pl/api/mcp', { body: JSON.stringify({ id: 1, jsonrpc: '2.0', method: 'initialize' }), headers: { 'content-type': 'application/json' }, method: 'POST' }),
)
expect(JSON.stringify(await mcp.json())).toContain('acme-site')
const md = await helpers.markdownRoute(new Request('https://acme.pl/md/uslugi'), { params: Promise.resolve({ slug: ['uslugi'], locale: 'pl' }) })
expect(md.status).toBe(200)
})
})
describe('consent log', () => {
const post = (body: unknown, ip = '10.6.0.1') =>
buildConsentLogEndpoint().handler({
+78
View File
@@ -0,0 +1,78 @@
import { describe, expect, test } from 'vitest'
import { buildSectionHeaderField, buildSectionSettingsField } from '../src/modules/blocks/sectionFields.js'
import { homeSlugFrom, resolveLink, resolveNav } from '../src/modules/links/resolveNav.js'
const config = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] }
const opts = { config, homeSlug: 'start', locale: 'pl' }
const page = (slug: string) => ({ type: 'internal' as const, label: slug, page: { slug } })
describe('resolveLink', () => {
test('internal page → next/link, no target', () => {
expect(resolveLink(page('kontakt'), opts)).toEqual({ href: '/pl/kontakt', internal: true, label: 'kontakt', newTab: false, targetProps: {} })
})
test('files always open in a new tab with rel; appearance is passed through', () => {
expect(resolveLink({ type: 'file', appearance: 'primary', file: { url: '/media/cennik.pdf' }, label: 'Cennik' }, opts)).toMatchObject({
appearance: 'primary',
href: '/media/cennik.pdf',
internal: false,
targetProps: { rel: 'noopener noreferrer', target: '_blank' },
})
})
test('nowhere → null: unsafe URL, missing page, empty link', () => {
expect(resolveLink({ type: 'external', url: 'javascript:alert(1)' }, opts)).toBeNull()
expect(resolveLink({ type: 'internal', page: 5 }, opts)).toBeNull()
expect(resolveLink(null, opts)).toBeNull()
})
test('the homepage collapses to the locale root', () => {
expect(resolveLink(page('start'), opts)?.href).toBe('/pl')
})
})
describe('resolveNav', () => {
test('nested items resolved; dead or unlabeled items dropped', () => {
const items = [
{ link: page('oferta'), subItems: [{ link: page('www') }, { link: { type: 'internal', label: 'x', page: null } }] },
{ link: { type: 'external', url: 'https://x.pl' } }, // no label
{ link: page('kontakt') },
]
const nav = resolveNav(items, opts)
expect(nav.map((i) => [i.href, i.children.map((c) => c.href)])).toEqual([
['/pl/oferta', ['/pl/www']],
['/pl/kontakt', []],
])
})
test('custom item shape and junk input', () => {
expect(resolveNav([{ children: [{ to: page('a') }], to: page('b') }], { ...opts, childrenField: 'children', linkField: 'to' })[0].children[0].href).toBe('/pl/a')
expect(resolveNav(null, opts)).toEqual([])
expect(resolveNav('x', opts)).toEqual([])
})
test('homeSlugFrom reads a populated homepage only', () => {
expect(homeSlugFrom({ homepage: { slug: 'start' } })).toBe('start')
expect(homeSlugFrom({ homepage: 3 })).toBeUndefined()
expect(homeSlugFrom(null)).toBeUndefined()
})
})
describe('section fields', () => {
test('defaults match the documented shape (types SectionHeaderData / SectionSettings)', () => {
const header = buildSectionHeaderField()
expect(header).toMatchObject({ name: 'header', interfaceName: 'SectionHeaderData' })
expect(header.fields.map((f) => ('name' in f ? f.name : ''))).toEqual(['eyebrow', 'heading', 'intro'])
const settings = buildSectionSettingsField()
expect(settings).toMatchObject({ name: 'settings', admin: { position: 'sidebar' }, interfaceName: 'SectionSettings' })
expect(settings.fields.map((f) => ('name' in f ? f.name : ''))).toEqual(['anchor', 'background'])
})
test('the project decides: own backgrounds, no anchor, extra fields', () => {
const s = buildSectionSettingsField({ anchor: false, backgrounds: [{ label: 'Brand', value: 'brand' }], fields: [{ name: 'spacing', type: 'text' }] })
expect(s.fields.map((f) => ('name' in f ? f.name : ''))).toEqual(['background', 'spacing'])
expect(s.fields[0]).toMatchObject({ defaultValue: 'brand' })
expect(buildSectionSettingsField({ backgrounds: false }).fields.map((f) => ('name' in f ? f.name : ''))).toEqual(['anchor'])
})
})