- admin-i18n module: AdminText { en, pl }, component texts under the ipal
namespace (project translations win), en + pl admin languages when the
project sets none (project's supportedLanguages wins)
- every plugin label, description, option, tab and group as { en, pl };
explicit labels instead of auto-labels; sentence case; glossary terms
- visible renames (slugs, names, data unchanged): Cookie banner, Form
messages, Privacy group, Search engines, Maintenance, Spam protection,
E-mail sending, stats nav link Overview (hidden without access)
- Polish visitor defaults by page locale: cookie banner, form messages,
validators, lightbox, accessibility widget; {field} uses the label
- fixes: e-mail status banner used Turnstile wording; developer words and
env var names out of editor messages; stats numbers/dates in the admin
language; test e-mail no longer says ipal-kit
- test/adminUx.test.ts: length limits, en + pl present, no developer words
Co-Authored-By: Claude Opus 5.5 <[email protected]>
196 lines
6.6 KiB
TypeScript
196 lines
6.6 KiB
TypeScript
'use client'
|
|
|
|
import { useCallback, useMemo, useRef, useState } from 'react'
|
|
|
|
/**
|
|
* Error map: a field key → its error message. A field is "in error" iff it has
|
|
* a key here, so `errors.email` is both the truthy flag (for a red border) AND
|
|
* the message (to display). Empty object = valid.
|
|
*/
|
|
export type FormErrors<T> = Partial<Record<keyof T, string>>
|
|
|
|
/**
|
|
* The project's server action that calls submitForm (server-only, holds the
|
|
* Turnstile secret). This hook is a client hook, so it can't call submitForm
|
|
* directly — the project injects its action. The result only needs `success`
|
|
* plus an optional `message`; richer shapes (SubmitFormResult) satisfy it.
|
|
*/
|
|
export type FormSubmitAction<T> = (
|
|
values: T,
|
|
turnstileToken?: string,
|
|
) => Promise<{ message?: string; success: boolean }>
|
|
|
|
/** Turns the current values into an error map. Empty map = valid. */
|
|
export type Validator<T> = (values: T) => FormErrors<T>
|
|
|
|
type UseFormOptions<T extends Record<string, unknown>> = {
|
|
/** Clear a field's error as soon as the user edits it. Default true. */
|
|
clearErrorOnChange?: boolean
|
|
/**
|
|
* Generic error shown when the action fails or throws without a message.
|
|
* Pass one in the page's language (e.g. getNotificationTexts(...).form.error).
|
|
*/
|
|
errorFallback?: string
|
|
/** Defines the field set AND the reset state. Any shape you like. */
|
|
initialValues: T
|
|
/**
|
|
* Called once after a SUCCESSFUL submit, with the submitted values and the
|
|
* action's result. The place to fire analytics — e.g. a GTM `form_submit`
|
|
* event so a Meta Pixel / GA "Lead" tag can trigger:
|
|
*
|
|
* onSuccess: (_r, v) => pushDataLayer('form_submit', { form_name: v.topic || 'kontakt' })
|
|
*
|
|
* Runs client-side after the server action resolves; errors thrown here are
|
|
* swallowed so a broken analytics call can't blank out a successful submit.
|
|
*/
|
|
onSuccess?: (result: { message?: string; success: boolean }, values: T) => void
|
|
/** Require a Turnstile token before submit (when the widget is shown). */
|
|
requireTurnstile?: boolean
|
|
submitAction: FormSubmitAction<T>
|
|
/** Project-owned validation. Compose one with `buildValidator` + rules, or write your own. */
|
|
validate?: Validator<T>
|
|
}
|
|
|
|
/**
|
|
* Fully generic form engine: state, validation, Turnstile token, submit,
|
|
* success/error — WITHOUT any markup. The project owns 100% of the look AND
|
|
* the field set: there is no baked-in shape here. Replaces the identical
|
|
* ~150 lines of form plumbing copied into every project.
|
|
*
|
|
* The field set comes from `initialValues`; the rules come from `validate`
|
|
* (so dynamic/builder-driven forms just build both at runtime). For the
|
|
* everyday contact form use the `useContactForm` preset instead — it wires
|
|
* the standard fields and rules for you.
|
|
*
|
|
* const f = useForm({
|
|
* initialValues: { email: '', message: '' },
|
|
* submitAction, // your server action
|
|
* validate: buildValidator({ email: [required(), email()], message: [required()] }),
|
|
* requireTurnstile: Boolean(siteKey),
|
|
* })
|
|
* <input value={f.values.email}
|
|
* onChange={(e) => f.setField('email', e.target.value)}
|
|
* className={f.errors.email ? 'border-red-500' : '…'} />
|
|
* <form onSubmit={f.handleSubmit}>…</form>
|
|
*/
|
|
export function useForm<T extends Record<string, unknown>>(options: UseFormOptions<T>) {
|
|
const {
|
|
clearErrorOnChange = true,
|
|
errorFallback = 'The form could not be sent. Please try again in a moment.',
|
|
initialValues,
|
|
requireTurnstile = false,
|
|
submitAction,
|
|
validate,
|
|
} = options
|
|
|
|
// Freeze the initial snapshot so `reset` is stable even though callers pass a
|
|
// fresh object literal every render.
|
|
const initialRef = useRef(initialValues)
|
|
|
|
const [values, setValues] = useState<T>(initialRef.current)
|
|
const [errors, setErrors] = useState<FormErrors<T>>({})
|
|
const [isSubmitting, setIsSubmitting] = useState(false)
|
|
const [isSuccess, setIsSuccess] = useState(false)
|
|
const [errorMessage, setErrorMessage] = useState<null | string>(null)
|
|
const [turnstileToken, setTurnstileToken] = useState<null | string>(null)
|
|
|
|
const setField = useCallback(
|
|
<K extends keyof T>(key: K, value: T[K]) => {
|
|
setValues((prev) => ({ ...prev, [key]: value }))
|
|
if (clearErrorOnChange) {
|
|
setErrors((prev) => {
|
|
if (!prev[key]) {return prev}
|
|
const next = { ...prev }
|
|
delete next[key]
|
|
return next
|
|
})
|
|
}
|
|
},
|
|
[clearErrorOnChange],
|
|
)
|
|
|
|
// Validate against the LATEST values via a ref, so handleSubmit stays stable
|
|
// and never reads a stale snapshot.
|
|
const valuesRef = useRef(values)
|
|
valuesRef.current = values
|
|
const validateRef = useRef(validate)
|
|
validateRef.current = validate
|
|
const onSuccessRef = useRef(options.onSuccess)
|
|
onSuccessRef.current = options.onSuccess
|
|
|
|
const handleSubmit = useCallback(
|
|
async (e?: { preventDefault?: () => void }) => {
|
|
e?.preventDefault?.()
|
|
setErrorMessage(null)
|
|
|
|
const errs = validateRef.current ? validateRef.current(valuesRef.current) : {}
|
|
setErrors(errs)
|
|
if (Object.keys(errs).length > 0) {return}
|
|
|
|
if (requireTurnstile && !turnstileToken) {
|
|
setErrorMessage(errorFallback)
|
|
return
|
|
}
|
|
|
|
setIsSubmitting(true)
|
|
try {
|
|
const result = await submitAction(valuesRef.current, turnstileToken ?? undefined)
|
|
if (result.success) {
|
|
setIsSuccess(true)
|
|
setTurnstileToken(null)
|
|
// Fire analytics (e.g. GTM form_submit) — never let it break the submit.
|
|
try {
|
|
onSuccessRef.current?.(result, valuesRef.current)
|
|
} catch {
|
|
/* analytics must not affect the form outcome */
|
|
}
|
|
} else {
|
|
setErrorMessage(result.message || errorFallback)
|
|
}
|
|
} catch {
|
|
// Never show the thrown error's text to a visitor — it can carry server internals.
|
|
setErrorMessage(errorFallback)
|
|
} finally {
|
|
setIsSubmitting(false)
|
|
}
|
|
},
|
|
[requireTurnstile, turnstileToken, submitAction, errorFallback],
|
|
)
|
|
|
|
const reset = useCallback(() => {
|
|
setValues(initialRef.current)
|
|
setErrors({})
|
|
setIsSuccess(false)
|
|
setErrorMessage(null)
|
|
setTurnstileToken(null)
|
|
}, [])
|
|
|
|
return useMemo(
|
|
() => ({
|
|
errorMessage,
|
|
errors,
|
|
handleSubmit,
|
|
isSubmitting,
|
|
isSuccess,
|
|
reset,
|
|
setErrors,
|
|
setField,
|
|
setTurnstileToken,
|
|
setValues,
|
|
turnstileToken,
|
|
values,
|
|
}),
|
|
[
|
|
values,
|
|
errors,
|
|
isSubmitting,
|
|
isSuccess,
|
|
errorMessage,
|
|
turnstileToken,
|
|
setField,
|
|
handleSubmit,
|
|
reset,
|
|
],
|
|
)
|
|
}
|