diff --git a/dev/app/(frontend)/[locale]/[[...slug]]/page.tsx b/dev/app/(frontend)/[locale]/[[...slug]]/page.tsx new file mode 100644 index 0000000..bf4962a --- /dev/null +++ b/dev/app/(frontend)/[locale]/[[...slug]]/page.tsx @@ -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 diff --git a/dev/app/(frontend)/[locale]/actions.ts b/dev/app/(frontend)/[locale]/actions.ts new file mode 100644 index 0000000..d2e3538 --- /dev/null +++ b/dev/app/(frontend)/[locale]/actions.ts @@ -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 }) diff --git a/dev/app/(frontend)/[locale]/layout.tsx b/dev/app/(frontend)/[locale]/layout.tsx new file mode 100644 index 0000000..bfe74ac --- /dev/null +++ b/dev/app/(frontend)/[locale]/layout.tsx @@ -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 ( + + + } logEndpoint="/api/ipal/consent" shell={await getSiteShell(locale)}> +
{children}
+
+ + + ) +} diff --git a/dev/app/(frontend)/[locale]/not-found.tsx b/dev/app/(frontend)/[locale]/not-found.tsx new file mode 100644 index 0000000..9252c29 --- /dev/null +++ b/dev/app/(frontend)/[locale]/not-found.tsx @@ -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:

404

}) diff --git a/dev/app/(frontend)/[locale]/styles.css b/dev/app/(frontend)/[locale]/styles.css new file mode 100644 index 0000000..d121be7 --- /dev/null +++ b/dev/app/(frontend)/[locale]/styles.css @@ -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; } diff --git a/dev/app/api/mcp/route.ts b/dev/app/api/mcp/route.ts new file mode 100644 index 0000000..53201e3 --- /dev/null +++ b/dev/app/api/mcp/route.ts @@ -0,0 +1,2 @@ +export { mcpGET as GET, mcpPOST as POST } from '../../../lib/content.js' +export const dynamic = 'force-dynamic' diff --git a/dev/app/llms.txt/route.ts b/dev/app/llms.txt/route.ts new file mode 100644 index 0000000..4ae6b5d --- /dev/null +++ b/dev/app/llms.txt/route.ts @@ -0,0 +1,2 @@ +export { llmsRoute as GET } from '../../lib/content.js' +export const dynamic = 'force-dynamic' diff --git a/dev/blocks/FormBlock.tsx b/dev/blocks/FormBlock.tsx new file mode 100644 index 0000000..b929327 --- /dev/null +++ b/dev/blocks/FormBlock.tsx @@ -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 +} diff --git a/dev/i18n.config.ts b/dev/i18n.config.ts new file mode 100644 index 0000000..6309547 --- /dev/null +++ b/dev/i18n.config.ts @@ -0,0 +1,7 @@ +export const i18nConfig = { + defaultLocale: 'pl', + locales: [ + { code: 'pl', label: 'Polski' }, + { code: 'en', label: 'English' }, + ], +} as const diff --git a/dev/lib/content.ts b/dev/lib/content.ts new file mode 100644 index 0000000..6bedc17 --- /dev/null +++ b/dev/lib/content.ts @@ -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' } }) diff --git a/dev/payload.config.ts b/dev/payload.config.ts index a29b654..bedf731 100644 --- a/dev/payload.config.ts +++ b/dev/payload.config.ts @@ -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'] }, diff --git a/dev/seed.ts b/dev/seed.ts index c6ebdd9..ca79a9a 100644 --- a/dev/seed.ts +++ b/dev/seed.ts @@ -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})`) +} + diff --git a/src/exports/client.ts b/src/exports/client.ts index dee3f4a..69785c2 100644 --- a/src/exports/client.ts +++ b/src/exports/client.ts @@ -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' diff --git a/src/exports/rsc.ts b/src/exports/rsc.ts index 6e1cecb..4e84a24 100644 --- a/src/exports/rsc.ts +++ b/src/exports/rsc.ts @@ -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' diff --git a/src/globals/Notifications/fields.ts b/src/globals/Notifications/fields.ts index fd2891b..2ee0994 100644 --- a/src/globals/Notifications/fields.ts +++ b/src/globals/Notifications/fields.ts @@ -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', }, diff --git a/src/index.ts b/src/index.ts index db0b092..04d4f43 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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' diff --git a/src/modules/blocks/index.ts b/src/modules/blocks/index.ts index c75fbc8..1d8cc81 100644 --- a/src/modules/blocks/index.ts +++ b/src/modules/blocks/index.ts @@ -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' diff --git a/src/modules/blocks/sectionFields.ts b/src/modules/blocks/sectionFields.ts new file mode 100644 index 0000000..162bd7a --- /dev/null +++ b/src/modules/blocks/sectionFields.ts @@ -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
/ 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 . */ +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
. + * 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', + } +} diff --git a/src/modules/forms/BuilderForm.tsx b/src/modules/forms/BuilderForm.tsx new file mode 100644 index 0000000..01af198 --- /dev/null +++ b/src/modules/forms/BuilderForm.tsx @@ -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 + /** + * 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(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('[aria-invalid="true"], input, select, textarea') ?? el + target?.focus() + }, [f.stepIndex]) + + if (f.isSuccess && options.form.confirmationType !== 'redirect') { + return ( +
+ {confirmation ?? f.resultMessage ?? options.texts.success} +
+ ) + } + + const label = (field: BuilderField) => ( + <> + {field.label} + {field.required && requiredMark ? {requiredMark} : null} + + ) + const errorOf = (field: BuilderField) => { + const error = field.name ? f.errors[field.name] : undefined + return error ?

{error}

: null + } + + const defaultField = (field: BuilderField, index: number): ReactNode => { + if (field.blockType === 'message') {return
{messages[index]}
} + switch (field.blockType) { + case 'checkbox': { + const props = f.getInputProps(field) + return ( + <> + + {errorOf(field)} + + ) + } + case 'checkboxGroup': + case 'radio': + return ( +
+ {label(field)} + {(field.options ?? []).map((option, i) => { + const o = f.getOptionProps(field, option, i) + return ( + + ) + })} + {errorOf(field)} +
+ ) + case 'select': { + const props = f.getSelectProps(field) + return ( + <> + + + {errorOf(field)} + + ) + } + case 'textarea': { + const props = f.getTextareaProps(field) + return ( + <> + +