Files
ipal-kit/src/modules/forms/useBuilderForm.ts
T

434 lines
18 KiB
TypeScript

'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, fileFieldError, fileFieldRules, initialBuilderValues, inputFields, splitSteps, stepOfField, validateBuilderFields, visibleFields } from './builderLogic.js'
import { formAnalyticsOnSuccess } from './formAnalytics.js'
import { HONEYPOT_FIELD, honeypotInputProps } from './honeypot.js'
import { useForm } from './useForm.js'
export type UseBuilderFormOptions = {
/** Bound server action (RenderForm binds createSubmitAction to formId + locale). */
action: BuilderFormAction
/**
* Where a submission WITH files is posted. Default: the form's own
* `fileSubmitUrl` (set by the server), then '/api/ipal/forms/submit'.
*/
fileSubmitUrl?: string
form: BuilderFormDoc
/** The page language — sent with a submission that carries files (prepareBuilderForm sets it). */
locale?: string
/** 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
/**
* 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<string, string>
}
/**
* 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, fileSubmitUrl, form, locale, 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<string, unknown>) => inputFields(visibleFields(fields, values)), [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)
// One key per submit attempt: a repeated request (double click, a resend by the
// browser or a proxy) carries the same key and the server sends nothing twice.
// A new key only once the server has answered.
const attemptKey = useRef('')
// The honeypot input is not part of the form values; its content is read at submit
// and sent along, so the server can drop a bot that filled it.
const honeypot = useRef<HTMLInputElement | null>(null)
const submitAction = useCallback(
async (values: Record<string, unknown>, token?: string) => {
const shownFields = visibleInputs(values)
const shown = new Set(shownFields.map((field) => field.name))
const fileNames = new Set(shownFields.filter((field) => field.blockType === 'file').map((field) => field.name))
const answers: Record<string, unknown> = Object.fromEntries(Object.entries(values).filter(([name]) => shown.has(name) && !fileNames.has(name)))
const trap = honeypot.current
if (trap?.value) {answers[trap.name || HONEYPOT_FIELD] = trap.value}
const files = [...fileNames].flatMap((name) => (Array.isArray(values[name]) ? (values[name] as File[]) : []).map((file) => ({ name, file })))
let result: Awaited<ReturnType<BuilderFormAction>>
if (files.length > 0) {
// Files never go through the server action: one multipart request to the
// plugin's endpoint — the answers first, the files last — read there as a stream.
attemptKey.current ||= (globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}${Math.random().toString(36).slice(2)}`).replace(/[^\w-]/g, '')
const body = new FormData()
body.append('_form', String(form.id))
if (locale) {body.append('_locale', locale)}
body.append('_attempt', attemptKey.current)
if (token) {body.append('_token', token)}
body.append('_values', JSON.stringify(answers))
for (const { name, file } of files) {body.append(name, file, file.name)}
const url = fileSubmitUrl ?? form.fileSubmitUrl ?? '/api/ipal/forms/submit'
const response = await fetch(locale ? `${url}?locale=${encodeURIComponent(locale)}` : url, { body, credentials: 'omit', method: 'POST' })
result = (await response.json()) as Awaited<ReturnType<BuilderFormAction>>
attemptKey.current = ''
} else {
result = await action(answers, token)
}
if (result.success) {setResultMessage(result.message ?? null)}
else if (result.field) {
// No message from the server → name the field by its label, as the visitor sees it.
const label = fields.find((field) => field.name === result.field)?.label || result.field
serverFieldError.current = { field: result.field, message: result.message ?? texts.validation.replace('{field}', label) }
}
return result
},
[action, fields, fileSubmitUrl, form.fileSubmitUrl, form.id, locale, texts.validation, visibleInputs],
)
const validate = useCallback((values: Record<string, unknown>) => validateBuilderFields(visibleInputs(values), values, texts), [visibleInputs, texts])
const f = useForm<Record<string, unknown>>({
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 <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 · time · 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'
: field.blockType === 'time' ? 'time'
: 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 the hidden honeypot input — render one `<input {...f.getHoneypotProps()} />` inside the form. */
const getHoneypotProps = useCallback(
(name?: string) => ({
...honeypotInputProps(name),
ref: (input: HTMLInputElement | null) => {
honeypot.current = input
},
}),
[],
)
const helpId = useCallback((field: BuilderField) => `${fieldId(field)}-help`, [fieldId])
// File fields: the selected files live in the form values (File[]); the native
// inputs are kept in step with them, so removing a file really removes it.
const fileInputs = useRef(new Map<string, HTMLInputElement>())
const syncFileInput = useCallback((name: string, files: File[]) => {
const input = fileInputs.current.get(name)
if (!input) {return}
try {
const transfer = new DataTransfer()
for (const file of files) {transfer.items.add(file)}
input.files = transfer.files
} catch {
if (files.length === 0) {input.value = ''}
}
}, [])
/** The files picked for a File field. */
const getFiles = useCallback(
(field: BuilderField): File[] => {
const value = f.values[field.name ?? '']
return Array.isArray(value) ? (value as File[]) : []
},
[f.values],
)
const setFiles = useCallback(
(field: BuilderField, files: File[]) => {
const name = field.name ?? ''
f.setField(name, files)
syncFileInput(name, files)
// Instant feedback: too large, wrong type, too many — the server checks again, and the content too.
const problem = files.length ? fileFieldError(field, files, texts) : undefined
if (problem) {setErrors((prev) => ({ ...prev, [name]: problem }))}
},
[f, setErrors, syncFileInput, texts],
)
/** Props of the `<input type="file">` of a File field. */
const getFileProps = useCallback(
(field: BuilderField) => {
const name = field.name ?? ''
const rules = fileFieldRules(field)
const base = getFieldProps(field)
return {
...base,
type: 'file' as const,
accept: rules.accept || undefined,
'aria-describedby': [field.help ? helpId(field) : undefined, base['aria-describedby']].filter(Boolean).join(' ') || undefined,
multiple: rules.maxFiles > 1,
onChange: (e: ChangeEvent<HTMLInputElement>) => {
const picked = Array.from(e.target.files ?? [])
// Several files: each pick adds to the list (the same file twice counts once).
const current = rules.maxFiles > 1 ? getFiles(field) : []
const known = new Set(current.map((file) => `${file.name}:${file.size}`))
setFiles(field, [...current, ...picked.filter((file) => !known.has(`${file.name}:${file.size}`))])
},
ref: (input: HTMLInputElement | null) => {
if (input) {fileInputs.current.set(name, input)}
else {fileInputs.current.delete(name)}
},
}
},
[getFieldProps, getFiles, helpId, setFiles],
)
/** Removes one picked file and puts the focus back on the field. */
const removeFile = useCallback(
(field: BuilderField, index: number) => {
setFiles(field, getFiles(field).filter((_, i) => i !== index))
fileInputs.current.get(field.name ?? '')?.focus()
},
[getFiles, setFiles],
)
/** 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,
getFileProps,
getFiles,
getHoneypotProps,
getInputProps,
getOptionProps,
getSelectProps,
getTextareaProps,
goTo,
helpId,
isFirst,
isFixed,
isLast,
next,
removeFile,
/** 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>