Import instead of code: panel forms (steps, choice lists, dates), layout, page route, GEO routes, links, section fields
- Forms: step and checkboxGroup field types (radio, date on), server validation for them, useBuilderForm (logic) + BuilderForm (unstyled default) + RenderForm (/rsc: rich text, bound action, public part of the form only — the Emails tab never reaches the browser) - Notifications: next / back / stepOf texts - createContentHelpers: getSiteShell, getFormTexts, getLinkOptions, resolveLink, resolveNav, resolvePageRedirect, one-line route handlers (llms, llms-full, md, mcp, health, indexnow, manifest) - /rsc: SiteProviders, createPageRoute, createNotFoundPage - resolveLink / resolveNav / homeSlugFrom, buildSectionHeaderField / buildSectionSettingsField - Dev sandbox frontend built on these imports; tests (unit + real Payload) Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,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>
|
||||
)
|
||||
}
|
||||
@@ -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}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -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' },
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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'])
|
||||
@@ -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 }
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user