'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, visibleFields } 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) => void /** Redirect target resolved on the server (RenderForm). Falls back to the form's custom URL. */ redirectHref?: null | string texts: BuilderFormTexts /** * Fields the page fills, by name (e.g. `{ subject: 'Ring · white gold · 0.70 ct' }`): * kept in sync when the prop changes, read-only in BuilderForm, sent like any * field. Names not in the form are ignored (the server rejects unknown fields). */ values?: Record } /** * 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. 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 }) *
* {f.step.fields.map(({ field }) => )} // getTextareaProps, getSelectProps, getOptionProps * * {!f.isFirst && } * * */ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref, texts, values: pageValues }: UseBuilderFormOptions) { const fields = useMemo(() => form.fields ?? [], [form.fields]) // Fields behind a failed "Show only when" are neither shown, validated nor sent. const visibleInputs = useCallback((values: Record) => inputFields(visibleFields(fields, values)), [fields]) const [stepIndex, setStepIndex] = useState(0) const [resultMessage, setResultMessage] = useState(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, token?: string) => { const shown = new Set(visibleInputs(values).map((field) => field.name)) const result = await action(Object.fromEntries(Object.entries(values).filter(([name]) => shown.has(name))), 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, visibleInputs], ) const validate = useCallback((values: Record) => validateBuilderFields(visibleInputs(values), values, texts), [visibleInputs, texts]) const f = useForm>({ errorFallback: texts.error, // Page values are in the first render too — server HTML shows them before hydration. initialValues: { ...initialBuilderValues(fields), ...Object.fromEntries(Object.entries(pageValues ?? {}).filter(([name]) => fields.some((field) => field.name === name))), }, 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, setField, setTurnstileToken } = f // Page-supplied values follow the prop (a configurator changes them in the browser). const fixedNames = useMemo( () => new Set(Object.keys(pageValues ?? {}).filter((name) => fields.some((field) => field.name === name))), [pageValues, fields], ) const fixedKey = JSON.stringify(pageValues ?? {}) useEffect(() => { for (const name of fixedNames) {setField(name, pageValues?.[name] ?? '')} }, [fixedKey, fixedNames, setField]) /** True for a field whose value comes from the page (`values`) — show it, don't let the visitor edit it. */ const isFixed = useCallback((field: BuilderField) => Boolean(field.name && fixedNames.has(field.name)), [fixedNames]) // Steps follow the answers: a Step whose condition fails drops out, later steps renumber. const steps = useMemo(() => { const shown = new Set(visibleFields(fields, f.values)) return splitSteps(fields, (field) => shown.has(field)) }, [fields, f.values]) // 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
: 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 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) => 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) => f.setField(name, e.target.value), placeholder: field.placeholder ?? undefined, value: textValue(name), } }, [f, getFieldProps, textValue], ) /** Props of a