Admin panel in English and Polish, reworded per docs/dev/admin-ux.md

- 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]>
This commit is contained in:
Radosław Smoliński
2026-10-27 15:46:25 +01:00
co-authored by Claude Opus 5.5
parent eeac33ed2f
commit 6b46bc0c14
108 changed files with 2806 additions and 981 deletions
+80 -31
View File
@@ -13,7 +13,7 @@ import type { Block, Field } from 'payload'
* Built-in text · email · textarea · number get a localized "Placeholder"
* (withPlaceholder) — the hint inside the empty field, e.g. "e.g. 10:00–12:00".
*
* Plain English labels (the panel is EN). Rendered by BuilderForm /
* Labels in English and Polish. Rendered by BuilderForm /
* useBuilderForm, validated by submitForm like every other field.
*
* Every block (built-in ones too, see withShowWhen) also gets "Show only when"
@@ -23,41 +23,69 @@ import type { Block, Field } from 'payload'
const name: Field = {
name: 'name',
type: 'text',
admin: { description: 'Technical name, e.g. "services" — no spaces.', width: '50%' },
label: 'Name (lowercase, no special characters)',
admin: {
description: { en: 'No spaces, e.g. services.', pl: 'Bez spacji, np. uslugi.' },
width: '50%',
},
label: { en: 'Field key', pl: 'Klucz pola' },
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' }
const label: Field = { name: 'label', type: 'text', admin: { width: '50%' }, label: { en: 'Label', pl: 'Etykieta' }, localized: true }
const width: Field = { name: 'width', type: 'number', admin: { width: '50%' }, label: { en: 'Width (%)', pl: 'Szerokość (%)' } }
const required: Field = { name: 'required', type: 'checkbox', admin: { width: '50%' }, label: { en: 'Required', pl: 'Wymagane' } }
/**
* "Show only when": the field — or, on a Step, the whole step — appears only
* when another field has one of the given values. Evaluated by visibleFields
* in the browser and again on the server (hidden fields are neither required nor stored).
*
* The named group keeps the data at `showWhen.field` / `showWhen.values`; its
* heading is hidden and a collapsible inside it (presentation only) carries
* the label, collapsed by default.
*/
export const showWhenField: Field = {
name: 'showWhen',
type: 'group',
admin: {
description:
'Leave empty to always show. Otherwise this appears only when the field named below has one of the values — e.g. field "areas", values "web, it".',
},
admin: { hideGutter: true },
fields: [
{
type: 'row',
type: 'collapsible',
admin: {
description: {
en: 'Leave empty to always show it.',
pl: 'Zostaw puste, aby zawsze było widoczne.',
},
initCollapsed: true,
},
fields: [
{ name: 'field', type: 'text', admin: { description: 'Technical name of another field.', width: '50%' }, label: 'Field name' },
{
name: 'values',
type: 'text',
admin: { description: 'Comma-separated option values. Empty = when that field is filled in or ticked.', width: '50%' },
label: 'Values',
type: 'row',
fields: [
{
name: 'field',
type: 'text',
admin: { description: { en: 'Key of the field it depends on.', pl: 'Klucz pola, od którego zależy.' }, width: '50%' },
label: { en: 'Field key', pl: 'Klucz pola' },
},
{
name: 'values',
type: 'text',
admin: {
description: {
en: 'Separate with commas; leave empty for any value.',
pl: 'Oddziel przecinkami; zostaw puste dla dowolnej wartości.',
},
width: '50%',
},
label: { en: 'Values', pl: 'Wartości' },
},
],
},
],
label: { en: 'Show only when', pl: 'Pokaż tylko, gdy' },
},
],
label: 'Show only when',
label: false,
}
/** Adds "Show only when" at the end of a block's fields. */
@@ -69,8 +97,11 @@ export function withShowWhen<B extends Block>(block: B): B {
export const placeholderField: Field = {
name: 'placeholder',
type: 'text',
admin: { description: 'Hint shown inside the empty field, e.g. "e.g. 10:00–12:00". Empty → none.' },
label: 'Placeholder',
admin: {
description: { en: 'Example shown inside the empty field.', pl: 'Przykład widoczny w pustym polu.' },
placeholder: { en: 'e.g. 10:00–12:00', pl: 'np. 10:00–12:00' },
},
label: { en: 'Placeholder', pl: 'Tekst podpowiedzi' },
localized: true,
}
@@ -85,7 +116,7 @@ const timeBase: Block = {
{ type: 'row', fields: [name, label] },
{ type: 'row', fields: [width, required] },
],
labels: { plural: 'Times', singular: 'Time' },
labels: { plural: { en: 'Time fields', pl: 'Pola godziny' }, singular: { en: 'Time', pl: 'Godzina' } },
}
const stepBase: Block = {
@@ -95,15 +126,17 @@ const stepBase: Block = {
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.',
description: {
en: 'Starts a new step with the fields below it, up to the next step.',
pl: 'Zaczyna nowy krok z polami poniżej, aż do następnego kroku.',
},
},
label: 'Step title',
label: { en: 'Step title', pl: 'Tytuł kroku' },
localized: true,
},
{ name: 'description', type: 'textarea', admin: { rows: 2 }, label: 'Step description', localized: true },
{ name: 'description', type: 'textarea', admin: { rows: 2 }, label: { en: 'Step description', pl: 'Opis kroku' }, localized: true },
],
labels: { plural: 'Steps', singular: 'Step' },
labels: { plural: { en: 'Steps', pl: 'Kroki' }, singular: { en: 'Step', pl: 'Krok' } },
}
const checkboxGroupBase: Block = {
@@ -118,23 +151,39 @@ const checkboxGroupBase: Block = {
{
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 },
{ name: 'label', type: 'text', admin: { width: '50%' }, label: { en: 'Label', pl: 'Etykieta' }, localized: true, required: true },
{ name: 'value', type: 'text', admin: { width: '50%' }, label: { en: 'Value', pl: 'Wartość' }, required: true },
],
},
],
labels: { plural: 'Options', singular: 'Option' },
label: { en: 'Options', pl: 'Opcje' },
labels: { plural: { en: 'Options', pl: 'Opcje' }, singular: { en: 'Option', pl: 'Opcja' } },
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 },
{
name: 'minSelected',
type: 'number',
admin: { description: { en: 'Leave empty for no minimum.', pl: 'Zostaw puste, aby nie ustalać minimum.' }, width: '50%' },
label: { en: 'Minimum selected', pl: 'Minimum zaznaczonych' },
min: 0,
},
{
name: 'maxSelected',
type: 'number',
admin: { description: { en: 'Leave empty for no limit.', pl: 'Zostaw puste, aby nie ustalać limitu.' }, width: '50%' },
label: { en: 'Maximum selected', pl: 'Maksimum zaznaczonych' },
min: 1,
},
],
},
],
labels: { plural: 'Checkbox groups', singular: 'Checkbox group' },
labels: {
plural: { en: 'Multiple choice fields', pl: 'Pola wielokrotnego wyboru' },
singular: { en: 'Multiple choice', pl: 'Wielokrotny wybór' },
},
}
export const stepBlock: Block = withShowWhen(stepBase)
+29 -7
View File
@@ -114,7 +114,7 @@ ${footerLines ? `<tr><td class="ipal-pad" style="padding:20px 36px 28px;backgrou
</table></td></tr></table></body></html>`
}
/** Site Settings → "Emails" tab (shown with `forms: { emailLayout: true }`). */
/** Site settings → "E-mails" tab (shown with `forms: { emailLayout: true }`). */
export const emailSettingsFields: Field[] = [
{
name: 'email',
@@ -124,18 +124,40 @@ export const emailSettingsFields: Field[] = [
{
name: 'logo',
type: 'upload',
admin: { description: 'PNG or JPG for a light background — Gmail and Outlook do not show SVG. Empty = the site name.' },
label: 'E-mail logo',
admin: {
description: {
en: 'PNG or JPG on a light background, as many e-mail apps do not show SVG; leave empty to show the site name.',
pl: 'PNG lub JPG na jasnym tle, bo wiele programów pocztowych nie wyświetla SVG; zostaw puste, aby pokazać nazwę witryny.',
},
},
label: { en: 'E-mail logo', pl: 'Logo w e-mailach' },
relationTo: 'media',
},
{
name: 'accentColor',
type: 'text',
admin: { description: 'Hex, e.g. #017BD0 — top bar and section titles.' },
label: 'Accent colour',
validate: (value: unknown) => !value || /^#(?:[0-9a-f]{3}){1,2}$/i.test(String(value)) || 'Use a hex colour, e.g. #017BD0.',
admin: {
description: {
en: 'Used for the top bar and section titles.',
pl: 'Używany na górnym pasku i w tytułach sekcji.',
},
placeholder: '#017BD0',
},
label: { en: 'Accent colour', pl: 'Kolor akcentu' },
validate: (value: unknown, { req }: { req?: { i18n?: { language?: string } } } = {}) =>
!value ||
/^#(?:[0-9a-f]{3}){1,2}$/i.test(String(value)) ||
(req?.i18n?.language === 'pl' ? 'Wpisz kolor w formacie HEX, np. #017BD0.' : 'Enter a hex colour, e.g. #017BD0.'),
},
{
name: 'footer',
type: 'textarea',
admin: {
description: { en: 'E.g. company name and address.', pl: 'Np. nazwa i adres firmy.' },
},
label: { en: 'Footer', pl: 'Stopka' },
localized: true,
},
{ name: 'footer', type: 'textarea', admin: { description: 'E.g. company name and address.' }, label: 'Footer', localized: true },
],
label: false,
},
+15 -11
View File
@@ -25,35 +25,39 @@ export function buildFormAnalyticsFields(): Field[] {
name: 'analytics',
type: 'group',
admin: {
description:
'Event pushed to the dataLayer on a successful submit. In GTM, attach a tag (e.g. Lead) with a trigger on this event name.',
description: {
en: 'Sent to Google Tag Manager after a successful submission.',
pl: 'Wysyłane do Google Tag Manager po udanym wysłaniu formularza.',
},
},
fields: [
{
name: 'event',
type: 'text',
admin: {
description:
'Empty = nothing is pushed. Default "form_submit" — attach your GTM trigger to it.',
description: { en: 'Leave empty to send nothing.', pl: 'Zostaw puste, aby nic nie wysyłać.' },
},
defaultValue: 'form_submit',
label: 'Event name',
label: { en: 'Event name', pl: 'Nazwa zdarzenia' },
},
{
name: 'params',
type: 'array',
admin: {
description:
'Key/value pairs sent with the event. A value starting with "$" is taken from a form field, e.g. $topic → the chosen topic.',
description: {
en: 'A value starting with $ is taken from a form field, e.g. $topic.',
pl: 'Wartość zaczynająca się od $ pochodzi z pola formularza, np. $topic.',
},
},
fields: [
{ name: 'key', type: 'text', required: true },
{ name: 'value', type: 'text', required: true },
{ name: 'key', type: 'text', label: { en: 'Key', pl: 'Klucz' }, required: true },
{ name: 'value', type: 'text', label: { en: 'Value', pl: 'Wartość' }, required: true },
],
label: 'Event parameters',
label: { en: 'Event parameters', pl: 'Parametry zdarzenia' },
labels: { plural: { en: 'Parameters', pl: 'Parametry' }, singular: { en: 'Parameter', pl: 'Parametr' } },
},
],
label: 'Analytics (GTM / dataLayer)',
label: { en: 'Analytics event', pl: 'Zdarzenie analityki' },
},
]
}
+142 -4
View File
@@ -3,6 +3,7 @@ import type { Block, Field, Plugin } from 'payload'
import { fields as builtinBlocks, formBuilderPlugin } from '@payloadcms/plugin-form-builder'
import type { AdminText } from '../admin-i18n/define.js'
import type { FormsOption } from './types.js'
import { userMeetsRole } from '../access/predicates.js'
@@ -11,6 +12,139 @@ import { buildEmailLayoutHook } from './emailLayout.js'
type AccessArgs = { req: { user?: unknown } }
/**
* Panel wording for form-builder's own fields, by its translation key. Its
* labels are functions (`({ t }) => t('plugin-form-builder:name')`); these
* replace them with `{ en, pl }` text — labels only, names and data unchanged.
* Keys not listed keep form-builder's own text.
*/
const FORM_BUILDER_TEXTS: Record<string, AdminText> = {
name: { en: 'Field key', pl: 'Klucz pola' },
bcc: { en: 'BCC', pl: 'UDW' },
cc: { en: 'CC', pl: 'DW' },
checkboxPlural: { en: 'Checkboxes', pl: 'Pola wyboru' },
checkboxSingular: { en: 'Checkbox', pl: 'Pole wyboru' },
checkedByDefault: { en: 'Checked by default', pl: 'Domyślnie zaznaczone' },
chooseConfirmationType: {
en: 'Show a message or go to another page after the form is sent.',
pl: 'Pokaż komunikat lub przejdź na inną stronę po wysłaniu formularza.',
},
confirmationMessage: { en: 'Confirmation message', pl: 'Komunikat potwierdzenia' },
confirmationType: { en: 'After sending', pl: 'Po wysłaniu' },
countryPlural: { en: 'Country fields', pl: 'Pola kraju' },
countrySingular: { en: 'Country', pl: 'Kraj' },
customURL: { en: 'Address (URL)', pl: 'Adres (URL)' },
datePlural: { en: 'Date fields', pl: 'Pola daty' },
dateSingular: { en: 'Date', pl: 'Data' },
defaultValue: { en: 'Default value', pl: 'Wartość domyślna' },
documentToLinkTo: { en: 'Page', pl: 'Strona' },
emailFrom: { en: 'From', pl: 'Od' },
emailPlural: { en: 'E-mail fields', pl: 'Pola e-mail' },
emailsDescription: {
en: 'Sent after each submission; use {{email}} for a field value and {{*:table}} for all values.',
pl: 'Wysyłane po każdym zgłoszeniu; {{email}} wstawia wartość pola, a {{*:table}} wszystkie wartości.',
},
emailSingular: { en: 'E-mail', pl: 'E-mail' },
emailTo: { en: 'To', pl: 'Do' },
field: { en: 'Field', pl: 'Pole' },
fields: { en: 'Fields', pl: 'Pola' },
fieldWidth: { en: 'Width (%)', pl: 'Szerokość (%)' },
internalLink: { en: 'Page', pl: 'Strona' },
label: { en: 'Label', pl: 'Etykieta' },
message: { en: 'Message', pl: 'Wiadomość' },
messageDescription: { en: 'Text of the e-mail.', pl: 'Treść wiadomości e-mail.' },
messagePlural: { en: 'Text blocks', pl: 'Bloki tekstu' },
messageSingular: { en: 'Text block', pl: 'Blok tekstu' },
numberPlural: { en: 'Number fields', pl: 'Pola liczbowe' },
numberSingular: { en: 'Number', pl: 'Liczba' },
optionPlural: { en: 'Options', pl: 'Opcje' },
optionSingular: { en: 'Option', pl: 'Opcja' },
placeholder: { en: 'Placeholder', pl: 'Tekst podpowiedzi' },
radioOptions: { en: 'Options', pl: 'Opcje' },
radioPlural: { en: 'Single choice fields', pl: 'Pola jednokrotnego wyboru' },
radioSingular: { en: 'Single choice', pl: 'Jednokrotny wybór' },
redirect: { en: 'Redirect', pl: 'Przekierowanie' },
replyTo: { en: 'Reply to', pl: 'Odpowiedź do' },
required: { en: 'Required', pl: 'Wymagane' },
selectOptions: { en: 'Options', pl: 'Opcje' },
selectPlural: { en: 'Dropdown fields', pl: 'Listy rozwijane' },
selectSingular: { en: 'Dropdown', pl: 'Lista rozwijana' },
statePlural: { en: 'Region fields', pl: 'Pola regionu' },
stateSingular: { en: 'Region', pl: 'Region' },
subject: { en: 'Subject', pl: 'Temat' },
submitButton: { en: 'Button text', pl: 'Tekst przycisku' },
textareaPlural: { en: 'Long text fields', pl: 'Pola długiego tekstu' },
textareaSingular: { en: 'Long text', pl: 'Długi tekst' },
textPlural: { en: 'Text fields', pl: 'Pola tekstowe' },
textSingular: { en: 'Text', pl: 'Tekst' },
title: { en: 'Title', pl: 'Tytuł' },
urlToRedirectTo: { en: 'Address (URL)', pl: 'Adres (URL)' },
value: { en: 'Value', pl: 'Wartość' },
}
/** `({ t }) => t('plugin-form-builder:<key>')` → our `{ en, pl }`; anything else unchanged. */
function formBuilderText<V>(value: V): AdminText | V {
if (typeof value !== 'function') {return value}
try {
const key = String((value as (args: unknown) => unknown)({ i18n: {}, t: (k: string) => k }))
return FORM_BUILDER_TEXTS[key.replace(/^plugin-form-builder:/, '')] ?? value
} catch {
return value
}
}
/** Replaces form-builder's labels, descriptions and option labels, deep (blocks, arrays, rows, groups). */
function localizeFormBuilder<T>(node: T): T {
if (Array.isArray(node)) {return node.map(localizeFormBuilder) as T}
if (!node || typeof node !== 'object') {return node}
const f = node as Record<string, unknown>
const out: Record<string, unknown> = { ...f }
if ('label' in f) {out.label = formBuilderText(f.label)}
// The text block's rich text has no label of its own.
if (f.type === 'richText' && f.name === 'message' && !f.label) {out.label = { en: 'Text', pl: 'Treść' }}
if (f.labels && typeof f.labels === 'object') {
const labels = f.labels as Record<string, unknown>
out.labels = { ...labels, plural: formBuilderText(labels.plural), singular: formBuilderText(labels.singular) }
}
if (f.admin && typeof f.admin === 'object' && 'description' in f.admin) {
const admin = f.admin as Record<string, unknown>
out.admin = { ...admin, description: formBuilderText(admin.description) }
}
if (Array.isArray(f.options)) {out.options = f.options.map((o) => (o && typeof o === 'object' ? { ...o, label: formBuilderText((o as { label?: unknown }).label) } : o))}
for (const key of ['fields', 'blocks', 'tabs'] as const) {
if (Array.isArray(f[key])) {out[key] = localizeFormBuilder(f[key])}
}
return out as T
}
/** Labels for the submission fields form-builder leaves unlabelled. */
const SUBMISSION_LABELS: Record<string, AdminText> = {
form: { en: 'Form', pl: 'Formularz' },
submissionData: { en: 'Answers', pl: 'Odpowiedzi' },
submissionUploads: { en: 'Files', pl: 'Pliki' },
}
const SUBMISSION_ROW_LABELS: Record<string, AdminText> = {
field: { en: 'Field key', pl: 'Klucz pola' },
value: { en: 'Value', pl: 'Wartość' },
}
function labelSubmissionFields(fields: Field[]): Field[] {
return fields.map((field) => {
if (!('name' in field) || !SUBMISSION_LABELS[field.name] || field.label) {return field}
const labelled = { ...field, label: SUBMISSION_LABELS[field.name] } as Field
if (labelled.type === 'array') {
return {
...labelled,
fields: labelled.fields.map((sub) =>
'name' in sub && SUBMISSION_ROW_LABELS[sub.name] && !sub.label ? ({ ...sub, label: SUBMISSION_ROW_LABELS[sub.name] } as Field) : sub,
),
labels: labelled.labels ?? { plural: { en: 'Answers', pl: 'Odpowiedzi' }, singular: { en: 'Answer', pl: 'Odpowiedź' } },
} as Field
}
return labelled
})
}
/** A built-in form-builder block with "Show only when" added (full block — form-builder merges arrays by replacing). */
const builtin = (key: 'checkbox' | 'date' | 'email' | 'message' | 'number' | 'radio' | 'select' | 'text' | 'textarea') =>
withShowWhen(builtinBlocks[key] as Block)
@@ -65,7 +199,7 @@ function hideEmails(fields: Field[]): Field[] {
* really needs public REST submissions can override `formSubmissionOverrides.access.create`.
*/
export function buildFormsPlugin(forms: FormsOption): Plugin {
const adminGroup = forms.adminGroup === undefined ? 'Forms' : forms.adminGroup
const adminGroup = forms.adminGroup === undefined ? { en: 'Forms', pl: 'Formularze' } : forms.adminGroup
const group = adminGroup ? { group: adminGroup } : {}
const layout = forms.emailLayout ? buildEmailLayoutHook({ formsSlug: forms.formOverrides?.slug ?? 'forms' }) : undefined
const beforeEmail: BeforeEmail | undefined =
@@ -109,7 +243,7 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
// Tidy panel by default: both collections under one sidebar group with plain
// labels — no per-project overrides needed just to sort the sidebar.
formOverrides: {
labels: { plural: 'Forms', singular: 'Form' },
labels: { plural: { en: 'Forms', pl: 'Formularze' }, singular: { en: 'Form', pl: 'Formularz' } },
...forms.formOverrides,
access: {
create: staffAccess,
@@ -120,12 +254,12 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
},
admin: { ...group, ...forms.formOverrides?.admin },
fields: ({ defaultFields }) => {
const protectedFields = hideEmails(defaultFields)
const protectedFields = hideEmails(localizeFormBuilder(defaultFields))
return forms.formOverrides?.fields ? forms.formOverrides.fields({ defaultFields: protectedFields }) : protectedFields
},
},
formSubmissionOverrides: {
labels: { plural: 'Submissions', singular: 'Submission' },
labels: { plural: { en: 'Submissions', pl: 'Zgłoszenia' }, singular: { en: 'Submission', pl: 'Zgłoszenie' } },
...forms.formSubmissionOverrides,
access: {
create: submissionsCreateAccess,
@@ -134,6 +268,10 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
...forms.formSubmissionOverrides?.access,
},
admin: { ...group, defaultColumns: ['form', 'createdAt'], ...forms.formSubmissionOverrides?.admin },
fields: ({ defaultFields }) => {
const labelled = labelSubmissionFields(defaultFields)
return forms.formSubmissionOverrides?.fields ? forms.formSubmissionOverrides.fields({ defaultFields: labelled }) : labelled
},
},
})
}
+4 -1
View File
@@ -31,9 +31,12 @@ export {
custom,
email,
isEmail,
localizedRules,
maxLength,
minLength,
pattern,
required,
VALIDATION_MESSAGES,
validationMessages,
} from './validators.js'
export type { Rule } from './validators.js'
export type { Rule, ValidationMessages } from './validators.js'
+24
View File
@@ -67,6 +67,8 @@ export type SubmitFailure =
field?: string
/** What was wrong with it. */
kind?: 'invalid_format' | 'required' | 'too_long' | 'unknown_fields'
/** The offending field's label in the page's language — what the visitor sees. Absent when the field has none. */
label?: string
reason: 'validation'
success: false
}
@@ -141,11 +143,13 @@ export async function submitForm({
if (validation.reason === 'consent') {
return { field: validation.field, reason: 'consent', success: false }
}
const label = validation.field ? await fieldLabel(payload, formId, validation.field, locale) : undefined
return {
reason: 'validation',
success: false,
...(validation.field ? { field: validation.field } : {}),
...(validation.kind ? { kind: validation.kind } : {}),
...(label ? { label } : {}),
}
}
@@ -170,3 +174,23 @@ export async function submitForm({
return { reason: 'error', success: false }
}
}
/**
* The label of one form field in the page's language, so a message names the
* field the way the visitor sees it ("E-mail address", not "email"). Only read
* when a submission fails; never throws.
*/
async function fieldLabel(payload: BasePayload, formId: string, name: string, locale?: string): Promise<string | undefined> {
try {
const form = (await payload.findByID({
id: formId,
collection: 'forms',
depth: 0,
...(locale ? { locale: locale as never } : {}),
})) as { fields?: { label?: unknown; name?: unknown }[] }
const label = form.fields?.find((f) => f.name === name)?.label
return typeof label === 'string' && label.trim() ? label.trim() : undefined
} catch {
return undefined
}
}
+1 -1
View File
@@ -25,7 +25,7 @@ export type FormsOption = {
* `false` = Payload default ("Collections"). An explicit `admin.group` in
* formOverrides / formSubmissionOverrides still wins.
*/
adminGroup?: false | string
adminGroup?: false | Record<string, string> | string
/**
* form-builder `beforeEmail` — change the e-mails before they go out. Runs after
* the ipal layout when `emailLayout` is on.
+6 -2
View File
@@ -61,10 +61,14 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
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) }}
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, texts.validation, visibleInputs],
[action, fields, texts.validation, visibleInputs],
)
const validate = useCallback((values: Record<string, unknown>) => validateBuilderFields(visibleInputs(values), values, texts), [visibleInputs, texts])
+8 -4
View File
@@ -26,7 +26,10 @@ 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 message shown when the action fails/throws with no message. */
/**
* 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
@@ -73,7 +76,7 @@ type UseFormOptions<T extends Record<string, unknown>> = {
export function useForm<T extends Record<string, unknown>>(options: UseFormOptions<T>) {
const {
clearErrorOnChange = true,
errorFallback = 'Something went wrong. Please try again.',
errorFallback = 'The form could not be sent. Please try again in a moment.',
initialValues,
requireTurnstile = false,
submitAction,
@@ -144,8 +147,9 @@ export function useForm<T extends Record<string, unknown>>(options: UseFormOptio
} else {
setErrorMessage(result.message || errorFallback)
}
} catch (err) {
setErrorMessage(err instanceof Error ? err.message : errorFallback)
} catch {
// Never show the thrown error's text to a visitor — it can carry server internals.
setErrorMessage(errorFallback)
} finally {
setIsSubmitting(false)
}
+70 -6
View File
@@ -31,9 +31,54 @@ const EMAIL_RE = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/
/** Standalone e-mail check, handy outside the rule system too. */
export const isEmail = (v: unknown): boolean => typeof v === 'string' && EMAIL_RE.test(v.trim())
/**
* Default rule messages, per language. English is used unless a rule gets its
* own message; `localizedRules('pl')` builds the same rules with the Polish
* set (any other language falls back to English).
*/
export type ValidationMessages = {
checked: string
email: string
maxLength: (n: number) => string
minLength: (n: number) => string
pattern: string
required: string
}
/** Polish plural of "znak" (character): 1 znak, 2–4 znaki, 5+ znaków. */
const znaki = (n: number) => {
const form = new Intl.PluralRules('pl').select(n)
return form === 'one' ? 'znak' : form === 'few' ? 'znaki' : 'znaków'
}
export const VALIDATION_MESSAGES: { en: ValidationMessages; pl: ValidationMessages } = {
en: {
checked: 'Tick this box to continue.',
email: 'Enter a valid e-mail address, e.g. [email protected].',
maxLength: (n) => `Enter no more than ${n} ${n === 1 ? 'character' : 'characters'}.`,
minLength: (n) => `Enter at least ${n} ${n === 1 ? 'character' : 'characters'}.`,
pattern: 'Check the format of this field.',
required: 'Fill in this field.',
},
pl: {
checked: 'Zaznacz to pole, aby kontynuować.',
email: 'Wpisz poprawny adres e-mail, np. [email protected].',
maxLength: (n) => `Wpisz najwyżej ${n} ${znaki(n)}.`,
minLength: (n) => `Wpisz co najmniej ${n} ${znaki(n)}.`,
pattern: 'Sprawdź format tego pola.',
required: 'Uzupełnij to pole.',
},
}
/** The message set for a page language ('pl', 'pl-PL' → Polish; anything else → English). */
export const validationMessages = (locale?: string): ValidationMessages =>
locale?.toLowerCase().startsWith('pl') ? VALIDATION_MESSAGES.pl : VALIDATION_MESSAGES.en
const EN = VALIDATION_MESSAGES.en
/** Non-empty string, non-null, and (for checkboxes) not `false`. */
export const required =
(msg = 'required'): Rule =>
(msg = EN.required): Rule =>
(v) => {
if (v == null) {return msg}
if (typeof v === 'string' && !v.trim()) {return msg}
@@ -42,32 +87,51 @@ export const required =
}
export const email =
(msg = 'invalid email'): Rule =>
(msg = EN.email): Rule =>
(v) =>
isEmail(v) ? true : msg
export const minLength =
(n: number, msg?: string): Rule =>
(v) =>
typeof v === 'string' && v.trim().length >= n ? true : (msg ?? `min ${n} chars`)
typeof v === 'string' && v.trim().length >= n ? true : (msg ?? EN.minLength(n))
export const maxLength =
(n: number, msg?: string): Rule =>
(v) =>
typeof v === 'string' && v.trim().length <= n ? true : (msg ?? `max ${n} chars`)
typeof v === 'string' && v.trim().length <= n ? true : (msg ?? EN.maxLength(n))
/** Checkbox must be ticked (true). */
export const checked =
(msg = 'required'): Rule =>
(msg = EN.checked): Rule =>
(v) =>
v === true ? true : msg
/** Value must match a regex (ignored when empty — pair with `required` to force). */
export const pattern =
(re: RegExp, msg = 'invalid format'): Rule =>
(re: RegExp, msg = EN.pattern): Rule =>
(v) =>
typeof v !== 'string' || v.trim() === '' || re.test(v.trim()) ? true : msg
/**
* The rules with default messages in the page's language. A message passed to
* a rule still wins:
*
* const r = localizedRules(locale)
* buildValidator({ email: [r.required(), r.email()], message: [r.minLength(10)] })
*/
export function localizedRules(locale?: string) {
const m = validationMessages(locale)
return {
checked: (msg?: string) => checked(msg ?? m.checked),
email: (msg?: string) => email(msg ?? m.email),
maxLength: (n: number, msg?: string) => maxLength(n, msg ?? m.maxLength(n)),
minLength: (n: number, msg?: string) => minLength(n, msg ?? m.minLength(n)),
pattern: (re: RegExp, msg?: string) => pattern(re, msg ?? m.pattern),
required: (msg?: string) => required(msg ?? m.required),
}
}
/** Escape hatch: any predicate → rule. */
export const custom =
(test: (value: unknown, values: Record<string, unknown>) => boolean, msg: string): Rule =>